code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
// Copyright (C) 2016 André Bargull. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-white-space description: > Mongolian Vowel Separator is not recognized as white space. info: | 11.2 White Space WhiteSpace :: <TAB> <VT> <FF> <SP> <NBSP> <ZWNBSP> <USP> <USP> :: Other category “Zs” code points General Category of U+180E is “Cf” (Format). negative: phase: parse type: SyntaxError features: [u180e] ---*/ throw "Test262: This statement should not be evaluated."; // U+180E between "var" and "foo"; UTF8(0x180E) = 0xE1 0xA0 0x8E var᠎foo;
sebastienros/jint
Jint.Tests.Test262/test/language/white-space/mongolian-vowel-separator.js
JavaScript
bsd-2-clause
659
#!/usr/bin/env python __author__ = 'Adam R. Smith, Michael Meisinger, Dave Foster <dfoster@asascience.com>' import threading import traceback import gevent from gevent import greenlet, Timeout from gevent.event import Event, AsyncResult from gevent.queue import Queue from pyon.core import MSG_HEADER_ACTOR from pyon.core.bootstrap import CFG from pyon.core.exception import IonException, ContainerError from pyon.core.exception import Timeout as IonTimeout from pyon.core.thread import PyonThreadManager, PyonThread, ThreadManager, PyonThreadTraceback, PyonHeartbeatError from pyon.datastore.postgresql.pg_util import init_db_stats, get_db_stats, clear_db_stats from pyon.ion.service import BaseService from pyon.util.containers import get_ion_ts, get_ion_ts_millis from pyon.util.log import log STAT_INTERVAL_LENGTH = 60000 # Interval time for process saturation stats collection stats_callback = None class OperationInterruptedException(BaseException): """ Interrupted exception. Used by external items timing out execution in the IonProcessThread's control thread. Derived from BaseException to specifically avoid try/except Exception blocks, such as in Publisher's publish_event. """ pass class IonProcessError(StandardError): pass class IonProcessThread(PyonThread): """ The control part of an ION process. """ def __init__(self, target=None, listeners=None, name=None, service=None, cleanup_method=None, heartbeat_secs=10, **kwargs): """ Constructs the control part of an ION process. Used by the container's IonProcessThreadManager, as part of spawn_process. @param target A callable to run in the PyonThread. If None (typical), will use the target method defined in this class. @param listeners A list of listening endpoints attached to this thread. @param name The name of this ION process. @param service An instance of the BaseService derived class which contains the business logic for the ION process. @param cleanup_method An optional callable to run when the process is stopping. Runs after all other notify_stop calls have run. Should take one param, this instance. @param heartbeat_secs Number of seconds to wait in between heartbeats. """ self._startup_listeners = listeners or [] self.listeners = [] self._listener_map = {} self.name = name self.service = service self._cleanup_method = cleanup_method self.thread_manager = ThreadManager(failure_notify_callback=self._child_failed) # bubbles up to main thread manager self._dead_children = [] # save any dead children for forensics self._ctrl_thread = None self._ctrl_queue = Queue() self._ready_control = Event() self._errors = [] self._ctrl_current = None # set to the AR generated by _routing_call when in the context of a call # processing vs idle time (ms) self._start_time = None self._proc_time = 0 # busy time since start self._proc_time_prior = 0 # busy time at the beginning of the prior interval self._proc_time_prior2 = 0 # busy time at the beginning of 2 interval's ago self._proc_interval_num = 0 # interval num of last record # for heartbeats, used to detect stuck processes self._heartbeat_secs = heartbeat_secs # amount of time to wait between heartbeats self._heartbeat_stack = None # stacktrace of last heartbeat self._heartbeat_time = None # timestamp of heart beat last matching the current op self._heartbeat_op = None # last operation (by AR) self._heartbeat_count = 0 # number of times this operation has been seen consecutively self._log_call_exception = CFG.get_safe("container.process.log_exceptions", False) self._log_call_dbstats = CFG.get_safe("container.process.log_dbstats", False) self._warn_call_dbstmt_threshold = CFG.get_safe("container.process.warn_dbstmt_threshold", 0) PyonThread.__init__(self, target=target, **kwargs) def heartbeat(self): """ Returns a 3-tuple indicating everything is ok. Should only be called after the process has been started. Checks the following: - All attached endpoints are alive + listening (this means ready) - The control flow greenlet is alive + listening or processing @return 3-tuple indicating (listeners ok, ctrl thread ok, heartbeat status). Use all on it for a boolean indication of success. """ listeners_ok = True for l in self.listeners: if not (l in self._listener_map and not self._listener_map[l].proc.dead and l.get_ready_event().is_set()): listeners_ok = False ctrl_thread_ok = self._ctrl_thread.running # are we currently processing something? heartbeat_ok = True if self._ctrl_current is not None: st = traceback.extract_stack(self._ctrl_thread.proc.gr_frame) if self._ctrl_current == self._heartbeat_op: if st == self._heartbeat_stack: self._heartbeat_count += 1 # we've seen this before! increment count # we've been in this for the last X ticks, or it's been X seconds, fail this part of the heartbeat if self._heartbeat_count > CFG.get_safe('container.timeout.heartbeat_proc_count_threshold', 30) or \ get_ion_ts_millis() - int(self._heartbeat_time) >= CFG.get_safe('container.timeout.heartbeat_proc_time_threshold', 30) * 1000: heartbeat_ok = False else: # it's made some progress self._heartbeat_count = 1 self._heartbeat_stack = st self._heartbeat_time = get_ion_ts() else: self._heartbeat_op = self._ctrl_current self._heartbeat_count = 1 self._heartbeat_time = get_ion_ts() self._heartbeat_stack = st else: self._heartbeat_op = None self._heartbeat_count = 0 #log.debug("%s %s %s", listeners_ok, ctrl_thread_ok, heartbeat_ok) return (listeners_ok, ctrl_thread_ok, heartbeat_ok) @property def time_stats(self): """ Returns a 5-tuple of (total time, idle time, processing time, time since prior interval start, busy since prior interval start), all in ms (int). """ now = get_ion_ts_millis() running_time = now - self._start_time idle_time = running_time - self._proc_time cur_interval = now / STAT_INTERVAL_LENGTH now_since_prior = now - (cur_interval - 1) * STAT_INTERVAL_LENGTH if cur_interval == self._proc_interval_num: proc_time_since_prior = self._proc_time-self._proc_time_prior2 elif cur_interval-1 == self._proc_interval_num: proc_time_since_prior = self._proc_time-self._proc_time_prior else: proc_time_since_prior = 0 return (running_time, idle_time, self._proc_time, now_since_prior, proc_time_since_prior) def _child_failed(self, child): """ Callback from gevent as set in the TheadManager, when a child greenlet fails. Kills the ION process main greenlet. This propagates the error up to the process supervisor. """ # remove the child from the list of children (so we can shut down cleanly) for x in self.thread_manager.children: if x.proc == child: self.thread_manager.children.remove(x) break self._dead_children.append(child) # kill this process's main greenlet. This should be noticed by the container's proc manager self.proc.kill(child.exception) def add_endpoint(self, listener, activate=True): """ Adds a listening endpoint to be managed by this ION process. Spawns the listen loop and sets the routing call to synchronize incoming messages here. If this process hasn't been started yet, adds it to the list of listeners to start on startup. @param activate If True (default), start consuming from listener """ if self.proc: listener.routing_call = self._routing_call if self.name: svc_name = "unnamed-service" if self.service is not None and hasattr(self.service, 'name'): svc_name = self.service.name listen_thread_name = "%s-%s-listen-%s" % (svc_name, self.name, len(self.listeners)+1) else: listen_thread_name = "unknown-listener-%s" % (len(self.listeners)+1) listen_thread = self.thread_manager.spawn(listener.listen, thread_name=listen_thread_name, activate=activate) listen_thread.proc._glname = "ION Proc listener %s" % listen_thread_name self._listener_map[listener] = listen_thread self.listeners.append(listener) else: self._startup_listeners.append(listener) def remove_endpoint(self, listener): """ Removes a listening endpoint from management by this ION process. If the endpoint is unknown to this ION process, raises an error. @return The PyonThread running the listen loop, if it exists. You are responsible for closing it when appropriate. """ if listener in self.listeners: self.listeners.remove(listener) return self._listener_map.pop(listener) elif listener in self._startup_listeners: self._startup_listeners.remove(listener) return None else: raise IonProcessError("Cannot remove unrecognized listener: %s" % listener) def target(self, *args, **kwargs): """ Entry point for the main process greenlet. Setup the base properties for this process (mainly the control thread). """ if self.name: threading.current_thread().name = "%s-target" % self.name # start time self._start_time = get_ion_ts_millis() self._proc_interval_num = self._start_time / STAT_INTERVAL_LENGTH # spawn control flow loop self._ctrl_thread = self.thread_manager.spawn(self._control_flow) self._ctrl_thread.proc._glname = "ION Proc CL %s" % self.name # wait on control flow loop, heartbeating as appropriate while not self._ctrl_thread.ev_exit.wait(timeout=self._heartbeat_secs): hbst = self.heartbeat() if not all(hbst): log.warn("Heartbeat status for process %s returned %s", self, hbst) if self._heartbeat_stack is not None: stack_out = "".join(traceback.format_list(self._heartbeat_stack)) else: stack_out = "N/A" #raise PyonHeartbeatError("Heartbeat failed: %s, stacktrace:\n%s" % (hbst, stack_out)) log.warn("Heartbeat failed: %s, stacktrace:\n%s", hbst, stack_out) # this is almost a no-op as we don't fall out of the above loop without # exiting the ctrl_thread, but having this line here makes testing much easier. self._ctrl_thread.join() def _routing_call(self, call, context, *callargs, **callkwargs): """ Endpoints call into here to synchronize across the entire IonProcess. Returns immediately with an AsyncResult that can be waited on. Calls are made by the loop in _control_flow. We pass in the calling greenlet so exceptions are raised in the correct context. @param call The call to be made within this ION processes' calling greenlet. @param callargs The keyword args to pass to the call. @param context Optional process-context (usually the headers of the incoming call) to be set. Process-context is greenlet-local, and since we're crossing greenlet boundaries, we must set it again in the ION process' calling greenlet. """ ar = AsyncResult() if len(callargs) == 0 and len(callkwargs) == 0: log.trace("_routing_call got no arguments for the call %s, check your call's parameters", call) self._ctrl_queue.put((greenlet.getcurrent(), ar, call, callargs, callkwargs, context)) return ar def has_pending_call(self, ar): """ Returns true if the call (keyed by the AsyncResult returned by _routing_call) is still pending. """ for _, qar, _, _, _, _ in self._ctrl_queue.queue: if qar == ar: return True return False def _cancel_pending_call(self, ar): """ Cancels a pending call (keyed by the AsyncResult returend by _routing_call). @return True if the call was truly pending. """ if self.has_pending_call(ar): ar.set(False) return True return False def _interrupt_control_thread(self): """ Signal the control flow thread that it needs to abort processing, likely due to a timeout. """ self._ctrl_thread.proc.kill(exception=OperationInterruptedException, block=False) def cancel_or_abort_call(self, ar): """ Either cancels a future pending call, or aborts the current processing if the given AR is unset. The pending call is keyed by the AsyncResult returned by _routing_call. """ if not self._cancel_pending_call(ar) and not ar.ready(): self._interrupt_control_thread() def _control_flow(self): """ Entry point for process control thread of execution. This method is run by the control greenlet for each ION process. Listeners attached to the process, either RPC Servers or Subscribers, synchronize calls to the process by placing call requests into the queue by calling _routing_call. This method blocks until there are calls to be made in the synchronized queue, and then calls from within this greenlet. Any exception raised is caught and re-raised in the greenlet that originally scheduled the call. If successful, the AsyncResult created at scheduling time is set with the result of the call. """ svc_name = getattr(self.service, "name", "unnamed-service") if self.service else "unnamed-service" proc_id = getattr(self.service, "id", "unknown-pid") if self.service else "unknown-pid" if self.name: threading.current_thread().name = "%s-%s" % (svc_name, self.name) thread_base_name = threading.current_thread().name self._ready_control.set() for calltuple in self._ctrl_queue: calling_gl, ar, call, callargs, callkwargs, context = calltuple request_id = (context or {}).get("request-id", None) if request_id: threading.current_thread().name = thread_base_name + "-" + str(request_id) #log.debug("control_flow making call: %s %s %s (has context: %s)", call, callargs, callkwargs, context is not None) res = None start_proc_time = get_ion_ts_millis() self._record_proc_time(start_proc_time) # check context for expiration if context is not None and 'reply-by' in context: if start_proc_time >= int(context['reply-by']): log.info("control_flow: attempting to process message already exceeding reply-by, ignore") # raise a timeout in the calling thread to allow endpoints to continue processing e = IonTimeout("Reply-by time has already occurred (reply-by: %s, op start time: %s)" % (context['reply-by'], start_proc_time)) calling_gl.kill(exception=e, block=False) continue # If ar is set, means it is cancelled if ar.ready(): log.info("control_flow: attempting to process message that has been cancelled, ignore") continue init_db_stats() try: # ****************************************************************** # ****** THIS IS WHERE THE RPC OPERATION/SERVICE CALL IS MADE ****** with self.service.push_context(context), \ self.service.container.context.push_context(context): self._ctrl_current = ar res = call(*callargs, **callkwargs) # ****** END CALL, EXCEPTION HANDLING FOLLOWS ****** # ****************************************************************** except OperationInterruptedException: # endpoint layer takes care of response as it's the one that caused this log.debug("Operation interrupted") pass except Exception as e: if self._log_call_exception: log.exception("PROCESS exception: %s" % e.message) # Raise the exception in the calling greenlet. # Try decorating the args of the exception with the true traceback - # this should be reported by ThreadManager._child_failed exc = PyonThreadTraceback("IonProcessThread _control_flow caught an exception " "(call: %s, *args %s, **kwargs %s, context %s)\n" "True traceback captured by IonProcessThread' _control_flow:\n\n%s" % ( call, callargs, callkwargs, context, traceback.format_exc())) e.args = e.args + (exc,) if isinstance(e, (TypeError, IonException)): # Pass through known process exceptions, in particular IonException calling_gl.kill(exception=e, block=False) else: # Otherwise, wrap unknown, forward and hopefully we can continue on our way self._errors.append((call, callargs, callkwargs, context, e, exc)) log.warn(exc) log.warn("Attempting to continue...") # Note: Too large exception string will crash the container (when passed on as msg header). exception_str = str(exc) if len(exception_str) > 10000: exception_str = ( "Exception string representation too large. " "Begin and end of the exception:\n" + exception_str[:2000] + "\n...\n" + exception_str[-2000:] ) calling_gl.kill(exception=ContainerError(exception_str), block=False) finally: try: # Compute statistics self._compute_proc_stats(start_proc_time) db_stats = get_db_stats() if db_stats: if self._warn_call_dbstmt_threshold > 0 and db_stats.get("count.all", 0) >= self._warn_call_dbstmt_threshold: stats_str = ", ".join("{}={}".format(k, db_stats[k]) for k in sorted(db_stats.keys())) log.warn("PROC_OP '%s.%s' EXCEEDED DB THRESHOLD. stats=%s", svc_name, call.__name__, stats_str) elif self._log_call_dbstats: stats_str = ", ".join("{}={}".format(k, db_stats[k]) for k in sorted(db_stats.keys())) log.info("PROC_OP '%s.%s' DB STATS: %s", svc_name, call.__name__, stats_str) clear_db_stats() if stats_callback: stats_callback(proc_id=proc_id, proc_name=self.name, svc=svc_name, op=call.__name__, request_id=request_id, context=context, db_stats=db_stats, proc_stats=self.time_stats, result=res, exc=None) except Exception: log.exception("Error computing process call stats") self._ctrl_current = None threading.current_thread().name = thread_base_name # Set response in AsyncEvent of caller (endpoint greenlet) ar.set(res) def _record_proc_time(self, cur_time): """ Keep the _proc_time of the prior and prior-prior intervals for stats computation """ cur_interval = cur_time / STAT_INTERVAL_LENGTH if cur_interval == self._proc_interval_num: # We're still in the same interval - no update pass elif cur_interval-1 == self._proc_interval_num: # Record the stats from the prior interval self._proc_interval_num = cur_interval self._proc_time_prior2 = self._proc_time_prior self._proc_time_prior = self._proc_time elif cur_interval-1 > self._proc_interval_num: # We skipped an entire interval - everything is prior2 self._proc_interval_num = cur_interval self._proc_time_prior2 = self._proc_time self._proc_time_prior = self._proc_time def _compute_proc_stats(self, start_proc_time): cur_time = get_ion_ts_millis() self._record_proc_time(cur_time) proc_time = cur_time - start_proc_time self._proc_time += proc_time def start_listeners(self): """ Starts all listeners in managed greenlets. Usually called by the ProcManager, unless using IonProcess manually. """ try: # disable normal error reporting, this method should only be called from startup self.thread_manager._failure_notify_callback = None # spawn all listeners in startup listeners (from initializer, or added later) for listener in self._startup_listeners: self.add_endpoint(listener) with Timeout(seconds=CFG.get_safe('container.messaging.timeout.start_listener', 30)): gevent.wait([x.get_ready_event() for x in self.listeners]) except Timeout: # remove failed endpoints before reporting failure above for listener, proc in self._listener_map.iteritems(): if proc.proc.dead: log.info("removed dead listener: %s", listener) self.listeners.remove(listener) self.thread_manager.children.remove(proc) raise IonProcessError("start_listeners did not complete in expected time") finally: self.thread_manager._failure_notify_callback = self._child_failed def _notify_stop(self): """ Called when the process is about to be shut down. Instructs all listeners to close, puts a StopIteration into the synchronized queue, and waits for the listeners to close and for the control queue to exit. """ for listener in self.listeners: try: listener.close() except Exception as ex: tb = traceback.format_exc() log.warn("Could not close listener, attempting to ignore: %s\nTraceback:\n%s", ex, tb) self._ctrl_queue.put(StopIteration) # wait_children will join them and then get() them, which may raise an exception if any of them # died with an exception. self.thread_manager.wait_children(30) PyonThread._notify_stop(self) # run the cleanup method if we have one if self._cleanup_method is not None: try: self._cleanup_method(self) except Exception as ex: log.warn("Cleanup method error, attempting to ignore: %s\nTraceback: %s", ex, traceback.format_exc()) def get_ready_event(self): """ Returns an Event that is set when the control greenlet is up and running. """ return self._ready_control class IonProcessThreadManager(PyonThreadManager): def _create_thread(self, target=None, **kwargs): return IonProcessThread(target=target, heartbeat_secs=self.heartbeat_secs, **kwargs) # --------------------------------------------------------------------------------------------------- # Process type variants class StandaloneProcess(BaseService): """ A process is an ION process of type "standalone" that has an incoming messaging attachment for the process and operations as defined in a service YML. """ process_type = "standalone" class SimpleProcess(BaseService): """ A simple process is an ION process of type "simple" that has no incoming messaging attachment. """ process_type = "simple" class ImmediateProcess(BaseService): """ An immediate process is an ION process of type "immediate" that does its action in the on_init and on_start hooks, and that it terminated immediately after completion. Has no messaging attachment. """ process_type = "immediate" class StreamProcess(BaseService): """ Base class for a stream process. Such a process handles a sequence of otherwise unconstrained messages, resulting from a subscription. There are no operations. """ process_type = "stream_process" def call_process(self, message, stream_route, stream_id): """ Handles pre-processing of packet and process work """ self.process(message) def process(self, message): """ Process a message as arriving based on a subscription. """ pass # --------------------------------------------------------------------------------------------------- # Process helpers def get_ion_actor_id(process): """Given an ION process, return the ion-actor-id from the context, if set and present""" ion_actor_id = None if process: ctx = process.get_context() ion_actor_id = ctx.get(MSG_HEADER_ACTOR, None) if ctx else None return ion_actor_id def set_process_stats_callback(stats_cb): """ Sets a callback function (hook) to push stats after a process operation call. """ global stats_callback if stats_cb is None: pass elif stats_callback: log.warn("Stats callback already defined") stats_callback = stats_cb
scionrep/scioncc
src/pyon/ion/process.py
Python
bsd-2-clause
27,034
# Author: Nick Raptis <airscorp@gmail.com> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: output = "\n".join((public, private)) elif 'pub' in arg or self.target.startswith('#'): output = public elif 'priv' in arg or not self.target.startswith('#'): output = private else: # we shouldn't be here self.logger.error("cmd_list") return self.send(self.target, output) def cmd_modules(self, argument): """List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output) def cmd_help(self, argument): """Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: s = "usage: help <command> [public|private] / help module <module>" self.send(target, s) elif args[0] == 'module': args.pop(0) if not args: self.send(target, "usage: help module <module>") else: help_item = index['modules'].get(args[0]) if help_item: self.send(target, help_item['summary']) else: self.send(target, _("No help for %s"), args[0]) else: args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here self.logger.error("cmd_list") return help_item = index[cmd_type].get(cmd) if help_item: self.send(target, index[cmd_type][cmd]['summary']) else: self.send(target, _("No help for %s"), cmd) class HelpModule(BaseModule): context_class = HelpContext module = HelpModule
nickraptis/fidibot
src/modules/help.py
Python
bsd-2-clause
2,615
cask 'feeder' do version '3.6.8' sha256 '4399609c1b04b1b92aa51bf9c240fc7dfec49e534eae014dbe750e7c7bbdfd2d' url "https://reinventedsoftware.com/feeder/downloads/Feeder_#{version}.dmg" appcast "https://reinventedsoftware.com/feeder/downloads/Feeder#{version.major}.xml" name 'Feeder' homepage 'https://reinventedsoftware.com/feeder/' app "Feeder #{version.major}.app" end
uetchy/homebrew-cask
Casks/feeder.rb
Ruby
bsd-2-clause
386
// This file was procedurally generated from the following sources: // - src/async-generators/yield-as-identifier-reference-escaped.case // - src/async-generators/syntax/async-class-expr-method.template /*--- description: yield is a reserved keyword within generator function bodies and may not be used as an identifier reference. (Async generator method as a ClassExpression element) esid: prod-AsyncGeneratorMethod features: [async-iteration] flags: [generated] negative: phase: parse type: SyntaxError info: | ClassElement : MethodDefinition MethodDefinition : AsyncGeneratorMethod Async Generator Function Definitions AsyncGeneratorMethod : async [no LineTerminator here] * PropertyName ( UniqueFormalParameters ) { AsyncGeneratorBody } IdentifierReference : Identifier It is a Syntax Error if this production has a [Yield] parameter and StringValue of Identifier is "yield". ---*/ throw "Test262: This statement should not be evaluated."; var C = class { async *gen() { void yi\u0065ld; }};
sebastienros/jint
Jint.Tests.Test262/test/language/expressions/class/async-gen-method-yield-as-identifier-reference-escaped.js
JavaScript
bsd-2-clause
1,059
#!/usr/bin/env python #Copyright (c) <2015>, <Jaakko Leppakangas> #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. # #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 the FreeBSD Project. ''' Created on Dec 16, 2014 @author: Jaakko Leppakangas ''' import sys from PyQt4 import QtGui from ui.preprocessDialog import PreprocessDialog def main(): app = QtGui.QApplication(sys.argv) window=PreprocessDialog() window.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
jaeilepp/eggie
eggie.py
Python
bsd-2-clause
1,903
L.CommunistWorker = L.AbstractWorker.extend({ statics: { // number of web workers, not using web workers when falsy NUM_WORKERS: 2 }, initialize: function (workerFunc) { this.workerFunc = workerFunc; }, onAdd: function (map) { this._workers = L.CommunistWorker.createWorkers(this.workerFunc); }, onRemove: function (map) { if (this._workers) { // TODO do not close when other layers are still using the static instance //this._workers.close(); } }, process: function(tile, callback) { if (this._workers){ tile._worker = this._workers.data(tile.datum).then(function(parsed) { if (tile._worker) { tile._worker = null; tile.parsed = parsed; tile.datum = null; callback(null, tile); } else { // tile has been unloaded, don't continue with adding //console.log('worker aborted ' + tile.key); } }); } else { callback(null, tile); } }, abort: function(tile) { if (tile._worker) { // TODO abort worker, would need to recreate after close //tile._worker.close(); tile._worker = null; } } }); L.communistWorker = function (workerFunc) { return new L.CommunistWorker(workerFunc); }; L.extend(L.CommunistWorker, { createWorkers: function(workerFunc) { if ( L.CommunistWorker.NUM_WORKERS && typeof Worker === "function" && typeof communist === "function" && !("workers" in L.CommunistWorker)) { L.CommunistWorker.workers = communist({ //data : L.TileLayer.Vector.parseData data : workerFunc }, L.CommunistWorker.NUM_WORKERS); } return L.CommunistWorker.workers; } });
nrenner/leaflet-tilelayer-vector
CommunistWorker.js
JavaScript
bsd-2-clause
1,976
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace nora.clara.machine { public enum Event { OPEN_REQUEST, ACTION_REQUEST, DEATH_REQUEST, CONNECTED_TO_STEAM, PLAYING_STATE_OPENED, PLAYING_STATE_CLOSED, DISCONNECTED_FROM_STEAM, WELCOMED_STALE_LOBBY, WELCOMED, JOINED_CHAT, CREATED_LOBBY, LEFT_LOBBY, PLAYER_JOINED, EMPTIED, LOBBY_READY, LOBBY_NOT_READY, GOT_APP_TICKET, GOT_AUTH, GOT_SESSION, GOT_TV, GAME_SERVER_NOT_FOUND, DENIED_TV, SERVER_RUNNING, SERVER_WAITING_FOR_PLAYERS, GAME_SERVER_QUIT, } }
dschleck/nora
clara/machine/Event.cs
C#
bsd-2-clause
795
/* * Copyright (c) 2009-2010 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.gde.core.filters.impl; import com.jme3.gde.core.filters.AbstractFilterNode; import com.jme3.gde.core.filters.FilterNode; import com.jme3.post.Filter; import com.jme3.water.WaterFilter; import org.openide.loaders.DataObject; import org.openide.nodes.Node; import org.openide.nodes.Sheet; /** * * @author Rémy Bouquet */ @org.openide.util.lookup.ServiceProvider(service = FilterNode.class) public class JmeWaterFilter extends AbstractFilterNode { public JmeWaterFilter() { } public JmeWaterFilter(WaterFilter filter, DataObject object, boolean readOnly) { super(filter); this.dataObject = object; this.readOnly = readOnly; } @Override protected Sheet createSheet() { Sheet sheet = super.createSheet(); Sheet.Set set = Sheet.createPropertiesSet(); set.setDisplayName("Water"); set.setName("Water"); WaterFilter obj = (WaterFilter) filter; if (obj == null) { return sheet; } createFields(WaterFilter.class, set, obj); sheet.put(set); return sheet; } @Override public Class<?> getExplorerObjectClass() { return WaterFilter.class; } @Override public Node[] createNodes(Object key, DataObject dataObject, boolean readOnly) { return new Node[]{new JmeWaterFilter((WaterFilter) key, dataObject, readOnly)}; } }
chototsu/MikuMikuStudio
sdk/jme3-core/src/com/jme3/gde/core/filters/impl/JmeWaterFilter.java
Java
bsd-2-clause
3,026
<?php namespace Nether\Object\Meta; use Attribute; use Nether\Object\Prototype\AttributeInterface; use Nether\Object\Prototype\PropertyAttributes; #[Attribute(Attribute::TARGET_PROPERTY)] class PropertyOrigin implements AttributeInterface { /*// @date 2021-08-05 @related Nether\Object\Prototype::__Construct when attached to a class property with a single string argument that will tell the prototype object to pull the data stored in the arguement and to put it into the property this is attached to. //*/ public string $Name; public function __Construct(string $Name) { $this->Name = $Name; return; } public function OnPropertyAttributes(PropertyAttributes $Attrib): static { $Attrib->Origin = $this->Name; return $this; } }
netherphp/object
src/Nether/Object/Meta/PropertyOrigin.php
PHP
bsd-2-clause
753
/** * Copyright (c) 2013, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * https://raw.github.com/facebook/regenerator/master/LICENSE file. An * additional grant of patent rights can be found in the PATENTS file in * the same directory. */ var assert = require("assert"); var types = require("ast-types"); var n = types.namedTypes; var b = types.builders; var inherits = require("util").inherits; function Entry() { assert.ok(this instanceof Entry); } function FunctionEntry(returnLoc) { Entry.call(this); n.Literal.assert(returnLoc); Object.defineProperties(this, { returnLoc: { value: returnLoc } }); } inherits(FunctionEntry, Entry); exports.FunctionEntry = FunctionEntry; function LoopEntry(breakLoc, continueLoc, label) { Entry.call(this); n.Literal.assert(breakLoc); n.Literal.assert(continueLoc); if (label) { n.Identifier.assert(label); } else { label = null; } Object.defineProperties(this, { breakLoc: { value: breakLoc }, continueLoc: { value: continueLoc }, label: { value: label } }); } inherits(LoopEntry, Entry); exports.LoopEntry = LoopEntry; function SwitchEntry(breakLoc) { Entry.call(this); n.Literal.assert(breakLoc); Object.defineProperties(this, { breakLoc: { value: breakLoc } }); } inherits(SwitchEntry, Entry); exports.SwitchEntry = SwitchEntry; function TryEntry(catchEntry, finallyEntry) { Entry.call(this); if (catchEntry) { assert.ok(catchEntry instanceof CatchEntry); } else { catchEntry = null; } if (finallyEntry) { assert.ok(finallyEntry instanceof FinallyEntry); } else { finallyEntry = null; } Object.defineProperties(this, { catchEntry: { value: catchEntry }, finallyEntry: { value: finallyEntry } }); } inherits(TryEntry, Entry); exports.TryEntry = TryEntry; function CatchEntry(firstLoc, paramId) { Entry.call(this); n.Literal.assert(firstLoc); n.Identifier.assert(paramId); Object.defineProperties(this, { firstLoc: { value: firstLoc }, paramId: { value: paramId } }); } inherits(CatchEntry, Entry); exports.CatchEntry = CatchEntry; function FinallyEntry(firstLoc, nextLocTempVar) { Entry.call(this); n.Literal.assert(firstLoc); n.Identifier.assert(nextLocTempVar); Object.defineProperties(this, { firstLoc: { value: firstLoc }, nextLocTempVar: { value: nextLocTempVar } }); } inherits(FinallyEntry, Entry); exports.FinallyEntry = FinallyEntry; function LeapManager(emitter) { assert.ok(this instanceof LeapManager); var Emitter = require("./emit").Emitter; assert.ok(emitter instanceof Emitter); Object.defineProperties(this, { emitter: { value: emitter }, entryStack: { value: [new FunctionEntry(emitter.finalLoc)] } }); } var LMp = LeapManager.prototype; exports.LeapManager = LeapManager; LMp.withEntry = function(entry, callback) { assert.ok(entry instanceof Entry); this.entryStack.push(entry); try { callback.call(this.emitter); } finally { var popped = this.entryStack.pop(); assert.strictEqual(popped, entry); } }; LMp._leapToEntry = function(predicate, defaultLoc) { var entry, loc; var finallyEntries = []; var skipNextTryEntry = null; for (var i = this.entryStack.length - 1; i >= 0; --i) { entry = this.entryStack[i]; if (entry instanceof CatchEntry || entry instanceof FinallyEntry) { // If we are inside of a catch or finally block, then we must // have exited the try block already, so we shouldn't consider // the next TryStatement as a handler for this throw. skipNextTryEntry = entry; } else if (entry instanceof TryEntry) { if (skipNextTryEntry) { // If an exception was thrown from inside a catch block and this // try statement has a finally block, make sure we execute that // finally block. if (skipNextTryEntry instanceof CatchEntry && entry.finallyEntry) { finallyEntries.push(entry.finallyEntry); } skipNextTryEntry = null; } else if ((loc = predicate.call(this, entry))) { break; } else if (entry.finallyEntry) { finallyEntries.push(entry.finallyEntry); } } else if ((loc = predicate.call(this, entry))) { break; } } if (loc) { // fall through } else if (defaultLoc) { loc = defaultLoc; } else { return null; } n.Literal.assert(loc); var finallyEntry; while ((finallyEntry = finallyEntries.pop())) { this.emitter.emitAssign(finallyEntry.nextLocTempVar, loc); loc = finallyEntry.firstLoc; } return loc; }; function getLeapLocation(entry, property, label) { var loc = entry[property]; if (loc) { if (label) { if (entry.label && entry.label.name === label.name) { return loc; } } else { return loc; } } return null; } LMp.emitBreak = function(label) { var loc = this._leapToEntry(function(entry) { return getLeapLocation(entry, "breakLoc", label); }); if (loc === null) { throw new Error("illegal break statement"); } this.emitter.clearPendingException(); this.emitter.jump(loc); }; LMp.emitContinue = function(label) { var loc = this._leapToEntry(function(entry) { return getLeapLocation(entry, "continueLoc", label); }); if (loc === null) { throw new Error("illegal continue statement"); } this.emitter.clearPendingException(); this.emitter.jump(loc); };
jlongster/unwinder
lib/leap.js
JavaScript
bsd-2-clause
5,549
var http = require('http') var url = require('url') var path = require('path') var sleep = require('sleep-ref') var Router = require("routes-router") var concat = require('concat-stream') var ldj = require('ldjson-stream') var manifest = require('level-manifest') var multilevel = require('multilevel') var extend = require('extend') var prettyBytes = require('pretty-bytes') var jsonStream = require('JSONStream') var prebuiltEditor = require('dat-editor-prebuilt') var debug = require('debug')('rest-handler') var auth = require('./auth.js') var pump = require('pump') var zlib = require('zlib') var through = require('through2') module.exports = RestHandler function RestHandler(dat) { if (!(this instanceof RestHandler)) return new RestHandler(dat) this.dat = dat this.auth = auth(dat.options) this.router = this.createRoutes() this.sleep = sleep(function(opts) { opts.decode = true if (opts.live === 'true') opts.live = true if (opts.tail === 'true') opts.tail = true return dat.createChangesReadStream(opts) }, {style: 'newline'}) } RestHandler.prototype.createRoutes = function() { var router = Router() router.addRoute("/", this.dataTable.bind(this)) router.addRoute("/api/session", this.session.bind(this)) router.addRoute("/api/login", this.login.bind(this)) router.addRoute("/api/logout", this.logout.bind(this)) router.addRoute("/api/pull", this.pull.bind(this)) router.addRoute("/api/push", this.push.bind(this)) router.addRoute("/api/changes", this.changes.bind(this)) router.addRoute("/api/stats", this.stats.bind(this)) router.addRoute("/api/bulk", this.bulk.bind(this)) router.addRoute("/api/metadata", this.package.bind(this)) router.addRoute("/api/manifest", this.manifest.bind(this)) router.addRoute("/api/rpc", this.rpc.bind(this)) router.addRoute("/api/csv", this.exportCsv.bind(this)) router.addRoute("/api", this.hello.bind(this)) router.addRoute("/api/rows", this.document.bind(this)) router.addRoute("/api/rows/:key", this.document.bind(this)) router.addRoute("/api/rows/:key/:filename", this.blob.bind(this)) router.addRoute("/api/blobs/:key", this.blobs.bind(this)) router.addRoute("*", this.notFound.bind(this)) return router } RestHandler.prototype.session = function(req, res) { var self = this this.auth.handle(req, res, function(err, session) { debug('session', [err, session]) var data = {} if (err) return self.auth.error(req, res) if (session) data.session = session else data.loggedOut = true self.json(res, data) }) } RestHandler.prototype.login = function(req, res) { var self = this this.auth.handle(req, res, function(err, session) { debug('login', [err, session]) if (err) { res.setHeader("WWW-Authenticate", "Basic realm=\"Secure Area\"") self.auth.error(req, res) return } self.json(res, {session: session}) }) } RestHandler.prototype.logout = function(req, res) { return this.auth.error(req, res) } RestHandler.prototype.blob = function(req, res, opts) { var self = this if (req.method === 'GET') { var key = opts.key var blob = self.dat.createBlobReadStream(opts.key, opts.filename, opts) blob.on('error', function(err) { return self.error(res, 404, {"error": "Not Found"}) }) pump(blob, res) return } if (req.method === "POST") { var reqUrl = url.parse(req.url, true) var qs = reqUrl.query var doc = { key: opts.key, version: qs.version } self.auth.handle(req, res, function(err) { if (err) return self.auth.error(req, res) var key = doc.key self.dat.get(key, { version: doc.version }, function(err, existing) { if (existing) { doc = existing } var ws = self.dat.createBlobWriteStream(opts.filename, doc, function(err, updated) { if (err) return self.error(res, 500, err) self.json(res, updated) }) pump(req, ws) }) return }) return } self.error(res, 405, {error: 'method not supported'}) } RestHandler.prototype.blobs = function(req, res, opts) { var self = this if (req.method === 'HEAD') { var key = opts.key var blob = self.dat.blobs.backend.exists(opts, function(err, exists) { res.statusCode = exists ? 200 : 404 res.setHeader('content-length', 0) res.end() }) return } if (req.method === 'GET') { res.statusCode = 200 return pump(self.dat.blobs.backend.createReadStream(opts), res) } self.error(res, 405, {error: 'method not supported'}) } var unzip = function(req) { return req.headers['content-encoding'] === 'gzip' ? zlib.createGunzip() : through() } var zip = function(req, res) { if (!/gzip/.test(req.headers['accept-encoding'] || '')) return through() res.setHeader('Content-Encoding', 'gzip') return zlib.createGzip() } RestHandler.prototype.push = function(req, res) { var self = this this.auth.handle(req, res, function(err) { if (err) return self.auth.error(req, res) pump(req, unzip(req), self.dat.replicator.receive(), function(err) { if (err) { res.statusCode = err.status || 500 res.end(err.message) return } res.end() }) }) } RestHandler.prototype.pull = function(req, res) { var reqUrl = url.parse(req.url, true) var qs = reqUrl.query var send = this.dat.replicator.send({ since: parseInt(qs.since, 10) || 0, blobs: qs.blobs !== 'false', live: !!qs.live }) pump(send, zip(req, res), res) } RestHandler.prototype.changes = function(req, res) { this.sleep.httpHandler(req, res) } RestHandler.prototype.stats = function(req, res) { var statsStream = this.dat.createStatsStream() statsStream.on('error', function(err) { var errObj = { type: 'statsStreamError', message: err.message } res.statusCode = 400 serializer.write(errObj) serializer.end() }) var serializer = ldj.serialize() pump(statsStream, serializer, res) } RestHandler.prototype.package = function(req, res) { var meta = {changes: this.dat.storage.change, liveBackup: this.dat.supportsLiveBackup()} meta.columns = this.dat.schema.headers() this.json(res, meta) } RestHandler.prototype.manifest = function(req, res) { this.json(res, manifest(this.dat.storage)) } RestHandler.prototype.rpc = function(req, res) { var self = this this.auth.handle(req, res, function(err) { if (err) return self.auth.error(req, res) var mserver = multilevel.server(self.dat.storage) pump(req, mserver, res) }) } RestHandler.prototype.exportCsv = function(req, res) { var reqUrl = url.parse(req.url, true) var qs = reqUrl.query qs.csv = true var readStream = this.dat.createReadStream(qs) res.writeHead(200, {'content-type': 'text/csv'}) pump(readStream, res) } RestHandler.prototype.exportJson = function(req, res) { var reqUrl = url.parse(req.url, true) var qs = reqUrl.query if (typeof qs.limit === 'undefined') qs.limit = 50 else qs.limit = +qs.limit var readStream = this.dat.createReadStream(qs) res.writeHead(200, {'content-type': 'application/json'}) pump(readStream, jsonStream.stringify('{"rows": [\n', '\n,\n', '\n]}\n'), res) } RestHandler.prototype.handle = function(req, res) { debug(req.connection.remoteAddress + ' - ' + req.method + ' - ' + req.url + ' - ') this.router(req, res) } RestHandler.prototype.error = function(res, status, message) { if (!status) status = res.statusCode if (message) { if (message.status) status = message.status if (typeof message === "object") message.status = status if (typeof message === "string") message = {error: status, message: message} } res.statusCode = status || 500 this.json(res, message) } RestHandler.prototype.notFound = function(req, res) { this.error(res, 404, {"error": "Not Found"}) } RestHandler.prototype.hello = function(req, res) { var self = this var stats = { "dat": "Hello", "version": this.dat.version, "changes": this.dat.storage.change, "name": this.dat.options.name } this.dat.storage.stat(function(err, stat) { if (err) return self.json(res, stats) stats.rows = stat.rows self.dat.storage.approximateSize(function(err, size) { if (err) return self.json(res, stats) stats.approximateSize = { rows: prettyBytes(size) } self.json(res, stats) }) }) } RestHandler.prototype.dataTable = function(req, res) { res.setHeader('content-type', 'text/html; charset=utf-8') res.end(prebuiltEditor) } RestHandler.prototype.json = function(res, json) { res.setHeader('content-type', 'application/json') res.end(JSON.stringify(json) + '\n') } RestHandler.prototype.get = function(req, res, opts) { var self = this this.dat.get(opts.key, url.parse(req.url, true).query || {}, function(err, json) { if (err && err.message === 'range not found') return self.error(res, 404, {error: "Not Found"}) if (err) return self.error(res, 500, err.message) if (json === null) return self.error(res, 404, {error: "Not Found"}) self.json(res, json) }) } RestHandler.prototype.post = function(req, res) { var self = this self.bufferJSON(req, function(err, json) { if (err) return self.error(res, 500, err) if (!json) json = {} self.dat.put(json, function(err, stored) { if (err) { if (err.conflict) return self.error(res, 409, {conflict: true, error: "Document update conflict. Invalid version"}) return self.error(res, 500, err) } res.statusCode = 201 self.json(res, stored) }) }) } RestHandler.prototype.delete = function(req, res, opts) { var self = this self.dat.delete(opts.key, function(err, stored) { if (err) return self.error(res, 500, err) self.json(res, {deleted: true}) }) } RestHandler.prototype.bulk = function(req, res) { var self = this var opts = {} var ct = req.headers['content-type'] if (ct === 'application/json') opts.json = true else if (ct === 'text/csv') opts.csv = true else return self.error(res, 400, {error: 'missing or unsupported content-type'}) opts.results = true debug('/api/bulk', opts) this.auth.handle(req, res, function(err) { if (err) return self.auth.error(req, res) var writeStream = self.dat.createWriteStream(opts) writeStream.on('error', function(writeErr) { var errObj = { type: 'writeStreamError', message: writeErr.message } res.statusCode = 400 serializer.write(errObj) serializer.end() }) var serializer = ldj.serialize() pump(req, writeStream, serializer, res) }) } RestHandler.prototype.document = function(req, res, opts) { var self = this if (req.method === "GET" || req.method === "HEAD") { if (opts.key) return this.get(req, res, opts) else return this.exportJson(req, res) } this.auth.handle(req, res, function(err) { if (err) return self.auth.error(req, res) if (req.method === "POST") return self.post(req, res, opts) if (req.method === "DELETE") return self.delete(req, res, opts) self.error(res, 405, {error: 'method not supported'}) }) } RestHandler.prototype.bufferJSON = function(req, cb) { var self = this req.on('error', function(err) { cb(err) }) req.pipe(concat(function(buff) { var json if (buff && buff.length === 0) return cb() if (buff) { try { json = JSON.parse(buff) } catch(err) { return cb(err) } } if (!json) return cb(err) cb(null, json) })) }
giantoak/dat
lib/rest-handler.js
JavaScript
bsd-2-clause
11,585
/** * The main application class. An instance of this class is created by app.js when it calls * Ext.application(). This is the ideal place to handle application launch and initialization * details. * * */ Ext.define('Sample.Application', { extend: 'Devon.App', name: 'Sample', requires:[ 'Sample.Simlets' ], controllers: [ 'Sample.controller.main.MainController', 'Sample.controller.table.TablesController', 'Sample.controller.cook.CookController' ], launch: function() { Devon.Log.trace('Sample.app launch'); console.log('Sample.app launch'); if (document.location.toString().indexOf('useSimlets')>=0){ Sample.Simlets.useSimlets(); } this.callParent(arguments); } });
CoEValencia/chirr
demos/workspace/ExtSample/app/Application.js
JavaScript
bsd-2-clause
796
package com.glob3mobile.vectorial.processing; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import com.glob3mobile.utils.Progress; import com.glob3mobile.vectorial.lod.PointFeatureLODStorage; import com.glob3mobile.vectorial.lod.mapdb.PointFeatureLODMapDBStorage; import com.glob3mobile.vectorial.storage.PointFeature; import com.glob3mobile.vectorial.storage.PointFeatureStorage; import com.glob3mobile.vectorial.storage.mapdb.PointFeatureMapDBStorage; public class LODPointFeaturesPreprocessor { private static class LeafNodesImporter implements PointFeatureStorage.NodeVisitor { private final long _nodesCount; private final PointFeatureLODStorage _lodStorage; private final boolean _verbose; private Progress _progress; private LeafNodesImporter(final long nodesCount, final PointFeatureLODStorage lodStorage, final boolean verbose) { _nodesCount = nodesCount; _lodStorage = lodStorage; _verbose = verbose; } @Override public void start() { _progress = new Progress(_nodesCount) { @Override public void informProgress(final long stepsDone, final double percent, final long elapsed, final long estimatedMsToFinish) { if (_verbose) { System.out.println(_lodStorage.getName() + ": 1/4 Importing leaf nodes: " + progressString(stepsDone, percent, elapsed, estimatedMsToFinish)); } } }; } @Override public void stop() { _progress.finish(); _progress = null; } @Override public boolean visit(final PointFeatureStorage.Node node) { final List<PointFeature> features = new ArrayList<>(node.getFeatures()); _lodStorage.addLeafNode( // node.getID(), // node.getNodeSector(), // node.getMinimumSector(), // features // ); _progress.stepDone(); return true; } } public static void process(final File storageDir, final String storageName, final File lodDir, final String lodName, final int maxFeaturesPerNode, final Comparator<PointFeature> featuresComparator, final boolean createClusters, final boolean verbose) throws IOException { try (final PointFeatureStorage storage = PointFeatureMapDBStorage.openReadOnly(storageDir, storageName)) { try (final PointFeatureLODStorage lodStorage = PointFeatureLODMapDBStorage.createEmpty(storage.getSector(), lodDir, lodName, maxFeaturesPerNode, featuresComparator, createClusters)) { final PointFeatureStorage.Statistics statistics = storage.getStatistics(verbose); if (verbose) { statistics.show(); System.out.println(); } final int nodesCount = statistics.getNodesCount(); storage.acceptDepthFirstVisitor(new LeafNodesImporter(nodesCount, lodStorage, verbose)); lodStorage.createLOD(verbose); if (verbose) { System.out.println(lodStorage.getName() + ": 4/4 Optimizing storage..."); } lodStorage.optimize(); if (verbose) { System.out.println(); final PointFeatureLODStorage.Statistics lodStatistics = lodStorage.getStatistics(verbose); lodStatistics.show(); } } } } private LODPointFeaturesPreprocessor() { } public static void main(final String[] args) throws IOException { System.out.println("LODPointFeaturesPreprocessor 0.1"); System.out.println("--------------------------------\n"); final File sourceDir = new File("PointFeaturesStorage"); // final String sourceName = "Cities1000"; // final String sourceName = "AR"; // final String sourceName = "ES"; // final String sourceName = "GEONames-PopulatedPlaces"; // final String sourceName = "SpanishBars"; final String sourceName = "Tornados"; final File lodDir = new File("PointFeaturesLOD"); final String lodName = sourceName + "_LOD"; final int maxFeaturesPerNode = 64; // final int maxFeaturesPerNode = 96; final boolean createClusters = true; final Comparator<PointFeature> featuresComparator = createClusters ? null : new GEONamesComparator(); final boolean verbose = true; LODPointFeaturesPreprocessor.process( // sourceDir, sourceName, // lodDir, lodName, // maxFeaturesPerNode, // featuresComparator, // createClusters, // verbose); System.out.println("\n- done!"); } }
octavianiLocator/g3m
tools/vectorial-streaming/src/com/glob3mobile/vectorial/processing/LODPointFeaturesPreprocessor.java
Java
bsd-2-clause
5,344
#include <catch.hpp> #include <rapidcheck/catch.h> using namespace rc; TEST_CASE("scaleInteger") { prop("for uint32_t, equal to naive way", [] { const auto x = *gen::arbitrary<uint32_t>(); const auto size = *gen::nonNegative<int>(); RC_ASSERT(gen::detail::scaleInteger(x, size) == ((x * std::min<uint64_t>(kNominalSize, size) + (kNominalSize / 2)) / kNominalSize)); }); prop("result strictly increases with size", [](uint64_t x) { const auto sizeA = *gen::nonNegative<int>(); const auto sizeB = *gen::nonNegative<int>(); const auto small = std::min(sizeA, sizeB); const auto large = std::max(sizeA, sizeB); RC_ASSERT(gen::detail::scaleInteger(x, small) <= gen::detail::scaleInteger(x, large)); }); prop("result strictly increases with value", [](uint64_t a, uint64_t b){ const auto size = *gen::nonNegative<int>(); const auto small = std::min(a, b); const auto large = std::max(a, b); RC_ASSERT(gen::detail::scaleInteger(small, size) <= gen::detail::scaleInteger(large, size)); }); prop("yields input for kNominalSize", [](uint64_t x) { RC_ASSERT(gen::detail::scaleInteger(x, kNominalSize) == x); }); prop("yields 0 for 0", [](uint64_t x) { RC_ASSERT(gen::detail::scaleInteger(x, 0) == 0U); }); }
unapiedra/rapidfuzz
test/gen/detail/ScaleIntegerTests.cpp
C++
bsd-2-clause
1,493
// ------------------------------------------------------------------------------ // <copyright from='2002' to='2002' company='Scott Hanselman'> // Copyright (c) Scott Hanselman. All Rights Reserved. // </copyright> // ------------------------------------------------------------------------------ // // Scott Hanselman's Tiny Academic Virtual CPU and OS // Copyright (c) 2002, Scott Hanselman (scott@hanselman.com) // All rights reserved. // // A BSD 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. // Neither the name of Scott Hanselman nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS // BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace Hanselman.CST352 { using System; using System.Collections; /// <summary> /// A collection that stores <see cref='Hanselman.CST352.Instruction'/> objects. /// </summary> /// <seealso cref='Hanselman.CST352.InstructionCollection'/> [Serializable()] public class InstructionCollection : CollectionBase { /// <summary> /// Initializes a new instance of <see cref='Hanselman.CST352.InstructionCollection'/>. /// </summary> public InstructionCollection() { } /// <summary> /// Initializes a new instance of <see cref='Hanselman.CST352.InstructionCollection'/> based on another <see cref='Hanselman.CST352.InstructionCollection'/>. /// </summary> /// <param name='value'> /// A <see cref='Hanselman.CST352.InstructionCollection'/> from which the contents are copied /// </param> public InstructionCollection(InstructionCollection value) { this.AddRange(value); } /// <summary> /// Initializes a new instance of <see cref='Hanselman.CST352.InstructionCollection'/> containing any array of <see cref='Hanselman.CST352.Instruction'/> objects. /// </summary> /// <param name='value'> /// A array of <see cref='Hanselman.CST352.Instruction'/> objects with which to intialize the collection /// </param> public InstructionCollection(Instruction[] value) { this.AddRange(value); } /// <summary> /// Represents the entry at the specified index of the <see cref='Hanselman.CST352.Instruction'/>. /// </summary> /// <param name='index'>The zero-based index of the entry to locate in the collection.</param> /// <value> /// The entry at the specified index of the collection. /// </value> /// <exception cref='System.ArgumentOutOfRangeException'><paramref name='index'/> is outside the valid range of indexes for the collection.</exception> public Instruction this[int index] { get { return ((Instruction)(List[index])); } set { List[index] = value; } } /// <summary> /// Adds a <see cref='Hanselman.CST352.Instruction'/> with the specified value to the /// <see cref='Hanselman.CST352.InstructionCollection'/> . /// </summary> /// <param name='value'>The <see cref='Hanselman.CST352.Instruction'/> to add.</param> /// <returns> /// The index at which the new element was inserted. /// </returns> /// <seealso cref='Hanselman.CST352.InstructionCollection.AddRange(Instruction[])'/> public int Add(Instruction value) { return List.Add(value); } /// <summary> /// Copies the elements of an array to the end of the <see cref='Hanselman.CST352.InstructionCollection'/>. /// </summary> /// <param name='value'> /// An array of type <see cref='Hanselman.CST352.Instruction'/> containing the objects to add to the collection. /// </param> /// <returns> /// None. /// </returns> /// <seealso cref='Hanselman.CST352.InstructionCollection.Add'/> public void AddRange(Instruction[] value) { for (int i = 0; (i < value.Length); i = (i + 1)) { this.Add(value[i]); } } /// <summary> /// /// Adds the contents of another <see cref='Hanselman.CST352.InstructionCollection'/> to the end of the collection. /// /// </summary> /// <param name='value'> /// A <see cref='Hanselman.CST352.InstructionCollection'/> containing the objects to add to the collection. /// </param> /// <returns> /// None. /// </returns> /// <seealso cref='Hanselman.CST352.InstructionCollection.Add'/> public void AddRange(InstructionCollection value) { for (int i = 0; (i < value.Count); i = (i + 1)) { this.Add(value[i]); } } /// <summary> /// Gets a value indicating whether the /// <see cref='Hanselman.CST352.InstructionCollection'/> contains the specified <see cref='Hanselman.CST352.Instruction'/>. /// </summary> /// <param name='value'>The <see cref='Hanselman.CST352.Instruction'/> to locate.</param> /// <returns> /// <see langword='true'/> if the <see cref='Hanselman.CST352.Instruction'/> is contained in the collection; /// otherwise, <see langword='false'/>. /// </returns> /// <seealso cref='Hanselman.CST352.InstructionCollection.IndexOf'/> public bool Contains(Instruction value) { return List.Contains(value); } /// <summary> /// Copies the <see cref='Hanselman.CST352.InstructionCollection'/> values to a one-dimensional <see cref='System.Array'/> instance at the /// specified index. /// </summary> /// <param name='array'>The one-dimensional <see cref='System.Array'/> that is the destination of the values copied from <see cref='Hanselman.CST352.InstructionCollection'/> .</param> /// <param name='index'>The index in <paramref name='array'/> where copying begins.</param> /// <returns> /// None. /// </returns> /// <exception cref='System.ArgumentException'><paramref name='array'/> is multidimensional. -or- The number of elements in the <see cref='Hanselman.CST352.InstructionCollection'/> is greater than the available space between <paramref name='index'/> and the end of <paramref name='array'/>.</exception> /// <exception cref='System.ArgumentNullException'><paramref name='array'/> is <see langword='null'/>. </exception> /// <exception cref='System.ArgumentOutOfRangeException'><paramref name='index'/> is less than <paramref name='array'/>'s lowbound. </exception> /// <seealso cref='System.Array'/> public void CopyTo(Instruction[] array, int index) { List.CopyTo(array, index); } /// <summary> /// Returns the index of a <see cref='Hanselman.CST352.Instruction'/> in /// the <see cref='Hanselman.CST352.InstructionCollection'/> . /// </summary> /// <param name='value'>The <see cref='Hanselman.CST352.Instruction'/> to locate.</param> /// <returns> /// The index of the <see cref='Hanselman.CST352.Instruction'/> of <paramref name='value'/> in the /// <see cref='Hanselman.CST352.InstructionCollection'/>, if found; otherwise, -1. /// </returns> /// <seealso cref='Hanselman.CST352.InstructionCollection.Contains'/> public int IndexOf(Instruction value) { return List.IndexOf(value); } /// <summary> /// Inserts a <see cref='Hanselman.CST352.Instruction'/> into the <see cref='Hanselman.CST352.InstructionCollection'/> at the specified index. /// </summary> /// <param name='index'>The zero-based index where <paramref name='value'/> should be inserted.</param> /// <param name=' value'>The <see cref='Hanselman.CST352.Instruction'/> to insert.</param> /// <returns>None.</returns> /// <seealso cref='Hanselman.CST352.InstructionCollection.Add'/> public void Insert(int index, Instruction value) { List.Insert(index, value); } /// <summary> /// Returns an enumerator that can iterate through /// the <see cref='Hanselman.CST352.InstructionCollection'/> . /// </summary> /// <returns>None.</returns> /// <seealso cref='System.Collections.IEnumerator'/> public new InstructionEnumerator GetEnumerator() { return new InstructionEnumerator(this); } /// <summary> /// Removes a specific <see cref='Hanselman.CST352.Instruction'/> from the /// <see cref='Hanselman.CST352.InstructionCollection'/> . /// </summary> /// <param name='value'>The <see cref='Hanselman.CST352.Instruction'/> to remove from the <see cref='Hanselman.CST352.InstructionCollection'/> .</param> /// <returns>None.</returns> /// <exception cref='System.ArgumentException'><paramref name='value'/> is not found in the Collection. </exception> public void Remove(Instruction value) { List.Remove(value); } /// <summary> /// Provided for "foreach" support with this collection /// </summary> public class InstructionEnumerator : object, IEnumerator { private IEnumerator baseEnumerator; private IEnumerable temp; /// <summary> /// Public constructor for an InstructionEnumerator /// </summary> /// <param name="mappings">The <see cref="InstructionCollection"/>we are going to iterate over</param> public InstructionEnumerator(InstructionCollection mappings) { this.temp = ((IEnumerable)(mappings)); this.baseEnumerator = temp.GetEnumerator(); } /// <summary> /// The current <see cref="Instruction"/> /// </summary> public Instruction Current { get { return ((Instruction)(baseEnumerator.Current)); } } /// <summary> /// The current IEnumerator interface /// </summary> object IEnumerator.Current { get { return baseEnumerator.Current; } } /// <summary> /// Move to the next Instruction /// </summary> /// <returns>true or false based on success</returns> public bool MoveNext() { return baseEnumerator.MoveNext(); } /// <summary> /// Move to the next Instruction /// </summary> /// <returns>true or false based on success</returns> bool IEnumerator.MoveNext() { return baseEnumerator.MoveNext(); } /// <summary> /// Reset the cursor /// </summary> public void Reset() { baseEnumerator.Reset(); } /// <summary> /// Reset the cursor /// </summary> void IEnumerator.Reset() { baseEnumerator.Reset(); } } } }
shanselman/TinyOS
src/TinyOSCore/InstructionCollection.cs
C#
bsd-2-clause
12,715
#ifndef EXTRACTION_WAY_HPP #define EXTRACTION_WAY_HPP #include "extractor/guidance/road_classification.hpp" #include "extractor/travel_mode.hpp" #include "util/guidance/turn_lanes.hpp" #include "util/typedefs.hpp" #include <string> #include <vector> namespace osrm { namespace extractor { namespace detail { inline void maybeSetString(std::string &str, const char *value) { if (value == nullptr) { str.clear(); } else { str = std::string(value); } } } /** * This struct is the direct result of the call to ```way_function``` * in the lua based profile. * * It is split into multiple edge segments in the ExtractorCallback. */ struct ExtractionWay { ExtractionWay() { clear(); } void clear() { forward_speed = -1; backward_speed = -1; forward_rate = -1; backward_rate = -1; duration = -1; weight = -1; name.clear(); ref.clear(); pronunciation.clear(); destinations.clear(); exits.clear(); turn_lanes_forward.clear(); turn_lanes_backward.clear(); road_classification = guidance::RoadClassification(); forward_travel_mode = TRAVEL_MODE_INACCESSIBLE; backward_travel_mode = TRAVEL_MODE_INACCESSIBLE; roundabout = false; circular = false; is_startpoint = true; forward_restricted = false; backward_restricted = false; is_left_hand_driving = false; } // wrappers to allow assigning nil (nullptr) to string values void SetName(const char *value) { detail::maybeSetString(name, value); } const char *GetName() const { return name.c_str(); } void SetRef(const char *value) { detail::maybeSetString(ref, value); } const char *GetRef() const { return ref.c_str(); } void SetDestinations(const char *value) { detail::maybeSetString(destinations, value); } const char *GetDestinations() const { return destinations.c_str(); } void SetExits(const char *value) { detail::maybeSetString(exits, value); } const char *GetExits() const { return exits.c_str(); } void SetPronunciation(const char *value) { detail::maybeSetString(pronunciation, value); } const char *GetPronunciation() const { return pronunciation.c_str(); } void SetTurnLanesForward(const char *value) { detail::maybeSetString(turn_lanes_forward, value); } const char *GetTurnLanesForward() const { return turn_lanes_forward.c_str(); } void SetTurnLanesBackward(const char *value) { detail::maybeSetString(turn_lanes_backward, value); } const char *GetTurnLanesBackward() const { return turn_lanes_backward.c_str(); } // markers for determining user-defined classes for each way std::unordered_map<std::string, bool> forward_classes; std::unordered_map<std::string, bool> backward_classes; // speed in km/h double forward_speed; double backward_speed; // weight per meter double forward_rate; double backward_rate; // duration of the whole way in both directions double duration; // weight of the whole way in both directions double weight; std::string name; std::string ref; std::string pronunciation; std::string destinations; std::string exits; std::string turn_lanes_forward; std::string turn_lanes_backward; guidance::RoadClassification road_classification; TravelMode forward_travel_mode : 4; TravelMode backward_travel_mode : 4; // Boolean flags bool roundabout : 1; bool circular : 1; bool is_startpoint : 1; bool forward_restricted : 1; bool backward_restricted : 1; bool is_left_hand_driving : 1; bool : 2; }; } } #endif // EXTRACTION_WAY_HPP
frodrigo/osrm-backend
include/extractor/extraction_way.hpp
C++
bsd-2-clause
3,763
var crypto = require('crypto'); var Canvas = require('canvas'); var _ = require('lodash'); var bu = require('./bufutil'); var fmt = require('util').format; var unpack = require('./unpack'); var bright = require('./bright'); function fprint(buf, len) { if (len > 64) throw new Error(fmt("sha512 can only generate 64B of data: %dB requested", len)); return _(crypto.createHash('sha512').update(buf).digest()) .groupBy(function (x, k) { return Math.floor(k/len); }) .reduce(bu.xor); } function idhash(str, n, minFill, maxFill) { var buf = new Buffer(str.length + 1); buf.write(str); for (var i=0; i<0x100; i++) { buf[buf.length - 1] = i; var f = fprint(buf, Math.ceil(n/8)+6); var pixels = _(f.slice(6)) .map(function (x) { return unpack(x); }) .flatten().take(n); var setPixels = pixels.filter().size(); var c = [ f.slice(0, 3), f.slice(3, 6)]; c.sort(bright.cmp); if (setPixels > (minFill * n) && setPixels < (maxFill * n)) return { colors: c.map(function (x) { return x.toString('hex'); }), pixels: pixels.value() }; } throw new Error(fmt("String '''%s''' unhashable in single-byte search space.", str)); } function reflect(id, dimension) { var mid = Math.ceil(dimension / 2); var odd = Boolean(dimension % 2); var pic = []; for (var row=0; row<dimension; row++) { pic[row] = []; for (var col=0; col<dimension; col++) { var p = (row * mid) + col; if (col>=mid) { var d = mid - (odd ? 1 : 0) - col; var ad = Math.abs(d); p = (row * mid) + mid - 1 - ad; } pic[row][col] = id.pixels[p]; // console.error(fmt("looking for %d, of %d for %d,%d", p, id.pixels.length, row, col)) } } return pic; } function retricon(str, opts) { opts = _.merge({}, retricon.defaults, opts); var dimension = opts.tiles; var pixelSize = opts.pixelSize; var border = opts.pixelPadding; var mid = Math.ceil(dimension / 2); var id = idhash(str, mid * dimension, opts.minFill, opts.maxFill); var pic = reflect(id, dimension); var csize = (pixelSize * dimension) + (opts.imagePadding * 2); var c = Canvas.createCanvas(csize, csize); var ctx = c.getContext('2d'); if (_.isString(opts.bgColor)) { ctx.fillStyle = opts.bgColor; } else if (_.isNumber(opts.bgColor)) { ctx.fillStyle = '#' + id.colors[opts.bgColor]; } if (! _.isNull(opts.bgColor)) ctx.fillRect(0, 0, csize, csize); var drawOp = ctx.fillRect.bind(ctx); if (_.isString(opts.pixelColor)) { ctx.fillStyle = opts.pixelColor; } else if (_.isNumber(opts.pixelColor)) { ctx.fillStyle = '#' + id.colors[opts.pixelColor]; } else { drawOp = ctx.clearRect.bind(ctx); } for (var x=0; x<dimension; x++) for (var y=0; y<dimension; y++) if (pic[y][x]) drawOp((x*pixelSize) + border + opts.imagePadding, (y*pixelSize) + border + opts.imagePadding, pixelSize - (border * 2), pixelSize - (border * 2)); return c; } retricon.defaults = { pixelSize: 10, bgColor: null, pixelPadding: 0, imagePadding: 0, tiles: 5, minFill: 0.3, maxFill: 0.90, pixelColor: 0 }; retricon.style = { github: { pixelSize: 70, bgColor: '#F0F0F0', pixelPadding: -1, imagePadding: 35, tiles: 5 }, gravatar: { tiles: 8, bgColor: 1 }, mono: { bgColor: '#F0F0F0', pixelColor: '#000000', tiles: 6, pixelSize: 12, pixelPadding: -1, imagePadding: 6 }, mosaic: { imagePadding: 2, pixelPadding: 1, pixelSize: 16, bgColor: '#F0F0F0' }, mini: { pixelSize: 10, pixelPadding: 1, tiles: 3, bgColor: 0, pixelColor: 1 }, window: { pixelColor: null, bgColor: 0, imagePadding: 2, pixelPadding: 1, pixelSize: 16 } }; module.exports = retricon;
sehrgut/node-retricon
lib/index.js
JavaScript
bsd-2-clause
3,668
#include <mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_SerializationObjectManager.h> #include <mscorlib/System/mscorlib_System_Type.h> #include <mscorlib/System/mscorlib_System_String.h> namespace mscorlib { namespace System { namespace Runtime { namespace Serialization { //Public Methods void SerializationObjectManager::RegisterObject(mscorlib::System::Object obj) { MonoType *__parameter_types__[1]; void *__parameters__[1]; __parameter_types__[0] = Global::GetType(typeid(obj).name()); __parameters__[0] = (MonoObject*)obj; Global::InvokeMethod("mscorlib", "System.Runtime.Serialization", "SerializationObjectManager", 0, NULL, "RegisterObject", __native_object__, 1, __parameter_types__, __parameters__, NULL); } void SerializationObjectManager::RaiseOnSerializedEvent() { Global::InvokeMethod("mscorlib", "System.Runtime.Serialization", "SerializationObjectManager", 0, NULL, "RaiseOnSerializedEvent", __native_object__, 0, NULL, NULL, NULL); } } } } }
brunolauze/MonoNative
MonoNative/mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_SerializationObjectManager.cpp
C++
bsd-2-clause
1,080
var compilerSupport=require('../../src/compilerSupport');var main = function () { var __builder = new compilerSupport.TaskBuilder(), __state = 0, __continue = __builder.CONT, __ex; var data; return __builder.run(function () { switch (__state) { case 0: { data = 12345; console.log("data: " + data); __state = -1; __builder.ret(data); break; } default: throw 'Internal error: encountered wrong state'; } }); }; main().then(function(x) { console.log("returned: " + x); }, function(y) { console.log("failed: " + y); });
omgtehlion/asjs
tests/00-misc/00-fulfills-promise.exp.js
JavaScript
bsd-2-clause
678
// (c) 2010-2014 IndiegameGarden.com. Distributed under the FreeBSD license in LICENSE.txt using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("TTengine")] [assembly: AssemblyProduct("TTengine")] [assembly: AssemblyDescription("2D game engine for C# XNA 4.0")] [assembly: AssemblyCompany("IndiegameGarden.com")] [assembly: AssemblyCopyright("Copyright © IndiegameGarden.com 2010-2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. Only Windows // assemblies support COM. [assembly: ComVisible(false)] // On Windows, the following GUID is for the ID of the typelib if this // project is exposed to COM. On other platforms, it unique identifies the // title storage container when deploying this assembly to the device. [assembly: Guid("0de778ef-fe76-4a50-d0e9-cabba1a02517")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("5.0.0.1")]
IndiegameGarden/Quest
TTengine/Properties/AssemblyInfo.cs
C#
bsd-2-clause
1,485
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; namespace Mkko.Configuration { [ConfigurationCollection(typeof(ExecutionEnvironmentSettings), AddItemName = "executionEnvironment", CollectionType = ConfigurationElementCollectionType.BasicMap)] public class ExecutionEnvironmentCollection : ConfigurationElementCollection { public override ConfigurationElementCollectionType CollectionType { get { return ConfigurationElementCollectionType.BasicMap; } } protected override string ElementName { get { return "executionEnvironment"; } } protected override ConfigurationElement CreateNewElement() { return new ExecutionEnvironmentSettings(); } protected override object GetElementKey(ConfigurationElement element) { return (element as ExecutionEnvironmentSettings).Id; } } }
mk83ko/any-log-analyzer
AnyLogAnalyzerCore/Configuration/ExecutionEnvironmentCollection.cs
C#
bsd-2-clause
1,003
#region Copyright notice /** * Copyright (c) 2018 Samsung Electronics, Inc., * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion using System.Collections.Generic; namespace DexterCS { public class ProjectAnalysisConfiguration { public string ProjectName { get; set; } public string ProjectFullPath { get; set; } private List<string> sourceDirs; public List<string> SourceDirs { get { return sourceDirs ?? new List<string>(); } set { sourceDirs = value; } } private List<string> headerDirs; public List<string> HeaderDirs { get { return headerDirs ?? new List<string>(); } set { headerDirs = value; } } private List<string> targetDir; public List<string> TargetDirs { get { return targetDir ?? new List<string>(); } set { targetDir = value; } } public string Type { get; set; } } }
Samsung/Dexter
project/dexter-cs/DexterCS/Src/ProjectAnalysisConfiguration.cs
C#
bsd-2-clause
2,316
require "language/node" class HttpServer < Formula desc "Simple zero-configuration command-line HTTP server" homepage "https://github.com/http-party/http-server" url "https://registry.npmjs.org/http-server/-/http-server-13.0.1.tgz" sha256 "35e08960062d766ad4c1e098f65b6e8bfb44f12516da90fd2df9974729652f03" license "MIT" head "https://github.com/http-party/http-server.git" bottle do sha256 cellar: :any_skip_relocation, all: "27f327beb2f485c4885636bbede7d6096a69659ee595b10621cf0a59d8797d32" end depends_on "node" def install system "npm", "install", *Language::Node.std_npm_install_args(libexec) bin.install_symlink Dir["#{libexec}/bin/*"] end test do port = free_port pid = fork do exec "#{bin}/http-server", "-p#{port}" end sleep 3 output = shell_output("curl -sI http://localhost:#{port}") assert_match "200 OK", output ensure Process.kill("HUP", pid) end end
mbcoguno/homebrew-core
Formula/http-server.rb
Ruby
bsd-2-clause
944
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Ocronet.Dynamic.Recognizers; using Ocronet.Dynamic.OcroFST; using Ocronet.Dynamic; using Ocronet.Dynamic.ImgLib; using Ocronet.Dynamic.Interfaces; using Ocronet.Dynamic.Utils; using Ocronet.Dynamic.IOData; using System.IO; using Ocronet.Dynamic.Segmentation; using Ocronet.Dynamic.Recognizers.Lenet; namespace Ocronet.DynamicConsole { public class TestLinerec { public void TestSimple() { Global.SetEnv("debug", Global.GetEnv("debug") + ""); // image file name to recognize string imgFileName = "line.png"; string imgCsegFileName = "line.cseg.png"; string imgTranscriptFileName = "line.txt"; // line recognizer Linerec lrec = (Linerec)Linerec.LoadLinerec("default.model"); //Linerec lrec = (Linerec)Linerec.LoadLinerec("2m2-reject.cmodel"); //Linerec lrec = (Linerec)Linerec.LoadLinerec("multi3.cmodel"); //Linerec lrec = (Linerec)Linerec.LoadLinerec("latin-ascii.model"); lrec.Info(); // language model OcroFST default_lmodel = OcroFST.MakeOcroFst(); default_lmodel.Load("default.fst"); OcroFST lmodel = default_lmodel; // read image Bytearray image = new Bytearray(1, 1); ImgIo.read_image_gray(image, imgFileName); // recognize! OcroFST fst = OcroFST.MakeOcroFst(); Intarray rseg = new Intarray(); lrec.RecognizeLine(rseg, fst, image); // show result 1 string resStr; fst.BestPath(out resStr); Console.WriteLine("Fst BestPath: {0}", resStr); // find result 2 Intarray v1 = new Intarray(); Intarray v2 = new Intarray(); Intarray inp = new Intarray(); Intarray outp = new Intarray(); Floatarray c = new Floatarray(); BeamSearch.beam_search(v1, v2, inp, outp, c, fst, lmodel, 100); FstUtil.remove_epsilons(out resStr, outp); Console.WriteLine("Fst BeamSearch: {0}", resStr); Intarray cseg = new Intarray(); SegmRoutine.rseg_to_cseg(cseg, rseg, inp); SegmRoutine.make_line_segmentation_white(cseg); ImgLabels.simple_recolor(cseg); // for human readable ImgIo.write_image_packed(imgCsegFileName, cseg); File.WriteAllText(imgTranscriptFileName, resStr.Replace(" ", "")); } public void TestTrainLenetCseg() { string bookPath = "data\\0000\\"; string netFileName = "latin-lenet.model"; Linerec.GDef("linerec", "use_reject", 1); Linerec.GDef("lenet", "junk", 1); Linerec.GDef("lenet", "epochs", 4); // create Linerec Linerec linerec; if (File.Exists(netFileName)) linerec = Linerec.LoadLinerec(netFileName); else { linerec = new Linerec("lenet"); LenetClassifier classifier = linerec.GetClassifier() as LenetClassifier; if (classifier != null) classifier.InitNumSymbLatinAlphabet(); } // temporary disable junk //linerec.DisableJunk = true; linerec.StartTraining(); int nepochs = 10; LineSource lines = new LineSource(); lines.Init(new string[] { "data2" }); //linerec.GetClassifier().Set("epochs", 1); for (int epoch = 1; epoch <= nepochs; epoch++) { linerec.Epoch(epoch); // load cseg samples while (!lines.Done()) { lines.MoveNext(); Intarray cseg = new Intarray(); //Bytearray image = new Bytearray(); string transcript = lines.GetTranscript(); //lines.GetImage(image); if (!lines.GetCharSegmentation(cseg) && cseg.Length() == 0) { Global.Debugf("warn", "skipping book {0} page {1} line {2} (no or bad cseg)", lines.CurrentBook, lines.CurrentPage, lines.Current); continue; } SegmRoutine.make_line_segmentation_black(cseg); linerec.AddTrainingLine(cseg, transcript); } lines.Reset(); lines.Shuffle(); // do Train and clear Dataset linerec.FinishTraining(); // do save if (epoch % 1 == 0) linerec.Save(netFileName); // recognize test line bool bakDisJunk = linerec.DisableJunk; linerec.DisableJunk = false; DoTestLinerecRecognize(linerec, "data2\\", "test1.png"); linerec.DisableJunk = bakDisJunk; } // finnaly save linerec.Save(netFileName); } public void TestTrainLatinCseg() { string bookPath = "data\\0000\\"; string netFileName = "latin-amlp.model"; Linerec.GDef("linerec", "use_reject", 1); Linerec.GDef("lenet", "junk", 1); // create Linerec Linerec linerec; if (File.Exists(netFileName)) linerec = Linerec.LoadLinerec(netFileName); else { linerec = new Linerec("latin"); } // temporary disable junk //linerec.DisableJunk = true; linerec.StartTraining(); int nepochs = 1; LineSource lines = new LineSource(); lines.Init(new string[] { "data2" }); for (int epoch = 1; epoch <= nepochs; epoch++) { linerec.Epoch(epoch); // load cseg samples while (lines.MoveNext()) { Intarray cseg = new Intarray(); //Bytearray image = new Bytearray(); string transcript = lines.GetTranscript(); //lines.GetImage(image); if (!lines.GetCharSegmentation(cseg) && cseg.Length() == 0) { Global.Debugf("warn", "skipping book {0} page {1} line {2} (no or bad cseg)", lines.CurrentBook, lines.CurrentPage, lines.CurrentLine); continue; } SegmRoutine.make_line_segmentation_black(cseg); linerec.AddTrainingLine(cseg, transcript); } lines.Reset(); lines.Shuffle(); // do Train and clear Dataset linerec.FinishTraining(); // do save if (epoch % 1 == 0) linerec.Save(netFileName); // recognize test line bool bakDisJunk = linerec.DisableJunk; linerec.DisableJunk = false; DoTestLinerecRecognize(linerec, bookPath, "000010.png"); linerec.DisableJunk = bakDisJunk; } // finnaly save linerec.Save(netFileName); } private void DoTestLinerecRecognize(Linerec linerec, string bookPath, string filename) { Bytearray image = new Bytearray(); ImgIo.read_image_gray(image, bookPath + filename); // recognize! OcroFST fst = OcroFST.MakeOcroFst(); linerec.RecognizeLine(fst, image); // show result string resStr; fst.BestPath(out resStr); Console.WriteLine("Fst BestPath: {0}", resStr); } public void TestRecognizeCseg() { string book1Path = "data2\\0001\\"; string book2Path = "data\\0000\\"; //Linerec.GDef("linerec", "use_reject", 0); //Linerec.GDef("lenet", "junk", 0); Linerec linerec = Linerec.LoadLinerec("latin-amlp.model"); //Linerec linerec = Linerec.LoadLinerec("latin-lenet.model"); //Linerec linerec = Linerec.LoadLinerec("latin-ascii2.model"); //Linerec linerec = Linerec.LoadLinerec("default.model"); //linerec.Set("maxcost", 20); DoTestLinerecRecognize(linerec, book1Path, "0010.png"); DoTestLinerecRecognize(linerec, book1Path, "0001.png"); DoTestLinerecRecognize(linerec, book1Path, "0089.png"); DoTestLinerecRecognize(linerec, book1Path, "0026.png"); DoTestLinerecRecognize(linerec, book2Path, "000001.png"); } public void TestComputeMissingCseg() { //ComputeMissingCsegForBookStore("data", "default.model", ""); //ComputeMissingCsegForBookStore("data2", "latin-ascii.model", "gt"); ComputeMissingCsegForBookStore("data", "latin-lenet.model", ""); } /// <summary> /// Create char segmentation (cseg) files if missing /// </summary> /// <param name="bookPath">path to bookstore</param> /// <param name="modelFilename">Linerec model file</param> /// <param name="langModel">language model file</param> /// <param name="suffix">e.g., 'gt'</param> public void ComputeMissingCsegForBookStore(string bookPath, string model = "default.model", string suffix = "", bool saveRseg = false, string langModel = "default.fst") { // create line recognizer Linerec linerec = Linerec.LoadLinerec(model); // create IBookStore IBookStore bookstore = new SmartBookStore(); bookstore.SetPrefix(bookPath); bookstore.Info(); // language model OcroFST lmodel = OcroFST.MakeOcroFst(); lmodel.Load(langModel); // iterate lines of pages for (int page = 0; page < bookstore.NumberOfPages(); page++) { int nlines = bookstore.LinesOnPage(page); Console.WriteLine("Page {0} has {1} lines", page, nlines); for (int j = 0; j < nlines; j++) { int line = bookstore.GetLineId(page, j); Bytearray image = new Bytearray(); bookstore.GetLine(image, page, line); Intarray cseg = new Intarray(); bookstore.GetCharSegmentation(cseg, page, line, suffix); // check missing cseg file if (cseg.Length() <= 0 && image.Length() > 0) { // recognize line OcroFST fst = OcroFST.MakeOcroFst(); Intarray rseg = new Intarray(); linerec.RecognizeLine(rseg, fst, image); // find best results string resText; Intarray inp = new Intarray(); Floatarray costs = new Floatarray(); double totalCost = BeamSearch.beam_search(out resText, inp, costs, fst, lmodel, 100); Console.WriteLine(bookstore.PathFile(page, line, suffix)); Console.Write(" beam_search score: {0}", totalCost); /*string resText2; fst.BestPath(out resText2);*/ // write cseg to bookstore string trans; bookstore.GetLine(out trans, page, line, suffix); resText = resText.Replace(" ", ""); if (String.IsNullOrEmpty(trans)) { bookstore.PutLine(resText, page, line, suffix); Console.Write("; transcript saved"); } else if (trans == resText) { // convert inputs and rseg to cseg SegmRoutine.rseg_to_cseg(cseg, rseg, inp); bookstore.PutCharSegmentation(cseg, page, line, suffix); Console.Write("; cseg saved"); } else if (saveRseg) { // convert inputs and rseg to cseg SegmRoutine.rseg_to_cseg(cseg, rseg, inp); //SegmRoutine.remove_small_components(cseg, 4); /*bookstore.PutCharSegmentation(cseg, page, line, suffix); Console.Write("; cseg saved");*/ SegmRoutine.make_line_segmentation_white(cseg); ImgLabels.simple_recolor(cseg); string v = "rseg"; if (!String.IsNullOrEmpty(suffix)) { v += "."; v += suffix; } string rsegpath = bookstore.PathFile(page, line, v, "png"); ImgIo.write_image_packed(rsegpath, cseg); Console.Write("; rseg saved"); } Console.WriteLine(); } } } } } }
nickun/OCRonet
Ocronet.Dynamic/Tests/TestLinerec.cs
C#
bsd-2-clause
13,695
class Opusfile < Formula desc "API for decoding and seeking in .opus files" homepage "https://www.opus-codec.org/" url "https://archive.mozilla.org/pub/opus/opusfile-0.11.tar.gz" sha256 "74ce9b6cf4da103133e7b5c95df810ceb7195471e1162ed57af415fabf5603bf" revision 1 bottle do cellar :any rebuild 1 sha256 "acd200760db74feb30ea28bdb14cdf8b3ebdeb5a65759e1095fad3f9583c3ef3" => :catalina sha256 "44e1c4d26cac791ff40de7b15fb2718c6aaa99856a128c23a3c542a3132e2053" => :mojave sha256 "7f83ce800aaa0dedb44b18332e1628e307bf83d693586ed6359b02e6ea21737e" => :high_sierra end head do url "https://gitlab.xiph.org/xiph/opusfile.git" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build end depends_on "pkg-config" => :build depends_on "libogg" depends_on "openssl@1.1" depends_on "opus" resource "music_48kbps.opus" do url "https://www.opus-codec.org/static/examples/samples/music_48kbps.opus" sha256 "64571f56bb973c078ec784472944aff0b88ba0c88456c95ff3eb86f5e0c1357d" end def install system "./autogen.sh" if build.head? system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make", "install" end test do testpath.install resource("music_48kbps.opus") (testpath/"test.c").write <<~EOS #include <opus/opusfile.h> #include <stdlib.h> int main(int argc, const char **argv) { int ret; OggOpusFile *of; of = op_open_file(argv[1], &ret); if (of == NULL) { fprintf(stderr, "Failed to open file '%s': %i\\n", argv[1], ret); return EXIT_FAILURE; } op_free(of); return EXIT_SUCCESS; } EOS system ENV.cc, "test.c", "-I#{Formula["opus"].include}/opus", "-L#{lib}", "-lopusfile", "-o", "test" system "./test", "music_48kbps.opus" end end
edporras/homebrew-core
Formula/opusfile.rb
Ruby
bsd-2-clause
2,016
cask 'opera-beta' do version '50.0.2762.42' sha256 '0ae6866beb0047a2aebd22df7d2638f2d95ad8c08227879905d0e96e1add2235' url "https://get.geo.opera.com/pub/opera-beta/#{version}/mac/Opera_beta_#{version}_Setup.dmg" name 'Opera Beta' homepage 'https://www.opera.com/computer/beta' auto_updates true app 'Opera Beta.app' end
yurikoles/homebrew-versions
Casks/opera-beta.rb
Ruby
bsd-2-clause
337
# coding: utf8 from __future__ import unicode_literals from flask import abort, make_response, request from flask_api.decorators import set_renderers from flask_api import exceptions, renderers, status, FlaskAPI import json import unittest app = FlaskAPI(__name__) app.config['TESTING'] = True class JSONVersion1(renderers.JSONRenderer): media_type = 'application/json; api-version="1.0"' class JSONVersion2(renderers.JSONRenderer): media_type = 'application/json; api-version="2.0"' @app.route('/set_status_and_headers/') def set_status_and_headers(): headers = {'Location': 'http://example.com/456'} return {'example': 'content'}, status.HTTP_201_CREATED, headers @app.route('/set_headers/') def set_headers(): headers = {'Location': 'http://example.com/456'} return {'example': 'content'}, headers @app.route('/make_response_view/') def make_response_view(): response = make_response({'example': 'content'}) response.headers['Location'] = 'http://example.com/456' return response @app.route('/api_exception/') def api_exception(): raise exceptions.PermissionDenied() @app.route('/abort_view/') def abort_view(): abort(status.HTTP_403_FORBIDDEN) @app.route('/options/') def options_view(): return {} @app.route('/accepted_media_type/') @set_renderers([JSONVersion2, JSONVersion1]) def accepted_media_type(): return {'accepted_media_type': str(request.accepted_media_type)} class AppTests(unittest.TestCase): def test_set_status_and_headers(self): with app.test_client() as client: response = client.get('/set_status_and_headers/') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(response.headers['Location'], 'http://example.com/456') self.assertEqual(response.content_type, 'application/json') expected = '{"example": "content"}' self.assertEqual(response.get_data().decode('utf8'), expected) def test_set_headers(self): with app.test_client() as client: response = client.get('/set_headers/') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.headers['Location'], 'http://example.com/456') self.assertEqual(response.content_type, 'application/json') expected = '{"example": "content"}' self.assertEqual(response.get_data().decode('utf8'), expected) def test_make_response(self): with app.test_client() as client: response = client.get('/make_response_view/') self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.headers['Location'], 'http://example.com/456') self.assertEqual(response.content_type, 'application/json') expected = '{"example": "content"}' self.assertEqual(response.get_data().decode('utf8'), expected) def test_api_exception(self): with app.test_client() as client: response = client.get('/api_exception/') self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) self.assertEqual(response.content_type, 'application/json') expected = '{"message": "You do not have permission to perform this action."}' self.assertEqual(response.get_data().decode('utf8'), expected) def test_abort_view(self): with app.test_client() as client: response = client.get('/abort_view/') self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) def test_options_view(self): with app.test_client() as client: response = client.options('/options/') # Errors if `response.response` is `None` response.get_data() def test_accepted_media_type_property(self): with app.test_client() as client: # Explicitly request the "api-version 1.0" renderer. headers = {'Accept': 'application/json; api-version="1.0"'} response = client.get('/accepted_media_type/', headers=headers) data = json.loads(response.get_data().decode('utf8')) expected = {'accepted_media_type': 'application/json; api-version="1.0"'} self.assertEqual(data, expected) # Request the default renderer, which is "api-version 2.0". headers = {'Accept': '*/*'} response = client.get('/accepted_media_type/', headers=headers) data = json.loads(response.get_data().decode('utf8')) expected = {'accepted_media_type': 'application/json; api-version="2.0"'} self.assertEqual(data, expected)
theskumar-archive/flask-api
flask_api/tests/test_app.py
Python
bsd-2-clause
4,692
/* * Copyright 2016 Skynav, Inc. All rights reserved. * Portions Copyright 2009 Extensible Formatting Systems, Inc (XFSI). * * 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 SKYNAV, INC. AND ITS 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 SKYNAV, INC. OR ITS CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.xfsi.xav.validation.images.jpeg; import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.util.LinkedList; /** * Handles JPEG input stream. Tracks total bytes read and allows putting back of read data. */ class JpegInputStream { private int readByteCount = 0; private final DataInputStream inputStream; private LinkedList<Byte> putBack = new LinkedList<Byte>(); JpegInputStream(InputStream is) { this.inputStream = new DataInputStream(is); } byte readByte() throws EOFException, IOException { if (this.putBack.size() == 0) { byte b = this.inputStream.readByte(); this.readByteCount++; return b; } return this.putBack.remove(); } short readShort() throws EOFException, IOException { if (this.putBack.size() == 0) { short s = this.inputStream.readShort(); this.readByteCount += 2; return s; } short msb = readByte(); short lsb = readByte(); return (short) ((msb << 8) | (lsb & 0xff)); } int readInt() throws EOFException, IOException { if (this.putBack.size() == 0) { int i = this.inputStream.readInt(); this.readByteCount += 4; return i; } int mss = readShort(); int lss = readShort(); return (mss << 16) | (lss & 0xffff); } void skipBytes(int count) throws EOFException, IOException { // DataInputStream skipBytes() in jpegInputStream does not throw EOFException() if EOF reached, // which we are interested in, so read the bytes to skip them which WILL generate an EOFException(). for (int i = 0; i < count; i++) readByte(); } void putBack(byte b) { this.putBack.add(b); } int getTotalBytesRead() { return this.readByteCount; } }
skynav/ttt
ttt-ttv/src/main/java/com/xfsi/xav/validation/images/jpeg/JpegInputStream.java
Java
bsd-2-clause
3,933
// EarthShape.java // See copyright.txt for license and terms of use. package earthshape; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TreeSet; import javax.swing.JCheckBoxMenuItem; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import com.jogamp.opengl.GLCapabilities; import util.FloatUtil; import util.Vector3d; import util.Vector3f; import util.swing.ModalDialog; import util.swing.MyJFrame; import util.swing.MySwingWorker; import util.swing.ProgressDialog; import static util.swing.SwingUtil.log; /** This application demonstrates a procedure for inferring the shape * of a surface (such as the Earth) based on the observed locations of * stars from various locations at a fixed point in time. * * This class, EarthShape, manages UI components external to the 3D * display, such as the menu and status bars. It also contains all of * the code to construct the virtual 3D map using various algorithms. * The 3D display, along with its camera controls, is in EarthMapCanvas. */ public class EarthShape extends MyJFrame { // --------- Constants ---------- /** AWT boilerplate generated serial ID. */ private static final long serialVersionUID = 3903955302894393226L; /** Size of the first constructed square, in kilometers. The * displayed size is then determined by the map scale, which * is normally 1 unit per 1000 km. */ private static final float INITIAL_SQUARE_SIZE_KM = 1000; /** Initial value of 'adjustOrientationDegrees', and the value to * which it is reset when a new square is created. */ private static final float DEFAULT_ADJUST_ORIENTATION_DEGREES = 1.0f; /** Do not let 'adjustOrientationDegrees' go below this value. Below * this value is pointless because the precision of the variance is * not high enough to discriminate among the choices. */ private static final float MINIMUM_ADJUST_ORIENTATION_DEGREES = 1e-7f; // ---------- Instance variables ---------- // ---- Observation Information ---- /** The observations that will drive surface reconstruction. * By default, this will be data from the real world, but it * can be swapped out at the user's option. */ public WorldObservations worldObservations = new RealWorldObservations(); /** Set of stars that are enabled. */ private LinkedHashMap<String, Boolean> enabledStars = new LinkedHashMap<String, Boolean>(); // ---- Interactive surface construction state ---- /** The square we will build upon when the next square is added. * This may be null. */ private SurfaceSquare activeSquare; /** When adjusting the orientation of the active square, this * is how many degrees to rotate at once. */ private float adjustOrientationDegrees = DEFAULT_ADJUST_ORIENTATION_DEGREES; // ---- Options ---- /** When true, star observations are only compared by their * direction. When false, we also consider the location of the * observer, which allows us to handle nearby objects. */ public boolean assumeInfiniteStarDistance = false; /** When true, star observations are only compared by their * direction, and furthermore, only the elevation, ignoring * azimuth. This is potentially interesting because, in * practice, it is difficult to accurately measure azimuth * with just a hand-held sextant. */ public boolean onlyCompareElevations = false; /** When analyzing the solution space, use this many points of * rotation on each side of 0, for each axis. Note that the * algorithm is cubic in this parameter. */ private int solutionAnalysisPointsPerSide = 20; /** If the Sun's elevation is higher than this value, then * we cannot see any stars. */ private float maximumSunElevation = -5; /** When true, take the Sun's elevation into account. */ private boolean useSunElevation = true; /** When true, use the "new" orientation algorithm that * repeatedly applies the recommended command. Otherwise, * use the older one based on average deviation. The old * algorithm is faster, but slightly less accurate, and * does not mimic the process a user would use to manually * adjust a square's orientation. */ private boolean newAutomaticOrientationAlgorithm = true; // ---- Widgets ---- /** Canvas showing the Earth surface built so far. */ private EarthMapCanvas emCanvas; /** Widget to show various state variables such as camera position. */ private JLabel statusLabel; /** Selected square info panel on right side. */ private InfoPanel infoPanel; // Menu items to toggle various options. private JCheckBoxMenuItem drawCoordinateAxesCBItem; private JCheckBoxMenuItem drawCrosshairCBItem; private JCheckBoxMenuItem drawWireframeSquaresCBItem; private JCheckBoxMenuItem drawCompassesCBItem; private JCheckBoxMenuItem drawSurfaceNormalsCBItem; private JCheckBoxMenuItem drawCelestialNorthCBItem; private JCheckBoxMenuItem drawStarRaysCBItem; private JCheckBoxMenuItem drawUnitStarRaysCBItem; private JCheckBoxMenuItem drawBaseSquareStarRaysCBItem; private JCheckBoxMenuItem drawTravelPathCBItem; private JCheckBoxMenuItem drawActiveSquareAtOriginCBItem; private JCheckBoxMenuItem useSunElevationCBItem; private JCheckBoxMenuItem invertHorizontalCameraMovementCBItem; private JCheckBoxMenuItem invertVerticalCameraMovementCBItem; private JCheckBoxMenuItem newAutomaticOrientationAlgorithmCBItem; private JCheckBoxMenuItem assumeInfiniteStarDistanceCBItem; private JCheckBoxMenuItem onlyCompareElevationsCBItem; private JCheckBoxMenuItem drawWorldWireframeCBItem; private JCheckBoxMenuItem drawWorldStarsCBItem; private JCheckBoxMenuItem drawSkyboxCBItem; // ---------- Methods ---------- public EarthShape() { super("EarthShape"); this.setName("EarthShape (JFrame)"); this.setLayout(new BorderLayout()); this.setIcon(); for (String starName : this.worldObservations.getAllStars()) { // Initially all stars are enabled. this.enabledStars.put(starName, true); } this.setSize(1150, 800); this.setLocationByPlatform(true); this.setupJOGL(); this.buildMenuBar(); // Status bar on bottom. this.statusLabel = new JLabel(); this.statusLabel.setName("statusLabel"); this.add(this.statusLabel, BorderLayout.SOUTH); // Info panel on right. this.add(this.infoPanel = new InfoPanel(), BorderLayout.EAST); this.updateUIState(); } /** Initialize the JOGL library, then create a GL canvas and * associate it with this window. */ private void setupJOGL() { log("creating GLCapabilities"); // This call takes about one second to complete, which is // pretty slow... GLCapabilities caps = new GLCapabilities(null /*profile*/); log("caps: "+caps); caps.setDoubleBuffered(true); caps.setHardwareAccelerated(true); // Build the object that will show the surface. this.emCanvas = new EarthMapCanvas(this, caps); // Associate the canvas with 'this' window. this.add(this.emCanvas, BorderLayout.CENTER); } /** Set the window icon to my application's icon. */ private void setIcon() { try { URL url = this.getClass().getResource("globe-icon.png"); Image img = Toolkit.getDefaultToolkit().createImage(url); this.setIconImage(img); } catch (Exception e) { System.err.println("Failed to set app icon: "+e.getMessage()); } } private void showAboutBox() { String about = "EarthShape\n"+ "Copyright 2017 Scott McPeak\n"+ "\n"+ "Published under the 2-clause BSD license.\n"+ "See copyright.txt for details.\n"; JOptionPane.showMessageDialog(this, about, "About", JOptionPane.INFORMATION_MESSAGE); } private void showKeyBindings() { String bindings = "Left click in 3D view to enter FPS controls mode.\n"+ "Esc - Leave FPS mode.\n"+ "W/A/S/D - Move camera horizontally when in FPS mode.\n"+ "Space/Z - Move camera up or down in FPS mode.\n"+ "Left click on square in FPS mode to make it active.\n"+ "\n"+ "T - Reconstruct Earth from star data.\n"+ "\n"+ "C - Toggle compass or Earth texture.\n"+ "P - Toggle star rays for active square.\n"+ "G - Move camera to active square's center.\n"+ "H - Build complete Earth using assumed sphere.\n"+ "R - Build Earth using assumed sphere and random walk.\n"+ "\n"+ "U/O - Roll active square left or right.\n"+ "I/K - Pitch active square down or up.\n"+ "J/L - Yaw active square left or right.\n"+ "1 - Reset adjustment amount to 1 degree.\n"+ "-/= - Decrease or increase adjustment amount.\n"+ "; (semicolon) - Make recommended active square adjustment.\n"+ "/ (slash) - Automatically orient active square.\n"+ "\' (apostrophe) - Analyze rotation solution space for active square.\n"+ "\n"+ "N - Start a new surface.\n"+ "M - Add a square adjacent to the active square.\n"+ "Ctrl+N/S/E/W - Add a square to the N/S/E/W and automatically adjust it.\n"+ ", (comma) - Move to previous active square.\n"+ ". (period) - Move to next active square.\n"+ "Delete - Delete active square.\n"+ "\n"+ "0/PgUp/PgDn - Change animation state (not for general use)\n"+ ""; JOptionPane.showMessageDialog(this, bindings, "Bindings", JOptionPane.INFORMATION_MESSAGE); } /** Build the menu bar and attach it to 'this'. */ private void buildMenuBar() { // This ensures that the menu items do not appear underneath // the GL canvas. Strangely, this problem appeared suddenly, // after I made a seemingly irrelevant change (putting a // scroll bar on the info panel). But this call solves it, // so whatever. JPopupMenu.setDefaultLightWeightPopupEnabled(false); JMenuBar menuBar = new JMenuBar(); this.setJMenuBar(menuBar); // Used keys: // a - Move camera left // b // c - Toggle compass // d - Move camera right // e // f // g - Go to selected square's center // h - Build spherical Earth // i - Pitch active square down // j - Yaw active square left // k - Pitch active square up // l - Yaw active square right // m - Add adjacent square to surface // n - Build new surface // o - Roll active square right // p - Toggle star rays for active square // q // r - Build with random walk // s - Move camera backward // t - Build full Earth with star data // u - Roll active square left // v // w - Move camera forward // x // y // z - Move camera down // 0 - Reset animation state to 0 // 1 - Reset adjustment amount to 1 // - - Decrease adjustment amount // = - Increase adjustment amount // ; - One recommended rotation adjustment // ' - Analyze solution space // , - Select previous square // . - Select next square // / - Automatically orient active square // Space - Move camera up // Delete - Delete active square // Enter - enter FPS mode // Esc - leave FPS mode // Ins - canned commands // PgUp - Decrement animation state // PgDn - Increment animation state // Ctrl+E - build and orient to the East // Ctrl+W - build and orient to the West // Ctrl+N - build and orient to the North // Ctrl+S - build and orient to the South menuBar.add(this.buildFileMenu()); menuBar.add(this.buildDrawMenu()); menuBar.add(this.buildBuildMenu()); menuBar.add(this.buildSelectMenu()); menuBar.add(this.buildEditMenu()); menuBar.add(this.buildNavigateMenu()); menuBar.add(this.buildAnimateMenu()); menuBar.add(this.buildOptionsMenu()); menuBar.add(this.buildHelpMenu()); } private JMenu buildFileMenu() { JMenu menu = new JMenu("File"); addMenuItem(menu, "Use real world astronomical observations", null, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.changeObservations(new RealWorldObservations()); } }); menu.addSeparator(); addMenuItem(menu, "Use model: spherical Earth with nearby stars", null, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.changeObservations(new CloseStarObservations()); } }); addMenuItem(menu, "Use model: azimuthal equidistant projection flat Earth", null, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.changeObservations(new AzimuthalEquidistantObservations()); } }); addMenuItem(menu, "Use model: bowl-shaped Earth", null, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.changeObservations(new BowlObservations()); } }); addMenuItem(menu, "Use model: saddle-shaped Earth", null, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.changeObservations(new SaddleObservations()); } }); menu.addSeparator(); addMenuItem(menu, "Exit", null, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.dispose(); } }); return menu; } private JMenu buildDrawMenu() { JMenu drawMenu = new JMenu("Draw"); this.drawCoordinateAxesCBItem = addCBMenuItem(drawMenu, "Draw X/Y/Z coordinate axes", null, this.emCanvas.drawAxes, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.toggleDrawAxes(); } }); this.drawCrosshairCBItem = addCBMenuItem(drawMenu, "Draw crosshair when in FPS camera mode", null, this.emCanvas.drawCrosshair, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.toggleDrawCrosshair(); } }); this.drawWireframeSquaresCBItem = addCBMenuItem(drawMenu, "Draw squares as wireframes with translucent squares", null, this.emCanvas.drawWireframeSquares, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.toggleDrawWireframeSquares(); } }); this.drawCompassesCBItem = addCBMenuItem(drawMenu, "Draw squares with compass texture (vs. world map)", KeyStroke.getKeyStroke('c'), this.emCanvas.drawCompasses, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.toggleDrawCompasses(); } }); this.drawSurfaceNormalsCBItem = addCBMenuItem(drawMenu, "Draw surface normals", null, this.emCanvas.drawSurfaceNormals, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.toggleDrawSurfaceNormals(); } }); this.drawCelestialNorthCBItem = addCBMenuItem(drawMenu, "Draw celestial North", null, this.emCanvas.drawCelestialNorth, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.toggleDrawCelestialNorth(); } }); this.drawStarRaysCBItem = addCBMenuItem(drawMenu, "Draw star rays for active square", KeyStroke.getKeyStroke('p'), this.activeSquareDrawsStarRays(), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.toggleDrawStarRays(); } }); this.drawUnitStarRaysCBItem = addCBMenuItem(drawMenu, "Draw star rays as unit vectors", null, this.emCanvas.drawUnitStarRays, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.toggleDrawUnitStarRays(); } }); this.drawBaseSquareStarRaysCBItem = addCBMenuItem(drawMenu, "Draw star rays for the base square too, on the active square", null, this.emCanvas.drawBaseSquareStarRays, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.toggleDrawBaseSquareStarRays(); } }); this.drawTravelPathCBItem = addCBMenuItem(drawMenu, "Draw the travel path from base square to active square", null, this.emCanvas.drawTravelPath, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.toggleDrawTravelPath(); } }); this.drawActiveSquareAtOriginCBItem = addCBMenuItem(drawMenu, "Draw the active square at the 3D coordinate origin", null, this.emCanvas.drawActiveSquareAtOrigin, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.toggleDrawActiveSquareAtOrigin(); } }); this.drawWorldWireframeCBItem = addCBMenuItem(drawMenu, "Draw world wireframe (if one is in use)", null, this.emCanvas.drawWorldWireframe, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.toggleDrawWorldWireframe(); } }); this.drawWorldStarsCBItem = addCBMenuItem(drawMenu, "Draw world stars (if in use)", null, this.emCanvas.drawWorldStars, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.toggleDrawWorldStars(); } }); this.drawSkyboxCBItem = addCBMenuItem(drawMenu, "Draw skybox", null, this.emCanvas.drawSkybox, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.toggleDrawSkybox(); } }); addMenuItem(drawMenu, "Set skybox distance...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.setSkyboxDistance(); } }); addMenuItem(drawMenu, "Turn off all star rays", null, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.turnOffAllStarRays(); } }); return drawMenu; } private JMenu buildBuildMenu() { JMenu buildMenu = new JMenu("Build"); addMenuItem(buildMenu, "Build Earth using active observational data or model", KeyStroke.getKeyStroke('t'), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.buildEarthSurfaceFromStarData(); } }); addMenuItem(buildMenu, "Build complete Earth using assumed sphere", KeyStroke.getKeyStroke('h'), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.buildSphericalEarthSurfaceWithLatLong(); } }); addMenuItem(buildMenu, "Build partial Earth using assumed sphere and random walk", KeyStroke.getKeyStroke('r'), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.buildSphericalEarthWithRandomWalk(); } }); addMenuItem(buildMenu, "Start a new surface using star data", KeyStroke.getKeyStroke('n'), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.startNewSurface(); } }); addMenuItem(buildMenu, "Add another square to the surface", KeyStroke.getKeyStroke('m'), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.buildNextSquare(); } }); buildMenu.addSeparator(); addMenuItem(buildMenu, "Create new square 9 degrees to the East and orient it automatically", KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.CTRL_DOWN_MASK), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.createAndAutomaticallyOrientActiveSquare( 0 /*deltLatitude*/, +9 /*deltaLongitude*/); } }); addMenuItem(buildMenu, "Create new square 9 degrees to the West and orient it automatically", KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_DOWN_MASK), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.createAndAutomaticallyOrientActiveSquare( 0 /*deltLatitude*/, -9 /*deltaLongitude*/); } }); addMenuItem(buildMenu, "Create new square 9 degrees to the North and orient it automatically", KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_DOWN_MASK), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.createAndAutomaticallyOrientActiveSquare( +9 /*deltLatitude*/, 0 /*deltaLongitude*/); } }); addMenuItem(buildMenu, "Create new square 9 degrees to the South and orient it automatically", KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.createAndAutomaticallyOrientActiveSquare( -9 /*deltLatitude*/, 0 /*deltaLongitude*/); } }); buildMenu.addSeparator(); addMenuItem(buildMenu, "Do some canned setup for debugging", KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, 0), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.doCannedSetup(); } }); return buildMenu; } private JMenu buildSelectMenu() { JMenu selectMenu = new JMenu("Select"); addMenuItem(selectMenu, "Select previous square", KeyStroke.getKeyStroke(','), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.selectNextSquare(false /*forward*/); } }); addMenuItem(selectMenu, "Select next square", KeyStroke.getKeyStroke('.'), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.selectNextSquare(true /*forward*/); } }); return selectMenu; } private JMenu buildEditMenu() { JMenu editMenu = new JMenu("Edit"); for (RotationCommand rc : RotationCommand.values()) { this.addAdjustOrientationMenuItem(editMenu, rc.description, rc.key, rc.axis); } editMenu.addSeparator(); addMenuItem(editMenu, "Double active square adjustment angle", KeyStroke.getKeyStroke('='), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.changeAdjustOrientationDegrees(2.0f); } }); addMenuItem(editMenu, "Halve active square adjustment angle", KeyStroke.getKeyStroke('-'), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.changeAdjustOrientationDegrees(0.5f); } }); addMenuItem(editMenu, "Reset active square adjustment angle to 1 degree", KeyStroke.getKeyStroke('1'), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.adjustOrientationDegrees = 1; EarthShape.this.updateUIState(); } }); editMenu.addSeparator(); addMenuItem(editMenu, "Analyze solution space", KeyStroke.getKeyStroke('\''), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.analyzeSolutionSpace(); } }); addMenuItem(editMenu, "Set solution analysis resolution...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.setSolutionAnalysisResolution(); } }); editMenu.addSeparator(); addMenuItem(editMenu, "Do one recommended rotation adjustment", KeyStroke.getKeyStroke(';'), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.applyRecommendedRotationCommand(); } }); addMenuItem(editMenu, "Automatically orient active square", KeyStroke.getKeyStroke('/'), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.automaticallyOrientActiveSquare(); } }); addMenuItem(editMenu, "Delete active square", KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.deleteActiveSquare(); } }); return editMenu; } private JMenu buildNavigateMenu() { JMenu menu = new JMenu("Navigate"); addMenuItem(menu, "Control camera like a first-person shooter", KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.emCanvas.enterFPSMode(); } }); addMenuItem(menu, "Leave first-person shooter mode", KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.emCanvas.exitFPSMode(); } }); addMenuItem(menu, "Go to active square's center", KeyStroke.getKeyStroke('g'), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.goToActiveSquareCenter(); } }); addMenuItem(menu, "Go to origin", null, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.moveCamera(new Vector3f(0,0,0)); } }); menu.addSeparator(); addMenuItem(menu, "Curvature calculator...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.showCurvatureDialog(); } }); return menu; } private JMenu buildAnimateMenu() { JMenu menu = new JMenu("Animate"); addMenuItem(menu, "Reset to animation state 0", KeyStroke.getKeyStroke('0'), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.setAnimationState(0); } }); addMenuItem(menu, "Increment animation state", KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.setAnimationState(+1); } }); addMenuItem(menu, "Decrement animation state", KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.setAnimationState(-1); } }); return menu; } private JMenu buildOptionsMenu() { JMenu menu = new JMenu("Options"); addMenuItem(menu, "Choose enabled stars...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.chooseEnabledStars(); } }); addMenuItem(menu, "Set maximum Sun elevation...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.setMaximumSunElevation(); } }); this.useSunElevationCBItem = addCBMenuItem(menu, "Take Sun elevation into account", null, this.useSunElevation, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.useSunElevation = !EarthShape.this.useSunElevation; EarthShape.this.updateUIState(); } }); menu.addSeparator(); this.invertHorizontalCameraMovementCBItem = addCBMenuItem(menu, "Invert horizontal camera movement", null, this.emCanvas.invertHorizontalCameraMovement, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.emCanvas.invertHorizontalCameraMovement = !EarthShape.this.emCanvas.invertHorizontalCameraMovement; EarthShape.this.updateUIState(); } }); this.invertVerticalCameraMovementCBItem = addCBMenuItem(menu, "Invert vertical camera movement", null, this.emCanvas.invertVerticalCameraMovement, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.emCanvas.invertVerticalCameraMovement = !EarthShape.this.emCanvas.invertVerticalCameraMovement; EarthShape.this.updateUIState(); } }); menu.addSeparator(); this.newAutomaticOrientationAlgorithmCBItem = addCBMenuItem(menu, "Use new automatic orientation algorithm", null, this.newAutomaticOrientationAlgorithm, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.newAutomaticOrientationAlgorithm = !EarthShape.this.newAutomaticOrientationAlgorithm; EarthShape.this.updateUIState(); } }); this.assumeInfiniteStarDistanceCBItem = addCBMenuItem(menu, "Assume stars are infinitely far away", null, this.assumeInfiniteStarDistance, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.assumeInfiniteStarDistance = !EarthShape.this.assumeInfiniteStarDistance; EarthShape.this.updateAndRedraw(); } }); this.onlyCompareElevationsCBItem = addCBMenuItem(menu, "Only compare star elevations", null, this.onlyCompareElevations, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.onlyCompareElevations = !EarthShape.this.onlyCompareElevations; EarthShape.this.updateAndRedraw(); } }); return menu; } private JMenu buildHelpMenu() { JMenu helpMenu = new JMenu("Help"); addMenuItem(helpMenu, "Show all key bindings...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.showKeyBindings(); } }); addMenuItem(helpMenu, "About...", null, new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.showAboutBox(); } }); return helpMenu; } /** Add a menu item to adjust the orientation of the active square. */ private void addAdjustOrientationMenuItem( JMenu menu, String description, char key, Vector3f axis) { addMenuItem(menu, description, KeyStroke.getKeyStroke(key), new ActionListener() { public void actionPerformed(ActionEvent e) { EarthShape.this.adjustActiveSquareOrientation(axis); } }); } /** Make a new menu item and add it to 'menu' with the given * label and listener. */ private static void addMenuItem(JMenu menu, String itemLabel, KeyStroke accelerator, ActionListener listener) { JMenuItem item = new JMenuItem(itemLabel); item.addActionListener(listener); if (accelerator != null) { item.setAccelerator(accelerator); } menu.add(item); } private static JCheckBoxMenuItem addCBMenuItem(JMenu menu, String itemLabel, KeyStroke accelerator, boolean initState, ActionListener listener) { JCheckBoxMenuItem cbItem = new JCheckBoxMenuItem(itemLabel, initState); cbItem.addActionListener(listener); if (accelerator != null) { cbItem.setAccelerator(accelerator); } menu.add(cbItem); return cbItem; } /** Choose the set of stars to use. This only affects new * squares. */ private void chooseEnabledStars() { StarListDialog d = new StarListDialog(this, this.enabledStars); if (d.exec()) { this.enabledStars = d.stars; this.updateAndRedraw(); } } /** Clear out the virtual map and any dependent state. */ private void clearSurfaceSquares() { this.emCanvas.clearSurfaceSquares(); this.activeSquare = null; } /** Build a portion of the Earth's surface. Adds squares to * 'surfaceSquares'. This works by iterating over latitude * and longitude pairs and assuming a spherical Earth. It * assumes the Earth is a sphere. */ public void buildSphericalEarthSurfaceWithLatLong() { log("building spherical Earth"); this.clearSurfaceSquares(); // Size of squares to build, in km. float sizeKm = 1000; // Start with an arbitrary square centered at the origin // the 3D space, and at SF, CA in the real world. float startLatitude = 38; // 38N float startLongitude = -122; // 122W SurfaceSquare startSquare = new SurfaceSquare( new Vector3f(0,0,0), // center new Vector3f(0,0,-1), // north new Vector3f(0,1,0), // up sizeKm, startLatitude, startLongitude, null /*base*/, null /*midpoint*/, new Vector3f(0,0,0)); this.emCanvas.addSurfaceSquare(startSquare); // Outer loop 1: Walk North as far as we can. SurfaceSquare outer = startSquare; for (float latitude = startLatitude; latitude < 90; latitude += 9) { // Go North another step. outer = this.addSphericallyAdjacentSquare(outer, latitude, startLongitude); // Inner loop: Walk East until we get back to // the same longitude. float longitude = startLongitude; float prevLongitude = longitude; SurfaceSquare inner = outer; while (true) { inner = this.addSphericallyAdjacentSquare(inner, latitude, longitude); if (prevLongitude < outer.longitude && outer.longitude <= longitude) { break; } prevLongitude = longitude; longitude = FloatUtil.modulus2f(longitude+9, -180, 180); } } // Outer loop 2: Walk South as far as we can. outer = startSquare; for (float latitude = startLatitude - 9; latitude > -90; latitude -= 9) { // Go North another step. outer = this.addSphericallyAdjacentSquare(outer, latitude, startLongitude); // Inner loop: Walk East until we get back to // the same longitude. float longitude = startLongitude; float prevLongitude = longitude; SurfaceSquare inner = outer; while (true) { inner = this.addSphericallyAdjacentSquare(inner, latitude, longitude); if (prevLongitude < outer.longitude && outer.longitude <= longitude) { break; } prevLongitude = longitude; longitude = FloatUtil.modulus2f(longitude+9, -180, 180); } } this.emCanvas.redrawCanvas(); log("finished building Earth; nsquares="+this.emCanvas.numSurfaceSquares()); } /** Build the surface by walking randomly from a starting location, * assuming a Earth is a sphere. */ public void buildSphericalEarthWithRandomWalk() { log("building spherical Earth by random walk"); this.clearSurfaceSquares(); // Size of squares to build, in km. float sizeKm = 1000; // Start with an arbitrary square centered at the origin // the 3D space, and at SF, CA in the real world. float startLatitude = 38; // 38N float startLongitude = -122; // 122W SurfaceSquare startSquare = new SurfaceSquare( new Vector3f(0,0,0), // center new Vector3f(0,0,-1), // north new Vector3f(0,1,0), // up sizeKm, startLatitude, startLongitude, null /*base*/, null /*midpoint*/, new Vector3f(0,0,0)); this.emCanvas.addSurfaceSquare(startSquare); SurfaceSquare square = startSquare; for (int i=0; i < 1000; i++) { // Select a random change in latitude and longitude // of about 10 degrees. float deltaLatitude = (float)(Math.random() * 12 - 6); float deltaLongitude = (float)(Math.random() * 12 - 6); // Walk in that direction, keeping latitude and longitude // within their usual ranges. Also stay away from the poles // since the rounding errors cause problems there. square = this.addSphericallyAdjacentSquare(square, FloatUtil.clampf(square.latitude + deltaLatitude, -80, 80), FloatUtil.modulus2f(square.longitude + deltaLongitude, -180, 180)); } this.emCanvas.redrawCanvas(); log("finished building Earth; nsquares="+this.emCanvas.numSurfaceSquares()); } /** Given square 'old', add an adjacent square at the given * latitude and longitude. The relative orientation of the * new square will determined using the latitude and longitude, * assuming a spherical shape for the Earth. * * This is used by the routines that build the surface using * the sphere assumption, not those that use star observation * data. */ private SurfaceSquare addSphericallyAdjacentSquare( SurfaceSquare old, float newLatitude, float newLongitude) { // Calculate local East for 'old'. Vector3f oldEast = old.north.cross(old.up).normalize(); // Calculate celestial North for 'old', which is given by // the latitude plus geographic North. Vector3f celestialNorth = old.north.rotateDeg(old.latitude, oldEast); // Get lat/long deltas. float deltaLatitude = newLatitude - old.latitude; float deltaLongitude = FloatUtil.modulus2f( newLongitude - old.longitude, -180, 180); // If we didn't move, just return the old square. if (deltaLongitude == 0 && deltaLatitude == 0) { return old; } // What we want now is to first rotate Northward // around local East to account for change in latitude, then // Eastward around celestial North for change in longitude. Vector3f firstRotation = oldEast.times(-deltaLatitude); Vector3f secondRotation = celestialNorth.times(deltaLongitude); // But then we want to express the composition of those as a // single rotation vector in order to call the general routine. Vector3f combined = Vector3f.composeRotations(firstRotation, secondRotation); // Now call into the general procedure for adding a square // given the proper relative orientation rotation. return addRotatedAdjacentSquare(old, newLatitude, newLongitude, combined); } /** Build a surface using star data rather than any presumed * size and shape. */ public void buildEarthSurfaceFromStarData() { Cursor oldCursor = this.getCursor(); this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try { ProgressDialog<Void, Void> pd = new ProgressDialog<Void, Void>(this, "Building Surface with model: "+this.worldObservations.getDescription(), new BuildSurfaceTask(EarthShape.this)); pd.exec(); } finally { this.setCursor(oldCursor); } this.emCanvas.redrawCanvas(); } /** Task to manage construction of surface. * * I have to use a class rather than a simple closure so I have * something to pass to the build routines so they can set the * status and progress as the algorithm runs. */ private static class BuildSurfaceTask extends MySwingWorker<Void, Void> { private EarthShape earthShape; public BuildSurfaceTask(EarthShape earthShape_) { this.earthShape = earthShape_; } protected Void doTask() throws Exception { this.earthShape.buildEarthSurfaceFromStarDataInner(this); return null; } } /** Core of 'buildEarthSurfaceFromStarData', so I can more easily * wrap computation around it. */ public void buildEarthSurfaceFromStarDataInner(BuildSurfaceTask task) { log("building Earth using star data: "+this.worldObservations.getDescription()); this.clearSurfaceSquares(); // Size of squares to build, in km. float sizeKm = 1000; // Start at approximately my location in SF, CA. This is one of // the locations for which I have manual data, and when we build // the first latitude strip, that will pick up the other manual // data points. float latitude = 38; float longitude = -122; SurfaceSquare square = null; log("buildEarth: building first square at lat="+latitude+" long="+longitude); // First square will be placed at the 3D origin with // its North pointed along the -Z axis. square = new SurfaceSquare( new Vector3f(0,0,0), // center new Vector3f(0,0,-1), // north new Vector3f(0,1,0), // up sizeKm, latitude, longitude, null /*base*/, null /*midpoint*/, new Vector3f(0,0,0)); this.emCanvas.addSurfaceSquare(square); this.addMatchingData(square); // Go East and West. task.setStatus("Initial latitude strip at "+square.latitude); this.buildLatitudeStrip(square, +9); this.buildLatitudeStrip(square, -9); // Explore in all directions until all points on // the surface have been explored (to within 9 degrees). this.buildLongitudeStrip(square, +9, task); this.buildLongitudeStrip(square, -9, task); // Reset the adjustment angle. this.adjustOrientationDegrees = EarthShape.DEFAULT_ADJUST_ORIENTATION_DEGREES; log("buildEarth: finished using star data; nSquares="+this.emCanvas.numSurfaceSquares()); } /** Build squares by going North or South from a starting square * until we add 20 or we can't add any more. At each spot, also * build latitude strips in both directions. */ private void buildLongitudeStrip(SurfaceSquare startSquare, float deltaLatitude, BuildSurfaceTask task) { float curLatitude = startSquare.latitude; float curLongitude = startSquare.longitude; SurfaceSquare curSquare = startSquare; if (task.isCancelled()) { // Bail now, rather than repeat the cancellation log message. return; } while (!task.isCancelled()) { float newLatitude = curLatitude + deltaLatitude; if (!( -90 < newLatitude && newLatitude < 90 )) { // Do not go past the poles. break; } float newLongitude = curLongitude; log("buildEarth: building lat="+newLatitude+" long="+newLongitude); // Report progress. task.setStatus("Latitude strip at "+newLatitude); { // +1 since we did one strip before the first call to // buildLongitudeStrip. float totalStrips = 180 / (float)Math.abs(deltaLatitude) + 1; float completedStrips; if (deltaLatitude > 0) { completedStrips = (newLatitude - startSquare.latitude) / deltaLatitude + 1; } else { completedStrips = (90 - newLatitude) / -deltaLatitude + 1; } float fraction = completedStrips / totalStrips; log("progress fraction: "+fraction); task.setProgressFraction(fraction); } curSquare = this.createAndAutomaticallyOrientSquare(curSquare, newLatitude, newLongitude); if (curSquare == null) { log("buildEarth: could not place next square!"); break; } curLatitude = newLatitude; curLongitude = newLongitude; // Also build strips in each direction. this.buildLatitudeStrip(curSquare, +9); this.buildLatitudeStrip(curSquare, -9); } if (task.isCancelled()) { log("surface construction canceled"); } } /** Build squares by going East or West from a starting square * until we add 20 or we can't add any more. */ private void buildLatitudeStrip(SurfaceSquare startSquare, float deltaLongitude) { float curLatitude = startSquare.latitude; float curLongitude = startSquare.longitude; SurfaceSquare curSquare = startSquare; for (int i=0; i < 20; i++) { float newLatitude = curLatitude; float newLongitude = FloatUtil.modulus2f(curLongitude + deltaLongitude, -180, 180); log("buildEarth: building lat="+newLatitude+" long="+newLongitude); curSquare = this.createAndAutomaticallyOrientSquare(curSquare, newLatitude, newLongitude); if (curSquare == null) { log("buildEarth: could not place next square!"); break; } curLatitude = newLatitude; curLongitude = newLongitude; } } /** Create a square adjacent to 'old', positioned at the given latitude * and longitude, with orientation changed by 'rotation'. If there is * no change, return null. Even if not, do not add the square yet, * just return it. */ private SurfaceSquare createRotatedAdjacentSquare( SurfaceSquare old, float newLatitude, float newLongitude, Vector3f rotation) { // Normalize latitude and longitude. newLatitude = FloatUtil.clampf(newLatitude, -90, 90); newLongitude = FloatUtil.modulus2f(newLongitude, -180, 180); // If we didn't move, return null. if (old.latitude == newLatitude && old.longitude == newLongitude) { return null; } // Compute the new orientation vectors by rotating // the old ones by the given amount. Vector3f newNorth = old.north.rotateAADeg(rotation); Vector3f newUp = old.up.rotateAADeg(rotation); // Get observed travel details going to the new location. TravelObservation tobs = this.worldObservations.getTravelObservation( old.latitude, old.longitude, newLatitude, newLongitude); // For both old and new, calculate a unit vector for the // travel direction. Both headings are negated due to the // right hand rule for rotation. The new to old heading is // then flipped 180 since I want both to indicate the local // direction from old to new. Vector3f oldTravel = old.north.rotateDeg(-tobs.startToEndHeading, old.up); Vector3f newTravel = newNorth.rotateDeg(-tobs.endToStartHeading + 180, newUp); // Calculate the new square's center by going half the distance // according to the old orientation and then half the distance // according to the new orientation, in world coordinates. float halfDistWorld = tobs.distanceKm / 2.0f * EarthMapCanvas.SPACE_UNITS_PER_KM; Vector3f midPoint = old.center.plus(oldTravel.times(halfDistWorld)); Vector3f newCenter = midPoint.plus(newTravel.times(halfDistWorld)); // Make the new square and add it to the list. SurfaceSquare ret = new SurfaceSquare( newCenter, newNorth, newUp, old.sizeKm, newLatitude, newLongitude, old /*base*/, midPoint, rotation); return ret; } /** Add a square adjacent to 'old', positioned at the given latitude * and longitude, with orientation changed by 'rotation'. If we * did not move, this returns the old square. */ private SurfaceSquare addRotatedAdjacentSquare( SurfaceSquare old, float newLatitude, float newLongitude, Vector3f rotation) { SurfaceSquare ret = this.createRotatedAdjacentSquare( old, newLatitude, newLongitude, rotation); if (ret == null) { return old; // Did not move. } else { this.emCanvas.addSurfaceSquare(ret); } return ret; } /** Get star observations for the given location, at the particular * point in time that I am using for everything. */ private List<StarObservation> getStarObservationsFor( float latitude, float longitude) { return this.worldObservations.getStarObservations( StarObservation.unixTimeOfManualData, latitude, longitude); } /** Add to 'square.starObs' all entries of 'starObs' that have * the same latitude and longitude, and also are at least * 20 degrees above the horizon. */ private void addMatchingData(SurfaceSquare square) { for (StarObservation so : this.getStarObservationsFor(square.latitude, square.longitude)) { if (this.qualifyingStarObservation(so)) { square.addObservation(so); } } } /** Compare star data for 'startSquare' and for the given new * latitude and longitude. Return a rotation vector that will * transform the orientation of 'startSquare' to match the * best surface for a new square at the new location. The * vector's length is the amount of rotation in degrees. * * Returns null if there are not enough stars in common. */ private Vector3f calcRequiredRotation( SurfaceSquare startSquare, float newLatitude, float newLongitude) { // Set of stars visible at the start and end squares and // above 20 degrees above the horizon. HashMap<String, Vector3f> startStars = getVisibleStars(startSquare.latitude, startSquare.longitude); HashMap<String, Vector3f> endStars = getVisibleStars(newLatitude, newLongitude); // Current best rotation and average difference. Vector3f currentRotation = new Vector3f(0,0,0); // Iteratively refine the current rotation by computing the // average correction rotation and applying it until that // correction drops below a certain threshold. for (int iterationCount = 0; iterationCount < 1000; iterationCount++) { // Accumulate the vector sum of all the rotation difference // vectors as well as the max length. Vector3f diffSum = new Vector3f(0,0,0); float maxDiffLength = 0; int diffCount = 0; for (HashMap.Entry<String, Vector3f> e : startStars.entrySet()) { String starName = e.getKey(); Vector3f startVector = e.getValue(); Vector3f endVector = endStars.get(starName); if (endVector == null) { continue; } // Both vectors must first be rotated the way the start // surface was rotated since its creation so that when // we compute the final required rotation, it can be // applied to the start surface in its existing orientation, // not the nominal orientation that the star vectors have // before I do this. startVector = startVector.rotateAADeg(startSquare.rotationFromNominal); endVector = endVector.rotateAADeg(startSquare.rotationFromNominal); // Calculate a difference rotation vector from the // rotated end vector to the start vector. Rotating // the end star in one direction is like rotating // the start terrain in the opposite direction. Vector3f rot = endVector.rotateAADeg(currentRotation) .rotationToBecome(startVector); // Accumulate it. diffSum = diffSum.plus(rot); maxDiffLength = (float)Math.max(maxDiffLength, rot.length()); diffCount++; } if (diffCount < 2) { log("reqRot: not enough stars"); return null; } // Calculate the average correction rotation. Vector3f avgDiff = diffSum.times(1.0f / diffCount); // If the correction angle is small enough, stop. For any set // of observations, we should be able to drive the average // difference arbitrarily close to zero (this is like finding // the centroid, except in spherical rather than flat space). // The real question is whether the *maximum* difference is // large enough to indicate that the data is inconsistent. if (avgDiff.length() < 0.001) { log("reqRot finished: iters="+iterationCount+ " avgDiffLen="+avgDiff.length()+ " maxDiffLength="+maxDiffLength+ " diffCount="+diffCount); if (maxDiffLength > 0.2) { // For the data I am working with, I estimate it is // accurate to within 0.2 degrees. Consequently, // there should not be a max difference that large. log("reqRot: WARNING: maxDiffLength greater than 0.2"); } return currentRotation; } // Otherwise, apply it to the current rotation and // iterate again. currentRotation = currentRotation.plus(avgDiff); } log("reqRot: hit iteration limit!"); return currentRotation; } /** True if the given observation is available for use, meaning * it is high enough in the sky, is enabled, and not obscured * by light from the Sun. */ private boolean qualifyingStarObservation(StarObservation so) { if (this.sunIsTooHigh(so.latitude, so.longitude)) { return false; } return so.elevation >= 20.0f && this.enabledStars.containsKey(so.name) && this.enabledStars.get(so.name) == true; } /** Return true if, at StarObservation.unixTimeOfManualData, the * Sun is too high in the sky to see stars. This depends on * the configurable parameter 'maximumSunElevation'. */ private boolean sunIsTooHigh(float latitude, float longitude) { if (!this.useSunElevation) { return false; } StarObservation sun = this.worldObservations.getSunObservation( StarObservation.unixTimeOfManualData, latitude, longitude); if (sun == null) { return false; } return sun.elevation > this.maximumSunElevation; } /** For every visible star vislble at the specified coordinate * that has an elevation of at least 20 degrees, * add it to a map from star name to azEl vector. */ private HashMap<String, Vector3f> getVisibleStars( float latitude, float longitude) { HashMap<String, Vector3f> ret = new HashMap<String, Vector3f>(); for (StarObservation so : this.getStarObservationsFor(latitude, longitude)) { if (this.qualifyingStarObservation(so)) { ret.put(so.name, Vector3f.azimuthElevationToVector(so.azimuth, so.elevation)); } } return ret; } /** Get the unit ray, in world coordinates, from the center of 'square' to * the star recorded in 'so', which was observed at this square. */ public static Vector3f rayToStar(SurfaceSquare square, StarObservation so) { // Ray to star in nominal, -Z facing, coordinates. Vector3f nominalRay = Vector3f.azimuthElevationToVector(so.azimuth, so.elevation); // Ray to star in world coordinates, taking into account // how the surface is rotated. Vector3f worldRay = nominalRay.rotateAADeg(square.rotationFromNominal); return worldRay; } /** Hold results of call to 'fitOfObservations'. */ private static class ObservationStats { /** The total variance in star observation locations from the * indicated square to the observations of its base square as the * average square of the deviation angles. * * The reason for using a sum of squares approach is to penalize large * deviations and to ensure there is a unique "least deviated" point * (which need not exist when using a simple sum). The reason for using * the average is to make it easier to judge "good" or "bad" fits, * regardless of the number of star observations in common. * * I use the term "variance" here because it is similar to the idea in * statistics, except here we are measuring differences between pairs of * observations, rather than between individual observations and the mean * of the set. I'll then reserve "deviation", if I use it, to refer to * the square root of the variance, by analogy with "standard deviation". * */ public double variance; /** Maximum separation between observations, in degrees. */ public double maxSeparation; /** Number of pairs of stars used in comparison. */ public int numSamples; } /** Calculate variance and maximum separation for 'square'. Returns * null if there is no base or there are no observations in common. */ private ObservationStats fitOfObservations(SurfaceSquare square) { if (square.baseSquare == null) { return null; } double sumOfSquares = 0; int numSamples = 0; double maxSeparation = 0; for (Map.Entry<String, StarObservation> entry : square.starObs.entrySet()) { StarObservation so = entry.getValue(); // Ray to star in world coordinates. Vector3f starRay = EarthShape.rayToStar(square, so); // Calculate the deviation of this observation from that of // the base square. StarObservation baseObservation = square.baseSquare.findObservation(so.name); if (baseObservation != null) { // Get ray from base square to the base observation star // in world coordinates. Vector3f baseStarRay = EarthShape.rayToStar(square.baseSquare, baseObservation); // Visual separation angle between these rays. double sep; if (this.assumeInfiniteStarDistance) { sep = this.getStarRayDifference( square.up, starRay, baseStarRay); } else { sep = EarthShape.getModifiedClosestApproach( square.center, starRay, square.baseSquare.center, baseStarRay).separationAngleDegrees; } if (sep > maxSeparation) { maxSeparation = sep; } // Accumulate its square. sumOfSquares += sep * sep; numSamples++; } } if (numSamples == 0) { return null; } else { ObservationStats ret = new ObservationStats(); ret.variance = sumOfSquares / numSamples; ret.maxSeparation = maxSeparation; ret.numSamples = numSamples; return ret; } } /** Get closest approach, except with a modification to * smooth out the search space. */ public static Vector3d.ClosestApproach getModifiedClosestApproach( Vector3f p1f, Vector3f u1f, Vector3f p2f, Vector3f u2f) { Vector3d p1 = new Vector3d(p1f); Vector3d u1 = new Vector3d(u1f); Vector3d p2 = new Vector3d(p2f); Vector3d u2 = new Vector3d(u2f); Vector3d.ClosestApproach ca = Vector3d.getClosestApproach(p1, u1, p2, u2); if (ca.line1Closest != null) { // Now, there is a problem if the closest approach is behind // either observer. Not only does that not make logical sense, // but naively using the calculation will cause the search // space to be very lumpy, which creates local minima that my // hill-climbing algorithm gets trapped in. So, we require // that the points on each observation line be at least one // unit away, which currently means 1000 km. That smooths out // the search space so the hill climber will find its way to // the optimal solution more reliably. // How far along u1 is the closest approach? double m1 = ca.line1Closest.minus(p1).dot(u1); if (m1 < 1.0) { // That is unreasonably close. Push the approach point // out to one unit away along u1. ca.line1Closest = p1.plus(u1); // Find the closest point on (p2,u2) to that point. ca.line2Closest = ca.line1Closest.closestPointOnLine(p2, u2); // Recalculate the separation angle to that point. ca.separationAngleDegrees = u1.separationAngleDegrees(ca.line2Closest.minus(p1)); } // How far along u2? double m2 = ca.line2Closest.minus(p2).dot(u2); if (m2 < 1.0) { // Too close; push it. ca.line2Closest = p2.plus(u2); // What is closest on (p1,u1) to that? ca.line1Closest = ca.line2Closest.closestPointOnLine(p1, u1); // Re-check if that is too close to p1. if (ca.line1Closest.minus(p1).dot(u1) < 1.0) { // Push it without changing line2Closest. ca.line1Closest = p1.plus(u1); } // Recalculate the separation angle to that point. ca.separationAngleDegrees = u1.separationAngleDegrees(ca.line2Closest.minus(p1)); } } return ca; } /** Get the difference between the two star rays, for a location * with given unit 'up' vector, in degrees. This depends on the * option setting 'onlyCompareElevations'. */ public double getStarRayDifference( Vector3f up, Vector3f ray1, Vector3f ray2) { if (this.onlyCompareElevations) { return EarthShape.getElevationDifference(up, ray1, ray2); } else { return ray1.separationAngleDegrees(ray2); } } /** Given two star observation rays at a location with the given * 'up' unit vector, return the difference in elevation between * them, ignoring azimuth, in degrees. */ private static double getElevationDifference( Vector3f up, Vector3f ray1, Vector3f ray2) { double e1 = getElevation(up, ray1); double e2 = getElevation(up, ray2); return Math.abs(e1-e2); } /** Return the elevation of 'ray' at a location with unit 'up' * vector, in degrees. */ private static double getElevation(Vector3f up, Vector3f ray) { // Decompose into vertical and horizontal components. Vector3f v = ray.projectOntoUnitVector(up); Vector3f h = ray.minus(v); // Get lengths, with vertical possibly negative if below // horizon. double vLen = ray.dot(up); double hLen = h.length(); // Calculate corresponding angle. return FloatUtil.atan2Deg(vLen, hLen); } /** Begin constructing a new surface using star data. This just * places down the initial square to represent a user-specified * latitude and longitude. The square is placed into 3D space * at a fixed location. */ public void startNewSurface() { LatLongDialog d = new LatLongDialog(this, 38, -122); if (d.exec()) { this.startNewSurfaceAt(d.finalLatitude, d.finalLongitude); } } /** Same as 'startNewSurface' but at a specified location. */ public void startNewSurfaceAt(float latitude, float longitude) { log("starting new surface at lat="+latitude+", lng="+longitude); this.clearSurfaceSquares(); this.setActiveSquare(new SurfaceSquare( new Vector3f(0,0,0), // center new Vector3f(0,0,-1), // north new Vector3f(0,1,0), // up INITIAL_SQUARE_SIZE_KM, latitude, longitude, null /*base*/, null /*midpoint*/, new Vector3f(0,0,0))); this.addMatchingData(this.activeSquare); this.emCanvas.addSurfaceSquare(this.activeSquare); this.emCanvas.redrawCanvas(); } /** Get the active square, or null if none. */ public SurfaceSquare getActiveSquare() { return this.activeSquare; } /** Change which square is active, but do not trigger a redraw. */ public void setActiveSquareNoRedraw(SurfaceSquare sq) { if (this.activeSquare != null) { this.activeSquare.showAsActive = false; } this.activeSquare = sq; if (this.activeSquare != null) { this.activeSquare.showAsActive = true; } } /** Change which square is active. */ public void setActiveSquare(SurfaceSquare sq) { this.setActiveSquareNoRedraw(sq); this.updateAndRedraw(); } /** Add another square to the surface by building one adjacent * to the active square. */ private void buildNextSquare() { if (this.activeSquare == null) { this.errorBox("No square is active."); return; } LatLongDialog d = new LatLongDialog(this, this.activeSquare.latitude, this.activeSquare.longitude + 9); if (d.exec()) { this.buildNextSquareAt(d.finalLatitude, d.finalLongitude); } } /** Same as 'buildNextSquare' except at a specified location. */ private void buildNextSquareAt(float latitude, float longitude) { // The new square should draw star rays if the old did. boolean drawStarRays = this.activeSquare.drawStarRays; // Add it initially with no rotation. My plan is to add // the rotation interactively afterward. this.setActiveSquare( this.addRotatedAdjacentSquare(this.activeSquare, latitude, longitude, new Vector3f(0,0,0))); this.activeSquare.drawStarRays = drawStarRays; // Reset the rotation angle after adding a square. this.adjustOrientationDegrees = DEFAULT_ADJUST_ORIENTATION_DEGREES; this.addMatchingData(this.activeSquare); this.emCanvas.redrawCanvas(); } /** If there is an active square, assume we just built it, and now * we want to adjust its orientation. 'axis' indicates the axis * about which to rotate, relative to the square's current orientation, * where -Z is North, +Y is up, and +X is east, and the angle is given * by 'this.adjustOrientationDegrees'. */ private void adjustActiveSquareOrientation(Vector3f axis) { SurfaceSquare derived = this.activeSquare; if (derived == null) { this.errorBox("No active square."); return; } SurfaceSquare base = derived.baseSquare; if (base == null) { this.errorBox("The active square has no base square."); return; } // Replace the active square. this.setActiveSquare( this.adjustDerivedSquareOrientation(axis, derived, this.adjustOrientationDegrees)); this.emCanvas.redrawCanvas(); } /** Adjust the orientation of 'derived' by 'adjustDegrees' around * 'axis', where 'axis' is relative to the square's current * orientation. */ private SurfaceSquare adjustDerivedSquareOrientation(Vector3f axis, SurfaceSquare derived, float adjustDegrees) { SurfaceSquare base = derived.baseSquare; // Rotate by 'adjustOrientationDegrees'. Vector3f angleAxis = axis.times(adjustDegrees); // Rotate the axis to align it with the square. angleAxis = angleAxis.rotateAADeg(derived.rotationFromNominal); // Now add that to the square's existing rotation relative // to its base square. angleAxis = Vector3f.composeRotations(derived.rotationFromBase, angleAxis); // Now, replace it. return this.replaceWithNewRotation(base, derived, angleAxis); } /** Replace the square 'derived', with a new square that * is computed from 'base' by applying 'newRotation'. * Return the new square. */ public SurfaceSquare replaceWithNewRotation( SurfaceSquare base, SurfaceSquare derived, Vector3f newRotation) { // Replace the derived square with a new one created by // rotating from the same base by this new amount. this.emCanvas.removeSurfaceSquare(derived); SurfaceSquare ret = this.addRotatedAdjacentSquare(base, derived.latitude, derived.longitude, newRotation); // Copy some other data from the derived square that we // are in the process of discarding. ret.drawStarRays = derived.drawStarRays; ret.starObs = derived.starObs; return ret; } /** Calculate what the variation of observations would be for * 'derived' if its orientation were adjusted by * 'angleAxis.degrees()' around 'angleAxis'. Returns null if * the calculation cannot be done because of missing information. */ private ObservationStats fitOfAdjustedSquare( SurfaceSquare derived, Vector3f angleAxis) { // This part mirrors 'adjustActiveSquareOrientation'. SurfaceSquare base = derived.baseSquare; if (base == null) { return null; } angleAxis = angleAxis.rotateAADeg(derived.rotationFromNominal); angleAxis = Vector3f.composeRotations(derived.rotationFromBase, angleAxis); // Now, create a new square with this new rotation. SurfaceSquare newSquare = this.createRotatedAdjacentSquare(base, derived.latitude, derived.longitude, angleAxis); if (newSquare == null) { // If we do not move, use the original square's data. return this.fitOfObservations(derived); } // Copy the observation data since that is needed to calculate // the deviation. newSquare.starObs = derived.starObs; // Now calculate the new variance. return this.fitOfObservations(newSquare); } /** Like 'fitOfAdjustedSquare' except only retrieves the * variance. This returns 40000 if the data is unavailable. */ private double varianceOfAdjustedSquare( SurfaceSquare derived, Vector3f angleAxis) { ObservationStats os = this.fitOfAdjustedSquare(derived, angleAxis); if (os == null) { // The variance should never be greater than 180 squared, // since that would be the worst possible fit for a star. return 40000; } else { return os.variance; } } /** Change 'adjustOrientationDegrees' by the given multiplier. */ private void changeAdjustOrientationDegrees(float multiplier) { this.adjustOrientationDegrees *= multiplier; if (this.adjustOrientationDegrees < MINIMUM_ADJUST_ORIENTATION_DEGREES) { this.adjustOrientationDegrees = MINIMUM_ADJUST_ORIENTATION_DEGREES; } this.updateUIState(); } /** Compute and apply a single step rotation command to improve * the variance of the active square. */ private void applyRecommendedRotationCommand() { SurfaceSquare s = this.activeSquare; if (s == null) { this.errorBox("No active square."); return; } ObservationStats ostats = this.fitOfObservations(s); if (ostats == null) { this.errorBox("Not enough observational data available."); return; } if (ostats.variance == 0) { this.errorBox("Orientation is already optimal."); return; } // Get the recommended rotation. VarianceAfterRotations var = this.getVarianceAfterRotations(s, this.adjustOrientationDegrees); if (var.bestRC == null) { if (this.adjustOrientationDegrees <= MINIMUM_ADJUST_ORIENTATION_DEGREES) { this.errorBox("Cannot further improve orientation."); return; } else { this.changeAdjustOrientationDegrees(0.5f); } } else { this.adjustActiveSquareOrientation(var.bestRC.axis); } this.updateAndRedraw(); } /** Apply the recommended rotation to 's' until convergence. Return * the improved square, or null if that is not possible due to * insufficient constraints. */ private SurfaceSquare repeatedlyApplyRecommendedRotationCommand(SurfaceSquare s) { ObservationStats ostats = this.fitOfObservations(s); if (ostats == null || ostats.numSamples < 2) { return null; // Underconstrained. } if (ostats.variance == 0) { return s; // Already optimal. } // Rotation amount. This will be gradually reduced. float adjustDegrees = 1.0f; // Iteration cap for safety. int iters = 0; // Iterate until the adjust amount is too small. while (adjustDegrees > MINIMUM_ADJUST_ORIENTATION_DEGREES) { // Get the recommended rotation. VarianceAfterRotations var = this.getVarianceAfterRotations(s, adjustDegrees); if (var == null) { return null; } if (var.underconstrained) { log("repeatedlyApply: solution is underconstrained, adjustDegrees="+ adjustDegrees); return s; } if (var.bestRC == null) { adjustDegrees = adjustDegrees * 0.5f; // Set the UI adjust degrees to what we came up with here so I // can easily see where it ended up. this.adjustOrientationDegrees = adjustDegrees; } else { s = this.adjustDerivedSquareOrientation(var.bestRC.axis, s, adjustDegrees); } if (++iters > 1000) { log("repeatedlyApply: exceeded iteration cap!"); break; } } // Get the final variance. String finalVariance = "null"; ostats = this.fitOfObservations(s); if (ostats != null) { finalVariance = ""+ostats.variance; } log("repeatedlyApply done: iters="+iters+" adj="+ adjustDegrees+ " var="+finalVariance); return s; } /** Delete the active square. */ private void deleteActiveSquare() { if (this.activeSquare == null) { this.errorBox("No active square."); return; } this.emCanvas.removeSurfaceSquare(this.activeSquare); this.setActiveSquare(null); } /** Calculate and apply the optimal orientation for the active square; * make its replacement active if we do replace it.. */ private void automaticallyOrientActiveSquare() { SurfaceSquare derived = this.activeSquare; if (derived == null) { this.errorBox("No active square."); return; } SurfaceSquare base = derived.baseSquare; if (base == null) { this.errorBox("The active square has no base square."); return; } SurfaceSquare newDerived = automaticallyOrientSquare(derived); if (newDerived == null) { this.errorBox("Insufficient observations to determine proper orientation."); } else { this.setActiveSquare(newDerived); } this.updateAndRedraw(); } /** Given a square 'derived' that is known to have a base square, * adjust and/or replace it with one with a better orientation, * and return the improved square. Returns null if improvement * is not possible due to insufficient observational data. */ private SurfaceSquare automaticallyOrientSquare(SurfaceSquare derived) { if (this.newAutomaticOrientationAlgorithm) { return this.repeatedlyApplyRecommendedRotationCommand(derived); } else { // Calculate the best rotation. Vector3f rot = calcRequiredRotation(derived.baseSquare, derived.latitude, derived.longitude); if (rot == null) { return null; } // Now, replace the active square. return this.replaceWithNewRotation(derived.baseSquare, derived, rot); } } /** Make the next square in 'emCanvas.surfaceSquares' active. */ private void selectNextSquare(boolean forward) { this.setActiveSquare(this.emCanvas.getNextSquare(this.activeSquare, forward)); } /** Build a square offset from the active square, set its orientation, * and make it active. If we cannot make a new square, report that as * an error and leave the active square alone. */ private void createAndAutomaticallyOrientActiveSquare( float deltaLatitude, float deltaLongitude) { SurfaceSquare base = this.activeSquare; if (base == null) { this.errorBox("There is no active square."); return; } SurfaceSquare newSquare = this.createAndAutomaticallyOrientSquare( base, base.latitude + deltaLatitude, base.longitude + deltaLongitude); if (newSquare == null) { ModalDialog.errorBox(this, "Cannot place new square since observational data does not uniquely determine its orientation."); } else { newSquare.drawStarRays = base.drawStarRays; this.setActiveSquare(newSquare); } } /** Build a square adjacent to the base square, set its orientation, * and return it. Returns null and adds nothing if such a square * cannot be uniquely oriented. */ private SurfaceSquare createAndAutomaticallyOrientSquare(SurfaceSquare base, float newLatitude, float newLongitude) { // Make a new adjacent square, initially with the same orientation // as the base square. SurfaceSquare newSquare = this.addRotatedAdjacentSquare(base, newLatitude, newLongitude, new Vector3f(0,0,0)); if (base == newSquare) { return base; // Did not move, no new square created. } this.addMatchingData(newSquare); // Now try to set its orientation to match observations. SurfaceSquare adjustedSquare = this.automaticallyOrientSquare(newSquare); if (adjustedSquare == null) { // No unique solution; remove the new square too. this.emCanvas.removeSurfaceSquare(newSquare); } return adjustedSquare; } /** Show the user what the local rotation space looks like by. * considering the effect of rotating various amounts on each axis. */ private void analyzeSolutionSpace() { if (this.activeSquare == null) { this.errorBox("No active square."); return; } SurfaceSquare s = this.activeSquare; ObservationStats ostats = this.fitOfObservations(s); if (ostats == null) { this.errorBox("No observation fitness stats for the active square."); return; } // Prepare a task object in which to run the analysis. AnalysisTask task = new AnalysisTask(this, s); // Show a progress dialog while this run. ProgressDialog<PlotData3D, Void> progressDialog = new ProgressDialog<PlotData3D, Void>(this, "Analyzing rotations of active square...", task); // Run the dialog and the task. if (progressDialog.exec()) { // Retrieve the computed data. PlotData3D rollPitchYawPlotData; try { rollPitchYawPlotData = task.get(); } catch (Exception e) { String msg = "Internal error: solution space analysis failed: "+e.getMessage(); log(msg); e.printStackTrace(); this.errorBox(msg); return; } // Plot results. RotationCubeDialog d = new RotationCubeDialog(this, (float)ostats.variance, rollPitchYawPlotData); d.exec(); } else { log("Analysis canceled."); } } /** Task to analyze the solution space near a square, which can take a * while if 'solutionAnalysisPointsPerSide' is high. */ private static class AnalysisTask extends MySwingWorker<PlotData3D, Void> { /** Enclosing EarthShape instance. */ private EarthShape earthShape; /** Square whose solution will be analyzed. */ private SurfaceSquare square; public AnalysisTask( EarthShape earthShape_, SurfaceSquare square_) { this.earthShape = earthShape_; this.square = square_; } @Override protected PlotData3D doTask() throws Exception { return this.earthShape.getThreeRotationAxisPlotData(this.square, this); } } /** Get data for various rotation angles of all three axes. * * This runs in a worker thread. However, I haven't bothered * to synchronize access since the user shouldn't be able to * do anything while this is happening (although they can...), * and most of the shared data is immutable. */ private PlotData3D getThreeRotationAxisPlotData(SurfaceSquare s, AnalysisTask task) { // Number of data points on each side of 0. int pointsPerSide = this.solutionAnalysisPointsPerSide; // Total number of data points per axis, including 0. int pointsPerAxis = pointsPerSide * 2 + 1; // Complete search space cube. float[] wData = new float[pointsPerAxis * pointsPerAxis * pointsPerAxis]; Vector3f xAxis = new Vector3f(0, 0, -1); // Roll Vector3f yAxis = new Vector3f(1, 0, 0); // Pitch Vector3f zAxis = new Vector3f(0, -1, 0); // Yaw float xFirst = -pointsPerSide * this.adjustOrientationDegrees; float xLast = pointsPerSide * this.adjustOrientationDegrees; float yFirst = -pointsPerSide * this.adjustOrientationDegrees; float yLast = pointsPerSide * this.adjustOrientationDegrees; float zFirst = -pointsPerSide * this.adjustOrientationDegrees; float zLast = pointsPerSide * this.adjustOrientationDegrees; for (int zIndex=0; zIndex < pointsPerAxis; zIndex++) { if (task.isCancelled()) { log("analysis canceled"); return null; // Bail out. } task.setProgressFraction(zIndex / (float)pointsPerAxis); task.setStatus("Analyzing plane "+(zIndex+1)+" of "+pointsPerAxis); for (int yIndex=0; yIndex < pointsPerAxis; yIndex++) { for (int xIndex=0; xIndex < pointsPerAxis; xIndex++) { // Compose rotations about each axis: X then Y then Z. // // Note: Rotations don't commute, so the axes are not // being treated perfectly symmetrically here, but this // is still good for showing overall shape, and when // we zoom in to small angles, the non-commutativity // becomes insignificant. Vector3f rotX = xAxis.times(this.adjustOrientationDegrees * (xIndex - pointsPerSide)); Vector3f rotY = yAxis.times(this.adjustOrientationDegrees * (yIndex - pointsPerSide)); Vector3f rotZ = zAxis.times(this.adjustOrientationDegrees * (zIndex - pointsPerSide)); Vector3f rot = Vector3f.composeRotations( Vector3f.composeRotations(rotX, rotY), rotZ); // Get variance after that adjustment. wData[xIndex + pointsPerAxis * yIndex + pointsPerAxis * pointsPerAxis * zIndex] = (float)this.varianceOfAdjustedSquare(s, rot); } } } return new PlotData3D( xFirst, xLast, yFirst, yLast, zFirst, zLast, pointsPerAxis /*xValuesPerRow*/, pointsPerAxis /*yValuesPerColumn*/, wData); } /** Show a dialog to let the user change * 'solutionAnalysisPointsPerSide'. */ private void setSolutionAnalysisResolution() { String choice = JOptionPane.showInputDialog(this, "Specify number of data points on each side of 0 to sample "+ "when performing a solution analysis", (Integer)this.solutionAnalysisPointsPerSide); if (choice != null) { try { int c = Integer.valueOf(choice); if (c < 1) { this.errorBox("The minimum number of points is 1."); } else if (c > 100) { // At 100, it will take about a minute to complete. this.errorBox("The maximum number of points is 100."); } else { this.solutionAnalysisPointsPerSide = c; } } catch (NumberFormatException e) { this.errorBox("Invalid integer syntax: "+e.getMessage()); } } } /** Prompt the user for a floating-point value. Returns null if the * user cancels or enters an invalid value. In the latter case, an * error box has already been shown. */ private Float floatInputDialog(String label, float curValue) { String choice = JOptionPane.showInputDialog(this, label, (Float)curValue); if (choice != null) { try { return Float.valueOf(choice); } catch (NumberFormatException e) { this.errorBox("Invalid float syntax: "+e.getMessage()); return null; } } else { return null; } } /** Let the user specify a new maximum Sun elevation. */ private void setMaximumSunElevation() { Float newValue = this.floatInputDialog( "Specify maximum elevation of the Sun in degrees "+ "above the horizon (otherwise, stars are not visible)", this.maximumSunElevation); if (newValue != null) { this.maximumSunElevation = newValue; } } /** Let the user specify the distance to the skybox. */ private void setSkyboxDistance() { Float newValue = this.floatInputDialog( "Specify distance in 3D space units (each of which usually "+ "represents 1000km of surface) to the skybox.\n"+ "A value of 0 means the skybox is infinitely far away.", this.emCanvas.skyboxDistance); if (newValue != null) { if (newValue < 0) { this.errorBox("The skybox distance must be non-negative."); } else { this.emCanvas.skyboxDistance = newValue; this.updateAndRedraw(); } } } /** Make this window visible. */ public void makeVisible() { this.setVisible(true); // It seems I can only set the focus once the window is // visible. There is an example in the focus tutorial of // calling pack() first, but that resizes the window and // I don't want that. this.emCanvas.setFocusOnCanvas(); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { (new EarthShape()).makeVisible(); } }); } public void toggleDrawAxes() { this.emCanvas.drawAxes = !this.emCanvas.drawAxes; this.updateAndRedraw(); } public void toggleDrawCrosshair() { this.emCanvas.drawCrosshair = !this.emCanvas.drawCrosshair; this.updateAndRedraw(); } /** Toggle the 'drawWireframeSquares' flag. */ public void toggleDrawWireframeSquares() { this.emCanvas.drawWireframeSquares = !this.emCanvas.drawWireframeSquares; this.updateAndRedraw(); } /** Toggle the 'drawCompasses' flag, then update state and redraw. */ public void toggleDrawCompasses() { log("toggleDrawCompasses"); // The compass flag is ignored when wireframe is true, so if // we are toggling compass, also clear wireframe. this.emCanvas.drawWireframeSquares = false; this.emCanvas.drawCompasses = !this.emCanvas.drawCompasses; this.updateAndRedraw(); } /** Toggle the 'drawSurfaceNormals' flag. */ public void toggleDrawSurfaceNormals() { this.emCanvas.drawSurfaceNormals = !this.emCanvas.drawSurfaceNormals; this.updateAndRedraw(); } /** Toggle the 'drawCelestialNorth' flag. */ public void toggleDrawCelestialNorth() { this.emCanvas.drawCelestialNorth = !this.emCanvas.drawCelestialNorth; this.updateAndRedraw(); } /** Toggle the 'drawStarRays' flag. */ public void toggleDrawStarRays() { if (this.activeSquare == null) { this.errorBox("No square is active"); } else { this.activeSquare.drawStarRays = !this.activeSquare.drawStarRays; } this.emCanvas.redrawCanvas(); } private void toggleDrawUnitStarRays() { this.emCanvas.drawUnitStarRays = !this.emCanvas.drawUnitStarRays; this.updateAndRedraw(); } private void toggleDrawBaseSquareStarRays() { this.emCanvas.drawBaseSquareStarRays = !this.emCanvas.drawBaseSquareStarRays; this.updateAndRedraw(); } private void toggleDrawTravelPath() { this.emCanvas.drawTravelPath = !this.emCanvas.drawTravelPath; this.updateAndRedraw(); } private void toggleDrawActiveSquareAtOrigin() { this.emCanvas.drawActiveSquareAtOrigin = !this.emCanvas.drawActiveSquareAtOrigin; this.updateAndRedraw(); } private void toggleDrawWorldWireframe() { this.emCanvas.drawWorldWireframe = !this.emCanvas.drawWorldWireframe; this.updateAndRedraw(); } private void toggleDrawWorldStars() { this.emCanvas.drawWorldStars = !this.emCanvas.drawWorldStars; this.updateAndRedraw(); } private void toggleDrawSkybox() { this.emCanvas.drawSkybox = !this.emCanvas.drawSkybox; this.updateAndRedraw(); } private void turnOffAllStarRays() { this.emCanvas.turnOffAllStarRays(); this.emCanvas.redrawCanvas(); } /** Move the camera to the center of the active square. */ private void goToActiveSquareCenter() { if (this.activeSquare == null) { this.errorBox("No active square."); } else { this.moveCamera(this.activeSquare.center); } } /** Place the camera at the specified location. */ private void moveCamera(Vector3f loc) { this.emCanvas.cameraPosition = loc; this.updateAndRedraw(); } /** Update all stateful UI elements. */ public void updateUIState() { this.setStatusLabel(); this.setMenuState(); this.setInfoPanel(); } /** Set the status label text to reflect other state variables. * This also updates the state of stateful menu items. */ private void setStatusLabel() { StringBuilder sb = new StringBuilder(); sb.append(this.emCanvas.getStatusString()); sb.append(", model="+this.worldObservations.getDescription()); this.statusLabel.setText(sb.toString()); } /** Set the state of stateful menu items. */ private void setMenuState() { this.drawCoordinateAxesCBItem.setSelected(this.emCanvas.drawAxes); this.drawCrosshairCBItem.setSelected(this.emCanvas.drawCrosshair); this.drawWireframeSquaresCBItem.setSelected(this.emCanvas.drawWireframeSquares); this.drawCompassesCBItem.setSelected(this.emCanvas.drawCompasses); this.drawSurfaceNormalsCBItem.setSelected(this.emCanvas.drawSurfaceNormals); this.drawCelestialNorthCBItem.setSelected(this.emCanvas.drawCelestialNorth); this.drawStarRaysCBItem.setSelected(this.activeSquareDrawsStarRays()); this.drawUnitStarRaysCBItem.setSelected(this.emCanvas.drawUnitStarRays); this.drawBaseSquareStarRaysCBItem.setSelected(this.emCanvas.drawBaseSquareStarRays); this.drawTravelPathCBItem.setSelected(this.emCanvas.drawTravelPath); this.drawActiveSquareAtOriginCBItem.setSelected(this.emCanvas.drawActiveSquareAtOrigin); this.drawWorldWireframeCBItem.setSelected(this.emCanvas.drawWorldWireframe); this.drawWorldStarsCBItem.setSelected(this.emCanvas.drawWorldStars); this.drawSkyboxCBItem.setSelected(this.emCanvas.drawSkybox); this.useSunElevationCBItem.setSelected(this.useSunElevation); this.invertHorizontalCameraMovementCBItem.setSelected( this.emCanvas.invertHorizontalCameraMovement); this.invertVerticalCameraMovementCBItem.setSelected( this.emCanvas.invertVerticalCameraMovement); this.newAutomaticOrientationAlgorithmCBItem.setSelected( this.newAutomaticOrientationAlgorithm); this.assumeInfiniteStarDistanceCBItem.setSelected( this.assumeInfiniteStarDistance); this.onlyCompareElevationsCBItem.setSelected( this.onlyCompareElevations); } /** Update the contents of the info panel. */ private void setInfoPanel() { StringBuilder sb = new StringBuilder(); if (this.emCanvas.activeSquareAnimationState != 0) { sb.append("Animation state: "+this.emCanvas.activeSquareAnimationState+"\n"); } if (this.activeSquare == null) { sb.append("No active square.\n"); } else { sb.append("Active square:\n"); SurfaceSquare s = this.activeSquare; sb.append(" lat/lng: ("+s.latitude+","+s.longitude+")\n"); sb.append(" pos: "+s.center+"\n"); sb.append(" rot: "+s.rotationFromNominal+"\n"); ObservationStats ostats = this.fitOfObservations(s); if (ostats == null) { sb.append(" No obs stats\n"); } else { sb.append(" maxSep: "+ostats.maxSeparation+"\n"); sb.append(" sqrtVar: "+(float)Math.sqrt(ostats.variance)+"\n"); sb.append(" var: "+ostats.variance+"\n"); // What do we recommend to improve the variance? If it is // already zero, nothing. Otherwise, start by thinking we // should decrease the rotation angle. char recommendation = (ostats.variance == 0? ' ' : '-'); // What is the best rotation command, and what does it achieve? VarianceAfterRotations var = this.getVarianceAfterRotations(s, this.adjustOrientationDegrees); // Print the effects of all the available rotations. sb.append("\n"); for (RotationCommand rc : RotationCommand.values()) { sb.append(" adj("+rc.key+"): "); Double newVariance = var.rcToVariance.get(rc); if (newVariance == null) { sb.append("(none)\n"); } else { sb.append(""+newVariance+"\n"); } } // Make a final recommendation. if (var.bestRC != null) { recommendation = var.bestRC.key; } sb.append(" recommend: "+recommendation+"\n"); } } sb.append("\n"); sb.append("adjDeg: "+this.adjustOrientationDegrees+"\n"); // Compute average curvature from base. if (this.activeSquare != null && this.activeSquare.baseSquare != null) { sb.append("\n"); sb.append("Base at: ("+this.activeSquare.baseSquare.latitude+ ","+this.activeSquare.baseSquare.longitude+")\n"); CurvatureCalculator cc = this.computeAverageCurvature(this.activeSquare); double normalCurvatureDegPer1000km = FloatUtil.radiansToDegrees(cc.normalCurvature*1000); sb.append("Normal curvature: "+(float)normalCurvatureDegPer1000km+" deg per 1000 km\n"); if (cc.normalCurvature != 0) { sb.append("Radius: "+(float)(1/cc.normalCurvature)+" km\n"); } else { sb.append("Radius: Infinite\n"); } sb.append("Geodesic curvature: "+(float)(cc.geodesicCurvature*1000.0)+" deg per 1000 km\n"); sb.append("Geodesic torsion: "+(float)(cc.geodesicTorsion*1000.0)+" deg per 1000 km\n"); } // Also show star observation data. if (this.activeSquare != null) { sb.append("\n"); sb.append("Visible stars (az, el):\n"); // Iterate over stars in name order. TreeSet<String> stars = new TreeSet<String>(this.activeSquare.starObs.keySet()); for (String starName : stars) { StarObservation so = this.activeSquare.starObs.get(starName); sb.append(" "+so.name+": "+so.azimuth+", "+so.elevation+"\n"); } } this.infoPanel.setText(sb.toString()); } /** Compute the average curvature on a path from the base square * of 's' to 's'. */ private CurvatureCalculator computeAverageCurvature(SurfaceSquare s) { // Travel distance and heading. TravelObservation tobs = this.worldObservations.getTravelObservation( s.baseSquare.latitude, s.baseSquare.longitude, s.latitude, s.longitude); // Unit travel vector in base square coordinate system. Vector3f startTravel = Vector3f.headingToVector((float)tobs.startToEndHeading); startTravel = startTravel.rotateAADeg(s.baseSquare.rotationFromNominal); // And at derived square. Vector3f endTravel = Vector3f.headingToVector((float)tobs.endToStartHeading + 180); endTravel = endTravel.rotateAADeg(s.rotationFromNominal); // Calculate curvature and twist. CurvatureCalculator c = new CurvatureCalculator(); c.distanceKm = tobs.distanceKm; c.computeFromNormals(s.baseSquare.up, s.up, startTravel, endTravel); return c; } /** Result of call to 'getVarianceAfterRotations'. */ private static class VarianceAfterRotations { /** Variance produced by each rotation. The value can be null, * meaning the rotation produces a situation where we can't * measure the variance (e.g., because not enough stars are * above the horizon). */ public HashMap<RotationCommand, Double> rcToVariance = new HashMap<RotationCommand, Double>(); /** Which rotation command produces the greatest improvement * in variance, if any. */ public RotationCommand bestRC = null; /** If true, the solution space is underconstrained, meaning * the best orientation is not unique. */ public boolean underconstrained = false; } /** Perform a trial rotation in each direction and record the * resulting variance, plus a decision about which is best, if any. * This returns null if we do not have enough data to measure * the fitness of the square's orientation. */ private VarianceAfterRotations getVarianceAfterRotations(SurfaceSquare s, float adjustDegrees) { // Get variance if no rotation is performed. We only recommend // a rotation if it improves on this. ObservationStats ostats = this.fitOfObservations(s); if (ostats == null) { return null; } VarianceAfterRotations ret = new VarianceAfterRotations(); // Variance achieved by the best rotation command, if there is one. double bestNewVariance = 0; // Get the effects of all the available rotations. for (RotationCommand rc : RotationCommand.values()) { ObservationStats newStats = this.fitOfAdjustedSquare(s, rc.axis.times(adjustDegrees)); if (newStats == null || newStats.numSamples < 2) { ret.rcToVariance.put(rc, null); } else { double newVariance = newStats.variance; ret.rcToVariance.put(rc, newVariance); if (ostats.variance == 0 && newVariance == 0) { // The current orientation is ideal, but here // is a rotation that keeps it ideal. That // must mean that the solution space is under- // constrained. // // Note: This is an unnecessarily strong condition for // being underconstrained. It requires that we // find a zero in the objective function, and // furthermore that the solution space be parallel // to one of the three local rotation axes. I have // some ideas for more robust detection of underconstraint, // but haven't tried to implement them yet. For now I // will rely on manual inspection of the rotation cube // analysis dialog. ret.underconstrained = true; } if (newVariance < ostats.variance && (ret.bestRC == null || newVariance < bestNewVariance)) { ret.bestRC = rc; bestNewVariance = newVariance; } } } return ret; } /** True if there is an active square and it is drawing star rays. */ private boolean activeSquareDrawsStarRays() { return this.activeSquare != null && this.activeSquare.drawStarRays; } /** Replace the current observations with a new source and clear * the virtual map. */ private void changeObservations(WorldObservations obs) { this.clearSurfaceSquares(); this.worldObservations = obs; // Enable all stars in the new model. this.enabledStars.clear(); for (String starName : this.worldObservations.getAllStars()) { this.enabledStars.put(starName, true); } this.updateAndRedraw(); } /** Refresh all the UI elements and the map canvas. */ private void updateAndRedraw() { this.updateUIState(); this.emCanvas.redrawCanvas(); } /** Return true if the named star is enabled. */ public boolean isStarEnabled(String starName) { return this.enabledStars.containsKey(starName) && this.enabledStars.get(starName).equals(true); } /** Do some initial steps so I do not have to do them manually each * time I start the program when I'm working on a certain feature. * The exact setup here will vary over time as I work on different * things; it is only meant for use while testing or debugging. */ private void doCannedSetup() { // Disable all stars except for Betelgeuse and Dubhe. this.enabledStars.clear(); for (String starName : this.worldObservations.getAllStars()) { boolean en = (starName.equals("Betelgeuse") || starName.equals("Dubhe")); this.enabledStars.put(starName, en); } // Build first square in SF as usual. this.startNewSurfaceAt(38, -122); // Build next near Washington, DC. this.buildNextSquareAt(38, -77); // The plan is to align with just two stars, so we need this. this.assumeInfiniteStarDistance = true; // Position the camera to see DC square. if (this.emCanvas.drawActiveSquareAtOrigin) { // This is a canned command in the middle of a session. // Do not reposition the camera. } else { this.emCanvas.drawActiveSquareAtOrigin = true; // this.emCanvas.cameraPosition = new Vector3f(-0.19f, 0.56f, 1.20f); // this.emCanvas.cameraAzimuthDegrees = 0.0f; // this.emCanvas.cameraPitchDegrees = -11.0f; this.emCanvas.cameraPosition = new Vector3f(-0.89f, 0.52f, -1.06f); this.emCanvas.cameraAzimuthDegrees = 214.0f; this.emCanvas.cameraPitchDegrees = 1.0f; } // Use wireframes for squares, no world wireframe, but add surface normals. this.emCanvas.drawWireframeSquares = true; this.emCanvas.drawWorldWireframe = false; this.emCanvas.drawSurfaceNormals = true; this.emCanvas.drawTravelPath = false; // Show its star rays, and those at SF, as unit vectors. this.activeSquare.drawStarRays = true; this.emCanvas.drawBaseSquareStarRays = true; this.emCanvas.drawUnitStarRays = true; // Reset the animation. this.emCanvas.activeSquareAnimationState = 0; this.updateAndRedraw(); } /** Set the animation state either to 0, or to an amount * offset by 's'. */ private void setAnimationState(int s) { if (s == 0) { this.emCanvas.activeSquareAnimationState = 0; } else { this.emCanvas.activeSquareAnimationState += s; } this.updateAndRedraw(); } // ------------------------------- Animation -------------------------------- /** When animation begins, this is the rotation of the active * square relative to its base. */ private Vector3f animatedRotationStartRotation; /** Angle through which to rotate the active square. */ private double animatedRotationAngle; /** Axis about which to rotate the active square. */ private Vector3f animatedRotationAxis; /** Seconds the animation should take to complete. */ private float animatedRotationSeconds; /** How many seconds have elapsed since we started animating. * This is clamped to 'animatedRotationSeconds', and when * it is equal, the animation is complete. */ private float animatedRotationElapsed; /** Start a new rotation animation of the active square by * 'angle' degrees about 'axis' for 'seconds'. */ public void beginAnimatedRotation(double angle, Vector3f axis, float seconds) { if (this.activeSquare != null && this.activeSquare.baseSquare != null) { log("starting rotation animation"); this.animatedRotationStartRotation = this.activeSquare.rotationFromBase; this.animatedRotationAngle = angle; this.animatedRotationAxis = axis; this.animatedRotationSeconds = seconds; this.animatedRotationElapsed = 0; } } /** If animating, advance to the next frame, based on 'deltaSeconds' * having elapsed since the last animated frame. * * This should *not* trigger a redraw, since that will cause this * function to be called again during the same frame. */ public void nextAnimatedRotationFrame(float deltaSeconds) { if (this.animatedRotationElapsed < this.animatedRotationSeconds && this.activeSquare != null && this.activeSquare.baseSquare != null) { this.animatedRotationElapsed = FloatUtil.clampf( this.animatedRotationElapsed + deltaSeconds, 0, this.animatedRotationSeconds); // How much do we want the square to be rotated, // relative to its orientation at the start of // the animation? double rotFraction = this.animatedRotationElapsed / this.animatedRotationSeconds; Vector3f partialRot = this.animatedRotationAxis.timesd( this.animatedRotationAngle * rotFraction); // Compose with the original orientation. Vector3f newRotationFromBase = Vector3f.composeRotations(this.animatedRotationStartRotation, partialRot); SurfaceSquare s = replaceWithNewRotation( this.activeSquare.baseSquare, this.activeSquare, newRotationFromBase); this.setActiveSquareNoRedraw(s); if (this.animatedRotationElapsed >= this.animatedRotationSeconds) { log("rotation animation finished; normal: "+s.up); } } } /** Do any "physics" world updates. This is invoked prior to * rendering a frame in the GL canvas. */ public void updatePhysics(float elapsedSeconds) { this.nextAnimatedRotationFrame(elapsedSeconds); } /** Get list of stars for which both squares have observations. */ private List<String> getCommonStars(SurfaceSquare s1, SurfaceSquare s2) { ArrayList<String> ret = new ArrayList<String>(); for (Map.Entry<String, StarObservation> entry : s1.starObs.entrySet()) { if (s2.findObservation(entry.getKey()) != null) { ret.add(entry.getKey()); } } return ret; } private void showCurvatureDialog() { // Default initial values. CurvatureCalculator c = CurvatureCalculator.getDubheSirius(); // Try to populate 'c' with values from the current square. if (this.activeSquare != null && this.activeSquare.baseSquare != null) { SurfaceSquare start = this.activeSquare.baseSquare; SurfaceSquare end = this.activeSquare; List<String> common = getCommonStars(start, end); if (common.size() >= 2) { // When Dubhe and Betelgeuse are the only ones, I want // Dubhe first so the calculation agrees with the ad-hoc // animation, and doing them in this order accomplishes // that. String A = common.get(1); String B = common.get(0); log("initializing curvature dialog with "+A+" and "+B); c.start_A_az = start.findObservation(A).azimuth; c.start_A_el = start.findObservation(A).elevation; c.start_B_az = start.findObservation(B).azimuth; c.start_B_el = start.findObservation(B).elevation; c.end_A_az = end.findObservation(A).azimuth; c.end_A_el = end.findObservation(A).elevation; c.end_B_az = end.findObservation(B).azimuth; c.end_B_el = end.findObservation(B).elevation; c.setTravelByLatLong(start.latitude, start.longitude, end.latitude, end.longitude); } } // Run the dialog. (new CurvatureCalculatorDialog(EarthShape.this, c)).exec(); } } // EOF
smcpeak/earthshape
src/earthshape/EarthShape.java
Java
bsd-2-clause
118,405
var searchData= [ ['lcd_2ec',['lcd.c',['../lcd_8c.html',1,'']]], ['lcd_2eh',['lcd.h',['../lcd_8h.html',1,'']]], ['light_2ec',['light.c',['../light_8c.html',1,'']]], ['light_2eh',['light.h',['../light_8h.html',1,'']]] ];
bplainia/galaxyLightingSystem
doxygen/html/search/files_4.js
JavaScript
bsd-2-clause
228
/* Copyright (c) 2014, Lars Brubaker 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. 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 the FreeBSD Project. */ using System; using System.Collections.Generic; using System.Linq; using MatterHackers.VectorMath; namespace MatterHackers.PolygonMesh { public static class FaceBspTree { private static readonly double considerCoplaner = .1; /// <summary> /// This function will search for the first face that produces no polygon cuts /// and split the tree on it. If it can't find a non-cutting face, /// it will split on the face that minimizes the area that it divides. /// </summary> /// <param name="mesh"></param> /// <returns></returns> public static BspNode Create(Mesh mesh, int maxFacesToTest = 10, bool tryToBalanceTree = false) { BspNode root = new BspNode(); var sourceFaces = Enumerable.Range(0, mesh.Faces.Count).ToList(); var faces = Enumerable.Range(0, mesh.Faces.Count).ToList(); CreateNoSplittingFast(mesh, sourceFaces, root, faces, maxFacesToTest, tryToBalanceTree); return root; } /// <summary> /// Get an ordered list of the faces to render based on the camera position. /// </summary> /// <param name="node"></param> /// <param name="meshToViewTransform"></param> /// <param name="invMeshToViewTransform"></param> /// <param name="faceRenderOrder"></param> public static IEnumerable<int> GetFacesInVisibiltyOrder(Mesh mesh, BspNode root, Matrix4X4 meshToViewTransform, Matrix4X4 invMeshToViewTransform) { var renderOrder = new Stack<BspNode>(new BspNode[] { root.RenderOrder(mesh, meshToViewTransform, invMeshToViewTransform) }); do { var lastBack = renderOrder.Peek().BackNode; while (lastBack != null && lastBack.Index != -1) { renderOrder.Peek().BackNode = null; renderOrder.Push(lastBack.RenderOrder(mesh, meshToViewTransform, invMeshToViewTransform)); lastBack = renderOrder.Peek().BackNode; } var node = renderOrder.Pop(); if (node.Index != -1) { yield return node.Index; } var lastFront = node.FrontNode; if (lastFront != null && lastFront.Index != -1) { renderOrder.Push(lastFront.RenderOrder(mesh, meshToViewTransform, invMeshToViewTransform)); } } while (renderOrder.Any()); } private static (double, int) CalculateCrossingArea(Mesh mesh, int faceIndex, List<int> faces, double smallestCrossingArrea) { double negativeDistance = 0; double positiveDistance = 0; int negativeSideCount = 0; int positiveSideCount = 0; int checkFace = faces[faceIndex]; var pointOnCheckFace = mesh.Vertices[mesh.Faces[faces[faceIndex]].v0]; for (int i = 0; i < faces.Count; i++) { if (i < faces.Count && i != faceIndex) { var iFace = mesh.Faces[faces[i]]; var vertexIndices = new int[] { iFace.v0, iFace.v1, iFace.v2 }; foreach (var vertexIndex in vertexIndices) { double distanceToPlan = mesh.Faces[checkFace].normal.Dot(mesh.Vertices[vertexIndex] - pointOnCheckFace); if (Math.Abs(distanceToPlan) > considerCoplaner) { if (distanceToPlan < 0) { // Take the square of this distance to penalize far away points negativeDistance += (distanceToPlan * distanceToPlan); } else { positiveDistance += (distanceToPlan * distanceToPlan); } if (negativeDistance > smallestCrossingArrea && positiveDistance > smallestCrossingArrea) { return (double.MaxValue, int.MaxValue); } } } if (negativeDistance > positiveDistance) { negativeSideCount++; } else { positiveSideCount++; } } } // return whatever side is small as our rating of badness (0 being good) return (Math.Min(negativeDistance, positiveDistance), Math.Abs(negativeSideCount - positiveSideCount)); } private static void CreateBackAndFrontFaceLists(Mesh mesh, int faceIndex, List<int> faces, List<int> backFaces, List<int> frontFaces) { var checkFaceIndex = faces[faceIndex]; var checkFace = mesh.Faces[checkFaceIndex]; var pointOnCheckFace = mesh.Vertices[mesh.Faces[checkFaceIndex].v0]; for (int i = 0; i < faces.Count; i++) { if (i != faceIndex) { bool backFace = true; var vertexIndices = new int[] { checkFace.v0, checkFace.v1, checkFace.v2 }; foreach (var vertexIndex in vertexIndices) { double distanceToPlan = mesh.Faces[checkFaceIndex].normal.Dot(mesh.Vertices[vertexIndex] - pointOnCheckFace); if (Math.Abs(distanceToPlan) > considerCoplaner) { if (distanceToPlan > 0) { backFace = false; } } } if (backFace) { // it is a back face backFaces.Add(faces[i]); } else { // it is a front face frontFaces.Add(faces[i]); } } } } private static void CreateNoSplittingFast(Mesh mesh, List<int> sourceFaces, BspNode node, List<int> faces, int maxFacesToTest, bool tryToBalanceTree) { if (faces.Count == 0) { return; } int bestFaceIndex = -1; double smallestCrossingArrea = double.MaxValue; int bestBalance = int.MaxValue; // find the first face that does not split anything int step = Math.Max(1, faces.Count / maxFacesToTest); for (int i = 0; i < faces.Count; i += step) { // calculate how much of polygons cross this face (double crossingArrea, int balance) = CalculateCrossingArea(mesh, i, faces, smallestCrossingArrea); // keep track of the best face so far if (crossingArrea < smallestCrossingArrea) { smallestCrossingArrea = crossingArrea; bestBalance = balance; bestFaceIndex = i; if (crossingArrea == 0 && !tryToBalanceTree) { break; } } else if (crossingArrea == smallestCrossingArrea && balance < bestBalance) { // the crossing area is the same but the tree balance is better bestBalance = balance; bestFaceIndex = i; } } node.Index = sourceFaces.IndexOf(faces[bestFaceIndex]); // put the behind stuff in a list var backFaces = new List<int>(); var frontFaces = new List<int>(); CreateBackAndFrontFaceLists(mesh, bestFaceIndex, faces, backFaces, frontFaces); CreateNoSplittingFast(mesh, sourceFaces, node.BackNode = new BspNode(), backFaces, maxFacesToTest, tryToBalanceTree); CreateNoSplittingFast(mesh, sourceFaces, node.FrontNode = new BspNode(), frontFaces, maxFacesToTest, tryToBalanceTree); } } public class BspNode { public BspNode BackNode { get; internal set; } public BspNode FrontNode { get; internal set; } public int Index { get; internal set; } = -1; } public static class BspNodeExtensions { public static BspNode RenderOrder(this BspNode node, Mesh mesh, Matrix4X4 meshToViewTransform, Matrix4X4 invMeshToViewTransform) { var faceNormalInViewSpace = mesh.Faces[node.Index].normal.TransformNormalInverse(invMeshToViewTransform); var pointOnFaceInViewSpace = mesh.Vertices[mesh.Faces[node.Index].v0].Transform(meshToViewTransform); var infrontOfFace = faceNormalInViewSpace.Dot(pointOnFaceInViewSpace) < 0; if (infrontOfFace) { return new BspNode() { Index = node.Index, BackNode = node.BackNode, FrontNode = node.FrontNode }; } else { return new BspNode() { Index = node.Index, BackNode = node.FrontNode, FrontNode = node.BackNode }; } } } }
jlewin/agg-sharp
PolygonMesh/Processors/FaceBspTree.cs
C#
bsd-2-clause
8,877
using System; using System.Reflection; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace LabVIEW_CLI { class Program { static bool connected = false; static bool stop = false; static int Main(string[] args) { int exitCode = 0; Output output = Output.Instance; string[] cliArgs, lvArgs; lvComms lvInterface = new lvComms(); lvMsg latestMessage = new lvMsg("NOOP", ""); LvLauncher launcher = null; CliOptions options = new CliOptions(); lvVersion current = LvVersions.CurrentVersion; splitArguments(args, out cliArgs, out lvArgs); //CommandLine.Parser.Default.ParseArguments(cliArgs, options); if(!CommandLine.Parser.Default.ParseArguments(cliArgs, options)) { Environment.Exit(CommandLine.Parser.DefaultExitCodeFail); } if (options.Version) { output.writeMessage(Assembly.GetExecutingAssembly().GetName().Version.ToString()); Environment.Exit(0); } output.setVerbose(options.Verbose); output.writeInfo("LabVIEW CLI Started - Verbose Mode"); output.writeInfo("Version " + Assembly.GetExecutingAssembly().GetName().Version); output.writeInfo("LabVIEW CLI Arguments: " + String.Join(" ", cliArgs)); output.writeInfo("Arguments passed to LabVIEW: " + String.Join(" ", lvArgs)); if (options.noLaunch) { output.writeMessage("Auto Launch Disabled"); // disable timeout if noLaunch is specified options.timeout = -1; } else { // check launch vi if(options.LaunchVI == null) { output.writeError("No launch VI supplied!"); return 1; } if (!File.Exists(options.LaunchVI)) { output.writeError("File \"" + options.LaunchVI + "\" does not exist!"); return 1; } List<string> permittedExtensions = new List<string>{ ".vi", ".lvproj" }; string ext = Path.GetExtension(options.LaunchVI).ToLower(); if (!permittedExtensions.Contains(ext)) { output.writeError("Cannot handle *" + ext + " files"); return 1; } try { launcher = new LvLauncher(options.LaunchVI, lvPathFinder(options), lvInterface.port, lvArgs); launcher.Exited += Launcher_Exited; launcher.Start(); } catch(KeyNotFoundException ex) { // Fail gracefully if lv-ver option cannot be resolved string bitness = options.x64 ? " 64bit" : string.Empty; output.writeError("LabVIEW version \"" + options.lvVer + bitness + "\" not found!"); output.writeMessage("Available LabVIEW versions are:"); foreach(var ver in LvVersions.Versions) { output.writeMessage(ver.ToString()); } return 1; } catch(FileNotFoundException ex) { output.writeError(ex.Message); return 1; } } // wait for the LabVIEW application to connect to the cli connected = lvInterface.waitOnConnection(options.timeout); // if timed out, kill LabVIEW and exit with error code if (!connected && launcher!=null) { output.writeError("Connection to LabVIEW timed out!"); launcher.Kill(); launcher.Exited -= Launcher_Exited; return 1; } do { latestMessage = lvInterface.readMessage(); switch (latestMessage.messageType) { case "OUTP": Console.Write(latestMessage.messageData); break; case "EXIT": exitCode = lvInterface.extractExitCode(latestMessage.messageData); output.writeMessage("Recieved Exit Code " + exitCode); stop = true; break; case "RDER": exitCode = 1; output.writeError("Read Error"); stop = true; break; default: output.writeError("Unknown Message Type Recieved:" + latestMessage.messageType); break; } } while (!stop); lvInterface.Close(); return exitCode; } private static void Launcher_Exited(object sender, EventArgs e) { // Just quit by force if the tcp connection was not established or if LabVIEW exited without sending "EXIT" or "RDER" if (!connected || !stop) { Output output = Output.Instance; output.writeError("LabVIEW terminated unexpectedly!"); Environment.Exit(1); } } private static void splitArguments(string[] args, out string[] cliArgs, out string[] lvArgs) { int splitterLocation = -1; for(int i = 0; i < args.Length; i++) { if(args[i] == "--") { splitterLocation = i; } } if(splitterLocation > 0) { cliArgs = args.Take(splitterLocation).ToArray(); lvArgs = args.Skip(splitterLocation + 1).ToArray(); } else { cliArgs = args; lvArgs = new string[0]; } } private static string lvPathFinder(CliOptions options) { if (options.lvExe != null) { if (!File.Exists(options.lvExe)) throw new FileNotFoundException("specified executable not found", options.lvExe); return options.lvExe; } if (options.lvVer != null) { try { return LvVersions.ResolveVersionString(options.lvVer, options.x64).ExePath; } catch(KeyNotFoundException ex) { throw; // So the exception makes it to the handler above. } } if (LvVersions.CurrentVersion != null) { return LvVersions.CurrentVersion.ExePath; } else { throw new FileNotFoundException("No LabVIEW.exe found...", "LabVIEW.exe"); } } } }
rose-a/LabVIEW-CLI
C Sharp Source/LabVIEW CLI/Program.cs
C#
bsd-2-clause
7,352
from celery.task import Task import requests class StracksFlushTask(Task): def run(self, url, data): requests.post(url + "/", data=data)
Stracksapp/stracks_api
stracks_api/tasks.py
Python
bsd-2-clause
152
/* * Ferox, a graphics and game library in Java * * Copyright (c) 2012, Michael Ludwig * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.ferox.math.bounds; import com.ferox.math.*; /** * <p/> * Frustum represents the mathematical construction of a frustum. It is described as a 6 sided convex hull, * where at least two planes are parallel to each other. It supports generating frustums that represent * perspective projections (a truncated pyramid), or orthographic projections (a rectangular prism). * <p/> * Each frustum has a direction vector and an up vector. These vectors define an orthonormal basis for the * frustum. The two parallel planes of the frustum are specified as distances along the direction vector (near * and far). The additional planes are computed based on the locations of the four corners of the near plane * intersection. * <p/> * The mapping from world space to frustum space is not as straight-forward as is implied by the above state. * Frustum provides the functionality to get the {@link #getProjectionMatrix() project matrix} and {@link * #getViewMatrix() modelview matrix} suitable for use in an OpenGL system. The camera within an OpenGL system * looks down its local negative z-axis. Thus the provided direction in this Frustum represents the negative * z-axis within camera space. * * @author Michael Ludwig */ public class Frustum { /** * Result of a frustum test against a {@link AxisAlignedBox}. */ public static enum FrustumIntersection { /** * Returned when a candidate object is fully enclosed by the Frustum. */ INSIDE, /** * Returned when a candidate object is completely outside of the Frustum. */ OUTSIDE, /** * Returned when a candidate object intersects the Frustum but is not completely contained. */ INTERSECT } public static final int NUM_PLANES = 6; public static final int NEAR_PLANE = 0; public static final int FAR_PLANE = 1; public static final int TOP_PLANE = 2; public static final int BOTTOM_PLANE = 3; public static final int LEFT_PLANE = 4; public static final int RIGHT_PLANE = 5; private boolean useOrtho; // local values private double frustumLeft; private double frustumRight; private double frustumTop; private double frustumBottom; private double frustumNear; private double frustumFar; // frustum orientation private final Vector3 up; private final Vector3 direction; private final Vector3 location; private final Matrix4 projection; private final Matrix4 view; // planes representing frustum, adjusted for // position, direction and up private final Vector4[] worldPlanes; // temporary vector used during intersection queries, saved to avoid allocation private final Vector3 temp; /** * Instantiate a new Frustum that's positioned at the origin, looking down the negative z-axis. The given * values are equivalent to those described in setPerspective() and are used for the initial frustum * parameters. * * @param fov * @param aspect * @param znear * @param zfar */ public Frustum(double fov, double aspect, double znear, double zfar) { this(); setPerspective(fov, aspect, znear, zfar); } /** * Instantiate a new Frustum that's positioned at the origin, looking down the negative z-axis. The six * values are equivalent to those specified in setFrustum() and are taken as the initial frustum * parameters. * * @param ortho True if the frustum values are for an orthographic projection, otherwise it's a * perspective projection * @param fl * @param fr * @param fb * @param ft * @param fn * @param ff */ public Frustum(boolean ortho, double fl, double fr, double fb, double ft, double fn, double ff) { this(); setFrustum(ortho, fl, fr, fb, ft, fn, ff); } // initialize everything private Frustum() { worldPlanes = new Vector4[6]; location = new Vector3(); up = new Vector3(0, 1, 0); direction = new Vector3(0, 0, -1); view = new Matrix4(); projection = new Matrix4(); temp = new Vector3(); } /** * Get the left edge of the near frustum plane. * * @return The left edge of the near frustum plane * * @see #setFrustum(boolean, double, double, double, double, double, double) */ public double getFrustumLeft() { return frustumLeft; } /** * Get the right edge of the near frustum plane. * * @return The right edge of the near frustum plane * * @see #setFrustum(boolean, double, double, double, double, double, double) */ public double getFrustumRight() { return frustumRight; } /** * Get the top edge of the near frustum plane. * * @return The top edge of the near frustum plane * * @see #setFrustum(boolean, double, double, double, double, double, double) */ public double getFrustumTop() { return frustumTop; } /** * Get the bottom edge of the near frustum plane. * * @return The bottom edge of the near frustum plane * * @see #setFrustum(boolean, double, double, double, double, double, double) */ public double getFrustumBottom() { return frustumBottom; } /** * Get the distance to the near frustum plane from the origin, in camera coords. * * @return The distance to the near frustum plane * * @see #setFrustum(boolean, double, double, double, double, double, double) */ public double getFrustumNear() { return frustumNear; } /** * Get the distance to the far frustum plane from the origin, in camera coords. * * @return The distance to the far frustum plane * * @see #setFrustum(boolean, double, double, double, double, double, double) */ public double getFrustumFar() { return frustumFar; } /** * <p/> * Sets the dimensions of the viewing frustum in camera coords. left, right, bottom, and top specify edges * of the rectangular near plane. This plane is positioned perpendicular to the viewing direction, a * distance near along the direction vector from the view's location. * <p/> * If this Frustum is using orthogonal projection, the frustum is a rectangular prism extending from this * near plane, out to an identically sized plane, that is distance far away. If not, the far plane is the * far extent of a pyramid with it's point at the location, truncated at the near plane. * * @param ortho True if the Frustum should use an orthographic projection * @param left The left edge of the near frustum plane * @param right The right edge of the near frustum plane * @param bottom The bottom edge of the near frustum plane * @param top The top edge of the near frustum plane * @param near The distance to the near frustum plane * @param far The distance to the far frustum plane * * @throws IllegalArgumentException if left > right, bottom > top, near > far, or near <= 0 when the view * isn't orthographic */ public void setFrustum(boolean ortho, double left, double right, double bottom, double top, double near, double far) { if (left > right || bottom > top || near > far) { throw new IllegalArgumentException("Frustum values would create an invalid frustum: " + left + " " + right + " x " + bottom + " " + top + " x " + near + " " + far); } if (near <= 0 && !ortho) { throw new IllegalArgumentException("Illegal value for near frustum when using perspective projection: " + near); } frustumLeft = left; frustumRight = right; frustumBottom = bottom; frustumTop = top; frustumNear = near; frustumFar = far; useOrtho = ortho; update(); } /** * Set the frustum to be perspective projection with the given field of view (in degrees). Widths and * heights are calculated using the assumed aspect ration and near and far values. Because perspective * transforms only make sense for non-orthographic projections, it also sets this view to be * non-orthographic. * * @param fov The field of view * @param aspect The aspect ratio of the view region (width / height) * @param near The distance from the view's location to the near camera plane * @param far The distance from the view's location to the far camera plane * * @throws IllegalArgumentException if fov is outside of (0, 180], or aspect is <= 0, or near > far, or if * near <= 0 */ public void setPerspective(double fov, double aspect, double near, double far) { if (fov <= 0f || fov > 180f) { throw new IllegalArgumentException("Field of view must be in (0, 180], not: " + fov); } if (aspect <= 0) { throw new IllegalArgumentException("Aspect ration must be >= 0, not: " + aspect); } double h = Math.tan(Math.toRadians(fov * .5f)) * near; double w = h * aspect; setFrustum(false, -w, w, -h, h, near, far); } /** * Set the frustum to be an orthographic projection that uses the given boundary edges for the near * frustum plane. The near value is set to -1, and the far value is set to 1. * * @param left * @param right * @param bottom * @param top * * @throws IllegalArgumentException if left > right or bottom > top * @see #setFrustum(boolean, double, double, double, double, double, double) */ public void setOrtho(double left, double right, double bottom, double top) { setFrustum(true, left, right, bottom, top, -1f, 1f); } /** * Whether or not this view uses a perspective or orthogonal projection. * * @return True if the projection matrix is orthographic */ public boolean isOrthogonalProjection() { return useOrtho; } /** * <p/> * Get the location vector of this view, in world space. The returned vector is read-only. Modifications * to the frustum's view parameters must be done through {@link #setOrientation(Vector3, Vector3, * Vector3)}. * * @return The location of the view */ public @Const Vector3 getLocation() { return location; } /** * <p/> * Get the up vector of this view, in world space. Together up and direction form a right-handed * coordinate system. The returned vector is read-only. Modifications to the frustum's view parameters * must be done through {@link #setOrientation(Vector3, Vector3, Vector3)}. * * @return The up vector of this view */ public @Const Vector3 getUp() { return up; } /** * <p/> * Get the direction vector of this frustum, in world space. Together up and direction form a right-handed * coordinate system. The returned vector is read-only. Modifications to the frustum's view parameters * must be done through {@link #setOrientation(Vector3, Vector3, Vector3)}. * * @return The current direction that this frustum is pointing */ public @Const Vector3 getDirection() { return direction; } /** * Compute and return the field of view along the vertical axis that this Frustum uses. This is * meaningless for an orthographic projection, and returns -1 in that case. Otherwise, an angle in degrees * is returned in the range 0 to 180. This works correctly even when the bottom and top edges of the * Frustum are not centered about its location. * * @return The field of view of this Frustum */ public double getFieldOfView() { if (useOrtho) { return -1f; } double fovTop = Math.atan(frustumTop / frustumNear); double fovBottom = Math.atan(frustumBottom / frustumNear); return Math.toDegrees(fovTop - fovBottom); } /** * <p/> * Return the 4x4 projection matrix that represents the mathematical projection from the frustum to * homogenous device coordinates (essentially the unit cube). * <p/> * <p/> * The returned matrix is read-only and will be updated automatically as the projection of the Frustum * changes. * * @return The projection matrix */ public @Const Matrix4 getProjectionMatrix() { return projection; } /** * <p/> * Return the 'view' transform of this Frustum. The view transform represents the coordinate space * transformation from world space to camera/frustum space. The local basis of the Frustum is formed by * the left, up and direction vectors of the Frustum. The left vector is <code>up X direction</code>, and * up and direction are user defined vectors. * <p/> * The returned matrix is read-only and will be updated automatically as {@link #setOrientation(Vector3, * Vector3, Vector3)} is invoked. * * @return The view matrix */ public @Const Matrix4 getViewMatrix() { return view; } /** * <p/> * Copy the given vectors into this Frustum for its location, direction and up vectors. The orientation is * then normalized and orthogonalized, but the provided vectors are unmodified. * <p/> * Any later changes to the vectors' x, y, and z values will not be reflected in the frustum planes or * view transform, unless this method is called again. * * @param location The new location vector * @param direction The new direction vector * @param up The new up vector * * @throws NullPointerException if location, direction or up is null */ public void setOrientation(@Const Vector3 location, @Const Vector3 direction, @Const Vector3 up) { if (location == null || direction == null || up == null) { throw new NullPointerException("Orientation vectors cannot be null: " + location + " " + direction + " " + up); } this.location.set(location); this.direction.set(direction); this.up.set(up); update(); } /** * Set the orientation of this Frustum based on the affine <var>transform</var>. The 4th column's first 3 * values encode the transformation. The 3rd column holds the direction vector, and the 2nd column defines * the up vector. * * @param transform The new transform of the frustum * * @throws NullPointerException if transform is null */ public void setOrientation(@Const Matrix4 transform) { if (transform == null) { throw new NullPointerException("Transform cannot be null"); } this.location.set(transform.m03, transform.m13, transform.m23); this.direction.set(transform.m02, transform.m12, transform.m22); this.up.set(transform.m01, transform.m11, transform.m21); update(); } /** * Set the orientation of this Frustum based on the given location vector and 3x3 rotation matrix. * Together the vector and rotation represent an affine transform that is treated the same as in {@link * #setOrientation(Matrix4)}. * * @param location The location of the frustum * @param rotation The rotation of the frustum * * @throws NullPointerException if location or rotation are null */ public void setOrientation(@Const Vector3 location, @Const Matrix3 rotation) { if (location == null) { throw new NullPointerException("Location cannot be null"); } if (rotation == null) { throw new NullPointerException("Rotation matrix cannot be null"); } this.location.set(location); this.direction.set(rotation.m02, rotation.m12, rotation.m22); this.up.set(rotation.m01, rotation.m11, rotation.m21); update(); } /** * <p/> * Return a plane representing the given plane of the view frustum, in world coordinates. This plane * should not be modified. The returned plane's normal is configured so that it points into the center of * the Frustum. The returned {@link Vector4} is encoded as a plane as defined in {@link Plane}; it is also * normalized. * <p/> * <p/> * The returned plane vector is read-only. It will be updated automatically when the projection or view * parameters change. * * @param i The requested plane index * * @return The ReadOnlyVector4f instance for the requested plane, in world coordinates * * @throws IndexOutOfBoundsException if plane isn't in [0, 5] */ public @Const Vector4 getFrustumPlane(int i) { return worldPlanes[i]; } /** * <p/> * Compute and return the intersection of the AxisAlignedBox and this Frustum, <var>f</var>. It is assumed * that the Frustum and AxisAlignedBox exist in the same coordinate frame. {@link * FrustumIntersection#INSIDE} is returned when the AxisAlignedBox is fully contained by the Frustum. * {@link FrustumIntersection#INTERSECT} is returned when this box is partially contained by the Frustum, * and {@link FrustumIntersection#OUTSIDE} is returned when the box has no intersection with the Frustum. * <p/> * If <var>OUTSIDE</var> is returned, it is guaranteed that the objects enclosed by the bounds do not * intersect the Frustum. If <var>INSIDE</var> is returned, any object {@link * AxisAlignedBox#contains(AxisAlignedBox) contained} by the box will also be completely inside the * Frustum. When <var>INTERSECT</var> is returned, there is a chance that the true representation of the * objects enclosed by the box will be outside of the Frustum, but it is unlikely. This can occur when a * corner of the box intersects with the planes of <var>f</var>, but the shape does not exist in that * corner. * <p/> * The argument <var>planeState</var> can be used to hint to this function which planes of the Frustum * require checking and which do not. When a hierarchy of bounds is used, the planeState can be used to * remove unnecessary plane comparisons. If <var>planeState</var> is null it is assumed that all planes * need to be checked. If <var>planeState</var> is not null, this method will mark any plane that the box * is completely inside of as not requiring a comparison. It is the responsibility of the caller to save * and restore the plane state as needed based on the structure of the bound hierarchy. * * @param bounds The bounds to test for intersection with this frustm * @param planeState An optional PlaneState hint specifying which planes to check * * @return A FrustumIntersection indicating how the frustum and bounds intersect * * @throws NullPointerException if bounds is null */ public FrustumIntersection intersects(@Const AxisAlignedBox bounds, PlaneState planeState) { if (bounds == null) { throw new NullPointerException("Bounds cannot be null"); } // early escape for potentially deeply nested nodes in a tree if (planeState != null && !planeState.getTestsRequired()) { return FrustumIntersection.INSIDE; } FrustumIntersection result = FrustumIntersection.INSIDE; double distMax; double distMin; int plane = 0; Vector4 p; for (int i = Frustum.NUM_PLANES - 1; i >= 0; i--) { if (planeState == null || planeState.isTestRequired(i)) { p = getFrustumPlane(plane); // set temp to the normal of the plane then compute the extent // in-place; this is safe but we'll have to reset temp to the // normal later if needed temp.set(p.x, p.y, p.z).farExtent(bounds, temp); distMax = Plane.getSignedDistance(p, temp, true); if (distMax < 0) { // the point closest to the plane is behind the plane, so // we know the bounds must be outside of the frustum return FrustumIntersection.OUTSIDE; } else { // the point closest to the plane is in front of the plane, // but we need to check the farthest away point // make sure to reset temp to the normal before computing // the near extent in-place temp.set(p.x, p.y, p.z).nearExtent(bounds, temp); distMin = Plane.getSignedDistance(p, temp, true); if (distMin < 0) { // the farthest point is behind the plane, so at best // this box will be intersecting the frustum result = FrustumIntersection.INTERSECT; } else { // the box is completely contained by the plane, so // the return result can be INSIDE or INTERSECT (if set by another plane) if (planeState != null) { planeState.setTestRequired(plane, false); } } } } } return result; } /* * Update the plane instances returned by getFrustumPlane() to reflect any * changes to the frustum's local parameters or orientation. Also update the * view transform and projection matrix. */ private void update() { // compute the right-handed basis vectors of the frustum Vector3 n = new Vector3().scale(direction.normalize(), -1); // normalizes direction as well Vector3 u = new Vector3().cross(up, n).normalize(); Vector3 v = up.cross(n, u).normalize(); // recompute up to properly orthogonal to direction // view matrix view.set(u.x, u.y, u.z, -location.dot(u), v.x, v.y, v.z, -location.dot(v), n.x, n.y, n.z, -location.dot(n), 0f, 0f, 0f, 1f); // projection matrix if (useOrtho) { projection.set(2 / (frustumRight - frustumLeft), 0, 0, -(frustumRight + frustumLeft) / (frustumRight - frustumLeft), 0, 2 / (frustumTop - frustumBottom), 0, -(frustumTop + frustumBottom) / (frustumTop - frustumBottom), 0, 0, 2 / (frustumNear - frustumFar), -(frustumFar + frustumNear) / (frustumFar - frustumNear), 0, 0, 0, 1); } else { projection.set(2 * frustumNear / (frustumRight - frustumLeft), 0, (frustumRight + frustumLeft) / (frustumRight - frustumLeft), 0, 0, 2 * frustumNear / (frustumTop - frustumBottom), (frustumTop + frustumBottom) / (frustumTop - frustumBottom), 0, 0, 0, -(frustumFar + frustumNear) / (frustumFar - frustumNear), -2 * frustumFar * frustumNear / (frustumFar - frustumNear), 0, 0, -1, 0); } // generate world-space frustum planes, we pass in n and u since we // created them to compute the view matrix and they're just garbage // at this point, might as well let plane generation reuse them. if (useOrtho) { computeOrthoWorldPlanes(n, u); } else { computePerspectiveWorldPlanes(n, u); } } private void computeOrthoWorldPlanes(Vector3 n, Vector3 p) { // FAR p.scale(direction, frustumFar).add(location); n.scale(direction, -1); setWorldPlane(FAR_PLANE, n, p); // NEAR p.scale(direction, frustumNear).add(location); n.set(direction); setWorldPlane(NEAR_PLANE, n, p); // compute right vector for LEFT and RIGHT usage n.cross(direction, up); // LEFT p.scale(n, frustumLeft).add(location); setWorldPlane(LEFT_PLANE, n, p); // RIGHT p.scale(n, frustumRight).add(location); n.scale(-1); setWorldPlane(RIGHT_PLANE, n, p); // BOTTOM p.scale(up, frustumBottom).add(location); setWorldPlane(BOTTOM_PLANE, up, p); // TOP n.scale(up, -1); p.scale(up, frustumTop).add(location); setWorldPlane(TOP_PLANE, n, p); } private void computePerspectiveWorldPlanes(Vector3 n, Vector3 p) { // FAR p.scale(direction, frustumFar).add(location); p.scale(direction, -1); setWorldPlane(FAR_PLANE, n, p); // NEAR p.scale(direction, frustumNear).add(location); n.set(direction); setWorldPlane(NEAR_PLANE, n, p); // compute left vector for LEFT and RIGHT usage p.cross(up, direction); // LEFT double invHyp = 1 / Math.sqrt(frustumNear * frustumNear + frustumLeft * frustumLeft); n.scale(direction, Math.abs(frustumLeft) / frustumNear).sub(p).scale(frustumNear * invHyp); setWorldPlane(LEFT_PLANE, n, location); // RIGHT invHyp = 1 / Math.sqrt(frustumNear * frustumNear + frustumRight * frustumRight); n.scale(direction, Math.abs(frustumRight) / frustumNear).add(p).scale(frustumNear * invHyp); setWorldPlane(RIGHT_PLANE, n, location); // BOTTOM invHyp = 1 / Math.sqrt(frustumNear * frustumNear + frustumBottom * frustumBottom); n.scale(direction, Math.abs(frustumBottom) / frustumNear).add(up).scale(frustumNear * invHyp); setWorldPlane(BOTTOM_PLANE, n, location); // TOP invHyp = 1 / Math.sqrt(frustumNear * frustumNear + frustumTop * frustumTop); n.scale(direction, Math.abs(frustumTop) / frustumNear).sub(up).scale(frustumNear * invHyp); setWorldPlane(TOP_PLANE, n, location); } // set the given world plane so it's a plane with the given normal // that passes through pos, and then normalize it private void setWorldPlane(int plane, @Const Vector3 normal, @Const Vector3 pos) { setWorldPlane(plane, normal.x, normal.y, normal.z, -normal.dot(pos)); } // set the given world plane, with the 4 values, and then normalize it private void setWorldPlane(int plane, double a, double b, double c, double d) { Vector4 cp = worldPlanes[plane]; if (cp == null) { cp = new Vector4(a, b, c, d); worldPlanes[plane] = cp; } else { cp.set(a, b, c, d); } Plane.normalize(cp); } }
geronimo-iia/ferox
ferox-math/src/main/java/com/ferox/math/bounds/Frustum.java
Java
bsd-2-clause
28,685
var files = [ [ "Code", "dir_a44bec13de8698b1b3f25058862347f8.html", "dir_a44bec13de8698b1b3f25058862347f8" ] ];
crurik/GrapeFS
Doxygen/html/files.js
JavaScript
bsd-2-clause
116
package cocoonClient.Panels; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.event.ListSelectionEvent; import javax.swing.table.DefaultTableModel; import JSONTransmitProtocol.newReader.JSONReader; import cocoonClient.Connector.AbstractConnector; import cocoonClient.Data.UserInfo; public class StatusPanel extends CocoonDisplayPanel implements AbstractConnector{ private JTable table; public StatusPanel(){ super(UserInfo.getMainFrame()); setRightPanel(new TestRightPanel()); this.setSize(600, 500); this.setLayout(new FlowLayout()); init(); UserInfo.getPanels().put("Status", this); } private void init() { try{ //Table//以Model物件宣告建立表格的JTable元件 table = new JTable(){ public void valueChanged(ListSelectionEvent e){ super.valueChanged(e); //呼叫基礎類別的valueChanged()方法, 否則選取動作無法正常執行 if( table.getSelectedRow() == -1) return;//取得表格目前的選取列,若沒有選取列則終止執行方法 } }; table.setModel(new DefaultTableModel(){ @Override public boolean isCellEditable(int row, int column){ return false; } }); table.setShowGrid(true); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.setSelectionBackground(Color.ORANGE);//設定選取背景顏色 table.setCellSelectionEnabled(true); //設定允許儲存格選取 //取得處理表格資料的Model物件,建立關聯 DefaultTableModel dtm = (DefaultTableModel)table.getModel(); //宣告處理表格資料的TableModel物件 String columnTitle[] = new String[]{"Date", "Username", "Problem", "Status"}; int columnWidth[] = new int[]{150, 120, 190, 120}; for(int i = 0; i < columnTitle.length; i++){ dtm.addColumn(columnTitle[i]); } for(int i = 0; i < columnWidth.length; i++){ //欄寬設定 table.getColumnModel().getColumn(i).setPreferredWidth(columnWidth[i]); } //註冊回應JTable元件的MouseEvent事件的監聽器物件 /* table.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent e){ int selRow = table.rowAtPoint(e.getPoint());//取得滑鼠點選位置所在之資料的列索引 String Size = (String) table.getValueAt(selRow, 2); //取得被點選資料列的第3欄的值 if (Integer.parseInt(Size)> 0 ){ } } });*/ }catch ( Exception e){ e.printStackTrace(); } JScrollPane pane = new JScrollPane(table); pane.setPreferredSize(new Dimension(600, 450)); add(pane); } private void addStatus(String response){ JSONReader reader = new JSONReader(response); DefaultTableModel dtm = (DefaultTableModel)table.getModel(); String result = ""; try{ result = reader.getSubmission().getResult().split("\n")[0]; } catch(Exception e){} dtm.addRow(new String[] { reader.getSubmission().getTime(), reader.getSubmission().getUsername(), UserInfo.getProblemSet().getProblemName(reader.getSubmission().getPID()), result }); } @Override public void recieveResponse(String response) { addStatus(response); } }
hydai/Cocoon
Cocoon/src/cocoonClient/Panels/StatusPanel.java
Java
bsd-2-clause
3,759
package de.lman; import de.lman.engine.Colors; import de.lman.engine.Game; import de.lman.engine.InputState; import de.lman.engine.Keys; import de.lman.engine.Mouse; import de.lman.engine.math.Mat2f; import de.lman.engine.math.Scalar; import de.lman.engine.math.Transform; import de.lman.engine.math.Vec2f; import de.lman.engine.physics.Body; import de.lman.engine.physics.ContactStatePair; import de.lman.engine.physics.GeometryUtils; import de.lman.engine.physics.Physics; import de.lman.engine.physics.contacts.Contact; import de.lman.engine.physics.contacts.ContactListener; import de.lman.engine.physics.shapes.BoxShape; import de.lman.engine.physics.shapes.EdgeShape; import de.lman.engine.physics.shapes.PhysicsMaterial; import de.lman.engine.physics.shapes.PlaneShape; import de.lman.engine.physics.shapes.PolygonShape; import de.lman.engine.physics.shapes.Shape; /* Probleme lösen: - Linien-Zeichnen korrigieren Aufgaben: - Tastatureingaben robuster machen (ist gedrückt, war gedrückt) - Bitmap laden, konvertieren und zeichnen - Bitmap transformiert zeichnen (Rotation) - Bitmap fonts generieren - Bitmap fonts zeichnen - Bitmap Bilinär filtern - Debug Informationen - Fps / Framedauer anzeigen - Zeitmessungen - Speichern für mehrere Frames - Visualisierung (Bar, Line) - UI - Panel - Button - Label - Checkbox - Radiobutton - Sensor-Flag für Shape - ECS - Integrierter-Level-Editor - Skalierung - Propertionales vergrößern von Seiten - Verschiebung von Eckpunkten - Löschen - Kopieren / Einfügen - Gitter-Snap - Mehrere Shapetypen + Auswahlmöglichkeit: - Kreis - Linien-Segment - Polygone - Boxen - Ebenen - Laden / Speichern - Körper & Formen serialisieren und deserialisieren (JSON) - Rotationsdynamik: - Kreuzprodukt - updateAABB in Body robuster machen - getSupportPoints vereinfachen / robuster machen - Massenzentrum (COM) - Traegheitsmoment (Inertia, AngularVelocity) - Kontaktausschnitt - Asset-Management - Preloading - Erstellung von Kontakt-Szenarien vereinfachen -> offset() */ public class Leverman extends Game implements ContactListener { public Leverman() { super("Leverman"); } public static void main(String[] args) { Leverman game = new Leverman(); game.run(); } private Physics physics; private boolean showContacts = true; private boolean showAABBs = false; private boolean physicsSingleStep = false; public final static PhysicsMaterial MAT_STATIC = new PhysicsMaterial(0f, 0.1f); public final static PhysicsMaterial MAT_DYNAMIC = new PhysicsMaterial(1f, 0.1f); private Body playerBody; private boolean playerOnGround = false; private boolean playerJumping = false; private int playerGroundHash = 0; private final Vec2f groundNormal = new Vec2f(0, 1); @Override public void physicsBeginContact(int hash, ContactStatePair pair) { Contact contact = pair.pair.contacts[pair.contactIndex]; Vec2f normal = contact.normal; Body player = null; if (pair.pair.a.id == playerBody.id) { player = pair.pair.a; normal = new Vec2f(contact.normal).invert(); } else if (pair.pair.b.id == playerBody.id) { player = pair.pair.b; } float d = normal.dot(groundNormal); if (d > 0) { if (player != null && (!playerOnGround)) { playerOnGround = true; playerGroundHash = hash; } } } @Override public void physicsEndContact(int hash, ContactStatePair pair) { Contact contact = pair.pair.contacts[pair.contactIndex]; Vec2f normal = contact.normal; Body player = null; if (pair.pair.a.id == playerBody.id) { player = pair.pair.a; normal = new Vec2f(contact.normal).invert(); } else if (pair.pair.b.id == playerBody.id) { player = pair.pair.b; } float d = normal.dot(groundNormal); if (d > 0) { if (player != null && playerOnGround && (playerGroundHash == hash)) { playerOnGround = false; playerGroundHash = 0; } } } private void addPlatform(float x, float y, float rx, float ry) { Body body; physics.addBody(body = new Body().addShape(new BoxShape(new Vec2f(rx, ry)).setMaterial(MAT_STATIC))); body.pos.set(x, y); } private void addBox(float x, float y, float rx, float ry) { Body body; physics.addBody(body = new Body().addShape(new BoxShape(new Vec2f(rx, ry)).setMaterial(MAT_DYNAMIC))); body.pos.set(x, y); } protected void initGame() { physics = new Physics(this); physics.enableSingleStepMode(physicsSingleStep); Body body; physics.addBody(body = new Body().addShape(new PlaneShape(viewport.y).rotation(Scalar.PI * 0f).setMaterial(MAT_STATIC))); body.pos.set(-halfWidth + 0.5f, 0); physics.addBody(body = new Body().addShape(new PlaneShape(viewport.y).rotation(Scalar.PI * 1f).setMaterial(MAT_STATIC))); body.pos.set(halfWidth - 0.5f, 0); physics.addBody(body = new Body().addShape(new PlaneShape(viewport.x).rotation(Scalar.PI * 0.5f).setMaterial(MAT_STATIC))); body.pos.set(0, -halfHeight + 0.5f); physics.addBody(body = new Body().addShape(new PlaneShape(viewport.x).rotation(Scalar.PI * 1.5f).setMaterial(MAT_STATIC))); body.pos.set(0, halfHeight - 0.5f); addPlatform(0 - 2.9f, 0 - 2.0f, 0.6f, 0.1f); addPlatform(0, 0 - 1.3f, 0.7f, 0.1f); addPlatform(0 + 2.9f, 0 - 0.8f, 0.6f, 0.1f); //addBox(0, -0.5f, 0.2f, 0.2f); addPlatform(0 + 2.0f, -halfHeight + 0.2f + 0.5f, 0.2f, 0.2f); addPlatform(0 + 2.4f, -halfHeight + 0.2f + 0.5f, 0.2f, 0.2f); addPlatform(0 + 2.8f, -halfHeight + 0.2f + 0.5f, 0.2f, 0.2f); addPlatform(0 + 3.2f, -halfHeight + 0.2f + 0.5f, 0.2f, 0.2f); playerBody = new Body(); BoxShape playerBox = (BoxShape) new BoxShape(new Vec2f(0.2f, 0.4f)).setMaterial(MAT_DYNAMIC); playerBody.addShape(playerBox); playerBody.pos.set(0, -halfHeight + playerBox.radius.y + 0.5f); physics.addBody(playerBody); Vec2f[] polyVerts = new Vec2f[]{ new Vec2f(0, 0.5f), new Vec2f(-0.5f, -0.5f), new Vec2f(0.5f, -0.5f), }; physics.addBody(body = new Body().addShape(new PolygonShape(polyVerts).setMaterial(MAT_STATIC))); body.pos.set(0, 0); } private boolean dragging = false; private Vec2f dragStart = new Vec2f(); private Body dragBody = null; private void updateGameInput(float dt, InputState inputState) { boolean leftMousePressed = inputState.isMouseDown(Mouse.LEFT); if (!dragging) { if (leftMousePressed) { dragBody = null; for (int i = 0; i < physics.numBodies; i++) { Body body = physics.bodies[i]; if (body.invMass > 0) { if (GeometryUtils.isPointInAABB(inputState.mousePos.x, inputState.mousePos.y, body.aabb)) { dragging = true; dragStart.set(inputState.mousePos); dragBody = body; break; } } } } } else { if (leftMousePressed) { float dx = inputState.mousePos.x - dragStart.x; float dy = inputState.mousePos.y - dragStart.y; dragBody.vel.x += dx * 0.1f; dragBody.vel.y += dy * 0.1f; dragStart.set(inputState.mousePos); } else { dragging = false; } } // Kontakte ein/ausschalten if (inputState.isKeyDown(Keys.F2)) { showContacts = !showContacts; inputState.setKeyDown(Keys.F2, false); } // AABBs ein/ausschalten if (inputState.isKeyDown(Keys.F3)) { showAABBs = !showAABBs; inputState.setKeyDown(Keys.F3, false); } // Einzelschritt-Physik-Modus ein/ausschalten if (inputState.isKeyDown(Keys.F5)) { physicsSingleStep = !physicsSingleStep; physics.enableSingleStepMode(physicsSingleStep); inputState.setKeyDown(Keys.F5, false); } if (inputState.isKeyDown(Keys.F6)) { if (physicsSingleStep) { physics.nextStep(); } inputState.setKeyDown(Keys.F6, false); } // Player bewegen if (inputState.isKeyDown(Keys.W)) { if (!playerJumping && playerOnGround) { playerBody.acc.y += 4f / dt; playerJumping = true; } } else { if (playerJumping && playerOnGround) { playerJumping = false; } } if (inputState.isKeyDown(Keys.A)) { playerBody.acc.x -= 0.1f / dt; } else if (inputState.isKeyDown(Keys.D)) { playerBody.acc.x += 0.1f / dt; } } private final Editor editor = new Editor(); private boolean editorWasShownAABB = false; protected void updateInput(float dt, InputState input) { // Editormodus ein/ausschalten if (input.isKeyDown(Keys.F4)) { editor.active = !editor.active; if (editor.active) { editorWasShownAABB = showAABBs; showAABBs = true; editor.init(physics); } else { showAABBs = editorWasShownAABB; } input.setKeyDown(Keys.F4, false); } if (editor.active) { editor.updateInput(dt, physics, input); } else { updateGameInput(dt, input); } } @Override protected String getAdditionalTitle() { return String.format(" [Frames: %d, Bodies: %d, Contacts: %d]", numFrames, physics.numBodies, physics.numContacts); } protected void updateGame(float dt) { if (!editor.active) { physics.step(dt); } } private void renderEditor(float dt) { // TODO: Move to editor class clear(0x000000); for (int i = 0; i < viewport.x / Editor.GRID_SIZE; i++) { drawLine(-halfWidth + i * Editor.GRID_SIZE, -halfHeight, -halfWidth + i * Editor.GRID_SIZE, halfHeight, Colors.DarkSlateGray); } for (int i = 0; i < viewport.y / Editor.GRID_SIZE; i++) { drawLine(-halfWidth, -halfHeight + i * Editor.GRID_SIZE, halfWidth, -halfHeight + i * Editor.GRID_SIZE, Colors.DarkSlateGray); } drawBodies(physics.numBodies, physics.bodies); if (editor.selectedBody != null) { Editor.DragSide[] dragSides = editor.getDragSides(editor.selectedBody); Shape shape = editor.selectedBody.shapes[0]; if (dragSides.length > 0 && shape instanceof EdgeShape) { EdgeShape edgeShape = (EdgeShape) shape; Transform t = new Transform(shape.localPos, shape.localRotation).offset(editor.selectedBody.pos); Vec2f[] localVertices = edgeShape.getLocalVertices(); for (int i = 0; i < dragSides.length; i++) { Vec2f dragPoint = dragSides[i].center; drawPoint(dragPoint, Editor.DRAGPOINT_RADIUS, Colors.White); if (editor.resizeSideIndex == i) { Vec2f v0 = new Vec2f(localVertices[dragSides[i].index0]).transform(t); Vec2f v1 = new Vec2f(localVertices[dragSides[i].index1]).transform(t); drawPoint(v0, Editor.DRAGPOINT_RADIUS, Colors.GoldenRod); drawPoint(v1, Editor.DRAGPOINT_RADIUS, Colors.GoldenRod); } } } Mat2f mat = new Mat2f(shape.localRotation).transpose(); drawNormal(editor.selectedBody.pos, mat.col1, DEFAULT_ARROW_RADIUS, DEFAULT_ARROW_LENGTH, Colors.Red); } drawPoint(inputState.mousePos.x, inputState.mousePos.y, DEFAULT_POINT_RADIUS, 0x0000FF); } private void renderInternalGame(float dt) { clear(0x000000); drawBodies(physics.numBodies, physics.bodies); if (showAABBs) { drawAABBs(physics.numBodies, physics.bodies); } if (showContacts) { drawContacts(dt, physics.numPairs, physics.pairs, false, true); } } protected void renderGame(float dt) { if (editor.active) { renderEditor(dt); } else { renderInternalGame(dt); } } }
f1nalspace/leverman-devlog
lman/src/de/lman/Leverman.java
Java
bsd-2-clause
11,052
package org.jvnet.jaxb2_commons.plugin.mergeable; import java.util.Arrays; import java.util.Collection; import javax.xml.namespace.QName; import org.jvnet.jaxb2_commons.lang.JAXBMergeStrategy; import org.jvnet.jaxb2_commons.lang.MergeFrom2; import org.jvnet.jaxb2_commons.lang.MergeStrategy2; import org.jvnet.jaxb2_commons.locator.ObjectLocator; import org.jvnet.jaxb2_commons.locator.util.LocatorUtils; import org.jvnet.jaxb2_commons.plugin.AbstractParameterizablePlugin; import org.jvnet.jaxb2_commons.plugin.Customizations; import org.jvnet.jaxb2_commons.plugin.CustomizedIgnoring; import org.jvnet.jaxb2_commons.plugin.Ignoring; import org.jvnet.jaxb2_commons.plugin.util.FieldOutlineUtils; import org.jvnet.jaxb2_commons.plugin.util.StrategyClassUtils; import org.jvnet.jaxb2_commons.util.ClassUtils; import org.jvnet.jaxb2_commons.util.FieldAccessorFactory; import org.jvnet.jaxb2_commons.util.PropertyFieldAccessorFactory; import org.jvnet.jaxb2_commons.xjc.outline.FieldAccessorEx; import org.xml.sax.ErrorHandler; import com.sun.codemodel.JBlock; import com.sun.codemodel.JCodeModel; import com.sun.codemodel.JConditional; import com.sun.codemodel.JDefinedClass; import com.sun.codemodel.JExpr; import com.sun.codemodel.JExpression; import com.sun.codemodel.JMethod; import com.sun.codemodel.JMod; import com.sun.codemodel.JOp; import com.sun.codemodel.JType; import com.sun.codemodel.JVar; import com.sun.tools.xjc.Options; import com.sun.tools.xjc.outline.ClassOutline; import com.sun.tools.xjc.outline.FieldOutline; import com.sun.tools.xjc.outline.Outline; public class MergeablePlugin extends AbstractParameterizablePlugin { @Override public String getOptionName() { return "Xmergeable"; } @Override public String getUsage() { return "TBD"; } private FieldAccessorFactory fieldAccessorFactory = PropertyFieldAccessorFactory.INSTANCE; public FieldAccessorFactory getFieldAccessorFactory() { return fieldAccessorFactory; } public void setFieldAccessorFactory( FieldAccessorFactory fieldAccessorFactory) { this.fieldAccessorFactory = fieldAccessorFactory; } private String mergeStrategyClass = JAXBMergeStrategy.class.getName(); public void setMergeStrategyClass(final String mergeStrategyClass) { this.mergeStrategyClass = mergeStrategyClass; } public String getMergeStrategyClass() { return mergeStrategyClass; } public JExpression createMergeStrategy(JCodeModel codeModel) { return StrategyClassUtils.createStrategyInstanceExpression(codeModel, MergeStrategy2.class, getMergeStrategyClass()); } private Ignoring ignoring = new CustomizedIgnoring( org.jvnet.jaxb2_commons.plugin.mergeable.Customizations.IGNORED_ELEMENT_NAME, Customizations.IGNORED_ELEMENT_NAME, Customizations.GENERATED_ELEMENT_NAME); public Ignoring getIgnoring() { return ignoring; } public void setIgnoring(Ignoring ignoring) { this.ignoring = ignoring; } @Override public Collection<QName> getCustomizationElementNames() { return Arrays .asList(org.jvnet.jaxb2_commons.plugin.mergeable.Customizations.IGNORED_ELEMENT_NAME, Customizations.IGNORED_ELEMENT_NAME, Customizations.GENERATED_ELEMENT_NAME); } @Override public boolean run(Outline outline, Options opt, ErrorHandler errorHandler) { for (final ClassOutline classOutline : outline.getClasses()) if (!getIgnoring().isIgnored(classOutline)) { processClassOutline(classOutline); } return true; } protected void processClassOutline(ClassOutline classOutline) { final JDefinedClass theClass = classOutline.implClass; ClassUtils ._implements(theClass, theClass.owner().ref(MergeFrom2.class)); @SuppressWarnings("unused") final JMethod mergeFrom$mergeFrom0 = generateMergeFrom$mergeFrom0( classOutline, theClass); @SuppressWarnings("unused") final JMethod mergeFrom$mergeFrom = generateMergeFrom$mergeFrom( classOutline, theClass); if (!classOutline.target.isAbstract()) { @SuppressWarnings("unused") final JMethod createCopy = generateMergeFrom$createNewInstance( classOutline, theClass); } } protected JMethod generateMergeFrom$mergeFrom0( final ClassOutline classOutline, final JDefinedClass theClass) { JCodeModel codeModel = theClass.owner(); final JMethod mergeFrom$mergeFrom = theClass.method(JMod.PUBLIC, codeModel.VOID, "mergeFrom"); mergeFrom$mergeFrom.annotate(Override.class); { final JVar left = mergeFrom$mergeFrom.param(Object.class, "left"); final JVar right = mergeFrom$mergeFrom.param(Object.class, "right"); final JBlock body = mergeFrom$mergeFrom.body(); final JVar mergeStrategy = body.decl(JMod.FINAL, codeModel.ref(MergeStrategy2.class), "strategy", createMergeStrategy(codeModel)); body.invoke("mergeFrom").arg(JExpr._null()).arg(JExpr._null()) .arg(left).arg(right).arg(mergeStrategy); } return mergeFrom$mergeFrom; } protected JMethod generateMergeFrom$mergeFrom(ClassOutline classOutline, final JDefinedClass theClass) { final JCodeModel codeModel = theClass.owner(); final JMethod mergeFrom = theClass.method(JMod.PUBLIC, codeModel.VOID, "mergeFrom"); mergeFrom.annotate(Override.class); { final JVar leftLocator = mergeFrom.param(ObjectLocator.class, "leftLocator"); final JVar rightLocator = mergeFrom.param(ObjectLocator.class, "rightLocator"); final JVar left = mergeFrom.param(Object.class, "left"); final JVar right = mergeFrom.param(Object.class, "right"); final JVar mergeStrategy = mergeFrom.param(MergeStrategy2.class, "strategy"); final JBlock methodBody = mergeFrom.body(); Boolean superClassImplementsMergeFrom = StrategyClassUtils .superClassImplements(classOutline, getIgnoring(), MergeFrom2.class); if (superClassImplementsMergeFrom == null) { } else if (superClassImplementsMergeFrom.booleanValue()) { methodBody.invoke(JExpr._super(), "mergeFrom").arg(leftLocator) .arg(rightLocator).arg(left).arg(right) .arg(mergeStrategy); } else { } final FieldOutline[] declaredFields = FieldOutlineUtils.filter( classOutline.getDeclaredFields(), getIgnoring()); if (declaredFields.length > 0) { final JBlock body = methodBody._if(right._instanceof(theClass)) ._then(); JVar target = body.decl(JMod.FINAL, theClass, "target", JExpr._this()); JVar leftObject = body.decl(JMod.FINAL, theClass, "leftObject", JExpr.cast(theClass, left)); JVar rightObject = body.decl(JMod.FINAL, theClass, "rightObject", JExpr.cast(theClass, right)); for (final FieldOutline fieldOutline : declaredFields) { final FieldAccessorEx leftFieldAccessor = getFieldAccessorFactory() .createFieldAccessor(fieldOutline, leftObject); final FieldAccessorEx rightFieldAccessor = getFieldAccessorFactory() .createFieldAccessor(fieldOutline, rightObject); if (leftFieldAccessor.isConstant() || rightFieldAccessor.isConstant()) { continue; } final JBlock block = body.block(); final JExpression leftFieldHasSetValue = (leftFieldAccessor .isAlwaysSet() || leftFieldAccessor.hasSetValue() == null) ? JExpr.TRUE : leftFieldAccessor.hasSetValue(); final JExpression rightFieldHasSetValue = (rightFieldAccessor .isAlwaysSet() || rightFieldAccessor.hasSetValue() == null) ? JExpr.TRUE : rightFieldAccessor.hasSetValue(); final JVar shouldBeSet = block.decl( codeModel.ref(Boolean.class), fieldOutline.getPropertyInfo().getName(false) + "ShouldBeMergedAndSet", mergeStrategy.invoke("shouldBeMergedAndSet") .arg(leftLocator).arg(rightLocator) .arg(leftFieldHasSetValue) .arg(rightFieldHasSetValue)); final JConditional ifShouldBeSetConditional = block._if(JOp .eq(shouldBeSet, codeModel.ref(Boolean.class) .staticRef("TRUE"))); final JBlock ifShouldBeSetBlock = ifShouldBeSetConditional ._then(); final JConditional ifShouldNotBeSetConditional = ifShouldBeSetConditional ._elseif(JOp.eq( shouldBeSet, codeModel.ref(Boolean.class).staticRef( "FALSE"))); final JBlock ifShouldBeUnsetBlock = ifShouldNotBeSetConditional ._then(); // final JBlock ifShouldBeIgnoredBlock = // ifShouldNotBeSetConditional // ._else(); final JVar leftField = ifShouldBeSetBlock.decl( leftFieldAccessor.getType(), "lhs" + fieldOutline.getPropertyInfo().getName( true)); leftFieldAccessor.toRawValue(ifShouldBeSetBlock, leftField); final JVar rightField = ifShouldBeSetBlock.decl( rightFieldAccessor.getType(), "rhs" + fieldOutline.getPropertyInfo().getName( true)); rightFieldAccessor.toRawValue(ifShouldBeSetBlock, rightField); final JExpression leftFieldLocator = codeModel .ref(LocatorUtils.class).staticInvoke("property") .arg(leftLocator) .arg(fieldOutline.getPropertyInfo().getName(false)) .arg(leftField); final JExpression rightFieldLocator = codeModel .ref(LocatorUtils.class).staticInvoke("property") .arg(rightLocator) .arg(fieldOutline.getPropertyInfo().getName(false)) .arg(rightField); final FieldAccessorEx targetFieldAccessor = getFieldAccessorFactory() .createFieldAccessor(fieldOutline, target); final JExpression mergedValue = JExpr.cast( targetFieldAccessor.getType(), mergeStrategy.invoke("merge").arg(leftFieldLocator) .arg(rightFieldLocator).arg(leftField) .arg(rightField).arg(leftFieldHasSetValue) .arg(rightFieldHasSetValue)); final JVar merged = ifShouldBeSetBlock.decl( rightFieldAccessor.getType(), "merged" + fieldOutline.getPropertyInfo().getName( true), mergedValue); targetFieldAccessor.fromRawValue( ifShouldBeSetBlock, "unique" + fieldOutline.getPropertyInfo().getName( true), merged); targetFieldAccessor.unsetValues(ifShouldBeUnsetBlock); } } } return mergeFrom; } protected JMethod generateMergeFrom$createNewInstance( final ClassOutline classOutline, final JDefinedClass theClass) { final JMethod existingMethod = theClass.getMethod("createNewInstance", new JType[0]); if (existingMethod == null) { final JMethod newMethod = theClass.method(JMod.PUBLIC, theClass .owner().ref(Object.class), "createNewInstance"); newMethod.annotate(Override.class); { final JBlock body = newMethod.body(); body._return(JExpr._new(theClass)); } return newMethod; } else { return existingMethod; } } }
highsource/jaxb2-basics
basic/src/main/java/org/jvnet/jaxb2_commons/plugin/mergeable/MergeablePlugin.java
Java
bsd-2-clause
10,727
using System; using System.Collections.Generic; using System.Drawing; using DevExpress.XtraBars; namespace bv.winclient.Core.TranslationTool { public partial class PropertyGrid : BvForm { public ControlDesigner SourceControl { get; private set; } public ControlModel Model { get; private set; } public PropertyGrid() { InitializeComponent(); } public void RefreshPropertiesGrid(BarItemLinkCollection sourceControl) { rowCaption.Visible = categoryLocation.Visible = categorySize.Visible = false; categoryMenuItems.Visible = true; Model = new ControlModel { CanCaptionChange = false }; foreach (var o in sourceControl) { var caption = String.Empty; if (o is BarSubItemLink) { caption = ((BarSubItemLink) o).Item.Caption; } else if (o is BarLargeButtonItemLink) { caption = ((BarLargeButtonItemLink) o).Item.Caption; } if (caption.Length == 0) continue; Model.MenuItems.Add(caption); } propGrid.SelectedObject = Model; } public void RefreshPropertiesGrid(ControlDesigner sourceControl) { SourceControl = sourceControl; var control = SourceControl.RealControl; Model = new ControlModel { X = control.Location.X, Y = control.Location.Y, Width = control.Size.Width, Height = control.Size.Height, CanCaptionChange = TranslationToolHelperWinClient.IsEditableControl(control) }; if (Model.CanCaptionChange) { Model.OldCaption = Model.Caption = TranslationToolHelperWinClient.GetComponentText(control); } else { rowCaption.Visible = false; } if (SourceControl.MovingEnabled) { Model.OldLocation = control.Location; } else { categoryLocation.Visible = false; } if (SourceControl.SizingEnabled) { Model.OldSize = control.Size; } else { categorySize.Visible = false; } //we create a list with all menu items if (control is PopUpButton) { var pb = (PopUpButton) control; foreach (BarButtonItemLink action in pb.PopupActions.ItemLinks) { Model.MenuItems.Add(action.Item.Caption); } categoryMenuItems.Visible = true; } else { categoryMenuItems.Visible = false; } propGrid.SelectedObject = Model; } private void bCancel_Click(object sender, EventArgs e) { Close(); } private void BOk_Click(object sender, EventArgs e) { //todo validation? Close(); } } public class ControlModel { public string Caption { get; set; } public int X { get; set; } public int Y { get; set; } public int Width { get; set; } public int Height { get; set; } public bool CanCaptionChange { get; set; } public Point OldLocation { get; set; } public Size OldSize { get; set; } public string OldCaption { get; set; } public List<string> MenuItems { get; set; } public ControlModel() { Caption = String.Empty; OldCaption = String.Empty; X = Y = Width = Height = 0; CanCaptionChange = false; OldLocation = new Point(0, 0); OldSize = new Size(0, 0); MenuItems = new List<string>(); } public bool IsLocationChanged() { return new Point(X, Y) != OldLocation; } public bool IsSizeChanged() { return new Size(Width, Height) != OldSize; } public bool IsCaptionChanged() { return Caption != OldCaption; } } }
EIDSS/EIDSS-Legacy
EIDSS v6.1/bv.winclient/Core/TranslationTool/PropertyGrid.cs
C#
bsd-2-clause
4,672
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('freebasics', '0006_change_site_url_field_type'), ] operations = [ migrations.AddField( model_name='freebasicscontroller', name='postgres_db_url', field=models.TextField(null=True, blank=True), ), ]
praekeltfoundation/mc2-freebasics
freebasics/migrations/0007_freebasicscontroller_postgres_db_url.py
Python
bsd-2-clause
442
// Copyright (c) 2019 ASMlover. 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 ofconditions 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 materialsprovided 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. #pragma once #include "value.hh" namespace wrencc { class Compiler; FunctionObject* compile(WrenVM& vm, ModuleObject* module, const str_t& source_bytes, bool is_expression = false, bool print_errors = false); void mark_compiler(WrenVM& vm, Compiler* compiler); }
ASMlover/study
cplusplus/wren_cc/compiler.hh
C++
bsd-2-clause
1,647
def excise(conn, qrelname, tid): with conn.cursor() as cur: # Assume 'id' column exists and print that for bookkeeping. # # TODO: Instead should find unique constraints and print # those, or try to print all attributes that are not corrupt. sql = 'DELETE FROM {0} WHERE ctid = %s RETURNING id'.format(qrelname) params = (tid,) cur.execute(sql, params) row = cur.fetchone() if row: return row[0] return None
fdr/pg_corrupt
pg_corrupt/excise.py
Python
bsd-2-clause
506
<?php /* vim: set expandtab tabstop=4 shiftwidth=4: */ // +----------------------------------------------------------------------+ // | Artisan Smarty | // +----------------------------------------------------------------------+ // | PHP Version 4 | // +----------------------------------------------------------------------+ // | Copyright 2004-2005 ARTISAN PROJECT All rights reserved. | // +----------------------------------------------------------------------+ // | Authors: Akito<akito-artisan@five-foxes.com> | // +----------------------------------------------------------------------+ // /** * ArtisanSmarty plugin * @package ArtisanSmarty * @subpackage plugins */ /** * Smarty count_sentences modifier plugin * * Type: modifier<br> * Name: count_sentences * Purpose: count the number of sentences in a text * @link http://smarty.php.net/manual/en/language.modifier.count.paragraphs.php * count_sentences (Smarty online manual) * @param string * @return integer */ function smarty_modifier_count_sentences($string) { // find periods with a word before but not after. return preg_match_all('/[^\s]\.(?!\w)/', $string, $match); } /* vim: set expandtab: */ ?>
EpubBuilder/EpubBuilder
Smarty/plugins/modifier.count_sentences.php
PHP
bsd-2-clause
1,355
# frozen_string_literal: true require_relative '../helpers/load_file' module WavefrontCli module Subcommand # # Stuff to import an object # class Import attr_reader :wf, :options def initialize(calling_class, options) @calling_class = calling_class @wf = calling_class.wf @options = options @message = 'IMPORTED' end def run! errs = 0 [raw_input].flatten.each do |obj| resp = import_object(obj) next if options[:noop] errs += 1 unless resp.ok? puts import_message(obj, resp) end exit errs end private def raw_input WavefrontCli::Helper::LoadFile.new(options[:'<file>']).load end def import_message(obj, resp) format('%-15<id>s %-10<status>s %<message>s', id: obj[:id] || obj[:url], status: resp.ok? ? @message : 'FAILED', message: resp.status.message) end def import_object(raw) raw = preprocess_rawfile(raw) if respond_to?(:preprocess_rawfile) prepped = @calling_class.import_to_create(raw) if options[:upsert] import_upsert(raw, prepped) elsif options[:update] @message = 'UPDATED' import_update(raw) else wf.create(prepped) end end def import_upsert(raw, prepped) update_call = import_update(raw) if update_call.ok? @message = 'UPDATED' return update_call end puts 'update failed, inserting' if options[:verbose] || options[:debug] wf.create(prepped) end def import_update(raw) wf.update(raw[:id], raw, false) end end end end
snltd/wavefront-cli
lib/wavefront-cli/subcommands/import.rb
Ruby
bsd-2-clause
1,786
import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self): """ was_published_recently() should return False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=30) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() should return True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=1) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days): """ Creates a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class QuestionViewTests(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self): """ Questions with a pub_date in the past should be displayed on the index page. """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_a_future_question(self): """ Questions with a pub_date in the future should not be displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions should be displayed. """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_index_view_with_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionIndexDetailTests(TestCase): def test_detail_view_with_a_future_question(self): """ The detail view of a question with a pub_date in the future should return a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) response = self.client.get(url) self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_question(self): """ The detail view of a question with a pub_date in the past should display the question's text. """ past_question = create_question(question_text='Past Question.', days=-5) url = reverse('polls:detail', args=(past_question.id,)) response = self.client.get(url) self.assertContains(response, past_question.question_text)
congpc/DjangoExample
mysite/polls/tests.py
Python
bsd-2-clause
5,010
class GetIplayer < Formula desc "Utility for downloading TV and radio programmes from BBC iPlayer" homepage "https://github.com/get-iplayer/get_iplayer" url "https://github.com/get-iplayer/get_iplayer/archive/v3.06.tar.gz" sha256 "fba3f1abd01ca6f9aaed30f9650e1e520fd3b2147fe6aa48fe7c747725b205f7" head "https://github.com/get-iplayer/get_iplayer.git", :branch => "develop" bottle do cellar :any_skip_relocation sha256 "1ed429e5a0b2df706f9015c8ca40f5b485e7e0ae68dfee45c76f784eca32b553" => :high_sierra sha256 "1c9101656db2554d72b6f53d13fba9f84890f82119414675c5f62fb7e126373e" => :sierra sha256 "1c9101656db2554d72b6f53d13fba9f84890f82119414675c5f62fb7e126373e" => :el_capitan end depends_on "atomicparsley" => :recommended depends_on "ffmpeg" => :recommended depends_on :macos => :yosemite resource "IO::Socket::IP" do url "https://cpan.metacpan.org/authors/id/P/PE/PEVANS/IO-Socket-IP-0.39.tar.gz" sha256 "11950da7636cb786efd3bfb5891da4c820975276bce43175214391e5c32b7b96" end resource "Mojolicious" do url "https://cpan.metacpan.org/authors/id/S/SR/SRI/Mojolicious-7.48.tar.gz" sha256 "86d28e66a352e808ab1eae64ef93b90a9a92b3c1b07925bd2d3387a9e852388e" end def install ENV.prepend_create_path "PERL5LIB", libexec/"lib/perl5" resources.each do |r| r.stage do system "perl", "Makefile.PL", "INSTALL_BASE=#{libexec}" system "make", "install" end end inreplace ["get_iplayer", "get_iplayer.cgi"] do |s| s.gsub!(/^(my \$version_text);/i, "\\1 = \"#{pkg_version}-homebrew\";") s.gsub! "#!/usr/bin/env perl", "#!/usr/bin/perl" end bin.install "get_iplayer", "get_iplayer.cgi" bin.env_script_all_files(libexec/"bin", :PERL5LIB => ENV["PERL5LIB"]) man1.install "get_iplayer.1" end test do output = shell_output("\"#{bin}/get_iplayer\" --refresh --refresh-include=\"BBC None\" --quiet dontshowanymatches 2>&1") assert_match "get_iplayer #{pkg_version}-homebrew", output, "Unexpected version" assert_match "INFO: 0 matching programmes", output, "Unexpected output" assert_match "INFO: Indexing tv programmes (concurrent)", output, "Mojolicious not found" end end
grhawk/homebrew-core
Formula/get_iplayer.rb
Ruby
bsd-2-clause
2,242
/* * (C) 2014,2015,2017 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/asn1_print.h> #include <botan/bigint.h> #include <botan/hex.h> #include <botan/der_enc.h> #include <botan/ber_dec.h> #include <botan/asn1_time.h> #include <botan/asn1_str.h> #include <botan/oids.h> #include <iomanip> #include <sstream> #include <cctype> namespace Botan { namespace { bool all_printable_chars(const uint8_t bits[], size_t bits_len) { for(size_t i = 0; i != bits_len; ++i) { int c = bits[i]; if(c > 127) return false; if((std::isalnum(c) || c == '.' || c == ':' || c == '/' || c == '-') == false) return false; } return true; } /* * Special hack to handle GeneralName [2] and [6] (DNS name and URI) */ bool possibly_a_general_name(const uint8_t bits[], size_t bits_len) { if(bits_len <= 2) return false; if(bits[0] != 0x82 && bits[0] != 0x86) return false; if(bits[1] != bits_len - 2) return false; if(all_printable_chars(bits + 2, bits_len - 2) == false) return false; return true; } } std::string ASN1_Formatter::print(const uint8_t in[], size_t len) const { std::ostringstream output; print_to_stream(output, in, len); return output.str(); } void ASN1_Formatter::print_to_stream(std::ostream& output, const uint8_t in[], size_t len) const { BER_Decoder dec(in, len); decode(output, dec, 0); } void ASN1_Formatter::decode(std::ostream& output, BER_Decoder& decoder, size_t level) const { BER_Object obj = decoder.get_next_object(); while(obj.type_tag != NO_OBJECT) { const ASN1_Tag type_tag = obj.type_tag; const ASN1_Tag class_tag = obj.class_tag; const size_t length = obj.value.size(); /* hack to insert the tag+length back in front of the stuff now that we've gotten the type info */ DER_Encoder encoder; encoder.add_object(type_tag, class_tag, obj.value); const std::vector<uint8_t> bits = encoder.get_contents_unlocked(); BER_Decoder data(bits); if(class_tag & CONSTRUCTED) { BER_Decoder cons_info(obj.value); output << format(type_tag, class_tag, level, length, ""); decode(output, cons_info, level + 1); // recurse } else if((class_tag & APPLICATION) || (class_tag & CONTEXT_SPECIFIC)) { bool success_parsing_cs = false; if(m_print_context_specific) { try { if(possibly_a_general_name(bits.data(), bits.size())) { output << format(type_tag, class_tag, level, level, std::string(cast_uint8_ptr_to_char(&bits[2]), bits.size() - 2)); success_parsing_cs = true; } else { std::vector<uint8_t> inner_bits; data.decode(inner_bits, type_tag); BER_Decoder inner(inner_bits); std::ostringstream inner_data; decode(inner_data, inner, level + 1); // recurse output << inner_data.str(); success_parsing_cs = true; } } catch(...) { } } if(success_parsing_cs == false) { output << format(type_tag, class_tag, level, length, format_bin(type_tag, class_tag, bits)); } } else if(type_tag == OBJECT_ID) { OID oid; data.decode(oid); std::string out = OIDS::lookup(oid); if(out.empty()) { out = oid.as_string(); } else { out += " [" + oid.as_string() + "]"; } output << format(type_tag, class_tag, level, length, out); } else if(type_tag == INTEGER || type_tag == ENUMERATED) { BigInt number; if(type_tag == INTEGER) { data.decode(number); } else if(type_tag == ENUMERATED) { data.decode(number, ENUMERATED, class_tag); } const std::vector<uint8_t> rep = BigInt::encode(number, BigInt::Hexadecimal); std::string str; for(size_t i = 0; i != rep.size(); ++i) { str += static_cast<char>(rep[i]); } output << format(type_tag, class_tag, level, length, str); } else if(type_tag == BOOLEAN) { bool boolean; data.decode(boolean); output << format(type_tag, class_tag, level, length, (boolean ? "true" : "false")); } else if(type_tag == NULL_TAG) { output << format(type_tag, class_tag, level, length, ""); } else if(type_tag == OCTET_STRING || type_tag == BIT_STRING) { std::vector<uint8_t> decoded_bits; data.decode(decoded_bits, type_tag); try { BER_Decoder inner(decoded_bits); std::ostringstream inner_data; decode(inner_data, inner, level + 1); // recurse output << format(type_tag, class_tag, level, length, ""); output << inner_data.str(); } catch(...) { output << format(type_tag, class_tag, level, length, format_bin(type_tag, class_tag, decoded_bits)); } } else if(ASN1_String::is_string_type(type_tag)) { ASN1_String str; data.decode(str); output << format(type_tag, class_tag, level, length, str.value()); } else if(type_tag == UTC_TIME || type_tag == GENERALIZED_TIME) { X509_Time time; data.decode(time); output << format(type_tag, class_tag, level, length, time.readable_string()); } else { output << "Unknown ASN.1 tag class=" << static_cast<int>(class_tag) << " type=" << static_cast<int>(type_tag) << "\n";; } obj = decoder.get_next_object(); } } namespace { std::string format_type(ASN1_Tag type_tag, ASN1_Tag class_tag) { if(class_tag == UNIVERSAL) return asn1_tag_to_string(type_tag); if(class_tag == CONSTRUCTED && (type_tag == SEQUENCE || type_tag == SET)) return asn1_tag_to_string(type_tag); std::string name; if(class_tag & CONSTRUCTED) name += "cons "; name += "[" + std::to_string(type_tag) + "]"; if(class_tag & APPLICATION) { name += " appl"; } if(class_tag & CONTEXT_SPECIFIC) { name += " context"; } return name; } } std::string ASN1_Pretty_Printer::format(ASN1_Tag type_tag, ASN1_Tag class_tag, size_t level, size_t length, const std::string& value) const { bool should_skip = false; if(value.length() > m_print_limit) { should_skip = true; } if((type_tag == OCTET_STRING || type_tag == BIT_STRING) && value.length() > m_print_binary_limit) { should_skip = true; } level += m_initial_level; std::ostringstream oss; oss << " d=" << std::setw(2) << level << ", l=" << std::setw(4) << length << ":" << std::string(level + 1, ' ') << format_type(type_tag, class_tag); if(value != "" && !should_skip) { const size_t current_pos = static_cast<size_t>(oss.tellp()); const size_t spaces_to_align = (current_pos >= m_value_column) ? 1 : (m_value_column - current_pos); oss << std::string(spaces_to_align, ' ') << value; } oss << "\n"; return oss.str(); } std::string ASN1_Pretty_Printer::format_bin(ASN1_Tag /*type_tag*/, ASN1_Tag /*class_tag*/, const std::vector<uint8_t>& vec) const { if(all_printable_chars(vec.data(), vec.size())) { return std::string(cast_uint8_ptr_to_char(vec.data()), vec.size()); } else return hex_encode(vec); } }
Rohde-Schwarz-Cybersecurity/botan
src/lib/asn1/asn1_print.cpp
C++
bsd-2-clause
8,549
package operations; import data.Collector; import graph.implementation.Edge; import utility.GraphFunctions; /** * Set the curve point to an ideal position. * If source and destination are equal, it would be a line. * If not, it is a noose on top of the vertex. */ public class O_RelaxEdge implements EdgeOperation { private Edge edge; public O_RelaxEdge(Edge edge) { super(); this.edge = edge; } @Override public void run() { Collector.getSlides().addUndo(); GraphFunctions.relaxEdge(edge); } @Override public void setEdge(Edge edge) { this.edge = edge; } }
Drafigon/WildGraphs
src/operations/O_RelaxEdge.java
Java
bsd-2-clause
590
/** * @license AngularJS v1.3.0-build.2480+sha.fb6062f * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) {'use strict'; /* jshint maxlen: false */ /** * @ngdoc module * @name ngAnimate * @description * * # ngAnimate * * The `ngAnimate` module provides support for JavaScript, CSS3 transition and CSS3 keyframe animation hooks within existing core and custom directives. * * * <div doc-module-components="ngAnimate"></div> * * # Usage * * To see animations in action, all that is required is to define the appropriate CSS classes * or to register a JavaScript animation via the myModule.animation() function. The directives that support animation automatically are: * `ngRepeat`, `ngInclude`, `ngIf`, `ngSwitch`, `ngShow`, `ngHide`, `ngView` and `ngClass`. Custom directives can take advantage of animation * by using the `$animate` service. * * Below is a more detailed breakdown of the supported animation events provided by pre-existing ng directives: * * | Directive | Supported Animations | * |---------------------------------------------------------- |----------------------------------------------------| * | {@link ng.directive:ngRepeat#usage_animations ngRepeat} | enter, leave and move | * | {@link ngRoute.directive:ngView#usage_animations ngView} | enter and leave | * | {@link ng.directive:ngInclude#usage_animations ngInclude} | enter and leave | * | {@link ng.directive:ngSwitch#usage_animations ngSwitch} | enter and leave | * | {@link ng.directive:ngIf#usage_animations ngIf} | enter and leave | * | {@link ng.directive:ngClass#usage_animations ngClass} | add and remove | * | {@link ng.directive:ngShow#usage_animations ngShow & ngHide} | add and remove (the ng-hide class value) | * | {@link ng.directive:form#usage_animations form} | add and remove (dirty, pristine, valid, invalid & all other validations) | * | {@link ng.directive:ngModel#usage_animations ngModel} | add and remove (dirty, pristine, valid, invalid & all other validations) | * * You can find out more information about animations upon visiting each directive page. * * Below is an example of how to apply animations to a directive that supports animation hooks: * * ```html * <style type="text/css"> * .slide.ng-enter, .slide.ng-leave { * -webkit-transition:0.5s linear all; * transition:0.5s linear all; * } * * .slide.ng-enter { } /&#42; starting animations for enter &#42;/ * .slide.ng-enter-active { } /&#42; terminal animations for enter &#42;/ * .slide.ng-leave { } /&#42; starting animations for leave &#42;/ * .slide.ng-leave-active { } /&#42; terminal animations for leave &#42;/ * </style> * * <!-- * the animate service will automatically add .ng-enter and .ng-leave to the element * to trigger the CSS transition/animations * --> * <ANY class="slide" ng-include="..."></ANY> * ``` * * Keep in mind that if an animation is running, any child elements cannot be animated until the parent element's * animation has completed. * * <h2>CSS-defined Animations</h2> * The animate service will automatically apply two CSS classes to the animated element and these two CSS classes * are designed to contain the start and end CSS styling. Both CSS transitions and keyframe animations are supported * and can be used to play along with this naming structure. * * The following code below demonstrates how to perform animations using **CSS transitions** with Angular: * * ```html * <style type="text/css"> * /&#42; * The animate class is apart of the element and the ng-enter class * is attached to the element once the enter animation event is triggered * &#42;/ * .reveal-animation.ng-enter { * -webkit-transition: 1s linear all; /&#42; Safari/Chrome &#42;/ * transition: 1s linear all; /&#42; All other modern browsers and IE10+ &#42;/ * * /&#42; The animation preparation code &#42;/ * opacity: 0; * } * * /&#42; * Keep in mind that you want to combine both CSS * classes together to avoid any CSS-specificity * conflicts * &#42;/ * .reveal-animation.ng-enter.ng-enter-active { * /&#42; The animation code itself &#42;/ * opacity: 1; * } * </style> * * <div class="view-container"> * <div ng-view class="reveal-animation"></div> * </div> * ``` * * The following code below demonstrates how to perform animations using **CSS animations** with Angular: * * ```html * <style type="text/css"> * .reveal-animation.ng-enter { * -webkit-animation: enter_sequence 1s linear; /&#42; Safari/Chrome &#42;/ * animation: enter_sequence 1s linear; /&#42; IE10+ and Future Browsers &#42;/ * } * &#64-webkit-keyframes enter_sequence { * from { opacity:0; } * to { opacity:1; } * } * &#64keyframes enter_sequence { * from { opacity:0; } * to { opacity:1; } * } * </style> * * <div class="view-container"> * <div ng-view class="reveal-animation"></div> * </div> * ``` * * Both CSS3 animations and transitions can be used together and the animate service will figure out the correct duration and delay timing. * * Upon DOM mutation, the event class is added first (something like `ng-enter`), then the browser prepares itself to add * the active class (in this case `ng-enter-active`) which then triggers the animation. The animation module will automatically * detect the CSS code to determine when the animation ends. Once the animation is over then both CSS classes will be * removed from the DOM. If a browser does not support CSS transitions or CSS animations then the animation will start and end * immediately resulting in a DOM element that is at its final state. This final state is when the DOM element * has no CSS transition/animation classes applied to it. * * <h3>CSS Staggering Animations</h3> * A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a * curtain-like effect. The ngAnimate module, as of 1.2.0, supports staggering animations and the stagger effect can be * performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for * the animation. The style property expected within the stagger class can either be a **transition-delay** or an * **animation-delay** property (or both if your animation contains both transitions and keyframe animations). * * ```css * .my-animation.ng-enter { * /&#42; standard transition code &#42;/ * -webkit-transition: 1s linear all; * transition: 1s linear all; * opacity:0; * } * .my-animation.ng-enter-stagger { * /&#42; this will have a 100ms delay between each successive leave animation &#42;/ * -webkit-transition-delay: 0.1s; * transition-delay: 0.1s; * * /&#42; in case the stagger doesn't work then these two values * must be set to 0 to avoid an accidental CSS inheritance &#42;/ * -webkit-transition-duration: 0s; * transition-duration: 0s; * } * .my-animation.ng-enter.ng-enter-active { * /&#42; standard transition styles &#42;/ * opacity:1; * } * ``` * * Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations * on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this * are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation * will also be reset if more than 10ms has passed after the last animation has been fired. * * The following code will issue the **ng-leave-stagger** event on the element provided: * * ```js * var kids = parent.children(); * * $animate.leave(kids[0]); //stagger index=0 * $animate.leave(kids[1]); //stagger index=1 * $animate.leave(kids[2]); //stagger index=2 * $animate.leave(kids[3]); //stagger index=3 * $animate.leave(kids[4]); //stagger index=4 * * $timeout(function() { * //stagger has reset itself * $animate.leave(kids[5]); //stagger index=0 * $animate.leave(kids[6]); //stagger index=1 * }, 100, false); * ``` * * Stagger animations are currently only supported within CSS-defined animations. * * <h2>JavaScript-defined Animations</h2> * In the event that you do not want to use CSS3 transitions or CSS3 animations or if you wish to offer animations on browsers that do not * yet support CSS transitions/animations, then you can make use of JavaScript animations defined inside of your AngularJS module. * * ```js * //!annotate="YourApp" Your AngularJS Module|Replace this or ngModule with the module that you used to define your application. * var ngModule = angular.module('YourApp', ['ngAnimate']); * ngModule.animation('.my-crazy-animation', function() { * return { * enter: function(element, done) { * //run the animation here and call done when the animation is complete * return function(cancelled) { * //this (optional) function will be called when the animation * //completes or when the animation is cancelled (the cancelled * //flag will be set to true if cancelled). * }; * }, * leave: function(element, done) { }, * move: function(element, done) { }, * * //animation that can be triggered before the class is added * beforeAddClass: function(element, className, done) { }, * * //animation that can be triggered after the class is added * addClass: function(element, className, done) { }, * * //animation that can be triggered before the class is removed * beforeRemoveClass: function(element, className, done) { }, * * //animation that can be triggered after the class is removed * removeClass: function(element, className, done) { } * }; * }); * ``` * * JavaScript-defined animations are created with a CSS-like class selector and a collection of events which are set to run * a javascript callback function. When an animation is triggered, $animate will look for a matching animation which fits * the element's CSS class attribute value and then run the matching animation event function (if found). * In other words, if the CSS classes present on the animated element match any of the JavaScript animations then the callback function will * be executed. It should be also noted that only simple, single class selectors are allowed (compound class selectors are not supported). * * Within a JavaScript animation, an object containing various event callback animation functions is expected to be returned. * As explained above, these callbacks are triggered based on the animation event. Therefore if an enter animation is run, * and the JavaScript animation is found, then the enter callback will handle that animation (in addition to the CSS keyframe animation * or transition code that is defined via a stylesheet). * */ angular.module('ngAnimate', ['ng']) /** * @ngdoc provider * @name $animateProvider * @description * * The `$animateProvider` allows developers to register JavaScript animation event handlers directly inside of a module. * When an animation is triggered, the $animate service will query the $animate service to find any animations that match * the provided name value. * * Requires the {@link ngAnimate `ngAnimate`} module to be installed. * * Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application. * */ //this private service is only used within CSS-enabled animations //IE8 + IE9 do not support rAF natively, but that is fine since they //also don't support transitions and keyframes which means that the code //below will never be used by the two browsers. .factory('$$animateReflow', ['$$rAF', '$document', function($$rAF, $document) { var bod = $document[0].body; return function(fn) { //the returned function acts as the cancellation function return $$rAF(function() { //the line below will force the browser to perform a repaint //so that all the animated elements within the animation frame //will be properly updated and drawn on screen. This is //required to perform multi-class CSS based animations with //Firefox. DO NOT REMOVE THIS LINE. var a = bod.offsetWidth + 1; fn(); }); }; }]) .config(['$provide', '$animateProvider', function($provide, $animateProvider) { var noop = angular.noop; var forEach = angular.forEach; var selectors = $animateProvider.$$selectors; var ELEMENT_NODE = 1; var NG_ANIMATE_STATE = '$$ngAnimateState'; var NG_ANIMATE_CLASS_NAME = 'ng-animate'; var rootAnimateState = {running: true}; function extractElementNode(element) { for(var i = 0; i < element.length; i++) { var elm = element[i]; if(elm.nodeType == ELEMENT_NODE) { return elm; } } } function stripCommentsFromElement(element) { return angular.element(extractElementNode(element)); } function isMatchingElement(elm1, elm2) { return extractElementNode(elm1) == extractElementNode(elm2); } $provide.decorator('$animate', ['$delegate', '$injector', '$sniffer', '$rootElement', '$$asyncCallback', '$rootScope', '$document', function($delegate, $injector, $sniffer, $rootElement, $$asyncCallback, $rootScope, $document) { var globalAnimationCounter = 0; $rootElement.data(NG_ANIMATE_STATE, rootAnimateState); // disable animations during bootstrap, but once we bootstrapped, wait again // for another digest until enabling animations. The reason why we digest twice // is because all structural animations (enter, leave and move) all perform a // post digest operation before animating. If we only wait for a single digest // to pass then the structural animation would render its animation on page load. // (which is what we're trying to avoid when the application first boots up.) $rootScope.$$postDigest(function() { $rootScope.$$postDigest(function() { rootAnimateState.running = false; }); }); var classNameFilter = $animateProvider.classNameFilter(); var isAnimatableClassName = !classNameFilter ? function() { return true; } : function(className) { return classNameFilter.test(className); }; function lookup(name) { if (name) { var matches = [], flagMap = {}, classes = name.substr(1).split('.'); //the empty string value is the default animation //operation which performs CSS transition and keyframe //animations sniffing. This is always included for each //element animation procedure if the browser supports //transitions and/or keyframe animations if ($sniffer.transitions || $sniffer.animations) { classes.push(''); } for(var i=0; i < classes.length; i++) { var klass = classes[i], selectorFactoryName = selectors[klass]; if(selectorFactoryName && !flagMap[klass]) { matches.push($injector.get(selectorFactoryName)); flagMap[klass] = true; } } return matches; } } function animationRunner(element, animationEvent, className) { //transcluded directives may sometimes fire an animation using only comment nodes //best to catch this early on to prevent any animation operations from occurring var node = element[0]; if(!node) { return; } var isSetClassOperation = animationEvent == 'setClass'; var isClassBased = isSetClassOperation || animationEvent == 'addClass' || animationEvent == 'removeClass'; var classNameAdd, classNameRemove; if(angular.isArray(className)) { classNameAdd = className[0]; classNameRemove = className[1]; className = classNameAdd + ' ' + classNameRemove; } var currentClassName = element.attr('class'); var classes = currentClassName + ' ' + className; if(!isAnimatableClassName(classes)) { return; } var beforeComplete = noop, beforeCancel = [], before = [], afterComplete = noop, afterCancel = [], after = []; var animationLookup = (' ' + classes).replace(/\s+/g,'.'); forEach(lookup(animationLookup), function(animationFactory) { var created = registerAnimation(animationFactory, animationEvent); if(!created && isSetClassOperation) { registerAnimation(animationFactory, 'addClass'); registerAnimation(animationFactory, 'removeClass'); } }); function registerAnimation(animationFactory, event) { var afterFn = animationFactory[event]; var beforeFn = animationFactory['before' + event.charAt(0).toUpperCase() + event.substr(1)]; if(afterFn || beforeFn) { if(event == 'leave') { beforeFn = afterFn; //when set as null then animation knows to skip this phase afterFn = null; } after.push({ event : event, fn : afterFn }); before.push({ event : event, fn : beforeFn }); return true; } } function run(fns, cancellations, allCompleteFn) { var animations = []; forEach(fns, function(animation) { animation.fn && animations.push(animation); }); var count = 0; function afterAnimationComplete(index) { if(cancellations) { (cancellations[index] || noop)(); if(++count < animations.length) return; cancellations = null; } allCompleteFn(); } //The code below adds directly to the array in order to work with //both sync and async animations. Sync animations are when the done() //operation is called right away. DO NOT REFACTOR! forEach(animations, function(animation, index) { var progress = function() { afterAnimationComplete(index); }; switch(animation.event) { case 'setClass': cancellations.push(animation.fn(element, classNameAdd, classNameRemove, progress)); break; case 'addClass': cancellations.push(animation.fn(element, classNameAdd || className, progress)); break; case 'removeClass': cancellations.push(animation.fn(element, classNameRemove || className, progress)); break; default: cancellations.push(animation.fn(element, progress)); break; } }); if(cancellations && cancellations.length === 0) { allCompleteFn(); } } return { node : node, event : animationEvent, className : className, isClassBased : isClassBased, isSetClassOperation : isSetClassOperation, before : function(allCompleteFn) { beforeComplete = allCompleteFn; run(before, beforeCancel, function() { beforeComplete = noop; allCompleteFn(); }); }, after : function(allCompleteFn) { afterComplete = allCompleteFn; run(after, afterCancel, function() { afterComplete = noop; allCompleteFn(); }); }, cancel : function() { if(beforeCancel) { forEach(beforeCancel, function(cancelFn) { (cancelFn || noop)(true); }); beforeComplete(true); } if(afterCancel) { forEach(afterCancel, function(cancelFn) { (cancelFn || noop)(true); }); afterComplete(true); } } }; } /** * @ngdoc service * @name $animate * @function * * @description * The `$animate` service provides animation detection support while performing DOM operations (enter, leave and move) as well as during addClass and removeClass operations. * When any of these operations are run, the $animate service * will examine any JavaScript-defined animations (which are defined by using the $animateProvider provider object) * as well as any CSS-defined animations against the CSS classes present on the element once the DOM operation is run. * * The `$animate` service is used behind the scenes with pre-existing directives and animation with these directives * will work out of the box without any extra configuration. * * Requires the {@link ngAnimate `ngAnimate`} module to be installed. * * Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application. * */ return { /** * @ngdoc method * @name $animate#enter * @function * * @description * Appends the element to the parentElement element that resides in the document and then runs the enter animation. Once * the animation is started, the following CSS classes will be present on the element for the duration of the animation: * * Below is a breakdown of each step that occurs during enter animation: * * | Animation Step | What the element class attribute looks like | * |----------------------------------------------------------------------------------------------|---------------------------------------------| * | 1. $animate.enter(...) is called | class="my-animation" | * | 2. element is inserted into the parentElement element or beside the afterElement element | class="my-animation" | * | 3. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" | * | 4. the .ng-enter class is added to the element | class="my-animation ng-animate ng-enter" | * | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-enter" | * | 6. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate ng-enter" | * | 7. the .ng-enter-active and .ng-animate-active classes are added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active ng-enter ng-enter-active" | * | 8. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active ng-enter ng-enter-active" | * | 9. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | * | 10. The doneCallback() callback is fired (if provided) | class="my-animation" | * * @param {DOMElement} element the element that will be the focus of the enter animation * @param {DOMElement} parentElement the parent element of the element that will be the focus of the enter animation * @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the enter animation * @param {function()=} doneCallback the callback function that will be called once the animation is complete */ enter : function(element, parentElement, afterElement, doneCallback) { this.enabled(false, element); $delegate.enter(element, parentElement, afterElement); $rootScope.$$postDigest(function() { element = stripCommentsFromElement(element); performAnimation('enter', 'ng-enter', element, parentElement, afterElement, noop, doneCallback); }); }, /** * @ngdoc method * @name $animate#leave * @function * * @description * Runs the leave animation operation and, upon completion, removes the element from the DOM. Once * the animation is started, the following CSS classes will be added for the duration of the animation: * * Below is a breakdown of each step that occurs during leave animation: * * | Animation Step | What the element class attribute looks like | * |----------------------------------------------------------------------------------------------|---------------------------------------------| * | 1. $animate.leave(...) is called | class="my-animation" | * | 2. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" | * | 3. the .ng-leave class is added to the element | class="my-animation ng-animate ng-leave" | * | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-leave" | * | 5. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate ng-leave" | * | 6. the .ng-leave-active and .ng-animate-active classes is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active ng-leave ng-leave-active" | * | 7. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active ng-leave ng-leave-active" | * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | * | 9. The element is removed from the DOM | ... | * | 10. The doneCallback() callback is fired (if provided) | ... | * * @param {DOMElement} element the element that will be the focus of the leave animation * @param {function()=} doneCallback the callback function that will be called once the animation is complete */ leave : function(element, doneCallback) { cancelChildAnimations(element); this.enabled(false, element); $rootScope.$$postDigest(function() { performAnimation('leave', 'ng-leave', stripCommentsFromElement(element), null, null, function() { $delegate.leave(element); }, doneCallback); }); }, /** * @ngdoc method * @name $animate#move * @function * * @description * Fires the move DOM operation. Just before the animation starts, the animate service will either append it into the parentElement container or * add the element directly after the afterElement element if present. Then the move animation will be run. Once * the animation is started, the following CSS classes will be added for the duration of the animation: * * Below is a breakdown of each step that occurs during move animation: * * | Animation Step | What the element class attribute looks like | * |----------------------------------------------------------------------------------------------|---------------------------------------------| * | 1. $animate.move(...) is called | class="my-animation" | * | 2. element is moved into the parentElement element or beside the afterElement element | class="my-animation" | * | 3. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" | * | 4. the .ng-move class is added to the element | class="my-animation ng-animate ng-move" | * | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-move" | * | 6. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate ng-move" | * | 7. the .ng-move-active and .ng-animate-active classes is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active ng-move ng-move-active" | * | 8. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active ng-move ng-move-active" | * | 9. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | * | 10. The doneCallback() callback is fired (if provided) | class="my-animation" | * * @param {DOMElement} element the element that will be the focus of the move animation * @param {DOMElement} parentElement the parentElement element of the element that will be the focus of the move animation * @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the move animation * @param {function()=} doneCallback the callback function that will be called once the animation is complete */ move : function(element, parentElement, afterElement, doneCallback) { cancelChildAnimations(element); this.enabled(false, element); $delegate.move(element, parentElement, afterElement); $rootScope.$$postDigest(function() { element = stripCommentsFromElement(element); performAnimation('move', 'ng-move', element, parentElement, afterElement, noop, doneCallback); }); }, /** * @ngdoc method * @name $animate#addClass * * @description * Triggers a custom animation event based off the className variable and then attaches the className value to the element as a CSS class. * Unlike the other animation methods, the animate service will suffix the className value with {@type -add} in order to provide * the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if no CSS transitions * or keyframes are defined on the -add or base CSS class). * * Below is a breakdown of each step that occurs during addClass animation: * * | Animation Step | What the element class attribute looks like | * |------------------------------------------------------------------------------------------------|---------------------------------------------| * | 1. $animate.addClass(element, 'super') is called | class="my-animation" | * | 2. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" | * | 3. the .super-add class are added to the element | class="my-animation ng-animate super-add" | * | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate super-add" | * | 5. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate super-add" | * | 6. the .super, .super-add-active and .ng-animate-active classes are added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active super super-add super-add-active" | * | 7. $animate waits for X milliseconds for the animation to complete | class="my-animation super super-add super-add-active" | * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation super" | * | 9. The super class is kept on the element | class="my-animation super" | * | 10. The doneCallback() callback is fired (if provided) | class="my-animation super" | * * @param {DOMElement} element the element that will be animated * @param {string} className the CSS class that will be added to the element and then animated * @param {function()=} doneCallback the callback function that will be called once the animation is complete */ addClass : function(element, className, doneCallback) { element = stripCommentsFromElement(element); performAnimation('addClass', className, element, null, null, function() { $delegate.addClass(element, className); }, doneCallback); }, /** * @ngdoc method * @name $animate#removeClass * * @description * Triggers a custom animation event based off the className variable and then removes the CSS class provided by the className value * from the element. Unlike the other animation methods, the animate service will suffix the className value with {@type -remove} in * order to provide the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if * no CSS transitions or keyframes are defined on the -remove or base CSS classes). * * Below is a breakdown of each step that occurs during removeClass animation: * * | Animation Step | What the element class attribute looks like | * |-----------------------------------------------------------------------------------------------|---------------------------------------------| * | 1. $animate.removeClass(element, 'super') is called | class="my-animation super" | * | 2. $animate runs any JavaScript-defined animations on the element | class="my-animation super ng-animate" | * | 3. the .super-remove class are added to the element | class="my-animation super ng-animate super-remove"| * | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation super ng-animate super-remove" | * | 5. $animate waits for 10ms (this performs a reflow) | class="my-animation super ng-animate super-remove" | * | 6. the .super-remove-active and .ng-animate-active classes are added and .super is removed (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active super-remove super-remove-active" | * | 7. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active super-remove super-remove-active" | * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | * | 9. The doneCallback() callback is fired (if provided) | class="my-animation" | * * * @param {DOMElement} element the element that will be animated * @param {string} className the CSS class that will be animated and then removed from the element * @param {function()=} doneCallback the callback function that will be called once the animation is complete */ removeClass : function(element, className, doneCallback) { element = stripCommentsFromElement(element); performAnimation('removeClass', className, element, null, null, function() { $delegate.removeClass(element, className); }, doneCallback); }, /** * * @ngdoc function * @name $animate#setClass * @function * @description Adds and/or removes the given CSS classes to and from the element. * Once complete, the done() callback will be fired (if provided). * @param {DOMElement} element the element which will it's CSS classes changed * removed from it * @param {string} add the CSS classes which will be added to the element * @param {string} remove the CSS class which will be removed from the element * @param {Function=} done the callback function (if provided) that will be fired after the * CSS classes have been set on the element */ setClass : function(element, add, remove, doneCallback) { element = stripCommentsFromElement(element); performAnimation('setClass', [add, remove], element, null, null, function() { $delegate.setClass(element, add, remove); }, doneCallback); }, /** * @ngdoc method * @name $animate#enabled * @function * * @param {boolean=} value If provided then set the animation on or off. * @param {DOMElement=} element If provided then the element will be used to represent the enable/disable operation * @return {boolean} Current animation state. * * @description * Globally enables/disables animations. * */ enabled : function(value, element) { switch(arguments.length) { case 2: if(value) { cleanup(element); } else { var data = element.data(NG_ANIMATE_STATE) || {}; data.disabled = true; element.data(NG_ANIMATE_STATE, data); } break; case 1: rootAnimateState.disabled = !value; break; default: value = !rootAnimateState.disabled; break; } return !!value; } }; /* all animations call this shared animation triggering function internally. The animationEvent variable refers to the JavaScript animation event that will be triggered and the className value is the name of the animation that will be applied within the CSS code. Element, parentElement and afterElement are provided DOM elements for the animation and the onComplete callback will be fired once the animation is fully complete. */ function performAnimation(animationEvent, className, element, parentElement, afterElement, domOperation, doneCallback) { var runner = animationRunner(element, animationEvent, className); if(!runner) { fireDOMOperation(); fireBeforeCallbackAsync(); fireAfterCallbackAsync(); closeAnimation(); return; } className = runner.className; var elementEvents = angular.element._data(runner.node); elementEvents = elementEvents && elementEvents.events; if (!parentElement) { parentElement = afterElement ? afterElement.parent() : element.parent(); } var ngAnimateState = element.data(NG_ANIMATE_STATE) || {}; var runningAnimations = ngAnimateState.active || {}; var totalActiveAnimations = ngAnimateState.totalActive || 0; var lastAnimation = ngAnimateState.last; //only allow animations if the currently running animation is not structural //or if there is no animation running at all var skipAnimations = runner.isClassBased ? ngAnimateState.disabled || (lastAnimation && !lastAnimation.isClassBased) : false; //skip the animation if animations are disabled, a parent is already being animated, //the element is not currently attached to the document body or then completely close //the animation if any matching animations are not found at all. //NOTE: IE8 + IE9 should close properly (run closeAnimation()) in case an animation was found. if (skipAnimations || animationsDisabled(element, parentElement)) { fireDOMOperation(); fireBeforeCallbackAsync(); fireAfterCallbackAsync(); closeAnimation(); return; } var skipAnimation = false; if(totalActiveAnimations > 0) { var animationsToCancel = []; if(!runner.isClassBased) { if(animationEvent == 'leave' && runningAnimations['ng-leave']) { skipAnimation = true; } else { //cancel all animations when a structural animation takes place for(var klass in runningAnimations) { animationsToCancel.push(runningAnimations[klass]); cleanup(element, klass); } runningAnimations = {}; totalActiveAnimations = 0; } } else if(lastAnimation.event == 'setClass') { animationsToCancel.push(lastAnimation); cleanup(element, className); } else if(runningAnimations[className]) { var current = runningAnimations[className]; if(current.event == animationEvent) { skipAnimation = true; } else { animationsToCancel.push(current); cleanup(element, className); } } if(animationsToCancel.length > 0) { forEach(animationsToCancel, function(operation) { operation.cancel(); }); } } if(runner.isClassBased && !runner.isSetClassOperation && !skipAnimation) { skipAnimation = (animationEvent == 'addClass') == element.hasClass(className); //opposite of XOR } if(skipAnimation) { fireBeforeCallbackAsync(); fireAfterCallbackAsync(); fireDoneCallbackAsync(); return; } if(animationEvent == 'leave') { //there's no need to ever remove the listener since the element //will be removed (destroyed) after the leave animation ends or //is cancelled midway element.one('$destroy', function(e) { var element = angular.element(this); var state = element.data(NG_ANIMATE_STATE); if(state) { var activeLeaveAnimation = state.active['ng-leave']; if(activeLeaveAnimation) { activeLeaveAnimation.cancel(); cleanup(element, 'ng-leave'); } } }); } //the ng-animate class does nothing, but it's here to allow for //parent animations to find and cancel child animations when needed element.addClass(NG_ANIMATE_CLASS_NAME); var localAnimationCount = globalAnimationCounter++; totalActiveAnimations++; runningAnimations[className] = runner; element.data(NG_ANIMATE_STATE, { last : runner, active : runningAnimations, index : localAnimationCount, totalActive : totalActiveAnimations }); //first we run the before animations and when all of those are complete //then we perform the DOM operation and run the next set of animations fireBeforeCallbackAsync(); runner.before(function(cancelled) { var data = element.data(NG_ANIMATE_STATE); cancelled = cancelled || !data || !data.active[className] || (runner.isClassBased && data.active[className].event != animationEvent); fireDOMOperation(); if(cancelled === true) { closeAnimation(); } else { fireAfterCallbackAsync(); runner.after(closeAnimation); } }); function fireDOMCallback(animationPhase) { var eventName = '$animate:' + animationPhase; if(elementEvents && elementEvents[eventName] && elementEvents[eventName].length > 0) { $$asyncCallback(function() { element.triggerHandler(eventName, { event : animationEvent, className : className }); }); } } function fireBeforeCallbackAsync() { fireDOMCallback('before'); } function fireAfterCallbackAsync() { fireDOMCallback('after'); } function fireDoneCallbackAsync() { fireDOMCallback('close'); if(doneCallback) { $$asyncCallback(function() { doneCallback(); }); } } //it is less complicated to use a flag than managing and canceling //timeouts containing multiple callbacks. function fireDOMOperation() { if(!fireDOMOperation.hasBeenRun) { fireDOMOperation.hasBeenRun = true; domOperation(); } } function closeAnimation() { if(!closeAnimation.hasBeenRun) { closeAnimation.hasBeenRun = true; var data = element.data(NG_ANIMATE_STATE); if(data) { /* only structural animations wait for reflow before removing an animation, but class-based animations don't. An example of this failing would be when a parent HTML tag has a ng-class attribute causing ALL directives below to skip animations during the digest */ if(runner && runner.isClassBased) { cleanup(element, className); } else { $$asyncCallback(function() { var data = element.data(NG_ANIMATE_STATE) || {}; if(localAnimationCount == data.index) { cleanup(element, className, animationEvent); } }); element.data(NG_ANIMATE_STATE, data); } } fireDoneCallbackAsync(); } } } function cancelChildAnimations(element) { var node = extractElementNode(element); if (node) { var nodes = angular.isFunction(node.getElementsByClassName) ? node.getElementsByClassName(NG_ANIMATE_CLASS_NAME) : node.querySelectorAll('.' + NG_ANIMATE_CLASS_NAME); forEach(nodes, function(element) { element = angular.element(element); var data = element.data(NG_ANIMATE_STATE); if(data && data.active) { forEach(data.active, function(runner) { runner.cancel(); }); } }); } } function cleanup(element, className) { if(isMatchingElement(element, $rootElement)) { if(!rootAnimateState.disabled) { rootAnimateState.running = false; rootAnimateState.structural = false; } } else if(className) { var data = element.data(NG_ANIMATE_STATE) || {}; var removeAnimations = className === true; if(!removeAnimations && data.active && data.active[className]) { data.totalActive--; delete data.active[className]; } if(removeAnimations || !data.totalActive) { element.removeClass(NG_ANIMATE_CLASS_NAME); element.removeData(NG_ANIMATE_STATE); } } } function animationsDisabled(element, parentElement) { if (rootAnimateState.disabled) return true; if(isMatchingElement(element, $rootElement)) { return rootAnimateState.disabled || rootAnimateState.running; } do { //the element did not reach the root element which means that it //is not apart of the DOM. Therefore there is no reason to do //any animations on it if(parentElement.length === 0) break; var isRoot = isMatchingElement(parentElement, $rootElement); var state = isRoot ? rootAnimateState : parentElement.data(NG_ANIMATE_STATE); var result = state && (!!state.disabled || state.running || state.totalActive > 0); if(isRoot || result) { return result; } if(isRoot) return true; } while(parentElement = parentElement.parent()); return true; } }]); $animateProvider.register('', ['$window', '$sniffer', '$timeout', '$$animateReflow', function($window, $sniffer, $timeout, $$animateReflow) { // Detect proper transitionend/animationend event names. var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT; // If unprefixed events are not supported but webkit-prefixed are, use the latter. // Otherwise, just use W3C names, browsers not supporting them at all will just ignore them. // Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend` // but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`. // Register both events in case `window.onanimationend` is not supported because of that, // do the same for `transitionend` as Safari is likely to exhibit similar behavior. // Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit // therefore there is no reason to test anymore for other vendor prefixes: http://caniuse.com/#search=transition if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined) { CSS_PREFIX = '-webkit-'; TRANSITION_PROP = 'WebkitTransition'; TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend'; } else { TRANSITION_PROP = 'transition'; TRANSITIONEND_EVENT = 'transitionend'; } if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined) { CSS_PREFIX = '-webkit-'; ANIMATION_PROP = 'WebkitAnimation'; ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend'; } else { ANIMATION_PROP = 'animation'; ANIMATIONEND_EVENT = 'animationend'; } var DURATION_KEY = 'Duration'; var PROPERTY_KEY = 'Property'; var DELAY_KEY = 'Delay'; var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount'; var NG_ANIMATE_PARENT_KEY = '$$ngAnimateKey'; var NG_ANIMATE_CSS_DATA_KEY = '$$ngAnimateCSS3Data'; var NG_ANIMATE_BLOCK_CLASS_NAME = 'ng-animate-block-transitions'; var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3; var CLOSING_TIME_BUFFER = 1.5; var ONE_SECOND = 1000; var lookupCache = {}; var parentCounter = 0; var animationReflowQueue = []; var cancelAnimationReflow; function afterReflow(element, callback) { if(cancelAnimationReflow) { cancelAnimationReflow(); } animationReflowQueue.push(callback); cancelAnimationReflow = $$animateReflow(function() { forEach(animationReflowQueue, function(fn) { fn(); }); animationReflowQueue = []; cancelAnimationReflow = null; lookupCache = {}; }); } var closingTimer = null; var closingTimestamp = 0; var animationElementQueue = []; function animationCloseHandler(element, totalTime) { var node = extractElementNode(element); element = angular.element(node); //this item will be garbage collected by the closing //animation timeout animationElementQueue.push(element); //but it may not need to cancel out the existing timeout //if the timestamp is less than the previous one var futureTimestamp = Date.now() + (totalTime * 1000); if(futureTimestamp <= closingTimestamp) { return; } $timeout.cancel(closingTimer); closingTimestamp = futureTimestamp; closingTimer = $timeout(function() { closeAllAnimations(animationElementQueue); animationElementQueue = []; }, totalTime, false); } function closeAllAnimations(elements) { forEach(elements, function(element) { var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY); if(elementData) { (elementData.closeAnimationFn || noop)(); } }); } function getElementAnimationDetails(element, cacheKey) { var data = cacheKey ? lookupCache[cacheKey] : null; if(!data) { var transitionDuration = 0; var transitionDelay = 0; var animationDuration = 0; var animationDelay = 0; var transitionDelayStyle; var animationDelayStyle; var transitionDurationStyle; var transitionPropertyStyle; //we want all the styles defined before and after forEach(element, function(element) { if (element.nodeType == ELEMENT_NODE) { var elementStyles = $window.getComputedStyle(element) || {}; transitionDurationStyle = elementStyles[TRANSITION_PROP + DURATION_KEY]; transitionDuration = Math.max(parseMaxTime(transitionDurationStyle), transitionDuration); transitionPropertyStyle = elementStyles[TRANSITION_PROP + PROPERTY_KEY]; transitionDelayStyle = elementStyles[TRANSITION_PROP + DELAY_KEY]; transitionDelay = Math.max(parseMaxTime(transitionDelayStyle), transitionDelay); animationDelayStyle = elementStyles[ANIMATION_PROP + DELAY_KEY]; animationDelay = Math.max(parseMaxTime(animationDelayStyle), animationDelay); var aDuration = parseMaxTime(elementStyles[ANIMATION_PROP + DURATION_KEY]); if(aDuration > 0) { aDuration *= parseInt(elementStyles[ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY], 10) || 1; } animationDuration = Math.max(aDuration, animationDuration); } }); data = { total : 0, transitionPropertyStyle: transitionPropertyStyle, transitionDurationStyle: transitionDurationStyle, transitionDelayStyle: transitionDelayStyle, transitionDelay: transitionDelay, transitionDuration: transitionDuration, animationDelayStyle: animationDelayStyle, animationDelay: animationDelay, animationDuration: animationDuration }; if(cacheKey) { lookupCache[cacheKey] = data; } } return data; } function parseMaxTime(str) { var maxValue = 0; var values = angular.isString(str) ? str.split(/\s*,\s*/) : []; forEach(values, function(value) { maxValue = Math.max(parseFloat(value) || 0, maxValue); }); return maxValue; } function getCacheKey(element) { var parentElement = element.parent(); var parentID = parentElement.data(NG_ANIMATE_PARENT_KEY); if(!parentID) { parentElement.data(NG_ANIMATE_PARENT_KEY, ++parentCounter); parentID = parentCounter; } return parentID + '-' + extractElementNode(element).className; } function animateSetup(animationEvent, element, className, calculationDecorator) { var cacheKey = getCacheKey(element); var eventCacheKey = cacheKey + ' ' + className; var itemIndex = lookupCache[eventCacheKey] ? ++lookupCache[eventCacheKey].total : 0; var stagger = {}; if(itemIndex > 0) { var staggerClassName = className + '-stagger'; var staggerCacheKey = cacheKey + ' ' + staggerClassName; var applyClasses = !lookupCache[staggerCacheKey]; applyClasses && element.addClass(staggerClassName); stagger = getElementAnimationDetails(element, staggerCacheKey); applyClasses && element.removeClass(staggerClassName); } /* the animation itself may need to add/remove special CSS classes * before calculating the anmation styles */ calculationDecorator = calculationDecorator || function(fn) { return fn(); }; element.addClass(className); var formerData = element.data(NG_ANIMATE_CSS_DATA_KEY) || {}; var timings = calculationDecorator(function() { return getElementAnimationDetails(element, eventCacheKey); }); var transitionDuration = timings.transitionDuration; var animationDuration = timings.animationDuration; if(transitionDuration === 0 && animationDuration === 0) { element.removeClass(className); return false; } element.data(NG_ANIMATE_CSS_DATA_KEY, { running : formerData.running || 0, itemIndex : itemIndex, stagger : stagger, timings : timings, closeAnimationFn : noop }); //temporarily disable the transition so that the enter styles //don't animate twice (this is here to avoid a bug in Chrome/FF). var isCurrentlyAnimating = formerData.running > 0 || animationEvent == 'setClass'; if(transitionDuration > 0) { blockTransitions(element, className, isCurrentlyAnimating); } //staggering keyframe animations work by adjusting the `animation-delay` CSS property //on the given element, however, the delay value can only calculated after the reflow //since by that time $animate knows how many elements are being animated. Therefore, //until the reflow occurs the element needs to be blocked (where the keyframe animation //is set to `none 0s`). This blocking mechanism should only be set for when a stagger //animation is detected and when the element item index is greater than 0. if(animationDuration > 0 && stagger.animationDelay > 0 && stagger.animationDuration === 0) { blockKeyframeAnimations(element); } return true; } function isStructuralAnimation(className) { return className == 'ng-enter' || className == 'ng-move' || className == 'ng-leave'; } function blockTransitions(element, className, isAnimating) { if(isStructuralAnimation(className) || !isAnimating) { extractElementNode(element).style[TRANSITION_PROP + PROPERTY_KEY] = 'none'; } else { element.addClass(NG_ANIMATE_BLOCK_CLASS_NAME); } } function blockKeyframeAnimations(element) { extractElementNode(element).style[ANIMATION_PROP] = 'none 0s'; } function unblockTransitions(element, className) { var prop = TRANSITION_PROP + PROPERTY_KEY; var node = extractElementNode(element); if(node.style[prop] && node.style[prop].length > 0) { node.style[prop] = ''; } element.removeClass(NG_ANIMATE_BLOCK_CLASS_NAME); } function unblockKeyframeAnimations(element) { var prop = ANIMATION_PROP; var node = extractElementNode(element); if(node.style[prop] && node.style[prop].length > 0) { node.style[prop] = ''; } } function animateRun(animationEvent, element, className, activeAnimationComplete) { var node = extractElementNode(element); var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY); if(node.className.indexOf(className) == -1 || !elementData) { activeAnimationComplete(); return; } var activeClassName = ''; forEach(className.split(' '), function(klass, i) { activeClassName += (i > 0 ? ' ' : '') + klass + '-active'; }); var stagger = elementData.stagger; var timings = elementData.timings; var itemIndex = elementData.itemIndex; var maxDuration = Math.max(timings.transitionDuration, timings.animationDuration); var maxDelay = Math.max(timings.transitionDelay, timings.animationDelay); var maxDelayTime = maxDelay * ONE_SECOND; var startTime = Date.now(); var css3AnimationEvents = ANIMATIONEND_EVENT + ' ' + TRANSITIONEND_EVENT; var style = '', appliedStyles = []; if(timings.transitionDuration > 0) { var propertyStyle = timings.transitionPropertyStyle; if(propertyStyle.indexOf('all') == -1) { style += CSS_PREFIX + 'transition-property: ' + propertyStyle + ';'; style += CSS_PREFIX + 'transition-duration: ' + timings.transitionDurationStyle + ';'; appliedStyles.push(CSS_PREFIX + 'transition-property'); appliedStyles.push(CSS_PREFIX + 'transition-duration'); } } if(itemIndex > 0) { if(stagger.transitionDelay > 0 && stagger.transitionDuration === 0) { var delayStyle = timings.transitionDelayStyle; style += CSS_PREFIX + 'transition-delay: ' + prepareStaggerDelay(delayStyle, stagger.transitionDelay, itemIndex) + '; '; appliedStyles.push(CSS_PREFIX + 'transition-delay'); } if(stagger.animationDelay > 0 && stagger.animationDuration === 0) { style += CSS_PREFIX + 'animation-delay: ' + prepareStaggerDelay(timings.animationDelayStyle, stagger.animationDelay, itemIndex) + '; '; appliedStyles.push(CSS_PREFIX + 'animation-delay'); } } if(appliedStyles.length > 0) { //the element being animated may sometimes contain comment nodes in //the jqLite object, so we're safe to use a single variable to house //the styles since there is always only one element being animated var oldStyle = node.getAttribute('style') || ''; node.setAttribute('style', oldStyle + ' ' + style); } element.on(css3AnimationEvents, onAnimationProgress); element.addClass(activeClassName); elementData.closeAnimationFn = function() { onEnd(); activeAnimationComplete(); }; var staggerTime = itemIndex * (Math.max(stagger.animationDelay, stagger.transitionDelay) || 0); var animationTime = (maxDelay + maxDuration) * CLOSING_TIME_BUFFER; var totalTime = (staggerTime + animationTime) * ONE_SECOND; elementData.running++; animationCloseHandler(element, totalTime); return onEnd; // This will automatically be called by $animate so // there is no need to attach this internally to the // timeout done method. function onEnd(cancelled) { element.off(css3AnimationEvents, onAnimationProgress); element.removeClass(activeClassName); animateClose(element, className); var node = extractElementNode(element); for (var i in appliedStyles) { node.style.removeProperty(appliedStyles[i]); } } function onAnimationProgress(event) { event.stopPropagation(); var ev = event.originalEvent || event; var timeStamp = ev.$manualTimeStamp || ev.timeStamp || Date.now(); /* Firefox (or possibly just Gecko) likes to not round values up * when a ms measurement is used for the animation */ var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES)); /* $manualTimeStamp is a mocked timeStamp value which is set * within browserTrigger(). This is only here so that tests can * mock animations properly. Real events fallback to event.timeStamp, * or, if they don't, then a timeStamp is automatically created for them. * We're checking to see if the timeStamp surpasses the expected delay, * but we're using elapsedTime instead of the timeStamp on the 2nd * pre-condition since animations sometimes close off early */ if(Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) { activeAnimationComplete(); } } } function prepareStaggerDelay(delayStyle, staggerDelay, index) { var style = ''; forEach(delayStyle.split(','), function(val, i) { style += (i > 0 ? ',' : '') + (index * staggerDelay + parseInt(val, 10)) + 's'; }); return style; } function animateBefore(animationEvent, element, className, calculationDecorator) { if(animateSetup(animationEvent, element, className, calculationDecorator)) { return function(cancelled) { cancelled && animateClose(element, className); }; } } function animateAfter(animationEvent, element, className, afterAnimationComplete) { if(element.data(NG_ANIMATE_CSS_DATA_KEY)) { return animateRun(animationEvent, element, className, afterAnimationComplete); } else { animateClose(element, className); afterAnimationComplete(); } } function animate(animationEvent, element, className, animationComplete) { //If the animateSetup function doesn't bother returning a //cancellation function then it means that there is no animation //to perform at all var preReflowCancellation = animateBefore(animationEvent, element, className); if(!preReflowCancellation) { animationComplete(); return; } //There are two cancellation functions: one is before the first //reflow animation and the second is during the active state //animation. The first function will take care of removing the //data from the element which will not make the 2nd animation //happen in the first place var cancel = preReflowCancellation; afterReflow(element, function() { unblockTransitions(element, className); unblockKeyframeAnimations(element); //once the reflow is complete then we point cancel to //the new cancellation function which will remove all of the //animation properties from the active animation cancel = animateAfter(animationEvent, element, className, animationComplete); }); return function(cancelled) { (cancel || noop)(cancelled); }; } function animateClose(element, className) { element.removeClass(className); var data = element.data(NG_ANIMATE_CSS_DATA_KEY); if(data) { if(data.running) { data.running--; } if(!data.running || data.running === 0) { element.removeData(NG_ANIMATE_CSS_DATA_KEY); } } } return { enter : function(element, animationCompleted) { return animate('enter', element, 'ng-enter', animationCompleted); }, leave : function(element, animationCompleted) { return animate('leave', element, 'ng-leave', animationCompleted); }, move : function(element, animationCompleted) { return animate('move', element, 'ng-move', animationCompleted); }, beforeSetClass : function(element, add, remove, animationCompleted) { var className = suffixClasses(remove, '-remove') + ' ' + suffixClasses(add, '-add'); var cancellationMethod = animateBefore('setClass', element, className, function(fn) { /* when classes are removed from an element then the transition style * that is applied is the transition defined on the element without the * CSS class being there. This is how CSS3 functions outside of ngAnimate. * http://plnkr.co/edit/j8OzgTNxHTb4n3zLyjGW?p=preview */ var klass = element.attr('class'); element.removeClass(remove); element.addClass(add); var timings = fn(); element.attr('class', klass); return timings; }); if(cancellationMethod) { afterReflow(element, function() { unblockTransitions(element, className); unblockKeyframeAnimations(element); animationCompleted(); }); return cancellationMethod; } animationCompleted(); }, beforeAddClass : function(element, className, animationCompleted) { var cancellationMethod = animateBefore('addClass', element, suffixClasses(className, '-add'), function(fn) { /* when a CSS class is added to an element then the transition style that * is applied is the transition defined on the element when the CSS class * is added at the time of the animation. This is how CSS3 functions * outside of ngAnimate. */ element.addClass(className); var timings = fn(); element.removeClass(className); return timings; }); if(cancellationMethod) { afterReflow(element, function() { unblockTransitions(element, className); unblockKeyframeAnimations(element); animationCompleted(); }); return cancellationMethod; } animationCompleted(); }, setClass : function(element, add, remove, animationCompleted) { remove = suffixClasses(remove, '-remove'); add = suffixClasses(add, '-add'); var className = remove + ' ' + add; return animateAfter('setClass', element, className, animationCompleted); }, addClass : function(element, className, animationCompleted) { return animateAfter('addClass', element, suffixClasses(className, '-add'), animationCompleted); }, beforeRemoveClass : function(element, className, animationCompleted) { var cancellationMethod = animateBefore('removeClass', element, suffixClasses(className, '-remove'), function(fn) { /* when classes are removed from an element then the transition style * that is applied is the transition defined on the element without the * CSS class being there. This is how CSS3 functions outside of ngAnimate. * http://plnkr.co/edit/j8OzgTNxHTb4n3zLyjGW?p=preview */ var klass = element.attr('class'); element.removeClass(className); var timings = fn(); element.attr('class', klass); return timings; }); if(cancellationMethod) { afterReflow(element, function() { unblockTransitions(element, className); unblockKeyframeAnimations(element); animationCompleted(); }); return cancellationMethod; } animationCompleted(); }, removeClass : function(element, className, animationCompleted) { return animateAfter('removeClass', element, suffixClasses(className, '-remove'), animationCompleted); } }; function suffixClasses(classes, suffix) { var className = ''; classes = angular.isArray(classes) ? classes : classes.split(/\s+/); forEach(classes, function(klass, i) { if(klass && klass.length > 0) { className += (i > 0 ? ' ' : '') + klass + suffix; } }); return className; } }]); }]); })(window, window.angular);
sabhiram/nodejs-scaffolding
app/public/js/angular-animate.js
JavaScript
bsd-2-clause
74,308
#!/usr/bin/env python # -*- coding: utf-8 -*- """--- Day 3: Perfectly Spherical Houses in a Vacuum --- Santa is delivering presents to an infinite two-dimensional grid of houses. He begins by delivering a present to the house at his starting location, and then an elf at the North Pole calls him via radio and tells him where to move next. Moves are always exactly one house to the north (^), south (v), east (>), or west (<). After each move, he delivers another present to the house at his new location. However, the elf back at the north pole has had a little too much eggnog, and so his directions are a little off, and Santa ends up visiting some houses more than once. How many houses receive at least one present? For example: - > delivers presents to 2 houses: one at the starting location, and one to the east. - ^>v< delivers presents to 4 houses in a square, including twice to the house at his starting/ending location. - ^v^v^v^v^v delivers a bunch of presents to some very lucky children at only 2 houses. --- Part Two --- The next year, to speed up the process, Santa creates a robot version of himself, Robo-Santa, to deliver presents with him. Santa and Robo-Santa start at the same location (delivering two presents to the same starting house), then take turns moving based on instructions from the elf, who is eggnoggedly reading from the same script as the previous year. This year, how many houses receive at least one present? For example: - ^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa goes south. - ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa end up back where they started. - ^v^v^v^v^v now delivers presents to 11 houses, with Santa going one direction and Robo-Santa going the other. """ import sys import click def update_point(move, point): """Returns new point representing position after move""" moves = { '^': (0, -1), '<': (-1, 0), 'v': (0, 1), '>': (1, 0), } return (point[0]+moves.get(move, (0, 0))[0], point[1]+moves.get(move, (0, 0))[1]) def map_single_delivery(text): point = (0, 0) points = set({point}) for move in text: point = update_point(move, point) points.add(point) return points def number_of_houses_covered(text, robo_santa=False): return len(map_single_delivery(text)) if not robo_santa else \ len(map_multiple_deliveries(text)) def split_directions(directions): lists = ('', '') try: lists = directions[0::2], directions[1::2] except IndexError: pass return lists def map_multiple_deliveries(text): directions = split_directions(text) points = map_single_delivery(directions[0]) return points.union(map_single_delivery(directions[1])) def calculate_solution_1(text): return number_of_houses_covered(text) def calculate_solution_2(text): return number_of_houses_covered(text, robo_santa=True) @click.command() @click.option('--source_file', default='data/03.txt', help='source data file for problem') def main(source_file): """Simple solution to adventofcode problem 3.""" data = '' with open(source_file) as source: data = source.read() print('Santa gave at least one present to {} houses.'.format( number_of_houses_covered(data))) if __name__ == "__main__": sys.exit(main())
MattJDavidson/python-adventofcode
advent/problem_03.py
Python
bsd-2-clause
3,424
/****************************************************************************** * The MIT License * Copyright (c) 2007 Novell Inc., www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // Authors: // Thomas Wiest (twiest@novell.com) // Rusty Howell (rhowell@novell.com) // // (C) Novell Inc. using System; using System.Collections.Generic; using System.Text; namespace System.Management.Internal { internal class CimTable { public CimTable() { throw new Exception("Not yet implemented"); } } }
brunolauze/System.Management
System.Management/System.Management.Internal/CimDataTypes/CimTable.cs
C#
bsd-2-clause
1,669
// Copyright 2010 Google Inc. All Rights Reserved. // Refactored from contributions of various authors in strings/strutil.cc // // This file contains string processing functions related to // numeric values. #define __STDC_FORMAT_MACROS 1 #include "strings/numbers.h" #include <memory> #include <cassert> #include <ctype.h> #include <errno.h> #include <float.h> // for DBL_DIG and FLT_DIG #include <math.h> // for HUGE_VAL #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits> using std::numeric_limits; #include <string> using std::string; #include "base/int128.h" #include "base/integral_types.h" #include "base/logging.h" #include "strings/stringprintf.h" #include "strings/strtoint.h" #include "strings/ascii_ctype.h" // Reads a <double> in *text, which may not be whitespace-initiated. // *len is the length, or -1 if text is '\0'-terminated, which is more // efficient. Sets *text to the end of the double, and val to the // converted value, and the length of the double is subtracted from // *len. <double> may also be a '?', in which case val will be // unchanged. Returns true upon success. If initial_minus is // non-NULL, then *initial_minus will indicate whether the first // symbol seen was a '-', which will be ignored. Similarly, if // final_period is non-NULL, then *final_period will indicate whether // the last symbol seen was a '.', which will be ignored. This is // useful in case that an initial '-' or final '.' would have another // meaning (as a separator, e.g.). static inline bool EatADouble(const char** text, int* len, bool allow_question, double* val, bool* initial_minus, bool* final_period) { const char* pos = *text; int rem = *len; // remaining length, or -1 if null-terminated if (pos == NULL || rem == 0) return false; if (allow_question && (*pos == '?')) { *text = pos + 1; if (rem != -1) *len = rem - 1; return true; } if (initial_minus) { if ((*initial_minus = (*pos == '-'))) { // Yes, we want assignment. if (rem == 1) return false; ++pos; if (rem != -1) --rem; } } // a double has to begin one of these (we don't allow 'inf' or whitespace) // this also serves as an optimization. if (!strchr("-+.0123456789", *pos)) return false; // strtod is evil in that the second param is a non-const char** char* end_nonconst; double retval; if (rem == -1) { retval = strtod(pos, &end_nonconst); } else { // not '\0'-terminated & no obvious terminator found. must copy. std::unique_ptr<char[]> buf(new char[rem + 1]); memcpy(buf.get(), pos, rem); buf[rem] = '\0'; retval = strtod(buf.get(), &end_nonconst); end_nonconst = const_cast<char*>(pos) + (end_nonconst - buf.get()); } if (pos == end_nonconst) return false; if (final_period) { *final_period = (end_nonconst[-1] == '.'); if (*final_period) { --end_nonconst; } } *text = end_nonconst; *val = retval; if (rem != -1) *len = rem - (end_nonconst - pos); return true; } // If update, consume one of acceptable_chars from string *text of // length len and return that char, or '\0' otherwise. If len is -1, // *text is null-terminated. If update is false, don't alter *text and // *len. If null_ok, then update must be false, and, if text has no // more chars, then return '\1' (arbitrary nonzero). static inline char EatAChar(const char** text, int* len, const char* acceptable_chars, bool update, bool null_ok) { assert(!(update && null_ok)); if ((*len == 0) || (**text == '\0')) return (null_ok ? '\1' : '\0'); // if null_ok, we're in predicate mode. if (strchr(acceptable_chars, **text)) { char result = **text; if (update) { ++(*text); if (*len != -1) --(*len); } return result; } return '\0'; // no match; no update } // Parse an expression in 'text' of the form: <comparator><double> or // <double><sep><double> See full comments in header file. bool ParseDoubleRange(const char* text, int len, const char** end, double* from, double* to, bool* is_currency, const DoubleRangeOptions& opts) { const double from_default = opts.dont_modify_unbounded ? *from : -HUGE_VAL; if (!opts.dont_modify_unbounded) { *from = -HUGE_VAL; *to = HUGE_VAL; } if (opts.allow_currency && (is_currency != NULL)) *is_currency = false; assert(len >= -1); assert(opts.separators && (*opts.separators != '\0')); // these aren't valid separators assert(strlen(opts.separators) == strcspn(opts.separators, "+0123456789eE$")); assert(opts.num_required_bounds <= 2); // Handle easier cases of comparators (<, >) first if (opts.allow_comparators) { char comparator = EatAChar(&text, &len, "<>", true, false); if (comparator) { double* dest = (comparator == '>') ? from : to; EatAChar(&text, &len, "=", true, false); if (opts.allow_currency && EatAChar(&text, &len, "$", true, false)) if (is_currency != NULL) *is_currency = true; if (!EatADouble(&text, &len, opts.allow_unbounded_markers, dest, NULL, NULL)) return false; *end = text; return EatAChar(&text, &len, opts.acceptable_terminators, false, opts.null_terminator_ok); } } bool seen_dollar = (opts.allow_currency && EatAChar(&text, &len, "$", true, false)); // If we see a '-', two things could be happening: -<to> or // <from>... where <from> is negative. Treat initial minus sign as a // separator if '-' is a valid separator. // Similarly, we prepare for the possibility of seeing a '.' at the // end of the number, in case '.' (which really means '..') is a // separator. bool initial_minus_sign = false; bool final_period = false; bool* check_initial_minus = (strchr(opts.separators, '-') && !seen_dollar && (opts.num_required_bounds < 2)) ? (&initial_minus_sign) : NULL; bool* check_final_period = strchr(opts.separators, '.') ? (&final_period) : NULL; bool double_seen = EatADouble(&text, &len, opts.allow_unbounded_markers, from, check_initial_minus, check_final_period); // if 2 bounds required, must see a double (or '?' if allowed) if ((opts.num_required_bounds == 2) && !double_seen) return false; if (seen_dollar && !double_seen) { --text; if (len != -1) ++len; seen_dollar = false; } // If we're here, we've read the first double and now expect a // separator and another <double>. char separator = EatAChar(&text, &len, opts.separators, true, false); if (separator == '.') { // seen one '.' as separator; must check for another; perhaps set seplen=2 if (EatAChar(&text, &len, ".", true, false)) { if (final_period) { // We may have three periods in a row. The first is part of the // first number, the others are a separator. Policy: 234...567 // is "234." to "567", not "234" to ".567". EatAChar(&text, &len, ".", true, false); } } else if (!EatAChar(&text, &len, opts.separators, true, false)) { // just one '.' and no other separator; uneat the first '.' we saw --text; if (len != -1) ++len; separator = '\0'; } } // By now, we've consumed whatever separator there may have been, // and separator is true iff there was one. if (!separator) { if (final_period) // final period now considered part of first double EatAChar(&text, &len, ".", true, false); if (initial_minus_sign && double_seen) { *to = *from; *from = from_default; } else if (opts.require_separator || (opts.num_required_bounds > 0 && !double_seen) || (opts.num_required_bounds > 1) ) { return false; } } else { if (initial_minus_sign && double_seen) *from = -(*from); // read second <double> bool second_dollar_seen = (seen_dollar || (opts.allow_currency && !double_seen)) && EatAChar(&text, &len, "$", true, false); bool second_double_seen = EatADouble( &text, &len, opts.allow_unbounded_markers, to, NULL, NULL); if (opts.num_required_bounds > uint32(double_seen) + uint32(second_double_seen)) return false; if (second_dollar_seen && !second_double_seen) { --text; if (len != -1) ++len; second_dollar_seen = false; } seen_dollar = seen_dollar || second_dollar_seen; } if (seen_dollar && (is_currency != NULL)) *is_currency = true; // We're done. But we have to check that the next char is a proper // terminator. *end = text; char terminator = EatAChar(&text, &len, opts.acceptable_terminators, false, opts.null_terminator_ok); if (terminator == '.') --(*end); return terminator; } // ---------------------------------------------------------------------- // ConsumeStrayLeadingZeroes // Eliminates all leading zeroes (unless the string itself is composed // of nothing but zeroes, in which case one is kept: 0...0 becomes 0). // -------------------------------------------------------------------- void ConsumeStrayLeadingZeroes(string *const str) { const string::size_type len(str->size()); if (len > 1 && (*str)[0] == '0') { const char *const begin(str->c_str()), *const end(begin + len), *ptr(begin + 1); while (ptr != end && *ptr == '0') { ++ptr; } string::size_type remove(ptr - begin); DCHECK_GT(ptr, begin); if (remove == len) { --remove; // if they are all zero, leave one... } str->erase(0, remove); } } // ---------------------------------------------------------------------- // ParseLeadingInt32Value() // ParseLeadingUInt32Value() // A simple parser for [u]int32 values. Returns the parsed value // if a valid value is found; else returns deflt // This cannot handle decimal numbers with leading 0s. // -------------------------------------------------------------------- int32 ParseLeadingInt32Value(StringPiece str, int32 deflt) { if (str.empty()) return deflt; using std::numeric_limits; char *error = NULL; long value = strtol(str.data(), &error, 0); // Limit long values to int32 min/max. Needed for lp64; no-op on 32 bits. if (value > numeric_limits<int32>::max()) { value = numeric_limits<int32>::max(); } else if (value < numeric_limits<int32>::min()) { value = numeric_limits<int32>::min(); } return (error == str.data()) ? deflt : value; } uint32 ParseLeadingUInt32Value(StringPiece str, uint32 deflt) { using std::numeric_limits; if (str.empty()) return deflt; if (numeric_limits<unsigned long>::max() == numeric_limits<uint32>::max()) { // When long is 32 bits, we can use strtoul. char *error = NULL; const uint32 value = strtoul(str.data(), &error, 0); return (error == str.data()) ? deflt : value; } else { // When long is 64 bits, we must use strto64 and handle limits // by hand. The reason we cannot use a 64-bit strtoul is that // it would be impossible to differentiate "-2" (that should wrap // around to the value UINT_MAX-1) from a string with ULONG_MAX-1 // (that should be pegged to UINT_MAX due to overflow). char *error = NULL; int64 value = strto64(str.data(), &error, 0); if (value > numeric_limits<uint32>::max() || value < -static_cast<int64>(numeric_limits<uint32>::max())) { value = numeric_limits<uint32>::max(); } // Within these limits, truncation to 32 bits handles negatives correctly. return (error == str.data()) ? deflt : value; } } // ---------------------------------------------------------------------- // ParseLeadingDec32Value // ParseLeadingUDec32Value // A simple parser for [u]int32 values. Returns the parsed value // if a valid value is found; else returns deflt // The string passed in is treated as *10 based*. // This can handle strings with leading 0s. // -------------------------------------------------------------------- int32 ParseLeadingDec32Value(StringPiece str, int32 deflt) { using std::numeric_limits; char *error = NULL; long value = strtol(str.data(), &error, 10); // Limit long values to int32 min/max. Needed for lp64; no-op on 32 bits. if (value > numeric_limits<int32>::max()) { value = numeric_limits<int32>::max(); } else if (value < numeric_limits<int32>::min()) { value = numeric_limits<int32>::min(); } return (error == str.data()) ? deflt : value; } uint32 ParseLeadingUDec32Value(StringPiece str, uint32 deflt) { using std::numeric_limits; if (numeric_limits<unsigned long>::max() == numeric_limits<uint32>::max()) { // When long is 32 bits, we can use strtoul. char *error = NULL; const uint32 value = strtoul(str.data(), &error, 10); return (error == str.begin()) ? deflt : value; } else { // When long is 64 bits, we must use strto64 and handle limits // by hand. The reason we cannot use a 64-bit strtoul is that // it would be impossible to differentiate "-2" (that should wrap // around to the value UINT_MAX-1) from a string with ULONG_MAX-1 // (that should be pegged to UINT_MAX due to overflow). char *error = NULL; int64 value = strto64(str.data(), &error, 10); if (value > numeric_limits<uint32>::max() || value < -static_cast<int64>(numeric_limits<uint32>::max())) { value = numeric_limits<uint32>::max(); } // Within these limits, truncation to 32 bits handles negatives correctly. return (error == str.data()) ? deflt : value; } } // ---------------------------------------------------------------------- // ParseLeadingUInt64Value // ParseLeadingInt64Value // ParseLeadingHex64Value // A simple parser for 64-bit values. Returns the parsed value if a // valid integer is found; else returns deflt // UInt64 and Int64 cannot handle decimal numbers with leading 0s. // -------------------------------------------------------------------- uint64 ParseLeadingUInt64Value(StringPiece str, uint64 deflt) { char *error = NULL; const uint64 value = strtou64(str.data(), &error, 0); return (error == str.data()) ? deflt : value; } int64 ParseLeadingInt64Value(StringPiece str, int64 deflt) { char *error = NULL; const int64 value = strto64(str.data(), &error, 0); return (error == str.data()) ? deflt : value; } uint64 ParseLeadingHex64Value(StringPiece str, uint64 deflt) { char *error = NULL; const uint64 value = strtou64(str.data(), &error, 16); return (error == str.data()) ? deflt : value; } // ---------------------------------------------------------------------- // ParseLeadingDec64Value // ParseLeadingUDec64Value // A simple parser for [u]int64 values. Returns the parsed value // if a valid value is found; else returns deflt // The string passed in is treated as *10 based*. // This can handle strings with leading 0s. // -------------------------------------------------------------------- int64 ParseLeadingDec64Value(StringPiece str, int64 deflt) { char *error = NULL; const int64 value = strto64(str.data(), &error, 10); return (error == str.data()) ? deflt : value; } uint64 ParseLeadingUDec64Value(StringPiece str, uint64 deflt) { char *error = NULL; const uint64 value = strtou64(str.data(), &error, 10); return (error == str.data()) ? deflt : value; } // ---------------------------------------------------------------------- // ParseLeadingDoubleValue() // A simple parser for double values. Returns the parsed value // if a valid value is found; else returns deflt // -------------------------------------------------------------------- double ParseLeadingDoubleValue(const char *str, double deflt) { char *error = NULL; errno = 0; const double value = strtod(str, &error); if (errno != 0 || // overflow/underflow happened error == str) { // no valid parse return deflt; } else { return value; } } // ---------------------------------------------------------------------- // ParseLeadingBoolValue() // A recognizer of boolean string values. Returns the parsed value // if a valid value is found; else returns deflt. This skips leading // whitespace, is case insensitive, and recognizes these forms: // 0/1, false/true, no/yes, n/y // -------------------------------------------------------------------- bool ParseLeadingBoolValue(const char *str, bool deflt) { static const int kMaxLen = 5; char value[kMaxLen + 1]; // Skip whitespace while (ascii_isspace(*str)) { ++str; } int len = 0; for (; len <= kMaxLen && ascii_isalnum(*str); ++str) value[len++] = ascii_tolower(*str); if (len == 0 || len > kMaxLen) return deflt; value[len] = '\0'; switch (len) { case 1: if (value[0] == '0' || value[0] == 'n') return false; if (value[0] == '1' || value[0] == 'y') return true; break; case 2: if (!strcmp(value, "no")) return false; break; case 3: if (!strcmp(value, "yes")) return true; break; case 4: if (!strcmp(value, "true")) return true; break; case 5: if (!strcmp(value, "false")) return false; break; } return deflt; } // ---------------------------------------------------------------------- // FpToString() // FloatToString() // IntToString() // Convert various types to their string representation, possibly padded // with spaces, using snprintf format specifiers. // ---------------------------------------------------------------------- string FpToString(Fprint fp) { char buf[17]; snprintf(buf, sizeof(buf), "%016" PRIu64 "x", fp); return string(buf); } namespace { // Represents integer values of digits. // Uses 36 to indicate an invalid character since we support // bases up to 36. static const int8 kAsciiToInt[256] = { 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, // 16 36s. 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 36, 36, 36, 36, 36, 36, 36, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 36, 36, 36, 36, 36, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36 }; // Parse the sign and optional hex or oct prefix in range // [*start_ptr, *end_ptr). inline bool safe_parse_sign_and_base(const char** start_ptr /*inout*/, const char** end_ptr /*inout*/, int* base_ptr /*inout*/, bool* negative_ptr /*output*/) { const char* start = *start_ptr; const char* end = *end_ptr; int base = *base_ptr; // Consume whitespace. while (start < end && ascii_isspace(start[0])) { ++start; } while (start < end && ascii_isspace(end[-1])) { --end; } if (start >= end) { return false; } // Consume sign. *negative_ptr = (start[0] == '-'); if (*negative_ptr || start[0] == '+') { ++start; if (start >= end) { return false; } } // Consume base-dependent prefix. // base 0: "0x" -> base 16, "0" -> base 8, default -> base 10 // base 16: "0x" -> base 16 // Also validate the base. if (base == 0) { if (end - start >= 2 && start[0] == '0' && (start[1] == 'x' || start[1] == 'X')) { base = 16; start += 2; } else if (end - start >= 1 && start[0] == '0') { base = 8; start += 1; } else { base = 10; } } else if (base == 16) { if (end - start >= 2 && start[0] == '0' && (start[1] == 'x' || start[1] == 'X')) { start += 2; } } else if (base >= 2 && base <= 36) { // okay } else { return false; } *start_ptr = start; *end_ptr = end; *base_ptr = base; return true; } // Consume digits. // // The classic loop: // // for each digit // value = value * base + digit // value *= sign // // The classic loop needs overflow checking. It also fails on the most // negative integer, -2147483648 in 32-bit two's complement representation. // // My improved loop: // // if (!negative) // for each digit // value = value * base // value = value + digit // else // for each digit // value = value * base // value = value - digit // // Overflow checking becomes simple. template<typename IntType> inline bool safe_parse_positive_int( const char* start, const char* end, int base, IntType* value_p) { IntType value = 0; const IntType vmax = std::numeric_limits<IntType>::max(); assert(vmax > 0); // assert(vmax >= base); const IntType vmax_over_base = vmax / base; // loop over digits // loop body is interleaved for perf, not readability for (; start < end; ++start) { unsigned char c = static_cast<unsigned char>(start[0]); int digit = kAsciiToInt[c]; if (value > vmax_over_base) return false; value *= base; if (digit >= base) return false; if (value > vmax - digit) return false; value += digit; } *value_p = value; return true; } template<typename IntType> inline bool safe_parse_negative_int( const char* start, const char* end, int base, IntType* value_p) { IntType value = 0; const IntType vmin = std::numeric_limits<IntType>::min(); assert(vmin < 0); IntType vmin_over_base = vmin / base; // 2003 c++ standard [expr.mul] // "... the sign of the remainder is implementation-defined." // Although (vmin/base)*base + vmin%base is always vmin. // 2011 c++ standard tightens the spec but we cannot rely on it. if (vmin % base > 0) { vmin_over_base += 1; } // loop over digits // loop body is interleaved for perf, not readability for (; start < end; ++start) { unsigned char c = static_cast<unsigned char>(start[0]); int digit = kAsciiToInt[c]; if (value < vmin_over_base) return false; value *= base; if (digit >= base) return false; if (value < vmin + digit) return false; value -= digit; } *value_p = value; return true; } // Input format based on POSIX.1-2008 strtol // http://pubs.opengroup.org/onlinepubs/9699919799/functions/strtol.html template<typename IntType> bool safe_int_internal(const char* start, const char* end, int base, IntType* value_p) { bool negative; if (!safe_parse_sign_and_base(&start, &end, &base, &negative)) { return false; } if (!negative) { return safe_parse_positive_int(start, end, base, value_p); } else { return safe_parse_negative_int(start, end, base, value_p); } } template<typename IntType> inline bool safe_uint_internal(const char* start, const char* end, int base, IntType* value_p) { bool negative; if (!safe_parse_sign_and_base(&start, &end, &base, &negative) || negative) { return false; } return safe_parse_positive_int(start, end, base, value_p); } } // anonymous namespace bool safe_strto32_base(StringPiece str, int32* v, int base) { return safe_int_internal<int32>(str.begin(), str.end(), base, v); } bool safe_strto64_base(StringPiece str, int64* v, int base) { return safe_int_internal<int64>(str.begin(), str.end(), base, v); } bool safe_strto32(StringPiece str, int32* value) { return safe_int_internal<int32>(str.begin(), str.end(), 10, value); } bool safe_strtou32(StringPiece str, uint32* value) { return safe_uint_internal<uint32>(str.begin(), str.end(), 10, value); } bool safe_strto64(StringPiece str, int64* value) { return safe_int_internal<int64>(str.begin(), str.end(), 10, value); } bool safe_strtou64(StringPiece str, uint64* value) { return safe_uint_internal<uint64>(str.begin(), str.end(), 10, value); } bool safe_strtou32_base(StringPiece str, uint32* value, int base) { return safe_uint_internal<uint32>(str.begin(), str.end(), base, value); } bool safe_strtou64_base(StringPiece str, uint64* value, int base) { return safe_uint_internal<uint64>(str.begin(), str.end(), base, value); } // ---------------------------------------------------------------------- // u64tostr_base36() // Converts unsigned number to string representation in base-36. // -------------------------------------------------------------------- size_t u64tostr_base36(uint64 number, size_t buf_size, char* buffer) { CHECK_GT(buf_size, 0); CHECK(buffer); static const char kAlphabet[] = "0123456789abcdefghijklmnopqrstuvwxyz"; buffer[buf_size - 1] = '\0'; size_t result_size = 1; do { if (buf_size == result_size) { // Ran out of space. return 0; } int remainder = number % 36; number /= 36; buffer[buf_size - result_size - 1] = kAlphabet[remainder]; result_size++; } while (number); memmove(buffer, buffer + buf_size - result_size, result_size); return result_size - 1; } bool safe_strtof(StringPiece str, float* value) { char* endptr; *value = strtof(str.data(), &endptr); if (endptr != str.data()) { while (endptr < str.end() && ascii_isspace(*endptr)) ++endptr; } // Ignore range errors from strtod/strtof. // The values it returns on underflow and // overflow are the right fallback in a // robust setting. return !str.empty() && endptr == str.end(); } bool safe_strtod(StringPiece str, double* value) { char* endptr; *value = strtod(str.data(), &endptr); if (endptr != str.data()) { while (endptr < str.end() && ascii_isspace(*endptr)) ++endptr; } // Ignore range errors from strtod. The values it // returns on underflow and overflow are the right // fallback in a robust setting. return !str.empty() && endptr == str.end(); } uint64 atoi_kmgt(const char* s) { char* endptr; uint64 n = strtou64(s, &endptr, 10); uint64 scale = 1; char c = *endptr; if (c != '\0') { c = ascii_toupper(c); switch (c) { case 'K': scale = GG_ULONGLONG(1) << 10; break; case 'M': scale = GG_ULONGLONG(1) << 20; break; case 'G': scale = GG_ULONGLONG(1) << 30; break; case 'T': scale = GG_ULONGLONG(1) << 40; break; default: LOG(FATAL) << "Invalid mnemonic: `" << c << "';" << " should be one of `K', `M', `G', and `T'."; } } return n * scale; } // ---------------------------------------------------------------------- // FastIntToBuffer() // FastInt64ToBuffer() // FastHexToBuffer() // FastHex64ToBuffer() // FastHex32ToBuffer() // FastTimeToBuffer() // These are intended for speed. FastHexToBuffer() assumes the // integer is non-negative. FastHexToBuffer() puts output in // hex rather than decimal. FastTimeToBuffer() puts the output // into RFC822 format. If time is 0, uses the current time. // // FastHex64ToBuffer() puts a 64-bit unsigned value in hex-format, // padded to exactly 16 bytes (plus one byte for '\0') // // FastHex32ToBuffer() puts a 32-bit unsigned value in hex-format, // padded to exactly 8 bytes (plus one byte for '\0') // // All functions take the output buffer as an arg. FastInt() // uses at most 22 bytes, FastTime() uses exactly 30 bytes. // They all return a pointer to the beginning of the output, // which may not be the beginning of the input buffer. (Though // for FastTimeToBuffer(), we guarantee that it is.) // ---------------------------------------------------------------------- char *FastInt64ToBuffer(int64 i, char* buffer) { FastInt64ToBufferLeft(i, buffer); return buffer; } // Offset into buffer where FastInt32ToBuffer places the end of string // null character. Also used by FastInt32ToBufferLeft static const int kFastInt32ToBufferOffset = 11; char *FastInt32ToBuffer(int32 i, char* buffer) { FastInt32ToBufferLeft(i, buffer); return buffer; } char *FastHexToBuffer(int i, char* buffer) { CHECK_GE(i, 0) << "FastHexToBuffer() wants non-negative integers, not " << i; static const char *hexdigits = "0123456789abcdef"; char *p = buffer + 21; *p-- = '\0'; do { *p-- = hexdigits[i & 15]; // mod by 16 i >>= 4; // divide by 16 } while (i > 0); return p + 1; } char *InternalFastHexToBuffer(uint64 value, char* buffer, int num_byte) { static const char *hexdigits = "0123456789abcdef"; buffer[num_byte] = '\0'; for (int i = num_byte - 1; i >= 0; i--) { buffer[i] = hexdigits[value & 0xf]; value >>= 4; } return buffer; } char *FastHex64ToBuffer(uint64 value, char* buffer) { return InternalFastHexToBuffer(value, buffer, 16); } char *FastHex32ToBuffer(uint32 value, char* buffer) { return InternalFastHexToBuffer(value, buffer, 8); } const char two_ASCII_digits[100][2] = { {'0', '0'}, {'0', '1'}, {'0', '2'}, {'0', '3'}, {'0', '4'}, {'0', '5'}, {'0', '6'}, {'0', '7'}, {'0', '8'}, {'0', '9'}, {'1', '0'}, {'1', '1'}, {'1', '2'}, {'1', '3'}, {'1', '4'}, {'1', '5'}, {'1', '6'}, {'1', '7'}, {'1', '8'}, {'1', '9'}, {'2', '0'}, {'2', '1'}, {'2', '2'}, {'2', '3'}, {'2', '4'}, {'2', '5'}, {'2', '6'}, {'2', '7'}, {'2', '8'}, {'2', '9'}, {'3', '0'}, {'3', '1'}, {'3', '2'}, {'3', '3'}, {'3', '4'}, {'3', '5'}, {'3', '6'}, {'3', '7'}, {'3', '8'}, {'3', '9'}, {'4', '0'}, {'4', '1'}, {'4', '2'}, {'4', '3'}, {'4', '4'}, {'4', '5'}, {'4', '6'}, {'4', '7'}, {'4', '8'}, {'4', '9'}, {'5', '0'}, {'5', '1'}, {'5', '2'}, {'5', '3'}, {'5', '4'}, {'5', '5'}, {'5', '6'}, {'5', '7'}, {'5', '8'}, {'5', '9'}, {'6', '0'}, {'6', '1'}, {'6', '2'}, {'6', '3'}, {'6', '4'}, {'6', '5'}, {'6', '6'}, {'6', '7'}, {'6', '8'}, {'6', '9'}, {'7', '0'}, {'7', '1'}, {'7', '2'}, {'7', '3'}, {'7', '4'}, {'7', '5'}, {'7', '6'}, {'7', '7'}, {'7', '8'}, {'7', '9'}, {'8', '0'}, {'8', '1'}, {'8', '2'}, {'8', '3'}, {'8', '4'}, {'8', '5'}, {'8', '6'}, {'8', '7'}, {'8', '8'}, {'8', '9'}, {'9', '0'}, {'9', '1'}, {'9', '2'}, {'9', '3'}, {'9', '4'}, {'9', '5'}, {'9', '6'}, {'9', '7'}, {'9', '8'}, {'9', '9'} }; static inline void PutTwoDigits(int i, char* p) { DCHECK_GE(i, 0); DCHECK_LT(i, 100); p[0] = two_ASCII_digits[i][0]; p[1] = two_ASCII_digits[i][1]; } // ---------------------------------------------------------------------- // FastInt32ToBufferLeft() // FastUInt32ToBufferLeft() // FastInt64ToBufferLeft() // FastUInt64ToBufferLeft() // // Like the Fast*ToBuffer() functions above, these are intended for speed. // Unlike the Fast*ToBuffer() functions, however, these functions write // their output to the beginning of the buffer (hence the name, as the // output is left-aligned). The caller is responsible for ensuring that // the buffer has enough space to hold the output. // // Returns a pointer to the end of the string (i.e. the null character // terminating the string). // ---------------------------------------------------------------------- char* FastUInt32ToBufferLeft(uint32 u, char* buffer) { int digits; const char *ASCII_digits = NULL; // The idea of this implementation is to trim the number of divides to as few // as possible by using multiplication and subtraction rather than mod (%), // and by outputting two digits at a time rather than one. // The huge-number case is first, in the hopes that the compiler will output // that case in one branch-free block of code, and only output conditional // branches into it from below. if (u >= 1000000000) { // >= 1,000,000,000 digits = u / 100000000; // 100,000,000 ASCII_digits = two_ASCII_digits[digits]; buffer[0] = ASCII_digits[0]; buffer[1] = ASCII_digits[1]; buffer += 2; sublt100_000_000: u -= digits * 100000000; // 100,000,000 lt100_000_000: digits = u / 1000000; // 1,000,000 ASCII_digits = two_ASCII_digits[digits]; buffer[0] = ASCII_digits[0]; buffer[1] = ASCII_digits[1]; buffer += 2; sublt1_000_000: u -= digits * 1000000; // 1,000,000 lt1_000_000: digits = u / 10000; // 10,000 ASCII_digits = two_ASCII_digits[digits]; buffer[0] = ASCII_digits[0]; buffer[1] = ASCII_digits[1]; buffer += 2; sublt10_000: u -= digits * 10000; // 10,000 lt10_000: digits = u / 100; ASCII_digits = two_ASCII_digits[digits]; buffer[0] = ASCII_digits[0]; buffer[1] = ASCII_digits[1]; buffer += 2; sublt100: u -= digits * 100; lt100: digits = u; ASCII_digits = two_ASCII_digits[digits]; buffer[0] = ASCII_digits[0]; buffer[1] = ASCII_digits[1]; buffer += 2; done: *buffer = 0; return buffer; } if (u < 100) { digits = u; if (u >= 10) goto lt100; *buffer++ = '0' + digits; goto done; } if (u < 10000) { // 10,000 if (u >= 1000) goto lt10_000; digits = u / 100; *buffer++ = '0' + digits; goto sublt100; } if (u < 1000000) { // 1,000,000 if (u >= 100000) goto lt1_000_000; digits = u / 10000; // 10,000 *buffer++ = '0' + digits; goto sublt10_000; } if (u < 100000000) { // 100,000,000 if (u >= 10000000) goto lt100_000_000; digits = u / 1000000; // 1,000,000 *buffer++ = '0' + digits; goto sublt1_000_000; } // we already know that u < 1,000,000,000 digits = u / 100000000; // 100,000,000 *buffer++ = '0' + digits; goto sublt100_000_000; } char* FastInt32ToBufferLeft(int32 i, char* buffer) { uint32 u = i; if (i < 0) { *buffer++ = '-'; // We need to do the negation in modular (i.e., "unsigned") // arithmetic; MSVC++ apprently warns for plain "-u", so // we write the equivalent expression "0 - u" instead. u = 0 - u; } return FastUInt32ToBufferLeft(u, buffer); } char* FastUInt64ToBufferLeft(uint64 u64, char* buffer) { int digits; const char *ASCII_digits = NULL; uint32 u = static_cast<uint32>(u64); if (u == u64) return FastUInt32ToBufferLeft(u, buffer); uint64 top_11_digits = u64 / 1000000000; buffer = FastUInt64ToBufferLeft(top_11_digits, buffer); u = u64 - (top_11_digits * 1000000000); digits = u / 10000000; // 10,000,000 DCHECK_LT(digits, 100); ASCII_digits = two_ASCII_digits[digits]; buffer[0] = ASCII_digits[0]; buffer[1] = ASCII_digits[1]; buffer += 2; u -= digits * 10000000; // 10,000,000 digits = u / 100000; // 100,000 ASCII_digits = two_ASCII_digits[digits]; buffer[0] = ASCII_digits[0]; buffer[1] = ASCII_digits[1]; buffer += 2; u -= digits * 100000; // 100,000 digits = u / 1000; // 1,000 ASCII_digits = two_ASCII_digits[digits]; buffer[0] = ASCII_digits[0]; buffer[1] = ASCII_digits[1]; buffer += 2; u -= digits * 1000; // 1,000 digits = u / 10; ASCII_digits = two_ASCII_digits[digits]; buffer[0] = ASCII_digits[0]; buffer[1] = ASCII_digits[1]; buffer += 2; u -= digits * 10; digits = u; *buffer++ = '0' + digits; *buffer = 0; return buffer; } char* FastInt64ToBufferLeft(int64 i, char* buffer) { uint64 u = i; if (i < 0) { *buffer++ = '-'; u = 0 - u; } return FastUInt64ToBufferLeft(u, buffer); } int HexDigitsPrefix(const char* buf, int num_digits) { for (int i = 0; i < num_digits; i++) if (!ascii_isxdigit(buf[i])) return 0; // This also detects end of string as '\0' is not xdigit. return 1; } // ---------------------------------------------------------------------- // AutoDigitStrCmp // AutoDigitLessThan // StrictAutoDigitLessThan // autodigit_less // autodigit_greater // strict_autodigit_less // strict_autodigit_greater // These are like less<string> and greater<string>, except when a // run of digits is encountered at corresponding points in the two // arguments. Such digit strings are compared numerically instead // of lexicographically. Therefore if you sort by // "autodigit_less", some machine names might get sorted as: // exaf1 // exaf2 // exaf10 // When using "strict" comparison (AutoDigitStrCmp with the strict flag // set to true, or the strict version of the other functions), // strings that represent equal numbers will not be considered equal if // the string representations are not identical. That is, "01" < "1" in // strict mode, but "01" == "1" otherwise. // ---------------------------------------------------------------------- int AutoDigitStrCmp(const char* a, int alen, const char* b, int blen, bool strict) { int aindex = 0; int bindex = 0; while ((aindex < alen) && (bindex < blen)) { if (isdigit(a[aindex]) && isdigit(b[bindex])) { // Compare runs of digits. Instead of extracting numbers, we // just skip leading zeroes, and then get the run-lengths. This // allows us to handle arbitrary precision numbers. We remember // how many zeroes we found so that we can differentiate between // "1" and "01" in strict mode. // Skip leading zeroes, but remember how many we found int azeroes = aindex; int bzeroes = bindex; while ((aindex < alen) && (a[aindex] == '0')) aindex++; while ((bindex < blen) && (b[bindex] == '0')) bindex++; azeroes = aindex - azeroes; bzeroes = bindex - bzeroes; // Count digit lengths int astart = aindex; int bstart = bindex; while ((aindex < alen) && isdigit(a[aindex])) aindex++; while ((bindex < blen) && isdigit(b[bindex])) bindex++; if (aindex - astart < bindex - bstart) { // a has shorter run of digits: so smaller return -1; } else if (aindex - astart > bindex - bstart) { // a has longer run of digits: so larger return 1; } else { // Same lengths, so compare digit by digit for (int i = 0; i < aindex-astart; i++) { if (a[astart+i] < b[bstart+i]) { return -1; } else if (a[astart+i] > b[bstart+i]) { return 1; } } // Equal: did one have more leading zeroes? if (strict && azeroes != bzeroes) { if (azeroes > bzeroes) { // a has more leading zeroes: a < b return -1; } else { // b has more leading zeroes: a > b return 1; } } // Equal: so continue scanning } } else if (a[aindex] < b[bindex]) { return -1; } else if (a[aindex] > b[bindex]) { return 1; } else { aindex++; bindex++; } } if (aindex < alen) { // b is prefix of a return 1; } else if (bindex < blen) { // a is prefix of b return -1; } else { // a is equal to b return 0; } } bool AutoDigitLessThan(const char* a, int alen, const char* b, int blen) { return AutoDigitStrCmp(a, alen, b, blen, false) < 0; } bool StrictAutoDigitLessThan(const char* a, int alen, const char* b, int blen) { return AutoDigitStrCmp(a, alen, b, blen, true) < 0; } // ---------------------------------------------------------------------- // SimpleDtoa() // SimpleFtoa() // DoubleToBuffer() // FloatToBuffer() // We want to print the value without losing precision, but we also do // not want to print more digits than necessary. This turns out to be // trickier than it sounds. Numbers like 0.2 cannot be represented // exactly in binary. If we print 0.2 with a very large precision, // e.g. "%.50g", we get "0.2000000000000000111022302462515654042363167". // On the other hand, if we set the precision too low, we lose // significant digits when printing numbers that actually need them. // It turns out there is no precision value that does the right thing // for all numbers. // // Our strategy is to first try printing with a precision that is never // over-precise, then parse the result with strtod() to see if it // matches. If not, we print again with a precision that will always // give a precise result, but may use more digits than necessary. // // An arguably better strategy would be to use the algorithm described // in "How to Print Floating-Point Numbers Accurately" by Steele & // White, e.g. as implemented by David M. Gay's dtoa(). It turns out, // however, that the following implementation is about as fast as // DMG's code. Furthermore, DMG's code locks mutexes, which means it // will not scale well on multi-core machines. DMG's code is slightly // more accurate (in that it will never use more digits than // necessary), but this is probably irrelevant for most users. // // Rob Pike and Ken Thompson also have an implementation of dtoa() in // third_party/fmt/fltfmt.cc. Their implementation is similar to this // one in that it makes guesses and then uses strtod() to check them. // Their implementation is faster because they use their own code to // generate the digits in the first place rather than use snprintf(), // thus avoiding format string parsing overhead. However, this makes // it considerably more complicated than the following implementation, // and it is embedded in a larger library. If speed turns out to be // an issue, we could re-implement this in terms of their // implementation. // ---------------------------------------------------------------------- string SimpleDtoa(double value) { char buffer[kDoubleToBufferSize]; return DoubleToBuffer(value, buffer); } string SimpleFtoa(float value) { char buffer[kFloatToBufferSize]; return FloatToBuffer(value, buffer); } char* DoubleToBuffer(double value, char* buffer) { // DBL_DIG is 15 for IEEE-754 doubles, which are used on almost all // platforms these days. Just in case some system exists where DBL_DIG // is significantly larger -- and risks overflowing our buffer -- we have // this assert. COMPILE_ASSERT(DBL_DIG < 20, DBL_DIG_is_too_big); int snprintf_result = snprintf(buffer, kDoubleToBufferSize, "%.*g", DBL_DIG, value); // The snprintf should never overflow because the buffer is significantly // larger than the precision we asked for. DCHECK(snprintf_result > 0 && snprintf_result < kDoubleToBufferSize); if (strtod(buffer, NULL) != value) { snprintf_result = snprintf(buffer, kDoubleToBufferSize, "%.*g", DBL_DIG+2, value); // Should never overflow; see above. DCHECK(snprintf_result > 0 && snprintf_result < kDoubleToBufferSize); } return buffer; } char* FloatToBuffer(float value, char* buffer) { // FLT_DIG is 6 for IEEE-754 floats, which are used on almost all // platforms these days. Just in case some system exists where FLT_DIG // is significantly larger -- and risks overflowing our buffer -- we have // this assert. COMPILE_ASSERT(FLT_DIG < 10, FLT_DIG_is_too_big); int snprintf_result = snprintf(buffer, kFloatToBufferSize, "%.*g", FLT_DIG, value); // The snprintf should never overflow because the buffer is significantly // larger than the precision we asked for. DCHECK(snprintf_result > 0 && snprintf_result < kFloatToBufferSize); float parsed_value; if (!safe_strtof(buffer, &parsed_value) || parsed_value != value) { snprintf_result = snprintf(buffer, kFloatToBufferSize, "%.*g", FLT_DIG+2, value); // Should never overflow; see above. DCHECK(snprintf_result > 0 && snprintf_result < kFloatToBufferSize); } return buffer; } // ---------------------------------------------------------------------- // SimpleItoaWithCommas() // Description: converts an integer to a string. // Puts commas every 3 spaces. // Faster than printf("%d")? // // Return value: string // ---------------------------------------------------------------------- string SimpleItoaWithCommas(int32 i) { // 10 digits, 3 commas, and sign are good for 32-bit or smaller ints. // Longest is -2,147,483,648. char local[14]; char *p = local + sizeof(local); // Need to use uint32 instead of int32 to correctly handle // -2,147,483,648. uint32 n = i; if (i < 0) n = 0 - n; // negate the unsigned value to avoid overflow *--p = '0' + n % 10; // this case deals with the number "0" n /= 10; while (n) { *--p = '0' + n % 10; n /= 10; if (n == 0) break; *--p = '0' + n % 10; n /= 10; if (n == 0) break; *--p = ','; *--p = '0' + n % 10; n /= 10; // For this unrolling, we check if n == 0 in the main while loop } if (i < 0) *--p = '-'; return string(p, local + sizeof(local)); } // We need this overload because otherwise SimpleItoaWithCommas(5U) wouldn't // compile. string SimpleItoaWithCommas(uint32 i) { // 10 digits and 3 commas are good for 32-bit or smaller ints. // Longest is 4,294,967,295. char local[13]; char *p = local + sizeof(local); *--p = '0' + i % 10; // this case deals with the number "0" i /= 10; while (i) { *--p = '0' + i % 10; i /= 10; if (i == 0) break; *--p = '0' + i % 10; i /= 10; if (i == 0) break; *--p = ','; *--p = '0' + i % 10; i /= 10; // For this unrolling, we check if i == 0 in the main while loop } return string(p, local + sizeof(local)); } string SimpleItoaWithCommas(int64 i) { // 19 digits, 6 commas, and sign are good for 64-bit or smaller ints. char local[26]; char *p = local + sizeof(local); // Need to use uint64 instead of int64 to correctly handle // -9,223,372,036,854,775,808. uint64 n = i; if (i < 0) n = 0 - n; *--p = '0' + n % 10; // this case deals with the number "0" n /= 10; while (n) { *--p = '0' + n % 10; n /= 10; if (n == 0) break; *--p = '0' + n % 10; n /= 10; if (n == 0) break; *--p = ','; *--p = '0' + n % 10; n /= 10; // For this unrolling, we check if n == 0 in the main while loop } if (i < 0) *--p = '-'; return string(p, local + sizeof(local)); } // We need this overload because otherwise SimpleItoaWithCommas(5ULL) wouldn't // compile. string SimpleItoaWithCommas(uint64 i) { // 20 digits and 6 commas are good for 64-bit or smaller ints. // Longest is 18,446,744,073,709,551,615. char local[26]; char *p = local + sizeof(local); *--p = '0' + i % 10; // this case deals with the number "0" i /= 10; while (i) { *--p = '0' + i % 10; i /= 10; if (i == 0) break; *--p = '0' + i % 10; i /= 10; if (i == 0) break; *--p = ','; *--p = '0' + i % 10; i /= 10; // For this unrolling, we check if i == 0 in the main while loop } return string(p, local + sizeof(local)); } // ---------------------------------------------------------------------- // ItoaKMGT() // Description: converts an integer to a string // Truncates values to a readable unit: K, G, M or T // Opposite of atoi_kmgt() // e.g. 100 -> "100" 1500 -> "1500" 4000 -> "3K" 57185920 -> "45M" // // Return value: string // ---------------------------------------------------------------------- string ItoaKMGT(int64 i) { const char *sign = "", *suffix = ""; if (i < 0) { // We lose some accuracy if the caller passes LONG_LONG_MIN, but // that's OK as this function is only for human readability if (i == std::numeric_limits<int64>::min()) i++; sign = "-"; i = -i; } int64 val; if ((val = (i >> 40)) > 1) { suffix = "T"; } else if ((val = (i >> 30)) > 1) { suffix = "G"; } else if ((val = (i >> 20)) > 1) { suffix = "M"; } else if ((val = (i >> 10)) > 1) { suffix = "K"; } else { val = i; } return StringPrintf("%s%" PRId64 "d%s", sign, val, suffix); } // DEPRECATED(wadetregaskis). // These are non-inline because some BUILD files turn on -Wformat-non-literal. string FloatToString(float f, const char* format) { return StringPrintf(format, f); } string IntToString(int i, const char* format) { return StringPrintf(format, i); } string Int64ToString(int64 i64, const char* format) { return StringPrintf(format, i64); } string UInt64ToString(uint64 ui64, const char* format) { return StringPrintf(format, ui64); } // DEPRECATED(wadetregaskis). Just call StringPrintf. string FloatToString(float f) { return StringPrintf("%7f", f); } // DEPRECATED(wadetregaskis). Just call StringPrintf. string IntToString(int i) { return StringPrintf("%7d", i); } // DEPRECATED(wadetregaskis). Just call StringPrintf. string Int64ToString(int64 i64) { return StringPrintf("%7" PRId64, i64); } // DEPRECATED(wadetregaskis). Just call StringPrintf. string UInt64ToString(uint64 ui64) { return StringPrintf("%7" PRIu64, ui64); }
romange/beeri
strings/numbers.cc
C++
bsd-2-clause
49,536
require "language/haskell" class Ghc < Formula include Language::Haskell::Cabal desc "Glorious Glasgow Haskell Compilation System" homepage "https://haskell.org/ghc/" url "https://downloads.haskell.org/~ghc/8.6.3/ghc-8.6.3-src.tar.xz" sha256 "9f9e37b7971935d88ba80426c36af14b1e0b3ec1d9c860f44a4391771bc07f23" bottle do sha256 "9415b057d996a9d4d27f61edf2e31b3f11fb511661313d9f266fa029254c9088" => :mojave sha256 "b16adbcf90f33bf12162855bd2f2308d5f4656cbb2f533a8cb6a0ed48519be83" => :high_sierra sha256 "c469d291be7683a759ac950c11226d080994b9e4d44f9f784ab81d0f0483b498" => :sierra end head do url "https://git.haskell.org/ghc.git", :branch => "ghc-8.6" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build resource "cabal" do url "https://hackage.haskell.org/package/cabal-install-2.4.0.0/cabal-install-2.4.0.0.tar.gz" sha256 "1329e9564b736b0cfba76d396204d95569f080e7c54fe355b6d9618e3aa0bef6" end end depends_on "python" => :build depends_on "sphinx-doc" => :build resource "gmp" do url "https://ftp.gnu.org/gnu/gmp/gmp-6.1.2.tar.xz" mirror "https://gmplib.org/download/gmp/gmp-6.1.2.tar.xz" mirror "https://ftpmirror.gnu.org/gmp/gmp-6.1.2.tar.xz" sha256 "87b565e89a9a684fe4ebeeddb8399dce2599f9c9049854ca8c0dfbdea0e21912" end # https://www.haskell.org/ghc/download_ghc_8_0_1#macosx_x86_64 # "This is a distribution for Mac OS X, 10.7 or later." resource "binary" do url "https://downloads.haskell.org/~ghc/8.4.4/ghc-8.4.4-x86_64-apple-darwin.tar.xz" sha256 "28dc89ebd231335337c656f4c5ead2ae2a1acc166aafe74a14f084393c5ef03a" end def install ENV["CC"] = ENV.cc ENV["LD"] = "ld" # Build a static gmp rather than in-tree gmp, otherwise all ghc-compiled # executables link to Homebrew's GMP. gmp = libexec/"integer-gmp" # GMP *does not* use PIC by default without shared libs so --with-pic # is mandatory or else you'll get "illegal text relocs" errors. resource("gmp").stage do system "./configure", "--prefix=#{gmp}", "--with-pic", "--disable-shared", "--build=#{Hardware.oldest_cpu}-apple-darwin#{`uname -r`.to_i}" system "make" system "make", "check" system "make", "install" end args = ["--with-gmp-includes=#{gmp}/include", "--with-gmp-libraries=#{gmp}/lib"] # As of Xcode 7.3 (and the corresponding CLT) `nm` is a symlink to `llvm-nm` # and the old `nm` is renamed `nm-classic`. Building with the new `nm`, a # segfault occurs with the following error: # make[1]: * [compiler/stage2/dll-split.stamp] Segmentation fault: 11 # Upstream is aware of the issue and is recommending the use of nm-classic # until Apple restores POSIX compliance: # https://ghc.haskell.org/trac/ghc/ticket/11744 # https://ghc.haskell.org/trac/ghc/ticket/11823 # https://mail.haskell.org/pipermail/ghc-devs/2016-April/011862.html # LLVM itself has already fixed the bug: llvm-mirror/llvm@ae7cf585 # rdar://25311883 and rdar://25299678 if DevelopmentTools.clang_build_version >= 703 && DevelopmentTools.clang_build_version < 800 args << "--with-nm=#{`xcrun --find nm-classic`.chomp}" end resource("binary").stage do binary = buildpath/"binary" system "./configure", "--prefix=#{binary}", *args ENV.deparallelize { system "make", "install" } ENV.prepend_path "PATH", binary/"bin" end if build.head? resource("cabal").stage do system "sh", "bootstrap.sh", "--sandbox" (buildpath/"bootstrap-tools/bin").install ".cabal-sandbox/bin/cabal" end ENV.prepend_path "PATH", buildpath/"bootstrap-tools/bin" cabal_sandbox do cabal_install "--only-dependencies", "happy", "alex" cabal_install "--prefix=#{buildpath}/bootstrap-tools", "happy", "alex" end system "./boot" end system "./configure", "--prefix=#{prefix}", *args system "make" ENV.deparallelize { system "make", "install" } Dir.glob(lib/"*/package.conf.d/package.cache") { |f| rm f } end def post_install system "#{bin}/ghc-pkg", "recache" end test do (testpath/"hello.hs").write('main = putStrLn "Hello Homebrew"') system "#{bin}/runghc", testpath/"hello.hs" end end
jdubois/homebrew-core
Formula/ghc.rb
Ruby
bsd-2-clause
4,374
# pylint:disable=line-too-long import logging from ...sim_type import SimTypeFunction, SimTypeShort, SimTypeInt, SimTypeLong, SimTypeLongLong, SimTypeDouble, SimTypeFloat, SimTypePointer, SimTypeChar, SimStruct, SimTypeFixedSizeArray, SimTypeBottom, SimUnion, SimTypeBool from ...calling_conventions import SimCCStdcall, SimCCMicrosoftAMD64 from .. import SIM_PROCEDURES as P from . import SimLibrary _l = logging.getLogger(name=__name__) lib = SimLibrary() lib.set_default_cc('X86', SimCCStdcall) lib.set_default_cc('AMD64', SimCCMicrosoftAMD64) lib.set_library_names("aclui.dll") prototypes = \ { # 'CreateSecurityPage': SimTypeFunction([SimTypeBottom(label="ISecurityInformation")], SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), arg_names=["psi"]), # 'EditSecurity': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeBottom(label="ISecurityInformation")], SimTypeInt(signed=True, label="Int32"), arg_names=["hwndOwner", "psi"]), # 'EditSecurityAdvanced': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeBottom(label="ISecurityInformation"), SimTypeInt(signed=False, label="SI_PAGE_TYPE")], SimTypeInt(signed=True, label="Int32"), arg_names=["hwndOwner", "psi", "uSIPage"]), } lib.set_prototypes(prototypes)
angr/angr
angr/procedures/definitions/win32_aclui.py
Python
bsd-2-clause
1,451
require_relative 'model' Record.where(version: 10606).delete_all
panjia1983/channel_backward
benchmarks/needle_steering/06clear_records6.rb
Ruby
bsd-2-clause
65
# -*- coding: utf-8 -*- """ femagtools.plot ~~~~~~~~~~~~~~~ Creating plots """ import numpy as np import scipy.interpolate as ip import logging try: import matplotlib import matplotlib.pyplot as plt import matplotlib.cm as cm from mpl_toolkits.mplot3d import Axes3D matplotlibversion = matplotlib.__version__ except ImportError: # ModuleNotFoundError: matplotlibversion = 0 logger = logging.getLogger("femagtools.plot") def _create_3d_axis(): """creates a subplot with 3d projection if one does not already exist""" from matplotlib.projections import get_projection_class from matplotlib import _pylab_helpers create_axis = True if _pylab_helpers.Gcf.get_active() is not None: if isinstance(plt.gca(), get_projection_class('3d')): create_axis = False if create_axis: plt.figure() plt.subplot(111, projection='3d') def _plot_surface(ax, x, y, z, labels, azim=None): """helper function for surface plots""" # ax.tick_params(axis='both', which='major', pad=-3) assert np.size(x) > 1 and np.size(y) > 1 and np.size(z) > 1 if azim is not None: ax.azim = azim X, Y = np.meshgrid(x, y) Z = np.ma.masked_invalid(z) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.viridis, alpha=0.85, vmin=np.nanmin(z), vmax=np.nanmax(z), linewidth=0, antialiased=True) # edgecolor=(0, 0, 0, 0)) # ax.set_xticks(xticks) # ax.set_yticks(yticks) # ax.set_zticks(zticks) ax.set_xlabel(labels[0]) ax.set_ylabel(labels[1]) ax.set_title(labels[2]) # plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0) def __phasor_plot(ax, up, idq, uxdq): uref = max(up, uxdq[0]) uxd = uxdq[0]/uref uxq = uxdq[1]/uref u1d, u1q = (uxd, 1+uxq) u1 = np.sqrt(u1d**2 + u1q**2)*uref i1 = np.linalg.norm(idq) i1d, i1q = (idq[0]/i1, idq[1]/i1) qhw = 6 # width arrow head qhl = 15 # length arrow head qlw = 2 # line width qts = 10 # textsize # Length of the Current adjust to Ud: Initally 0.9, Maier(Oswald) = 0.5 curfac = max(0.9, 1.5*i1q/up) def label_line(ax, X, Y, U, V, label, color='k', size=8): """Add a label to a line, at the proper angle. Arguments --------- line : matplotlib.lines.Line2D object, label : str x : float x-position to place center of text (in data coordinated y : float y-position to place center of text (in data coordinates) color : str size : float """ x1, x2 = X, X + U y1, y2 = Y, Y + V if y2 == 0: y2 = y1 if x2 == 0: x2 = x1 x = (x1 + x2) / 2 y = (y1 + y2) / 2 slope_degrees = np.rad2deg(np.angle(U + V * 1j)) if slope_degrees < 0: slope_degrees += 180 if 90 < slope_degrees <= 270: slope_degrees += 180 x_offset = np.sin(np.deg2rad(slope_degrees)) y_offset = np.cos(np.deg2rad(slope_degrees)) bbox_props = dict(boxstyle="Round4, pad=0.1", fc="white", lw=0) text = ax.annotate(label, xy=(x, y), xytext=(x_offset * 10, y_offset * 8), textcoords='offset points', size=size, color=color, horizontalalignment='center', verticalalignment='center', fontfamily='monospace', fontweight='bold', bbox=bbox_props) text.set_rotation(slope_degrees) return text if ax == 0: ax = plt.gca() ax.axes.xaxis.set_ticklabels([]) ax.axes.yaxis.set_ticklabels([]) # ax.set_aspect('equal') ax.set_title( r'$U_1$={0} V, $I_1$={1} A, $U_p$={2} V'.format( round(u1, 1), round(i1, 1), round(up, 1)), fontsize=14) up /= uref ax.quiver(0, 0, 0, up, angles='xy', scale_units='xy', scale=1, units='dots', headwidth=qhw/2, headlength=qhl/2, headaxislength=qhl/2, width=qlw*2, color='k') label_line(ax, 0, 0, 0, up, '$U_p$', 'k', qts) ax.quiver(0, 0, u1d, u1q, angles='xy', scale_units='xy', scale=1, units='dots', headwidth=qhw, headlength=qhl, headaxislength=qhl, width=qlw, color='r') label_line(ax, 0, 0, u1d, u1q, '$U_1$', 'r', qts) ax.quiver(0, 1, uxd, 0, angles='xy', scale_units='xy', scale=1, units='dots', headwidth=qhw, headlength=qhl, headaxislength=qhl, width=qlw, color='g') label_line(ax, 0, 1, uxd, 0, '$U_d$', 'g', qts) ax.quiver(uxd, 1, 0, uxq, angles='xy', scale_units='xy', scale=1, units='dots', headwidth=qhw, headlength=qhl, headaxislength=qhl, width=qlw, color='g') label_line(ax, uxd, 1, 0, uxq, '$U_q$', 'g', qts) ax.quiver(0, 0, curfac*i1d, curfac*i1q, angles='xy', scale_units='xy', scale=1, units='dots', headwidth=qhw, headlength=qhl, headaxislength=qhl, width=qlw, color='b') label_line(ax, 0, 0, curfac*i1d, curfac*i1q, '$I_1$', 'b', qts) xmin, xmax = (min(0, uxd, i1d), max(0, i1d, uxd)) ymin, ymax = (min(0, i1q, 1-uxq), max(1, i1q, 1+uxq)) ax.set_xlim([xmin-0.1, xmax+0.1]) ax.set_ylim([ymin-0.1, ymax+0.1]) ax.grid(True) def i1beta_phasor(up, i1, beta, r1, xd, xq, ax=0): """creates a phasor plot up: internal voltage i1: current beta: angle i1 vs up [deg] r1: resistance xd: reactance in direct axis xq: reactance in quadrature axis""" i1d, i1q = (i1*np.sin(beta/180*np.pi), i1*np.cos(beta/180*np.pi)) uxdq = ((r1*i1d - xq*i1q), (r1*i1q + xd*i1d)) __phasor_plot(ax, up, (i1d, i1q), uxdq) def iqd_phasor(up, iqd, uqd, ax=0): """creates a phasor plot up: internal voltage iqd: current uqd: terminal voltage""" uxdq = (uqd[1]/np.sqrt(2), (uqd[0]/np.sqrt(2)-up)) __phasor_plot(ax, up, (iqd[1]/np.sqrt(2), iqd[0]/np.sqrt(2)), uxdq) def phasor(bch, ax=0): """create phasor plot from bch""" f1 = bch.machine['p']*bch.dqPar['speed'] w1 = 2*np.pi*f1 xd = w1*bch.dqPar['ld'][-1] xq = w1*bch.dqPar['lq'][-1] r1 = bch.machine['r1'] i1beta_phasor(bch.dqPar['up'][-1], bch.dqPar['i1'][-1], bch.dqPar['beta'][-1], r1, xd, xq, ax) def airgap(airgap, ax=0): """creates plot of flux density in airgap""" if ax == 0: ax = plt.gca() ax.set_title('Airgap Flux Density [T]') ax.plot(airgap['pos'], airgap['B'], label='Max {:4.2f} T'.format(max(airgap['B']))) ax.plot(airgap['pos'], airgap['B_fft'], label='Base Ampl {:4.2f} T'.format(airgap['Bamp'])) ax.set_xlabel('Position/°') ax.legend() ax.grid(True) def airgap_fft(airgap, bmin=1e-2, ax=0): """plot airgap harmonics""" unit = 'T' if ax == 0: ax = plt.gca() ax.set_title('Airgap Flux Density Harmonics / {}'.format(unit)) ax.grid(True) order, fluxdens = np.array([(n, b) for n, b in zip(airgap['nue'], airgap['B_nue']) if b > bmin]).T try: markerline1, stemlines1, _ = ax.stem(order, fluxdens, '-.', basefmt=" ", use_line_collection=True) ax.set_xticks(order) except ValueError: # empty sequence pass def torque(pos, torque, ax=0): """creates plot from torque vs position""" k = 20 alpha = np.linspace(pos[0], pos[-1], k*len(torque)) f = ip.interp1d(pos, torque, kind='quadratic') unit = 'Nm' scale = 1 if np.min(torque) < -9.9e3 or np.max(torque) > 9.9e3: scale = 1e-3 unit = 'kNm' if ax == 0: ax = plt.gca() ax.set_title('Torque / {}'.format(unit)) ax.grid(True) ax.plot(pos, [scale*t for t in torque], 'go') ax.plot(alpha, scale*f(alpha)) if np.min(torque) > 0 and np.max(torque) > 0: ax.set_ylim(bottom=0) elif np.min(torque) < 0 and np.max(torque) < 0: ax.set_ylim(top=0) def torque_fft(order, torque, ax=0): """plot torque harmonics""" unit = 'Nm' scale = 1 if np.min(torque) < -9.9e3 or np.max(torque) > 9.9e3: scale = 1e-3 unit = 'kNm' if ax == 0: ax = plt.gca() ax.set_title('Torque Harmonics / {}'.format(unit)) ax.grid(True) try: bw = 2.5E-2*max(order) ax.bar(order, [scale*t for t in torque], width=bw, align='center') ax.set_xlim(left=-bw/2) except ValueError: # empty sequence pass def force(title, pos, force, xlabel='', ax=0): """plot force vs position""" unit = 'N' scale = 1 if min(force) < -9.9e3 or max(force) > 9.9e3: scale = 1e-3 unit = 'kN' if ax == 0: ax = plt.gca() ax.set_title('{} / {}'.format(title, unit)) ax.grid(True) ax.plot(pos, [scale*f for f in force]) if xlabel: ax.set_xlabel(xlabel) if min(force) > 0: ax.set_ylim(bottom=0) def force_fft(order, force, ax=0): """plot force harmonics""" unit = 'N' scale = 1 if min(force) < -9.9e3 or max(force) > 9.9e3: scale = 1e-3 unit = 'kN' if ax == 0: ax = plt.gca() ax.set_title('Force Harmonics / {}'.format(unit)) ax.grid(True) try: bw = 2.5E-2*max(order) ax.bar(order, [scale*t for t in force], width=bw, align='center') ax.set_xlim(left=-bw/2) except ValueError: # empty sequence pass def forcedens(title, pos, fdens, ax=0): """plot force densities""" if ax == 0: ax = plt.gca() ax.set_title(title) ax.grid(True) ax.plot(pos, [1e-3*ft for ft in fdens[0]], label='F tang') ax.plot(pos, [1e-3*fn for fn in fdens[1]], label='F norm') ax.legend() ax.set_xlabel('Pos / deg') ax.set_ylabel('Force Density / kN/m²') def forcedens_surface(fdens, ax=0): if ax == 0: _create_3d_axis() ax = plt.gca() xpos = [p for p in fdens.positions[0]['X']] ypos = [p['position'] for p in fdens.positions] z = 1e-3*np.array([p['FN'] for p in fdens.positions]) _plot_surface(ax, xpos, ypos, z, (u'Rotor pos/°', u'Pos/°', u'F N / kN/m²')) def forcedens_fft(title, fdens, ax=0): """plot force densities FFT Args: title: plot title fdens: force density object """ if ax == 0: ax = plt.axes(projection="3d") F = 1e-3*fdens.fft() fmin = 0.2 num_bars = F.shape[0] + 1 _xx, _yy = np.meshgrid(np.arange(1, num_bars), np.arange(1, num_bars)) z_size = F[F > fmin] x_pos, y_pos = _xx[F > fmin], _yy[F > fmin] z_pos = np.zeros_like(z_size) x_size = 2 y_size = 2 ax.bar3d(x_pos, y_pos, z_pos, x_size, y_size, z_size) ax.view_init(azim=120) ax.set_xlim(0, num_bars+1) ax.set_ylim(0, num_bars+1) ax.set_title(title) ax.set_xlabel('M') ax.set_ylabel('N') ax.set_zlabel('kN/m²') def winding_flux(pos, flux, ax=0): """plot flux vs position""" if ax == 0: ax = plt.gca() ax.set_title('Winding Flux / Vs') ax.grid(True) for p, f in zip(pos, flux): ax.plot(p, f) def winding_current(pos, current, ax=0): """plot winding currents""" if ax == 0: ax = plt.gca() ax.set_title('Winding Currents / A') ax.grid(True) for p, i in zip(pos, current): ax.plot(p, i) def voltage(title, pos, voltage, ax=0): """plot voltage vs. position""" if ax == 0: ax = plt.gca() ax.set_title('{} / V'.format(title)) ax.grid(True) ax.plot(pos, voltage) def voltage_fft(title, order, voltage, ax=0): """plot FFT harmonics of voltage""" if ax == 0: ax = plt.gca() ax.set_title('{} / V'.format(title)) ax.grid(True) if max(order) < 5: order += [5] voltage += [0] try: bw = 2.5E-2*max(order) ax.bar(order, voltage, width=bw, align='center') except ValueError: # empty sequence pass def mcv_hbj(mcv, log=True, ax=0): """plot H, B, J of mcv dict""" import femagtools.mcv MUE0 = 4e-7*np.pi ji = [] csiz = len(mcv['curve']) if ax == 0: ax = plt.gca() ax.set_title(mcv['name']) for k, c in enumerate(mcv['curve']): bh = [(bi, hi*1e-3) for bi, hi in zip(c['bi'], c['hi'])] try: if csiz == 1 and mcv['ctype'] in (femagtools.mcv.MAGCRV, femagtools.mcv.ORIENT_CRV): ji = [b-MUE0*h*1e3 for b, h in bh] except Exception: pass bi, hi = zip(*bh) label = 'Flux Density' if csiz > 1: label = 'Flux Density ({0}°)'.format(mcv.mc1_angle[k]) if log: ax.semilogx(hi, bi, label=label) if ji: ax.semilogx(hi, ji, label='Polarisation') else: ax.plot(hi, bi, label=label) if ji: ax.plot(hi, ji, label='Polarisation') ax.set_xlabel('H / kA/m') ax.set_ylabel('T') if ji or csiz > 1: ax.legend(loc='lower right') ax.grid() def mcv_muer(mcv, ax=0): """plot rel. permeability vs. B of mcv dict""" MUE0 = 4e-7*np.pi bi, ur = zip(*[(bx, bx/hx/MUE0) for bx, hx in zip(mcv['curve'][0]['bi'], mcv['curve'][0]['hi']) if not hx == 0]) if ax == 0: ax = plt.gca() ax.plot(bi, ur) ax.set_xlabel('B / T') ax.set_title('rel. Permeability') ax.grid() def mtpa(pmrel, i1max, title='', projection='', ax=0): """create a line or surface plot with torque and mtpa curve""" nsamples = 10 i1 = np.linspace(0, i1max, nsamples) iopt = np.array([pmrel.mtpa(x) for x in i1]).T iqmax, idmax = pmrel.iqdmax(i1max) iqmin, idmin = pmrel.iqdmin(i1max) if projection == '3d': nsamples = 50 else: if iqmin == 0: iqmin = 0.1*iqmax id = np.linspace(idmin, idmax, nsamples) iq = np.linspace(iqmin, iqmax, nsamples) torque_iqd = np.array( [[pmrel.torque_iqd(x, y) for y in id] for x in iq]) if projection == '3d': ax = idq_torque(id, iq, torque_iqd, ax) ax.plot(iopt[1], iopt[0], iopt[2], color='red', linewidth=2, label='MTPA: {0:5.0f} Nm'.format( np.max(iopt[2][-1]))) else: if ax == 0: ax = plt.gca() ax.set_aspect('equal') x, y = np.meshgrid(id, iq) CS = ax.contour(x, y, torque_iqd, 6, colors='k') ax.clabel(CS, fmt='%d', inline=1) ax.set_xlabel('Id/A') ax.set_ylabel('Iq/A') ax.plot(iopt[1], iopt[0], color='red', linewidth=2, label='MTPA: {0:5.0f} Nm'.format( np.max(iopt[2][-1]))) ax.grid() if title: ax.set_title(title) ax.legend() def mtpv(pmrel, u1max, i1max, title='', projection='', ax=0): """create a line or surface plot with voltage and mtpv curve""" w1 = pmrel.w2_imax_umax(i1max, u1max) nsamples = 20 if projection == '3d': nsamples = 50 iqmax, idmax = pmrel.iqdmax(i1max) iqmin, idmin = pmrel.iqdmin(i1max) id = np.linspace(idmin, idmax, nsamples) iq = np.linspace(iqmin, iqmax, nsamples) u1_iqd = np.array( [[np.linalg.norm(pmrel.uqd(w1, iqx, idx))/np.sqrt(2) for idx in id] for iqx in iq]) u1 = np.mean(u1_iqd) imtpv = np.array([pmrel.mtpv(wx, u1, i1max) for wx in np.linspace(w1, 20*w1, nsamples)]).T if projection == '3d': torque_iqd = np.array( [[pmrel.torque_iqd(x, y) for y in id] for x in iq]) ax = idq_torque(id, iq, torque_iqd, ax) ax.plot(imtpv[1], imtpv[0], imtpv[2], color='red', linewidth=2) else: if ax == 0: ax = plt.gca() ax.set_aspect('equal') x, y = np.meshgrid(id, iq) CS = ax.contour(x, y, u1_iqd, 4, colors='b') # linestyles='dashed') ax.clabel(CS, fmt='%d', inline=1) ax.plot(imtpv[1], imtpv[0], color='red', linewidth=2, label='MTPV: {0:5.0f} Nm'.format(np.max(imtpv[2]))) # beta = np.arctan2(imtpv[1][0], imtpv[0][0]) # b = np.linspace(beta, 0) # ax.plot(np.sqrt(2)*i1max*np.sin(b), np.sqrt(2)*i1max*np.cos(b), 'r-') ax.grid() ax.legend() ax.set_xlabel('Id/A') ax.set_ylabel('Iq/A') if title: ax.set_title(title) def __get_linearForce_title_keys(lf): if 'force_r' in lf: return ['Force r', 'Force z'], ['force_r', 'force_z'] return ['Force x', 'Force y'], ['force_x', 'force_y'] def pmrelsim(bch, title=''): """creates a plot of a PM/Rel motor simulation""" cols = 2 rows = 4 if len(bch.flux['1']) > 1: rows += 1 htitle = 1.5 if title else 0 fig, ax = plt.subplots(nrows=rows, ncols=cols, figsize=(10, 3*rows + htitle)) if title: fig.suptitle(title, fontsize=16) row = 1 plt.subplot(rows, cols, row) if bch.torque: torque(bch.torque[-1]['angle'], bch.torque[-1]['torque']) plt.subplot(rows, cols, row+1) tq = list(bch.torque_fft[-1]['torque']) order = list(bch.torque_fft[-1]['order']) if order and max(order) < 5: order += [15] tq += [0] torque_fft(order, tq) plt.subplot(rows, cols, row+2) force('Force Fx', bch.torque[-1]['angle'], bch.torque[-1]['force_x']) plt.subplot(rows, cols, row+3) force('Force Fy', bch.torque[-1]['angle'], bch.torque[-1]['force_y']) row += 3 elif bch.linearForce: title, keys = __get_linearForce_title_keys(bch.linearForce[-1]) force(title[0], bch.linearForce[-1]['displ'], bch.linearForce[-1][keys[0]], 'Displt. / mm') plt.subplot(rows, cols, row+1) force_fft(bch.linearForce_fft[-2]['order'], bch.linearForce_fft[-2]['force']) plt.subplot(rows, cols, row+2) force(title[1], bch.linearForce[-1]['displ'], bch.linearForce[-1][keys[1]], 'Displt. / mm') plt.subplot(rows, cols, row+3) force_fft(bch.linearForce_fft[-1]['order'], bch.linearForce_fft[-1]['force']) row += 3 plt.subplot(rows, cols, row+1) flux = [bch.flux[k][-1] for k in bch.flux] pos = [f['displ'] for f in flux] winding_flux(pos, [f['flux_k'] for f in flux]) plt.subplot(rows, cols, row+2) winding_current(pos, [f['current_k'] for f in flux]) plt.subplot(rows, cols, row+3) voltage('Internal Voltage', bch.flux['1'][-1]['displ'], bch.flux['1'][-1]['voltage_dpsi']) plt.subplot(rows, cols, row+4) try: voltage_fft('Internal Voltage Harmonics', bch.flux_fft['1'][-1]['order'], bch.flux_fft['1'][-1]['voltage']) except: pass if len(bch.flux['1']) > 1: plt.subplot(rows, cols, row+5) voltage('No Load Voltage', bch.flux['1'][0]['displ'], bch.flux['1'][0]['voltage_dpsi']) plt.subplot(rows, cols, row+6) try: voltage_fft('No Load Voltage Harmonics', bch.flux_fft['1'][0]['order'], bch.flux_fft['1'][0]['voltage']) except: pass fig.tight_layout(h_pad=3.5) if title: fig.subplots_adjust(top=0.92) def multcal(bch, title=''): """creates a plot of a MULT CAL simulation""" cols = 2 rows = 4 htitle = 1.5 if title else 0 fig, ax = plt.subplots(nrows=rows, ncols=cols, figsize=(10, 3*rows + htitle)) if title: fig.suptitle(title, fontsize=16) row = 1 plt.subplot(rows, cols, row) if bch.torque: torque(bch.torque[-1]['angle'], bch.torque[-1]['torque']) plt.subplot(rows, cols, row+1) tq = list(bch.torque_fft[-1]['torque']) order = list(bch.torque_fft[-1]['order']) if order and max(order) < 5: order += [15] tq += [0] torque_fft(order, tq) plt.subplot(rows, cols, row+2) force('Force Fx', bch.torque[-1]['angle'], bch.torque[-1]['force_x']) plt.subplot(rows, cols, row+3) force('Force Fy', bch.torque[-1]['angle'], bch.torque[-1]['force_y']) row += 3 elif bch.linearForce: title, keys = __get_linearForce_title_keys(bch.linearForce[-1]) force(title[0], bch.linearForce[-1]['displ'], bch.linearForce[-1][keys[0]], 'Displt. / mm') plt.subplot(rows, cols, row+1) force_fft(bch.linearForce_fft[-2]['order'], bch.linearForce_fft[-2]['force']) plt.subplot(rows, cols, row+2) force(title[1], bch.linearForce[-1]['displ'], bch.linearForce[-1][keys[1]], 'Displt. / mm') plt.subplot(rows, cols, row+3) force_fft(bch.linearForce_fft[-1]['order'], bch.linearForce_fft[-1]['force']) row += 3 plt.subplot(rows, cols, row+1) flux = [bch.flux[k][-1] for k in bch.flux] pos = [f['displ'] for f in flux] winding_flux(pos, [f['flux_k'] for f in flux]) plt.subplot(rows, cols, row+2) winding_current(pos, [f['current_k'] for f in flux]) plt.subplot(rows, cols, row+3) voltage('Internal Voltage', bch.flux['1'][-1]['displ'], bch.flux['1'][-1]['voltage_dpsi']) plt.subplot(rows, cols, row+4) try: voltage_fft('Internal Voltage Harmonics', bch.flux_fft['1'][-1]['order'], bch.flux_fft['1'][-1]['voltage']) except: pass if len(bch.flux['1']) > 1: plt.subplot(rows, cols, row+5) voltage('No Load Voltage', bch.flux['1'][0]['displ'], bch.flux['1'][0]['voltage_dpsi']) plt.subplot(rows, cols, row+6) try: voltage_fft('No Load Voltage Harmonics', bch.flux_fft['1'][0]['order'], bch.flux_fft['1'][0]['voltage']) except: pass fig.tight_layout(h_pad=3.5) if title: fig.subplots_adjust(top=0.92) def fasttorque(bch, title=''): """creates a plot of a Fast Torque simulation""" cols = 2 rows = 4 if len(bch.flux['1']) > 1: rows += 1 htitle = 1.5 if title else 0 fig, ax = plt.subplots(nrows=rows, ncols=cols, figsize=(10, 3*rows + htitle)) if title: fig.suptitle(title, fontsize=16) row = 1 plt.subplot(rows, cols, row) if bch.torque: torque(bch.torque[-1]['angle'], bch.torque[-1]['torque']) plt.subplot(rows, cols, row+1) torque_fft(bch.torque_fft[-1]['order'], bch.torque_fft[-1]['torque']) plt.subplot(rows, cols, row+2) force('Force Fx', bch.torque[-1]['angle'], bch.torque[-1]['force_x']) plt.subplot(rows, cols, row+3) force('Force Fy', bch.torque[-1]['angle'], bch.torque[-1]['force_y']) row += 3 elif bch.linearForce: title, keys = __get_linearForce_title_keys(bch.linearForce[-1]) force(title[0], bch.linearForce[-1]['displ'], bch.linearForce[-1][keys[0]], 'Displt. / mm') plt.subplot(rows, cols, row+1) force_fft(bch.linearForce_fft[-2]['order'], bch.linearForce_fft[-2]['force']) plt.subplot(rows, cols, row+2) force(title[1], bch.linearForce[-1]['displ'], bch.linearForce[-1][keys[1]], 'Displt. / mm') plt.subplot(rows, cols, row+3) force_fft(bch.linearForce_fft[-1]['order'], bch.linearForce_fft[-1]['force']) row += 3 plt.subplot(rows, cols, row+1) flux = [bch.flux[k][-1] for k in bch.flux] pos = [f['displ'] for f in flux] winding_flux(pos, [f['flux_k'] for f in flux]) plt.subplot(rows, cols, row+2) winding_current(pos, [f['current_k'] for f in flux]) plt.subplot(rows, cols, row+3) voltage('Internal Voltage', bch.flux['1'][-1]['displ'], bch.flux['1'][-1]['voltage_dpsi']) plt.subplot(rows, cols, row+4) try: voltage_fft('Internal Voltage Harmonics', bch.flux_fft['1'][-1]['order'], bch.flux_fft['1'][-1]['voltage']) except: pass if len(bch.flux['1']) > 1: plt.subplot(rows, cols, row+5) voltage('No Load Voltage', bch.flux['1'][0]['displ'], bch.flux['1'][0]['voltage_dpsi']) plt.subplot(rows, cols, row+6) try: voltage_fft('No Load Voltage Harmonics', bch.flux_fft['1'][0]['order'], bch.flux_fft['1'][0]['voltage']) except: pass fig.tight_layout(h_pad=3.5) if title: fig.subplots_adjust(top=0.92) def cogging(bch, title=''): """creates a cogging plot""" cols = 2 rows = 3 htitle = 1.5 if title else 0 fig, ax = plt.subplots(nrows=rows, ncols=cols, figsize=(10, 3*rows + htitle)) if title: fig.suptitle(title, fontsize=16) row = 1 plt.subplot(rows, cols, row) if bch.torque: torque(bch.torque[0]['angle'], bch.torque[0]['torque']) plt.subplot(rows, cols, row+1) if bch.torque_fft: torque_fft(bch.torque_fft[0]['order'], bch.torque_fft[0]['torque']) plt.subplot(rows, cols, row+2) force('Force Fx', bch.torque[0]['angle'], bch.torque[0]['force_x']) plt.subplot(rows, cols, row+3) force('Force Fy', bch.torque[0]['angle'], bch.torque[0]['force_y']) row += 3 elif bch.linearForce: title, keys = __get_linearForce_title_keys(bch.linearForce[-1]) force(title[0], bch.linearForce[-1]['displ'], bch.linearForce[-1][keys[0]], 'Displt. / mm') plt.subplot(rows, cols, row+1) force_fft(bch.linearForce_fft[-2]['order'], bch.linearForce_fft[-2]['force']) plt.subplot(rows, cols, row+2) force(title[1], bch.linearForce[-1]['displ'], bch.linearForce[-1][keys[1]], 'Displt. / mm') plt.subplot(rows, cols, row+3) force_fft(bch.linearForce_fft[-1]['order'], bch.linearForce_fft[-1]['force']) row += 3 plt.subplot(rows, cols, row+1) voltage('Voltage', bch.flux['1'][0]['displ'], bch.flux['1'][0]['voltage_dpsi']) plt.subplot(rows, cols, row+2) voltage_fft('Voltage Harmonics', bch.flux_fft['1'][0]['order'], bch.flux_fft['1'][0]['voltage']) fig.tight_layout(h_pad=2) if title: fig.subplots_adjust(top=0.92) def transientsc(bch, title=''): """creates a transient short circuit plot""" cols = 1 rows = 2 htitle = 1.5 if title else 0 fig, ax = plt.subplots(nrows=rows, ncols=cols, figsize=(10, 3*rows + htitle)) if title: fig.suptitle(title, fontsize=16) row = 1 plt.subplot(rows, cols, row) ax = plt.gca() ax.set_title('Currents / A') ax.grid(True) for i in ('ia', 'ib', 'ic'): ax.plot(bch.scData['time'], bch.scData[i], label=i) ax.set_xlabel('Time / s') ax.legend() row = 2 plt.subplot(rows, cols, row) ax = plt.gca() ax.set_title('Torque / Nm') ax.grid(True) ax.plot(bch.scData['time'], bch.scData['torque']) ax.set_xlabel('Time / s') fig.tight_layout(h_pad=2) if title: fig.subplots_adjust(top=0.92) def i1beta_torque(i1, beta, torque, title='', ax=0): """creates a surface plot of torque vs i1, beta""" if ax == 0: _create_3d_axis() ax = plt.gca() azim = 210 if 0 < np.mean(beta) or -90 > np.mean(beta): azim = -60 unit = 'Nm' scale = 1 if np.min(torque) < -9.9e3 or np.max(torque) > 9.9e3: scale = 1e-3 unit = 'kNm' if title: _plot_surface(ax, i1, beta, scale*np.asarray(torque), (u'I1/A', u'Beta/°', title), azim=azim) else: _plot_surface(ax, i1, beta, scale*np.asarray(torque), (u'I1/A', u'Beta/°', u'Torque/{}'.format(unit)), azim=azim) def i1beta_ld(i1, beta, ld, ax=0): """creates a surface plot of ld vs i1, beta""" if ax == 0: _create_3d_axis() ax = plt.gca() _plot_surface(ax, i1, beta, np.asarray(ld)*1e3, (u'I1/A', u'Beta/°', u'Ld/mH'), azim=60) def i1beta_lq(i1, beta, lq, ax=0): """creates a surface plot of ld vs i1, beta""" if ax == 0: _create_3d_axis() ax = plt.gca() azim = 60 if 0 < np.mean(beta) or -90 > np.mean(beta): azim = -120 _plot_surface(ax, i1, beta, np.asarray(lq)*1e3, (u'I1/A', u'Beta/°', u'Lq/mH'), azim=azim) def i1beta_psim(i1, beta, psim, ax=0): """creates a surface plot of psim vs i1, beta""" if ax == 0: _create_3d_axis() ax = plt.gca() _plot_surface(ax, i1, beta, psim, (u'I1/A', u'Beta/°', u'Psi m/Vs'), azim=60) def i1beta_up(i1, beta, up, ax=0): """creates a surface plot of up vs i1, beta""" if ax == 0: _create_3d_axis() ax = plt.gca() _plot_surface(ax, i1, beta, up, (u'I1/A', u'Beta/°', u'Up/V'), azim=60) def i1beta_psid(i1, beta, psid, ax=0): """creates a surface plot of psid vs i1, beta""" if ax == 0: _create_3d_axis() ax = plt.gca() azim = -60 if 0 < np.mean(beta) or -90 > np.mean(beta): azim = 60 _plot_surface(ax, i1, beta, psid, (u'I1/A', u'Beta/°', u'Psi d/Vs'), azim=azim) def i1beta_psiq(i1, beta, psiq, ax=0): """creates a surface plot of psiq vs i1, beta""" if ax == 0: _create_3d_axis() ax = plt.gca() azim = 210 if 0 < np.mean(beta) or -90 > np.mean(beta): azim = -60 _plot_surface(ax, i1, beta, psiq, (u'I1/A', u'Beta/°', u'Psi q/Vs'), azim=azim) def idq_torque(id, iq, torque, ax=0): """creates a surface plot of torque vs id, iq""" if ax == 0: _create_3d_axis() ax = plt.gca() unit = 'Nm' scale = 1 if np.min(torque) < -9.9e3 or np.max(torque) > 9.9e3: scale = 1e-3 unit = 'kNm' _plot_surface(ax, id, iq, scale*np.asarray(torque), (u'Id/A', u'Iq/A', u'Torque/{}'.format(unit)), azim=-60) return ax def idq_psid(id, iq, psid, ax=0): """creates a surface plot of psid vs id, iq""" if ax == 0: _create_3d_axis() ax = plt.gca() _plot_surface(ax, id, iq, psid, (u'Id/A', u'Iq/A', u'Psi d/Vs'), azim=210) def idq_psiq(id, iq, psiq, ax=0): """creates a surface plot of psiq vs id, iq""" if ax == 0: _create_3d_axis() ax = plt.gca() _plot_surface(ax, id, iq, psiq, (u'Id/A', u'Iq/A', u'Psi q/Vs'), azim=210) def idq_psim(id, iq, psim, ax=0): """creates a surface plot of psim vs. id, iq""" if ax == 0: _create_3d_axis() ax = plt.gca() _plot_surface(ax, id, iq, psim, (u'Id/A', u'Iq/A', u'Psi m [Vs]'), azim=120) def idq_ld(id, iq, ld, ax=0): """creates a surface plot of ld vs. id, iq""" if ax == 0: _create_3d_axis() ax = plt.gca() _plot_surface(ax, id, iq, np.asarray(ld)*1e3, (u'Id/A', u'Iq/A', u'L d/mH'), azim=120) def idq_lq(id, iq, lq, ax=0): """creates a surface plot of lq vs. id, iq""" if ax == 0: _create_3d_axis() ax = plt.gca() _plot_surface(ax, id, iq, np.asarray(lq)*1e3, (u'Id/A', u'Iq/A', u'L q/mH'), azim=120) def ldlq(bch): """creates the surface plots of a BCH reader object with a ld-lq identification""" beta = bch.ldq['beta'] i1 = bch.ldq['i1'] torque = bch.ldq['torque'] ld = np.array(bch.ldq['ld']) lq = np.array(bch.ldq['lq']) psid = bch.ldq['psid'] psiq = bch.ldq['psiq'] rows = 3 fig = plt.figure(figsize=(10, 4*rows)) fig.suptitle('Ld-Lq Identification {}'.format(bch.filename), fontsize=16) fig.add_subplot(rows, 2, 1, projection='3d') i1beta_torque(i1, beta, torque) fig.add_subplot(rows, 2, 2, projection='3d') i1beta_psid(i1, beta, psid) fig.add_subplot(rows, 2, 3, projection='3d') i1beta_psiq(i1, beta, psiq) fig.add_subplot(rows, 2, 4, projection='3d') try: i1beta_psim(i1, beta, bch.ldq['psim']) except: i1beta_up(i1, beta, bch.ldq['up']) fig.add_subplot(rows, 2, 5, projection='3d') i1beta_ld(i1, beta, ld) fig.add_subplot(rows, 2, 6, projection='3d') i1beta_lq(i1, beta, lq) def psidq(bch): """creates the surface plots of a BCH reader object with a psid-psiq identification""" id = bch.psidq['id'] iq = bch.psidq['iq'] torque = bch.psidq['torque'] ld = np.array(bch.psidq_ldq['ld']) lq = np.array(bch.psidq_ldq['lq']) psim = bch.psidq_ldq['psim'] psid = bch.psidq['psid'] psiq = bch.psidq['psiq'] rows = 3 fig = plt.figure(figsize=(10, 4*rows)) fig.suptitle('Psid-Psiq Identification {}'.format( bch.filename), fontsize=16) fig.add_subplot(rows, 2, 1, projection='3d') idq_torque(id, iq, torque) fig.add_subplot(rows, 2, 2, projection='3d') idq_psid(id, iq, psid) fig.add_subplot(rows, 2, 3, projection='3d') idq_psiq(id, iq, psiq) fig.add_subplot(rows, 2, 4, projection='3d') idq_psim(id, iq, psim) fig.add_subplot(rows, 2, 5, projection='3d') idq_ld(id, iq, ld) fig.add_subplot(rows, 2, 6, projection='3d') idq_lq(id, iq, lq) def felosses(losses, coeffs, title='', log=True, ax=0): """plot iron losses with steinmetz or jordan approximation Args: losses: dict with f, B, pfe values coeffs: list with steinmetz (cw, alpha, beta) or jordan (cw, alpha, ch, beta, gamma) coeffs title: title string log: log scale for x and y axes if True """ import femagtools.losscoeffs as lc if ax == 0: ax = plt.gca() fo = losses['fo'] Bo = losses['Bo'] B = plt.np.linspace(0.9*np.min(losses['B']), 1.1*0.9*np.max(losses['B'])) for i, f in enumerate(losses['f']): pfe = [p for p in np.array(losses['pfe'])[i] if p] if f > 0: if len(coeffs) == 5: ax.plot(B, lc.pfe_jordan(f, B, *coeffs, fo=fo, Bo=Bo)) elif len(coeffs) == 3: ax.plot(B, lc.pfe_steinmetz(f, B, *coeffs, fo=fo, Bo=Bo)) plt.plot(losses['B'][:len(pfe)], pfe, marker='o', label="{} Hz".format(f)) ax.set_title("Fe Losses/(W/kg) " + title) if log: ax.set_yscale('log') ax.set_xscale('log') ax.set_xlabel("Flux Density [T]") # plt.ylabel("Pfe [W/kg]") ax.legend() ax.grid(True) def spel(isa, with_axis=False, ax=0): """plot super elements of I7/ISA7 model Args: isa: Isa7 object """ from matplotlib.patches import Polygon if ax == 0: ax = plt.gca() ax.set_aspect('equal') for se in isa.superelements: ax.add_patch(Polygon([n.xy for nc in se.nodechains for n in nc.nodes], color=isa.color[se.color], lw=0)) ax.autoscale(enable=True) if not with_axis: ax.axis('off') def mesh(isa, with_axis=False, ax=0): """plot mesh of I7/ISA7 model Args: isa: Isa7 object """ from matplotlib.lines import Line2D if ax == 0: ax = plt.gca() ax.set_aspect('equal') for el in isa.elements: pts = [list(i) for i in zip(*[v.xy for v in el.vertices])] ax.add_line(Line2D(pts[0], pts[1], color='b', ls='-', lw=0.25)) # for nc in isa.nodechains: # pts = [list(i) for i in zip(*[(n.x, n.y) for n in nc.nodes])] # ax.add_line(Line2D(pts[0], pts[1], color="b", ls="-", lw=0.25, # marker=".", ms="2", mec="None")) # for nc in isa.nodechains: # if nc.nodemid is not None: # plt.plot(*nc.nodemid.xy, "rx") ax.autoscale(enable=True) if not with_axis: ax.axis('off') def _contour(ax, title, elements, values, label='', isa=None): from matplotlib.patches import Polygon from matplotlib.collections import PatchCollection if ax == 0: ax = plt.gca() ax.set_aspect('equal') ax.set_title(title, fontsize=18) if isa: for se in isa.superelements: ax.add_patch(Polygon([n.xy for nc in se.nodechains for n in nc.nodes], color='gray', alpha=0.1, lw=0)) valid_values = np.logical_not(np.isnan(values)) patches = np.array([Polygon([v.xy for v in e.vertices]) for e in elements])[valid_values] # , cmap=matplotlib.cm.jet, alpha=0.4) p = PatchCollection(patches, alpha=1.0, match_original=False) p.set_array(np.asarray(values)[valid_values]) ax.add_collection(p) cb = plt.colorbar(p) for patch in np.array([Polygon([v.xy for v in e.vertices], fc='white', alpha=1.0) for e in elements])[np.isnan(values)]: ax.add_patch(patch) if label: cb.set_label(label=label, fontsize=18) ax.autoscale(enable=True) ax.axis('off') def demag(isa, ax=0): """plot demag of NC/I7/ISA7 model Args: isa: Isa7/NC object """ emag = [e for e in isa.elements if e.is_magnet()] demag = np.array([e.demagnetization(isa.MAGN_TEMPERATURE) for e in emag]) _contour(ax, f'Demagnetization at {isa.MAGN_TEMPERATURE} °C', emag, demag, '-H / kA/m', isa) logger.info("Max demagnetization %f", np.max(demag)) def demag_pos(isa, pos, icur=-1, ibeta=-1, ax=0): """plot demag of NC/I7/ISA7 model at rotor position Args: isa: Isa7/NC object pos: rotor position in degree icur: cur amplitude index or last index if -1 ibeta: beta angle index or last index if -1 """ emag = [e for e in isa.elements if e.is_magnet()] demag = np.array([isa.demagnetization(e, icur, ibeta)[1] for e in emag]) for i, x in enumerate(isa.pos_el_fe_induction): if x >= pos/180*np.pi: break hpol = demag[:, i] hpol[hpol == 0] = np.nan _contour(ax, f'Demagnetization at Pos. {round(x/np.pi*180)}° ({isa.MAGN_TEMPERATURE} °C)', emag, hpol, '-H / kA/m', isa) logger.info("Max demagnetization %f kA/m", np.nanmax(hpol)) def flux_density(isa, subreg=[], ax=0): """plot flux density of NC/I7/ISA7 model Args: isa: Isa7/NC object """ if subreg: if isinstance(subreg, list): sr = subreg else: sr = [subreg] elements = [e for s in sr for se in isa.get_subregion(s).elements() for e in se] else: elements = [e for e in isa.elements] fluxd = np.array([np.linalg.norm(e.flux_density()) for e in elements]) _contour(ax, f'Flux Density T', elements, fluxd) logger.info("Max flux dens %f", np.max(fluxd)) def loss_density(isa, subreg=[], ax=0): """plot loss density of NC/I7/ISA7 model Args: isa: Isa7/NC object """ if subreg: if isinstance(subreg, list): sr = subreg else: sr = [subreg] elements = [e for s in sr for sre in isa.get_subregion(s).elements() for e in sre] else: elements = [e for e in isa.elements] lossd = np.array([e.loss_density*1e-3 for e in elements]) _contour(ax, 'Loss Density kW/m³', elements, lossd) def mmf(f, title='', ax=0): """plot magnetomotive force (mmf) of winding""" if ax == 0: ax = plt.gca() if title: ax.set_title(title) ax.plot(np.array(f['pos'])/np.pi*180, f['mmf']) ax.plot(np.array(f['pos_fft'])/np.pi*180, f['mmf_fft']) ax.set_xlabel('Position / Deg') phi = [f['alfa0']/np.pi*180, f['alfa0']/np.pi*180] y = [min(f['mmf_fft']), 1.1*max(f['mmf_fft'])] ax.plot(phi, y, '--') alfa0 = round(f['alfa0']/np.pi*180, 3) ax.text(phi[0]/2, y[0]+0.05, f"{alfa0}°", ha="center", va="bottom") ax.annotate(f"", xy=(phi[0], y[0]), xytext=(0, y[0]), arrowprops=dict(arrowstyle="->")) ax.grid() def mmf_fft(f, title='', mmfmin=1e-2, ax=0): """plot winding mmf harmonics""" if ax == 0: ax = plt.gca() if title: ax.set_title(title) else: ax.set_title('MMF Harmonics') ax.grid(True) order, mmf = np.array([(n, m) for n, m in zip(f['nue'], f['mmf_nue']) if m > mmfmin]).T try: markerline1, stemlines1, _ = ax.stem(order, mmf, '-.', basefmt=" ", use_line_collection=True) ax.set_xticks(order) except ValueError: # empty sequence pass def zoneplan(wdg, ax=0): """plot zone plan of winding wdg""" from matplotlib.patches import Rectangle upper, lower = wdg.zoneplan() Qb = len([n for l in upper for n in l]) from femagtools.windings import coil_color rh = 0.5 if lower: yl = rh ymax = 2*rh + 0.2 else: yl = 0 ymax = rh + 0.2 if ax == 0: ax = plt.gca() ax.axis('off') ax.set_xlim([-0.5, Qb-0.5]) ax.set_ylim([0, ymax]) ax.set_aspect(Qb/6+0.3) for i, p in enumerate(upper): for x in p: ax.add_patch(Rectangle((abs(x)-1.5, yl), 1, rh, facecolor=coil_color[i], edgecolor='white', fill=True)) s = f'+{i+1}' if x > 0 else f'-{i+1}' ax.text(abs(x)-1, yl+rh/2, s, color='black', ha="center", va="center") for i, p in enumerate(lower): for x in p: ax.add_patch(Rectangle((abs(x)-1.5, yl-rh), 1, rh, facecolor=coil_color[i], edgecolor='white', fill=True)) s = f'+{i+1}' if x > 0 else f'-{i+1}' ax.text(abs(x)-1, yl-rh/2, s, color='black', ha="center", va="center") yu = yl+rh step = 1 if Qb < 25 else 2 if lower: yl -= rh margin = 0.05 ax.text(-0.5, yu+margin, f'Q={wdg.Q}, p={wdg.p}, q={round(wdg.q,4)}', ha='left', va='bottom', size=15) for i in range(0, Qb, step): ax.text(i, yl-margin, f'{i+1}', ha="center", va="top") def winding_factors(wdg, n=8, ax=0): """plot winding factors""" ax = plt.gca() ax.set_title(f'Winding factors Q={wdg.Q}, p={wdg.p}, q={round(wdg.q,4)}') ax.grid(True) order, kwp, kwd, kw = np.array([(n, k1, k2, k3) for n, k1, k2, k3 in zip(wdg.kw_order(n), wdg.kwp(n), wdg.kwd(n), wdg.kw(n))]).T try: markerline1, stemlines1, _ = ax.stem(order-1, kwp, 'C1:', basefmt=" ", markerfmt='C1.', use_line_collection=True, label='Pitch') markerline2, stemlines2, _ = ax.stem(order+1, kwd, 'C2:', basefmt=" ", markerfmt='C2.', use_line_collection=True, label='Distribution') markerline3, stemlines3, _ = ax.stem(order, kw, 'C0-', basefmt=" ", markerfmt='C0o', use_line_collection=True, label='Total') ax.set_xticks(order) ax.legend() except ValueError: # empty sequence pass def winding(wdg, ax=0): """plot coils of windings wdg""" from matplotlib.patches import Rectangle from matplotlib.lines import Line2D from femagtools.windings import coil_color coil_len = 25 coil_height = 4 dslot = 8 arrow_head_length = 2 arrow_head_width = 2 if ax == 0: ax = plt.gca() z = wdg.zoneplan() xoff = 0 if z[-1]: xoff = 0.75 yd = dslot*wdg.yd mh = 2*coil_height/yd slots = sorted([abs(n) for m in z[0] for n in m]) smax = slots[-1]*dslot for n in slots: x = n*dslot ax.add_patch(Rectangle((x + dslot/4, 1), dslot / 2, coil_len - 2, fc="lightblue")) ax.text(x, coil_len / 2, str(n), horizontalalignment="center", verticalalignment="center", backgroundcolor="white", bbox=dict(boxstyle='circle,pad=0', fc="white", lw=0)) line_thickness = [0.6, 1.2] for i, layer in enumerate(z): b = -xoff if i else xoff lw = line_thickness[i] for m, mslots in enumerate(layer): for k in mslots: x = abs(k) * dslot + b xpoints = [] ypoints = [] if (i == 0 and (k > 0 or (k < 0 and wdg.l > 1))): # first layer, positive dir or neg. dir and 2-layers: # from right bottom if x + yd > smax+b: dx = dslot if yd > dslot else yd/4 xpoints = [x + yd//2 + dx - xoff] ypoints = [-coil_height + mh*dx] xpoints += [x + yd//2 - xoff, x, x, x + yd//2-xoff] ypoints += [-coil_height, 0, coil_len, coil_len+coil_height] if x + yd > smax+b: xpoints += [x + yd//2 + dx - xoff] ypoints += [coil_len+coil_height - mh*dx] else: # from left bottom if x - yd < 0: # and x - yd/2 > -3*dslot: dx = dslot if yd > dslot else yd/4 xpoints = [x - yd//2 - dx + xoff] ypoints = [- coil_height + mh*dx] xpoints += [x - yd//2+xoff, x, x, x - yd/2+xoff] ypoints += [-coil_height, 0, coil_len, coil_len+coil_height] if x - yd < 0: # and x - yd > -3*dslot: xpoints += [x - yd//2 - dx + xoff] ypoints += [coil_len + coil_height - mh*dx] ax.add_line(Line2D(xpoints, ypoints, color=coil_color[m], lw=lw)) if k > 0: h = arrow_head_length y = coil_len * 0.8 else: h = -arrow_head_length y = coil_len * 0.2 ax.arrow(x, y, 0, h, length_includes_head=True, head_starts_at_zero=False, head_length=arrow_head_length, head_width=arrow_head_width, fc=coil_color[m], lw=0) if False: # TODO show winding connections m = 0 for k in [n*wdg.Q/wdg.p/wdg.m + 1 for n in range(wdg.m)]: if k < len(slots): x = k * dslot + b + yd/2 - xoff ax.add_line(Line2D([x, x], [-2*coil_height, -coil_height], color=coil_color[m], lw=lw)) ax.text(x, -2*coil_height+0.5, str(m+1), color=coil_color[m]) m += 1 ax.autoscale(enable=True) ax.set_axis_off() def main(): import io import sys import argparse from .__init__ import __version__ from femagtools.bch import Reader argparser = argparse.ArgumentParser( description='Read BCH/BATCH/PLT file and create a plot') argparser.add_argument('filename', help='name of BCH/BATCH/PLT file') argparser.add_argument( "--version", "-v", action="version", version="%(prog)s {}, Python {}".format(__version__, sys.version), help="display version information", ) args = argparser.parse_args() if not matplotlibversion: sys.exit(0) if not args.filename: sys.exit(0) ext = args.filename.split('.')[-1].upper() if ext.startswith('MC'): import femagtools.mcv mcv = femagtools.mcv.read(sys.argv[1]) if mcv['mc1_type'] in (femagtools.mcv.MAGCRV, femagtools.mcv.ORIENT_CRV): ncols = 2 else: # Permanent Magnet ncols = 1 fig, ax = plt.subplots(nrows=1, ncols=ncols, figsize=(10, 6)) if ncols > 1: plt.subplot(1, 2, 1) mcv_hbj(mcv) plt.subplot(1, 2, 2) mcv_muer(mcv) else: mcv_hbj(mcv, log=False) fig.tight_layout() fig.subplots_adjust(top=0.94) plt.show() return if ext.startswith('PLT'): import femagtools.forcedens fdens = femagtools.forcedens.read(args.filename) cols = 1 rows = 2 fig, ax = plt.subplots(nrows=rows, ncols=cols, figsize=(10, 10*rows)) title = '{}, Rotor position {}'.format( fdens.title, fdens.positions[0]['position']) pos = fdens.positions[0]['X'] FT_FN = (fdens.positions[0]['FT'], fdens.positions[0]['FN']) plt.subplot(rows, cols, 1) forcedens(title, pos, FT_FN) title = 'Force Density Harmonics' plt.subplot(rows, cols, 2) forcedens_fft(title, fdens) # fig.tight_layout(h_pad=3.5) # if title: # fig.subplots_adjust(top=0.92) plt.show() return bchresults = Reader() with io.open(args.filename, encoding='latin1', errors='ignore') as f: bchresults.read(f.readlines()) if (bchresults.type.lower().find( 'pm-synchronous-motor simulation') >= 0 or bchresults.type.lower().find( 'permanet-magnet-synchronous-motor') >= 0 or bchresults.type.lower().find( 'simulation pm/universal-motor') >= 0): pmrelsim(bchresults, bchresults.filename) elif bchresults.type.lower().find( 'multiple calculation of forces and flux') >= 0: multcal(bchresults, bchresults.filename) elif bchresults.type.lower().find('cogging calculation') >= 0: cogging(bchresults, bchresults.filename) elif bchresults.type.lower().find('ld-lq-identification') >= 0: ldlq(bchresults) elif bchresults.type.lower().find('psid-psiq-identification') >= 0: psidq(bchresults) elif bchresults.type.lower().find('fast_torque calculation') >= 0: fasttorque(bchresults) elif bchresults.type.lower().find('transient sc') >= 0: transientsc(bchresults, bchresults.filename) else: raise ValueError("BCH type {} not yet supported".format( bchresults.type)) plt.show() def characteristics(char, title=''): fig, axs = plt.subplots(2, 2, figsize=(10, 8), sharex=True) if title: fig.suptitle(title) n = np.array(char['n'])*60 pmech = np.array(char['pmech'])*1e-3 axs[0, 0].plot(n, np.array(char['T']), 'C0-', label='Torque') axs[0, 0].set_ylabel("Torque / Nm") axs[0, 0].grid() axs[0, 0].legend(loc='center left') ax1 = axs[0, 0].twinx() ax1.plot(n, pmech, 'C1-', label='P mech') ax1.set_ylabel("Power / kW") ax1.legend(loc='lower center') axs[0, 1].plot(n[1:], np.array(char['u1'][1:]), 'C0-', label='Voltage') axs[0, 1].set_ylabel("Voltage / V",) axs[0, 1].grid() axs[0, 1].legend(loc='center left') ax2 = axs[0, 1].twinx() ax2.plot(n[1:], char['cosphi'][1:], 'C1-', label='Cos Phi') ax2.set_ylabel("Cos Phi") ax2.legend(loc='lower right') if 'id' in char: axs[1, 0].plot(n, np.array(char['id']), label='Id') if 'iq' in char: axs[1, 0].plot(n, np.array(char['iq']), label='Iq') axs[1, 0].plot(n, np.array(char['i1']), label='I1') axs[1, 0].set_xlabel("Speed / rpm") axs[1, 0].set_ylabel("Current / A") axs[1, 0].legend(loc='center left') if 'beta' in char: ax3 = axs[1, 0].twinx() ax3.plot(n, char['beta'], 'C3-', label='Beta') ax3.set_ylabel("Beta / °") ax3.legend(loc='center right') axs[1, 0].grid() plfe = np.array(char['plfe'])*1e-3 plcu = np.array(char['plcu'])*1e-3 pl = np.array(char['losses'])*1e-3 axs[1, 1].plot(n, plcu, 'C0-', label='Cu Losses') axs[1, 1].plot(n, plfe, 'C1-', label='Fe Losses') axs[1, 1].set_ylabel("Losses / kW") axs[1, 1].legend(loc='center left') axs[1, 1].grid() axs[1, 1].set_xlabel("Speed / rpm") ax4 = axs[1, 1].twinx() ax4.plot(n[1:-1], char['eta'][1:-1], 'C3-', label="Eta") ax4.legend(loc='upper center') ax4.set_ylabel("Efficiency") fig.tight_layout() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s') main()
SEMAFORInformatik/femagtools
femagtools/plot.py
Python
bsd-2-clause
54,354
import {Component, NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; @Component({ selector: 'application', template: `<div>Hello!</div>` }) export class BasicInlineComponent {} @NgModule({ imports: [BrowserModule], declarations: [BasicInlineComponent], bootstrap: [BasicInlineComponent], }) export class BasicInlineModule {}
clbond/angular-ssr
source/test/fixtures/application-basic-inline.ts
TypeScript
bsd-2-clause
377
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) from . import _wrap_numbers, Symbol, Number, Matrix def symbols(s): """ mimics sympy.symbols """ tup = tuple(map(Symbol, s.replace(',', ' ').split())) if len(tup) == 1: return tup[0] else: return tup def symarray(prefix, shape): import numpy as np arr = np.empty(shape, dtype=object) for index in np.ndindex(shape): arr[index] = Symbol('%s_%s' % ( prefix, '_'.join(map(str, index)))) return arr def lambdify(args, exprs): """ lambdify mimics sympy.lambdify """ try: nargs = len(args) except TypeError: args = (args,) nargs = 1 try: nexprs = len(exprs) except TypeError: exprs = (exprs,) nexprs = 1 @_wrap_numbers def f(*inp): if len(inp) != nargs: raise TypeError("Incorrect number of arguments") try: len(inp) except TypeError: inp = (inp,) subsd = dict(zip(args, inp)) return [expr.subs(subsd).evalf() for expr in exprs][ 0 if nexprs == 1 else slice(None)] return f class Lambdify(object): """ Lambdify mimics symengine.Lambdify """ def __init__(self, syms, exprs): self.syms = syms self.exprs = exprs def __call__(self, inp, out=None): inp = tuple(map(Number.make, inp)) subsd = dict(zip(self.syms, inp)) def _eval(expr_iter): return [expr.subs(subsd).evalf() for expr in expr_iter] exprs = self.exprs if out is not None: try: out.flat = _eval(exprs.flatten()) except AttributeError: out.flat = _eval(exprs) elif isinstance(exprs, Matrix): import numpy as np nr, nc = exprs.nrows, exprs.ncols out = np.empty((nr, nc)) for ri in range(nr): for ci in range(nc): out[ri, ci] = exprs._get_element( ri*nc + ci).subs(subsd).evalf() return out # return Matrix(nr, nc, _eval(exprs._get_element(i) for # i in range(nr*nc))) elif hasattr(exprs, 'reshape'): # NumPy like container: container = exprs.__class__(exprs.shape, dtype=float, order='C') container.flat = _eval(exprs.flatten()) return container else: return _eval(exprs)
bjodah/pysym
pysym/util.py
Python
bsd-2-clause
2,569
const maps = require('source-map-support'); maps.install({environment: 'node'});
clbond/angular-ssr
source/application/compiler/webpack/source-map.ts
TypeScript
bsd-2-clause
81
// Copyright (C) 2015 the V8 project authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-array.from es6id: 22.1.2.1 description: Value returned by mapping function (traversed via iterator) info: | [...] 2. If mapfn is undefined, let mapping be false. 3. else a. If IsCallable(mapfn) is false, throw a TypeError exception. b. If thisArg was supplied, let T be thisArg; else let T be undefined. c. Let mapping be true [...] 6. If usingIterator is not undefined, then [...] g. Repeat [...] vii. If mapping is true, then 1. Let mappedValue be Call(mapfn, T, «nextValue, k»). 2. If mappedValue is an abrupt completion, return IteratorClose(iterator, mappedValue). 3. Let mappedValue be mappedValue.[[value]]. features: [Symbol.iterator] ---*/ var thisVals = []; var nextResult = { done: false, value: {} }; var nextNextResult = { done: false, value: {} }; var firstReturnVal = {}; var secondReturnVal = {}; var mapFn = function(value, idx) { var returnVal = nextReturnVal; nextReturnVal = nextNextReturnVal; nextNextReturnVal = null; return returnVal; }; var nextReturnVal = firstReturnVal; var nextNextReturnVal = secondReturnVal; var items = {}; var result; items[Symbol.iterator] = function() { return { next: function() { var result = nextResult; nextResult = nextNextResult; nextNextResult = { done: true }; return result; } }; }; result = Array.from(items, mapFn); assert.sameValue(result.length, 2); assert.sameValue(result[0], firstReturnVal); assert.sameValue(result[1], secondReturnVal);
sebastienros/jint
Jint.Tests.Test262/test/built-ins/Array/from/iter-map-fn-return.js
JavaScript
bsd-2-clause
1,769
package com.mithos.bfg.loop; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; /** * This class is an adapter for {@link OnEvent}. All methods do * nothing and return true, so you need only implement the methods * that you need to. * @author James McMahon * */ public class OnEventAdapter implements OnEvent { @Override public boolean keyPressed(KeyEvent e) { return true; } @Override public boolean keyReleased(KeyEvent e) { return true; } @Override public boolean mousePressed(MouseEvent e) { return true; } @Override public boolean mouseMoved(MouseEvent e) { return true; } @Override public boolean mouseReleased(MouseEvent e) { return true; } @Override public boolean mouseWheel(MouseWheelEvent e) { return true; } }
James1345/bfg
src/com/mithos/bfg/loop/OnEventAdapter.java
Java
bsd-2-clause
821
using Esprima.Ast; namespace Jint.Runtime.Interpreter { /// <summary> /// Per Engine.Evalute() call context. /// </summary> internal sealed class EvaluationContext { public EvaluationContext(Engine engine, in Completion? resumedCompletion = null) { Engine = engine; DebugMode = engine._isDebugMode; ResumedCompletion = resumedCompletion ?? default; // TODO later OperatorOverloadingAllowed = engine.Options.Interop.AllowOperatorOverloading; } public Engine Engine { get; } public Completion ResumedCompletion { get; } public bool DebugMode { get; } public Node LastSyntaxNode { get; set; } public bool OperatorOverloadingAllowed { get; } } }
sebastienros/jint
Jint/Runtime/Interpreter/EvaluationContext.cs
C#
bsd-2-clause
780
log.enableAll(); (function(){ function animate() { requestAnimationFrame(animate); TWEEN.update(); } animate(); })(); var transform = getStyleProperty('transform'); var getStyle = ( function() { var getStyleFn = getComputedStyle ? function( elem ) { return getComputedStyle( elem, null ); } : function( elem ) { return elem.currentStyle; }; return function getStyle( elem ) { var style = getStyleFn( elem ); if ( !style ) { log.error( 'Style returned ' + style + '. Are you running this code in a hidden iframe on Firefox? ' + 'See http://bit.ly/getsizebug1' ); } return style; }; })(); var cache = { imgW: 5100, imgH: 852, panOffsetX: 0, ring: 0, deg: 0, runDeg: 0, minOffsetDeg: 8, rotationOffsetDeg: 0, onceRotationOffsetDeg: 0, nowOffset: 0, len: 0, touchLock: false, timer: null }; var tween1, tween2; var util = { setTranslateX: function setTranslateX(el, num) { el.style[transform] = "translate3d(" + num + "px,0,0)"; } }; var initPanoramaBox = function initPanoramaBox($el, opts) { var elH = $el.height(); var elW = $el.width(); var $panoramaBox = $('<div class="panorama-box">' + '<div class="panorama-item"></div>' + '<div class="panorama-item"></div>' + '</div>'); var $panoramaItem = $('.panorama-item', $panoramaBox); var scal = elH / opts.height; $panoramaItem.css({ width: opts.width, height: opts.height }); $panoramaBox.css({ width: elW / scal, height: opts.height, transform: 'scale3d(' + scal + ',' + scal + ',' + scal + ')', 'transform-origin': '0 0' }); util.setTranslateX($panoramaItem.get(0), 0); util.setTranslateX($panoramaItem.get(1), -opts.width); $el.append($panoramaBox); var offset = function offset(num) { var width = opts.width; var num1 = num % opts.width; var num2; if (num1 < -width / 2) { num2 = width + num1 - 2; } else { num2 = -width + num1 + 2; } util.setTranslateX($panoramaItem.get(0), num1); util.setTranslateX($panoramaItem.get(1), num2); }; var run = function (subBox1, subBox2, width) { return function offset(num) { num = parseInt(num); cache.len = num; var num1 = num % width; var num2; if (num1 < -width / 2) { num2 = width + num1 - 1; } else { num2 = -width + num1 + 2; } util.setTranslateX(subBox1, num1); util.setTranslateX(subBox2, num2); }; }; return run($panoramaItem.get(0), $panoramaItem.get(1), opts.width); }; var $el = {}; $el.main = $('.wrapper'); var offset = initPanoramaBox($el.main, { width: cache.imgW, height: cache.imgH }); var animOffset = function animOffset(length){ if(tween1){ tween1.stop(); } tween1 = new TWEEN.Tween({x: cache.len}); tween1.to({x: length}, 600); tween1.onUpdate(function(){ offset(this.x); }); tween1.start(); }; var animPanEnd = function animPanEnd(velocityX){ if(tween2){ tween2.stop(); } var oldLen = cache.len; var offsetLen ; tween2 = new TWEEN.Tween({x: cache.len}); tween2.to({x: cache.len - 200 * velocityX}, 600); tween2.easing(TWEEN.Easing.Cubic.Out); tween2.onUpdate(function(){ offset(this.x); offsetLen =oldLen - this.x; cache.nowOffset += + offsetLen; cache.panOffsetX += + offsetLen; }); tween2.start(); }; var initOrientationControl = function () { FULLTILT.getDeviceOrientation({'type': 'world'}) .then(function (orientationControl) { var orientationFunc = function orientationFunc() { var screenAdjustedEvent = orientationControl.getScreenAdjustedEuler(); cache.navDeg = 360 - screenAdjustedEvent.alpha; if (cache.navDeg > 270 && cache.navOldDeg < 90) { cache.ring -= 1; } else if (cache.navDeg < 90 && cache.navOldDeg > 270) { cache.ring += 1; } cache.navOldDeg = cache.navDeg; cache.oldDeg = cache.deg; cache.deg = cache.ring * 360 + cache.navDeg; var offsetDeg = cache.deg - cache.runDeg; if (!cache.touchLock && (Math.abs(offsetDeg) > cache.minOffsetDeg)) { var length = cache.imgW / 360 * -(cache.deg - cache.rotationOffsetDeg) + cache.panOffsetX; cache.runDeg = cache.deg; cache.nowOffset = length; animOffset(length); } }; orientationControl.listen(orientationFunc); }) .catch(function(e){ log.error(e); }); }; var initTouch = function(){ var mc = new Hammer.Manager($el.main.get(0)); var pan = new Hammer.Pan(); $el.main.on('touchstart', function (evt) { if (cache.timer) { clearTimeout(cache.timer); cache.timer = null; } cache.touchLock = true; if(tween1){ tween1.stop(); } if(tween2){ tween2.stop(); } cache.nowOffset = cache.len; }); $el.main.on('touchend', function (evt) { cache.timer = setTimeout(function () { cache.onceRotationOffsetDeg = cache.deg - cache.runDeg; cache.runDeg = cache.deg + cache.onceRotationOffsetDeg; cache.rotationOffsetDeg = cache.rotationOffsetDeg + cache.onceRotationOffsetDeg; cache.touchLock = false; }, 1000); }); mc.add(pan); mc.on('pan', function (evt) { offset(cache.nowOffset + evt.deltaX); }); mc.on('panend', function (evt) { cache.nowOffset += + evt.deltaX; cache.panOffsetX += + evt.deltaX; //animPanEnd(evt.velocityX); }); }; initTouch(); initOrientationControl();
wushuyi/panorama360
assets/js/functions_bak.js
JavaScript
bsd-2-clause
6,239
// Copyright (c) 2022, WNProject Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "WNNetworking/inc/WNReliableNetworkTransportSocket.h" #include "WNNetworking/inc/WNReliableNetworkListenSocket.h" #include <netdb.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/uio.h> namespace wn { namespace networking { network_error WNReliableNetworkTransportSocket::connect_to(logging::log* _log, const containers::string_view& target, uint32_t _connection_type, uint16_t _port) { char port_array[11] = {0}; memory::writeuint32(port_array, _port, 10); addrinfo* result; addrinfo* ptr; if (0 != getaddrinfo(target.to_string(m_allocator).c_str(), port_array, nullptr, &result)) { _log->log_error("Could not resolve local port ", port_array); return network_error::could_not_resolve; } ptr = result; for (ptr = result; ptr != nullptr; ptr = ptr->ai_next) { if ((_connection_type == 0xFFFFFFFF && (ptr->ai_family == AF_INET || ptr->ai_family == AF_INET6)) || ptr->ai_family == static_cast<int>(_connection_type)) { m_sock_fd = socket(ptr->ai_family, SOCK_STREAM, IPPROTO_TCP); if (m_sock_fd == -1) { continue; } if (0 != connect(m_sock_fd, ptr->ai_addr, ptr->ai_addrlen)) { ::close(m_sock_fd); m_sock_fd = -1; continue; } break; } } freeaddrinfo(result); if (ptr == nullptr) { _log->log_error("Could not resolve target ", target, ":", port_array); return network_error::could_not_resolve; } return network_error::ok; } network_error WNReliableNetworkTransportSocket::do_send( const send_ranges& _buffers) { iovec* send_buffers = static_cast<iovec*>(WN_STACK_ALLOC(sizeof(iovec) * _buffers.size())); size_t total_bytes = 0; for (size_t i = 0; i < _buffers.size(); ++i) { total_bytes += _buffers[i].size(); send_buffers[i].iov_base = const_cast<void*>(static_cast<const void*>(_buffers[i].data())); send_buffers[i].iov_len = _buffers[i].size(); } using iovlen_type = decltype(msghdr().msg_iovlen); msghdr header = {nullptr, // msg_name 0, // msg_namelen send_buffers, // msg_iov static_cast<iovlen_type>(_buffers.size()), // msg_iovlen nullptr, // msg_control 0, // msg_controllen 0}; ssize_t num_sent = 0; if (0 > (num_sent = sendmsg(m_sock_fd, &header, 0))) { return network_error::could_not_send; } if (num_sent != static_cast<ssize_t>(total_bytes)) { return network_error::could_not_send; ::close(m_sock_fd); m_sock_fd = -1; } return network_error::ok; } WNReceiveBuffer WNReliableNetworkTransportSocket::recv_sync() { WNReceiveBuffer buffer(m_manager->acquire_buffer()); ssize_t received = 0; if (0 >= (received = recv(m_sock_fd, buffer.data.data(), buffer.data.size(), 0))) { return WNReceiveBuffer(network_error::could_not_receive); } buffer.data = containers::contiguous_range<char>(buffer.data.data(), received); return buffer; } } // namespace networking } // namespace wn
WNProject/WNFramework
Overlays/Posix/Libraries/WNNetworking/src/WNReliableNetworkTransportSocket.cpp
C++
bsd-2-clause
3,381
var _ = require('lodash'); var requireAll = require('require-all'); function load(router, options) { if (_.isString(options)) options = {dirname: options}; return requireAll(_.defaults(options, { filter: /(.*Controller)\.js$/, recursive: true, resolve: function (Controller) { var c = new (Controller.__esModule ? Controller.default : Controller)(); c.register && c.register(router); return c; } })); } module.exports = load;
vvv-v13/express-starter
library/load.js
JavaScript
bsd-2-clause
476
/* * Copyright (c) 2012, JInterval Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package net.java.jinterval.ir; import com.cflex.util.lpSolve.LpConstant; import com.cflex.util.lpSolve.LpModel; import com.cflex.util.lpSolve.LpSolver; import java.util.ArrayList; //import org.apache.commons.math3.exception.MathIllegalArgumentException; //TODO: Add exceptions and throws public class IRPredictor { private double[][] X; private double[] Y; private double[] E; private boolean dataAreGiven; // Number of observations private int ObsNumber; // Number of variables private int VarNumber; // Storage for predictions private double PredictionMin; private double PredictionMax; private double[] PredictionMins; private double[] PredictionMaxs; // Last error int ExitCode; public IRPredictor(){ ObsNumber = 0; VarNumber = 0; dataAreGiven = false; } public IRPredictor(double[][] X, double[] Y, double[] E){ setData(X,Y,E); } public final void setData(double[][] X, double[] Y, double[] E) // throws IllegalDimensionException { // if(X.length != Y.length || X.length != E.length) // throw IllegalDimensionException; this.X=X; this.Y=Y; this.E=E; ObsNumber = X.length; VarNumber = X[0].length; dataAreGiven = true; } public int getExitCode() { return ExitCode; } private boolean solveLpp(double[] Objective) // throws IllegalDimensionException { if (Objective.length != VarNumber){ // throw IllegalDimensionException; ExitCode = -1; return false; } try { // Init LP Solver LpModel Lpp = new LpModel(0, VarNumber); // Define LPP double[] zObjective = new double[VarNumber+1]; System.arraycopy(Objective, 0, zObjective, 1, VarNumber); Lpp.setObjFn(zObjective); double[] zX=new double[VarNumber+1]; for (int i=0; i<ObsNumber; i++) { System.arraycopy(X[i], 0, zX, 1, VarNumber); Lpp.addConstraint(zX, LpConstant.LE, Y[i]+E[i]); Lpp.addConstraint(zX, LpConstant.GE, Y[i]-E[i]); // Solver.add_constraint(Lpp, zX, constant.LE, Y[i]+E[i]); // Solver.add_constraint(Lpp, zX, constant.GE, Y[i]-E[i]); } //Solver.set_minim(Lpp); //Lpp.setMinimum(); LpSolver Solver = new LpSolver(Lpp); ExitCode = Solver.solve(); // ExitCode = Solver.solve(Lpp); switch ( ExitCode ) { case LpConstant.OPTIMAL: PredictionMin = Lpp.getBestSolution(0); break; case LpConstant.INFEASIBLE: //throw InfeasibleException case LpConstant.UNBOUNDED: //throw UnboundedException } // Solver.set_maxim(Lpp); Lpp.setMaximum(); ExitCode = Solver.solve(); switch ( ExitCode ) { case LpConstant.OPTIMAL: PredictionMax = Lpp.getBestSolution(0); break; case LpConstant.INFEASIBLE: //throw InfeasibleException case LpConstant.UNBOUNDED: //throw UnboundedException } } catch (Exception e){ //e.printStackTrace(); } return ExitCode == LpConstant.OPTIMAL; } public boolean isDataConsistent(){ return solveLpp(X[0]); } public void compressData(){ } public boolean predictAt(double[] x){ return solveLpp(x); } public boolean predictAtEveryDataPoint(){ PredictionMins = new double[ObsNumber]; PredictionMaxs = new double[ObsNumber]; boolean Solved = true; for (int i=0; i<ObsNumber; i++){ Solved = Solved && predictAt(X[i]); if(!Solved) { break; } PredictionMins[i] = getMin(); PredictionMaxs[i] = getMax(); } return Solved; } public double getMin(){ return PredictionMin; } public double getMax(){ return PredictionMax; } public double getMin(int i) { return PredictionMins[i]; } public double getMax(int i) { return PredictionMaxs[i]; } public double[] getMins() { return PredictionMins; } public double[] getMaxs() { return PredictionMaxs; } public double[] getResiduals(){ //Residuals=(y-(vmax+vmin)/2)/beta double v; double[] residuals = new double[ObsNumber]; for(int i=0; i<ObsNumber; i++) { v = (PredictionMins[i]+PredictionMaxs[i])/2; residuals[i] = (Y[i]-v)/E[i]; } return residuals; } public double[] getLeverages(){ //Leverage=((vmax-vmin)/2)/beta double v; double[] leverages = new double[ObsNumber]; for(int i=0; i<ObsNumber; i++) { v = (PredictionMaxs[i]-PredictionMins[i])/2; leverages[i] = v/E[i]; } return leverages; } public int[] getBoundary(){ final double EPSILON = 1.0e-6; ArrayList<Integer> boundary = new ArrayList<Integer>(); double yp, ym, vp, vm; for (int i=0; i<ObsNumber; i++){ yp = Y[i]+E[i]; vp = PredictionMaxs[i]; ym = Y[i]-E[i]; vm = PredictionMins[i]; if ( Math.abs(yp - vp) < EPSILON || Math.abs(ym - vm) < EPSILON ) { boundary.add(1); } else { boundary.add(0); } } int[] a_boundary = new int[boundary.size()]; for (int i=0; i<a_boundary.length; i++){ a_boundary[i] = boundary.get(i).intValue(); } return a_boundary; } public int[] getBoundaryNumbers(){ int Count = 0; int[] boundary = getBoundary(); for (int i=0; i<boundary.length; i++){ if(boundary[i] == 1) { Count++; } } int j = 0; int[] numbers = new int[Count]; for (int i=0; i<boundary.length; i++){ if(boundary[i] == 1) { numbers[j++] = i; } } return numbers; } //TODO: Implement getOutliers() // public int[] getOutliers(){ // // } //TODO: Implement getOutliersNumbers() // public int[] getOutliersNumbers(){ // // } public double[] getOutliersWeights(){ double[] outliers = new double[ObsNumber]; for(int i=0; i<ObsNumber; i++) { outliers[i]=0; } try { LpModel Lpp = new LpModel(0, ObsNumber+VarNumber); // Build and set objective of LPP double[] zObjective = new double[ObsNumber+VarNumber+1]; for(int i=1;i<=VarNumber; i++) { zObjective[i] = 0; } for(int i=1;i<=ObsNumber; i++) { zObjective[VarNumber+i] = 1; } Lpp.setObjFn(zObjective); //Solver.set_minim(Lpp); // Build and set constraints of LPP double[] Row = new double[ObsNumber+VarNumber+1]; for (int i=0; i<ObsNumber; i++) { for (int j=1; j<=VarNumber; j++) { Row[j]=X[i][j-1]; } for(int j=1; j<=ObsNumber; j++) { Row[VarNumber+j] = 0; } Row[VarNumber+i+1] = -E[i]; // Solver.add_constraint(Lpp, Row, constant.LE, Y[i]); Lpp.addConstraint(Row, LpConstant.LE, Y[i]); Row[VarNumber+i+1] = E[i]; // Solver.add_constraint(Lpp, Row, constant.GE, Y[i]); Lpp.addConstraint(Row, LpConstant.GE, Y[i]); for (int j=1; j<=ObsNumber+VarNumber; j++) { Row[j] = 0; } Row[VarNumber+i+1] = 1; // Solver.add_constraint(Lpp, Row, constant.GE, 1); Lpp.addConstraint(Row, LpConstant.GE, 1); } // Solve LPP and get outliers' weights LpSolver Solver = new LpSolver(Lpp); ExitCode = Solver.solve(); for(int i = 0; i < ObsNumber; i++) { outliers[i] = Lpp.getBestSolution(Lpp.getRows()+VarNumber+i+1); } } catch(Exception e){ //e.printStackTrace(); } return outliers; } }
jinterval/jinterval
jinterval-ir/src/main/java/net/java/jinterval/ir/IRPredictor.java
Java
bsd-2-clause
10,164
/* * Copyright (c) 2016-2016, Roland Bock * 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 "compare.h" #include "Sample.h" #include <sqlpp11/sqlpp11.h> #include <iostream> namespace { auto getTrue() -> std::string { MockDb::_serializer_context_t printer = {}; return serialize(sqlpp::value(true), printer).str(); } auto getFalse() -> std::string { MockDb::_serializer_context_t printer = {}; return serialize(sqlpp::value(false), printer).str(); } } // namespace int Where(int, char*[]) { const auto foo = test::TabFoo{}; const auto bar = test::TabBar{}; // Unconditionally compare(__LINE__, select(foo.omega).from(foo).unconditionally(), "SELECT tab_foo.omega FROM tab_foo"); compare(__LINE__, remove_from(foo).unconditionally(), "DELETE FROM tab_foo"); compare(__LINE__, update(foo).set(foo.omega = 42).unconditionally(), "UPDATE tab_foo SET omega=42"); compare(__LINE__, update(foo).set(foo.omega = foo.omega - -1).unconditionally(), "UPDATE tab_foo SET omega=(tab_foo.omega - -1)"); compare(__LINE__, where(sqlpp::value(true)), " WHERE " + getTrue()); // Never compare(__LINE__, where(sqlpp::value(false)), " WHERE " + getFalse()); // Sometimes compare(__LINE__, where(bar.gamma), " WHERE tab_bar.gamma"); compare(__LINE__, where(bar.gamma == false), " WHERE (tab_bar.gamma=" + getFalse() + ")"); compare(__LINE__, where(bar.beta.is_null()), " WHERE (tab_bar.beta IS NULL)"); compare(__LINE__, where(bar.beta == "SQL"), " WHERE (tab_bar.beta='SQL')"); compare(__LINE__, where(is_equal_to_or_null(bar.beta, ::sqlpp::value_or_null("SQL"))), " WHERE (tab_bar.beta='SQL')"); compare(__LINE__, where(is_equal_to_or_null(bar.beta, ::sqlpp::value_or_null<sqlpp::text>(::sqlpp::null))), " WHERE (tab_bar.beta IS NULL)"); #if __cplusplus >= 201703L // string_view argument std::string_view sqlString = "SQL"; compare(__LINE__, where(bar.beta == sqlString), " WHERE (tab_bar.beta='SQL')"); #endif return 0; }
rbock/sqlpp11
tests/core/serialize/Where.cpp
C++
bsd-2-clause
3,294
#include <iostream> #include <string> #include <map> #include <unistd.h> #include <utility> #include <sstream> #include "./patricia-tree.hpp" int main(void) { std::cout << "Add new command!\n"; PatriciaTree<Node<std::string, StringKeySpec>> pt; std::string command = "command"; std::string key; while(command != "exit") { getline(std::cin, key); pt.insertNode(key, command); std::cout << pt << "\n"; } return 0; }
giovannicuriel/tinytools
src/c++/patricia-tree-demo.cpp
C++
bsd-2-clause
472
# Add your own choices here! fruit = ["apples", "oranges", "pears", "grapes", "blueberries"] lunch = ["pho", "timmies", "thai", "burgers", "buffet!", "indian", "montanas"] situations = {"fruit":fruit, "lunch":lunch}
rbracken/internbot
plugins/pick/choices.py
Python
bsd-2-clause
218
/* * Copyright (c) 2009-2010 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.gde.core.properties; import com.jme3.gde.core.scene.SceneApplication; import com.jme3.scene.Spatial; import java.beans.PropertyEditor; import java.lang.reflect.InvocationTargetException; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.logging.Level; import java.util.logging.Logger; import org.openide.nodes.PropertySupport; import org.openide.util.Exceptions; /** * * @author normenhansen */ public class UserDataProperty extends PropertySupport.ReadWrite<String> { private Spatial spatial; private String name = "null"; private int type = 0; private List<ScenePropertyChangeListener> listeners = new LinkedList<ScenePropertyChangeListener>(); public UserDataProperty(Spatial node, String name) { super(name, String.class, name, ""); this.spatial = node; this.name = name; this.type = getObjectType(node.getUserData(name)); } public static int getObjectType(Object type) { if (type instanceof Integer) { return 0; } else if (type instanceof Float) { return 1; } else if (type instanceof Boolean) { return 2; } else if (type instanceof String) { return 3; } else if (type instanceof Long) { return 4; } else { Logger.getLogger(UserDataProperty.class.getName()).log(Level.WARNING, "UserData not editable" + (type == null ? "null" : type.getClass())); return -1; } } @Override public String getValue() throws IllegalAccessException, InvocationTargetException { return spatial.getUserData(name) + ""; } @Override public void setValue(final String val) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { if (spatial == null) { return; } try { SceneApplication.getApplication().enqueue(new Callable<Void>() { public Void call() throws Exception { switch (type) { case 0: spatial.setUserData(name, Integer.parseInt(val)); break; case 1: spatial.setUserData(name, Float.parseFloat(val)); break; case 2: spatial.setUserData(name, Boolean.parseBoolean(val)); break; case 3: spatial.setUserData(name, val); break; case 4: spatial.setUserData(name, Long.parseLong(val)); break; default: // throw new UnsupportedOperationException(); } return null; } }).get(); notifyListeners(null, val); } catch (InterruptedException ex) { Exceptions.printStackTrace(ex); } catch (ExecutionException ex) { Exceptions.printStackTrace(ex); } } @Override public PropertyEditor getPropertyEditor() { return null; // return new AnimationPropertyEditor(control); } public void addPropertyChangeListener(ScenePropertyChangeListener listener) { listeners.add(listener); } public void removePropertyChangeListener(ScenePropertyChangeListener listener) { listeners.remove(listener); } private void notifyListeners(Object before, Object after) { for (Iterator<ScenePropertyChangeListener> it = listeners.iterator(); it.hasNext();) { ScenePropertyChangeListener propertyChangeListener = it.next(); propertyChangeListener.propertyChange(getName(), before, after); } } }
chototsu/MikuMikuStudio
sdk/jme3-core/src/com/jme3/gde/core/properties/UserDataProperty.java
Java
bsd-2-clause
5,643
// Copyright (c) 2017 ASMlover. 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 ofconditions 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 materialsprovided 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 "minipy.h" #include <iostream> #include <string> int main(int argc, char* argv[]) { (void)argc, (void)argv; const char* prompt = ">>> "; std::cout << "********** MiniPy 0.1 **********" << std::endl; std::cout << prompt; std::string command; while (std::getline(std::cin, command)) { if (command.empty()) ; else if (command == "exit") break; else Py_Execute(command); std::cout << prompt; } return 0; }
ASMlover/study
python/minipy/main.cc
C++
bsd-2-clause
1,837
# OCaml does not preserve binary compatibility across compiler releases, # so when updating it you should ensure that all dependent packages are # also updated by incrementing their revisions. # # Specific packages to pay attention to include: # - camlp5 # - lablgtk # # Applications that really shouldn't break on a compiler update are: # - coq # - coccinelle # - unison class Ocaml < Formula desc "General purpose programming language in the ML family" homepage "https://ocaml.org/" url "https://caml.inria.fr/pub/distrib/ocaml-4.12/ocaml-4.12.0.tar.xz" sha256 "39ee9db8dc1e3eb65473dd81a71fabab7cc253dbd7b85e9f9b5b28271319bec3" license "LGPL-2.1-only" => { with: "OCaml-LGPL-linking-exception" } head "https://github.com/ocaml/ocaml.git", branch: "trunk" livecheck do url "https://ocaml.org/releases/" regex(/href=.*?v?(\d+(?:\.\d+)+)\.html/i) end bottle do sha256 cellar: :any, arm64_big_sur: "23d4a0ea99bad00b29387d05eef233fb1ce44a71e9031644f984850820f7b1fc" sha256 cellar: :any, big_sur: "98ee5c246e559e6d494ce7e2927a8a4c11ff3c47c26d7a2da19053ba97aa6158" sha256 cellar: :any, catalina: "f1f72000415627bc8ea540dffc7fd29c2d7ebc41c70e76b03a994c7e6e746284" sha256 cellar: :any, mojave: "9badb226c3d92ae196c9a2922c73075eaa45ee90f3c9b06180e29706e95f2f0b" sha256 cellar: :any_skip_relocation, x86_64_linux: "779e6f230c29dd6ef71ec70e83fea42168c097c720c0a4d4b1ae34ab6e58be74" end pour_bottle? do # The ocaml compilers embed prefix information in weird ways that the default # brew detection doesn't find, and so needs to be explicitly blacklisted. reason "The bottle needs to be installed into #{Homebrew::DEFAULT_PREFIX}." satisfy { HOMEBREW_PREFIX.to_s == Homebrew::DEFAULT_PREFIX } end def install ENV.deparallelize # Builds are not parallel-safe, esp. with many cores # the ./configure in this package is NOT a GNU autoconf script! args = %W[ --prefix=#{HOMEBREW_PREFIX} --enable-debug-runtime --mandir=#{man} ] system "./configure", *args system "make", "world.opt" system "make", "prefix=#{prefix}", "install" end test do output = shell_output("echo 'let x = 1 ;;' | #{bin}/ocaml 2>&1") assert_match "val x : int = 1", output assert_match HOMEBREW_PREFIX.to_s, shell_output("#{bin}/ocamlc -where") end end
Linuxbrew/homebrew-core
Formula/ocaml.rb
Ruby
bsd-2-clause
2,431
class Xonsh < Formula include Language::Python::Virtualenv desc "Python-ish, BASHwards-compatible shell language and command prompt" homepage "https://xon.sh/" url "https://github.com/xonsh/xonsh/archive/0.8.12.tar.gz" sha256 "7c51ce752f86e9eaae786a4886a6328ba66e16d91d2b7ba696baa6560a4de4ec" head "https://github.com/xonsh/xonsh.git" bottle do cellar :any_skip_relocation sha256 "0946b4172b6c6f927f17d9bd12ecb2fdf18f8f086abe0e7841c9dcb3b4c634dc" => :mojave sha256 "19efaf5ee095bdbfd58e8b32b3629e3f5bd58f3dc3d310e382520554873bfaf6" => :high_sierra sha256 "188f0659e92c741173d0d9fd14ecfd050abdbc7d82a350cb5e38faf931a65d35" => :sierra end depends_on "python" # Resources based on `pip3 install xonsh[ptk,pygments,proctitle]` # See https://xon.sh/osx.html#dependencies resource "prompt_toolkit" do url "https://files.pythonhosted.org/packages/d9/a5/4b2dd1a05403e34c3ba0d9c00f237c01967c0a4f59a427c9b241129cdfe4/prompt_toolkit-2.0.7.tar.gz" sha256 "fd17048d8335c1e6d5ee403c3569953ba3eb8555d710bfc548faf0712666ea39" end resource "Pygments" do url "https://files.pythonhosted.org/packages/64/69/413708eaf3a64a6abb8972644e0f20891a55e621c6759e2c3f3891e05d63/Pygments-2.3.1.tar.gz" sha256 "5ffada19f6203563680669ee7f53b64dabbeb100eb51b61996085e99c03b284a" end resource "setproctitle" do url "https://files.pythonhosted.org/packages/5a/0d/dc0d2234aacba6cf1a729964383e3452c52096dc695581248b548786f2b3/setproctitle-1.1.10.tar.gz" sha256 "6283b7a58477dd8478fbb9e76defb37968ee4ba47b05ec1c053cb39638bd7398" end resource "six" do url "https://files.pythonhosted.org/packages/dd/bf/4138e7bfb757de47d1f4b6994648ec67a51efe58fa907c1e11e350cddfca/six-1.12.0.tar.gz" sha256 "d16a0141ec1a18405cd4ce8b4613101da75da0e9a7aec5bdd4fa804d0e0eba73" end resource "wcwidth" do url "https://files.pythonhosted.org/packages/55/11/e4a2bb08bb450fdbd42cc709dd40de4ed2c472cf0ccb9e64af22279c5495/wcwidth-0.1.7.tar.gz" sha256 "3df37372226d6e63e1b1e1eda15c594bca98a22d33a23832a90998faa96bc65e" end def install virtualenv_install_with_resources end test do assert_match "4", shell_output("#{bin}/xonsh -c 2+2") end end
bcg62/homebrew-core
Formula/xonsh.rb
Ruby
bsd-2-clause
2,201
<?php namespace Bacharu\Models; use \Prajna\Objects\VIFMetrics as PrajnaVIFMetrics; class VIFMetrics extends PrajnaVIFMetrics { public function __construct(){} }
cameronjacobson/Bacharu
src/Bacharu/Models/VIFMetrics.php
PHP
bsd-2-clause
166
# 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. """ sim_det_noise.py implements the noise simulation operator, OpSimNoise. """ import numpy as np from ..op import Operator from ..ctoast import sim_noise_sim_noise_timestream as sim_noise_timestream from .. import timing as timing class OpSimNoise(Operator): """ Operator which generates noise timestreams. This passes through each observation and every process generates data for its assigned samples. The dictionary for each observation should include a unique 'ID' used in the random number generation. The observation dictionary can optionally include a 'global_offset' member that might be useful if you are splitting observations and want to enforce reproducibility of a given sample, even when using different-sized observations. Args: out (str): accumulate data to the cache with name <out>_<detector>. If the named cache objects do not exist, then they are created. realization (int): if simulating multiple realizations, the realization index. component (int): the component index to use for this noise simulation. noise (str): PSD key in the observation dictionary. """ def __init__(self, out='noise', realization=0, component=0, noise='noise', rate=None, altFFT=False): # We call the parent class constructor, which currently does nothing super().__init__() self._out = out self._oversample = 2 self._realization = realization self._component = component self._noisekey = noise self._rate = rate self._altfft = altFFT def exec(self, data): """ Generate noise timestreams. This iterates over all observations and detectors and generates the noise timestreams based on the noise object for the current observation. Args: data (toast.Data): The distributed data. Raises: KeyError: If an observation in data does not have noise object defined under given key. RuntimeError: If observations are not split into chunks. """ autotimer = timing.auto_timer(type(self).__name__) for obs in data.obs: obsindx = 0 if 'id' in obs: obsindx = obs['id'] else: print("Warning: observation ID is not set, using zero!") telescope = 0 if 'telescope' in obs: telescope = obs['telescope_id'] global_offset = 0 if 'global_offset' in obs: global_offset = obs['global_offset'] tod = obs['tod'] if self._noisekey in obs: nse = obs[self._noisekey] else: raise KeyError('Observation does not contain noise under ' '"{}"'.format(self._noisekey)) if tod.local_chunks is None: raise RuntimeError('noise simulation for uniform distributed ' 'samples not implemented') # eventually we'll redistribute, to allow long correlations... if self._rate is None: times = tod.local_times() else: times = None # Iterate over each chunk. chunk_first = tod.local_samples[0] for curchunk in range(tod.local_chunks[1]): chunk_first += self.simulate_chunk( tod=tod, nse=nse, curchunk=curchunk, chunk_first=chunk_first, obsindx=obsindx, times=times, telescope=telescope, global_offset=global_offset) return def simulate_chunk(self, *, tod, nse, curchunk, chunk_first, obsindx, times, telescope, global_offset): """ Simulate one chunk of noise for all detectors. Args: tod (toast.tod.TOD): TOD object for the observation. nse (toast.tod.Noise): Noise object for the observation. curchunk (int): The local index of the chunk to simulate. chunk_first (int): First global sample index of the chunk. obsindx (int): Observation index for random number stream. times (int): Timestamps for effective sample rate. telescope (int): Telescope index for random number stream. global_offset (int): Global offset for random number stream. Returns: chunk_samp (int): Number of simulated samples """ autotimer = timing.auto_timer(type(self).__name__) chunk_samp = tod.total_chunks[tod.local_chunks[0] + curchunk] local_offset = chunk_first - tod.local_samples[0] if self._rate is None: # compute effective sample rate rate = 1 / np.median(np.diff( times[local_offset : local_offset+chunk_samp])) else: rate = self._rate for key in nse.keys: # Check if noise matching this PSD key is needed weight = 0. for det in tod.local_dets: weight += np.abs(nse.weight(det, key)) if weight == 0: continue # Simulate the noise matching this key #nsedata = sim_noise_timestream( # self._realization, telescope, self._component, obsindx, # nse.index(key), rate, chunk_first+global_offset, chunk_samp, # self._oversample, nse.freq(key), nse.psd(key), # self._altfft)[0] nsedata = sim_noise_timestream( self._realization, telescope, self._component, obsindx, nse.index(key), rate, chunk_first+global_offset, chunk_samp, self._oversample, nse.freq(key), nse.psd(key)) # Add the noise to all detectors that have nonzero weights for det in tod.local_dets: weight = nse.weight(det, key) if weight == 0: continue cachename = '{}_{}'.format(self._out, det) if tod.cache.exists(cachename): ref = tod.cache.reference(cachename) else: ref = tod.cache.create(cachename, np.float64, (tod.local_samples[1], )) ref[local_offset : local_offset+chunk_samp] += weight*nsedata del ref return chunk_samp
tskisner/pytoast
src/python/tod/sim_det_noise.py
Python
bsd-2-clause
6,740
(function(){ var slides = [ {title: 'Работы для отдела Клиентского сервиса и сапорта ФС\nТикетная админка, админка массовых сбоев', works: [ {img: 'i/works/ticket-admin.png', description: '<div class="presentation_mb10"><strong>Тикетная админка</strong></div>' + '<div class="presentation_mb10">Через эту админку сотрудники сапорта работают с обращениями пользователей соц. сети. Мною была реализована вся верстка раздела и код на js.</div>' + '<div class="presentation_mb10">Особенности:</div>' + '<ul class="presentation-list">' + '<li>Интерфейс занимают всю высоту экрана монитора - резиновый по вертикали (На странице могут быть три внутреннии области со скролом );</li>' + '<li>Автоподгрузка новых тикетов;</li>' + '<li>Большое число кастомных элементов управления.</li>' + '</ul>' }, {img: 'i/works/ticket-admin2.png', description: '<div class="presentation_mb10"><strong>Админка массовых сбоев</strong></div>' + '<div class="presentation_mb10">Инструмент взаимодействия сотрудников сапорта и тестеровщиков. При наличие однотипных обращений пользователей, их тикеты групируются в массовый сбой. Который попадает к тестировщикам в виде таска в редмайн для исследования.</div>' }, {img: 'i/works/ticket-admin3.png', description: 'Диалог просмотра массового сбоя.'}, {img: 'i/works/ticket-admin4.png', description: 'Пример реализации кастомного выпадающего списка.'}, ] },{title: 'Отдел модерации \nПопапы жалоб, страница заблокированного пользователя', works: [ {img: 'i/works/complaint_popup.png', description: '<div class="presentation_mb10"><strong>Попап подачи жалоб на пользователя</strong></div>' + '<div class="">Мною была реализована вся frontend часть - верстка и код на js.</div>' },{img: 'i/works/abusePopups.jpg', description: '<div class="">Реализовано несколько кейсов с последовательной навигацией.</div>' },{img: 'i/works/complaint_popup1.png', description: '<div class="">Содержимое попапа - вопросник с готовыми ответами и возможностью отправить расширенное описание.</div>' }, {img: 'i/works/abuse_form.jpg', description: 'Различные варианты попапов жалоб на нарушения со стороны пользователей. Попапы показываются на странице пользователя.'}, {img: 'i/works/abuse_page.jpg', description: 'Страница заблокированного пользователя. Реализована в нескольких вариантах для удаленного пользователя и расширенной для сотрудников Фотостраны. Мною была реализована верстка (html/php).'}, ] },{title: 'Раздел помощи (FAQ)', works: [ {img: 'i/works/faq1.png', description: '<div class="presentation_mb10">В разделе помощи я занимался поддержкой старого кода, правил баги. Поэтому там моя верстка присутствует только фрагментами. К примеру этот опросник сверстан мной. Весь hover эффект при выборе количества звезд реализован только на css.</div>' + '<div class="presentation_mb10">Раздел располагается по ссылке <a href="http://fotostrana.ru/support/feedback/ask/" target="_blank">http://fotostrana.ru/support/feedback/ask/</a></div>'}, ] },{title: 'Раздел "Мои финансы"', works: [ {img: 'i/works/finroom.png', description: '<div class="presentation_mb10"><strong>Раздел "Мои финансы" страницы пользователя</strong></div>' + '<div class="presentation_mb10">Мною была реализована верстка и необходимый код на js.</div>' + '<div class="presentation_mb10">Раздел располагается по ссылке <a href="http://fotostrana.ru/finance/index/" target="_blank">http://fotostrana.ru/finance/index/</a></div>' }, {img: 'i/works/finroom2.png', description: '<div class="presentation_mb10">Для страницы было реализовано много различных блоков показываемые разным сегментам пользовательской аудитории.</div>'}, {img: 'i/works/finroom3.png', description: 'Так же мною были сверстаны различные попапы сопутсвующих премиальных услуг, доступные из этого раздела.'}, {img: 'i/works/autopay1.png', description: 'Попап услуги &laquo;Автоплатеж&raquo;'}, {img: 'i/works/fotocheck.png', description: 'СМС информирование'}, {img: 'i/works/finroom4.png', description: ''}, ] },{title: 'Финансовый попап \nПопап пополнения счета пользователя', works: [ {img: 'i/works/finpopup1.png', description: '<div class="presentation_mb10">Попап с большим количеством переходов и кастомными элементами управления.</div>' + '<div class="presentation_mb10">Мною была сделана необходимая верстка и js код.</div>' }, {img: 'i/works/finpopup2.png', description: '<div class="presentation_mb10">Из сложных деталей интерфейса:</div>' + '<ul class="presentation-list">' + '<li>"резиновые" кнопки ввода необходимой суммы Фотомани, с возможностью указать произвольную сумму;</li>' + '<li>контроль за вводом и валидация пользовательских данных.</li>' + '</ul>' }, {img: 'i/works/finpopup3.png', description: ''}, ] },{title: 'Сервис "Я модератор"', works: [ {img: 'i/works/imoderator1.jpg', description: '<div class="presentation_mb10"><strong>Сервис "Я модератор"</strong> - пользователям за вознаграждение передается часть модерируемого контента.</div>' + '<div class="">Мною была выполнена вся верстка и весь js код. Из сложных деталей интерфеса - флип часы, реализованные с использованием css3 animation.</div>' }, {img: 'i/works/imoderator2.jpg', description: '<div class="presentation_mb10">В приложении реализовано несколько режимов модерации, в том числе и полно экранный режим (резиновый, скрывающий стандартный лэйаут страниц соц. сети).</div>' + '<div class="">Так же в приложении реализованы инструменты для мотивации "качественной" оценки фотографий пользователями. Используются тестовые проверочные изображения, принудительная отправка в режим обучения и поиск дубликатов изображений в Google/Yandex.</div>' }, ] },{title: 'Сервис "Голосование"', works: [ {img: 'i/works/contest.jpg', description: '<div class="presentation_mb10"><strong>Сервис "Голосование"</strong> - один из основных по доходности сервисов Фотостраны с большой аудиторией</div>' + '<div class="presentation_mb10">В этом сервисе, я занимался поддержкой старого кода и версткой скидочных акций и сезонных мероприятий по активизации пользовательской активности приуроченные к праздникам, мероприятиям (Новый год, Олимпийские игры, 8-е марта, день всех влюбленных, 23 февраля, 12 апреля и др.)</div>' + '<div class="presentation_mb10">Так же мною был переделан механизм рендеринга фотостены.</div>' + '<div class="">В сервис можно перейти по ссылке <a href="http://www.fotostrana.ru/contest/" target="_blank">www.fotostrana.ru/contest/</a></div>' }, {img: 'i/works/contest1.jpg', description: ''}, ] },{title: 'Игровой сервис "Битва кланов"', works: [ {img: 'i/works/clan1.jpg', description: '<div class="presentation_mb10"><strong>Игровой сервис "Битва Кланов"</strong> - игровой под сервис голосования. Игра в форме квеста.</div>' + '<div>В этом сервисе я делал верстку и js код. Много кейсов, много попапов, много backbon-а. Используется sass, require.js, backbone.</div>' }, {img: 'i/works/clan2.jpg', description: '<div class="">В сервис можно перейти по ссылке <a href="http://www.fotostrana.ru/contest/clan2/" target="_blank">www.fotostrana.ru/contest/clan2/</a></div>'}, {img: 'i/works/clan4.jpg', description: 'В сервисе много сложных интерфейсных решений, как на пример поле ввода сообщения в чат. Реализовано ограничение на длину вводимого сообщения и авторесайз высоты textarea.'}, {img: 'i/works/clan3.jpg', description: ''}, ] },{title: 'Сервис "Элитное голосование"', works: [ {img: 'i/works/elite1.jpg', description: '<div class="presentation_mb10"><strong>Игровой сервис "Элитное голосование"</strong> - игровой под сервис голосования, доступный несколько дней в месяце для активных участников основного голосования.</div>' + '<div>В этом сервисе я делал верстку и js код. Внешнее оформление переделывалось мною к каждому запуску сервиса.</div>'}, {img: 'i/works/elite2.jpg', description: ''}, ] },{title: 'Сервис "Люди"\nДейтинговый сервис Фотостраны', works: [ {img: 'i/works/people1.jpg', description: '<div class="presentation_mb10"><strong>Дейтинговый сервис "Люди"</strong> - на протяжении полу года поддерживал фронтенд сервиса - исправлял баги, верстал рекламные банеры и попапы.</div>' + '<div class="">В сервис можно перейти по ссылке <a href="http://fotostrana.ru/people/" target="_blank">fotostrana.ru/people/</a></div>'}, {img: 'i/works/people2.jpg', description: ''}, ] },{title: 'Сообщества и пиновый интерфейс', works: [ {img: 'i/works/community1.jpg', description: '<div class="presentation_mb10">Некоторое время работал над версткой сообществ и пиновым интерфейсом. Концепция пинов была позаимствована у другого сервиса Pinterest. Занимался проектом начиная с первого прототипа и до предрелизной подготовкой.</div>' + '<div class="">В сервис можно перейти по ссылке <a href="http://fotostrana.ru/public/" target="_blank">fotostrana.ru/public/</a></div>'}, ] },{title: 'Сайт http://www.blik-cleaning.ru/', works: [ {img: 'i/works/cleaning.jpg', description: '<div class="presentation_mb10"><strong>Разработка сайта клининговой компании</strong></div>' + '<div>Сайт сделан на CMS WordPress с оригинальной темой. </div>'}, {img: 'i/works/cleaning1.jpg', description: ''}, ] },{title: 'Сайт http://www.promalp.name/', works: [ {img: 'i/works/promalp1.jpg', description: '<div class="presentation_mb10"><strong>Сайт компании занимающейся промышленным альпинизмом.</strong></div>' + '<div>Сайт сделан на node.js (express). Полностью реализован мною.</div>'}, {img: 'i/works/promalp2.jpg', description: 'Страница с портфолио.'}, {img: 'i/works/promalp3.jpg', description: 'Форма заявки.'}, ] },{title: 'Расширение для браузера chrome Netmarks', works: [ {img: 'i/works/netmarks.jpg', description: '<div class="presentation_mb10"><strong>Chrome extension "NetMarks"</strong></div>' + '<div class="presentation_mb10">Расширение для удобной работы с браузерными закладками в виде выпадающего меню.</div>' + '<div class="">Доступно по ссылке в <a href="https://chrome.google.com/webstore/detail/netmarks/boepmphdpbdnficfifejnkejlljcefjb" target="_blank">Chrome store</a></div>' }, ] },{title: 'Приложение для браузера chrome Deposit.calc', works: [ {img: 'i/works/depcalc1.jpg', description: '<div class="presentation_mb10"><strong>Deposit.calc</strong></div>' + '<div class="presentation_mb10">Приложение позволяющее расчитать доход по вкладу с пополнениями. Используется собственный оригинальный алгоритм расчета.</div>' + '<div class="">Доступно по ссылке в <a href="https://chrome.google.com/webstore/detail/депозитный-калькулятор/cibblnjekngmoeiehohbkmcbfijpcjdj" target="_blank">Chrome store</a></div>'}, {img: 'i/works/depcalc2.jpg', description: 'Для вывода графиков был использован highcharts.'}, ] }, ]; var View = m3toolkit.View, CollectionView = m3toolkit.CollectionView, BlockView = m3toolkit.BlockView, _base = { // @param {Int} Index // @return {Model} model from collection by index getAnother: function(index){ return this.slideCollection.at(index); } }; var SlideModel = Backbone.Model.extend({ defaults: { title: '', works: [], index: undefined, next: undefined, prev: undefined } }); var SlidesCollection = Backbone.Collection.extend({ model: SlideModel, initialize: function(list){ var i = 0, len = list.length indexedList = list.map(function(item){ item.index = i; if(i > 0){ item.prev = i - 1; } if(i < len - 1){ item.next = i + 1; } if(Array.isArray(item.works)){ item.frontImage = item.works[0].img; } i++; return item; }); Backbone.Collection.prototype.initialize.call(this, indexedList); } }); var WorkItemModel = Backbone.Model.extend({ defaults: { img: '', description: '' } }); var WorkItemsCollections = Backbone.Collection.extend({ model: WorkItemModel }); var WorkItemPreview = View.extend({ className: 'presentation_work-item clearfix', template: _.template( '<img src="<%=img%>" class="Stretch m3-vertical "/>' + '<% if(obj.description){ %>' + '<div class="presentation_work-item_description"><%=obj.description%></div>' + '<% }%>' ) }); var SlideView = View.extend({ className: 'presentation_slide-wrap', template: _.template( '<div style="background-image: url(<%=obj.frontImage%>)" class="presentation_front-image"></div>' + '<div class="presentation_front-image_hover"></div>' ), events: { click: function(e){ _base.openFullScreenPresentation(this.model); } }, }); var FullscreenSlideView = BlockView.extend({ className: 'presentation_fullscreen-slide', template: '<div class="presentation_fullscreen-slide_back"></div>' + '<div class="presentation_fullscreen-slide_close" data-bind="close"></div>' + '<div class="presentation_fullscreen-slide_wrap">' + '<div class="presentation_fullscreen-slide_next" data-co="next">' + '<div class="presentation_fullscreen-slide_nav-btn presentation_fullscreen-slide_nav-btn_next "></div>' + '</div>' + '<div class="presentation_fullscreen-slide_prev" data-co="prev">' + '<div class="presentation_fullscreen-slide_nav-btn"></div>'+ '</div>' + '<pre class="presentation_fullscreen-slide_title" data-co="title"></pre>' + '<div class="" data-co="works" style=""></div>' + '</div>', events: { 'click [data-bind=close]': function(){ _base.hideFullScreenPresentation(); }, 'click [data-co=next]': function(){ var nextIndex = this.model.get('next'); nextIndex != undefined && this._navigateTo(nextIndex); }, 'click [data-co=prev]': function(){ var prevIndex = this.model.get('prev'); prevIndex != undefined && this._navigateTo(prevIndex); }, }, _navigateTo: function(index){ var prevModel =_base.getAnother(index); if(prevModel){ var data = prevModel.toJSON(); this.model.set(prevModel.toJSON()); } }, initialize: function(){ BlockView.prototype.initialize.call(this); this.controls.prev[this.model.get('prev') != undefined ? 'show': 'hide'](); this.controls.next[this.model.get('next') ? 'show': 'hide'](); var workItemsCollection = new WorkItemsCollections(this.model.get('works')); this.children.workCollection = new CollectionView({ collection: workItemsCollection, el: this.controls.works }, WorkItemPreview); this.listenTo(this.model, 'change:works', function(model){ console.log('Works Changed'); workItemsCollection.reset(model.get('works')); }); }, defineBindings: function(){ this._addComputed('works', 'works', function(control, model){ console.log('Refresh works'); var worksList = model.get('works'); console.dir(worksList); }); this._addTransform('title', function(control, model, value){ console.log('Set new Title: `%s`', value); control.text(value); }); this._addTransform('next', function(control, model, value){ control[value ? 'show': 'hide'](); }); this._addTransform('prev', function(control, model, value){ control[value != undefined ? 'show': 'hide'](); }); } }); var PresentationApp = View.extend({ className: 'presentation-wrap', template: '<div class="presentation-wrap_header">' + '<div class="presentation-wrap_header-container">' + '<div class="presentation-wrap_header-title clearfix">' + /*'<div class="presentation-wrap_header-contacts">' + '<div class="">Контакты для связи:</div>' + '<div class="">8 (960) 243 14 03</div>' + '<div class="">nsmalcev@bk.ru</div>' + '</div>' +*/ '<h2 class="presentation_header1">Портфолио презентация</h2>' + '<div class="presentation_liter1">Фронтенд разработчика Николая Мальцева</div>' + '<div class="presentation_liter1">8 (960) 243 14 03, nsmalcev@bk.ru</div>' + '<div class="presentation_liter1"><a href="http://matraska231.herokuapp.com/?portfolio=1#cv" target="_blank">Резюме</a></div>' + '</div>' + '</div>' + '</div>' + '<div class="presentation-wrap_body" data-bind="body">' + '<div class="presentation-wrap_slide clearfix" data-bind="slides">' + '</div>' + '</div>' + '<div data-bind="fullscreen" class="presentation_fullscreen-slide" style="display: none;"></div>', initialize: function(){ View.prototype.initialize.call(this); var $slides = this.$('[data-bind=slides]'), $body = this.$('[data-bind=body]'), slideCollection = new SlidesCollection(slides); _base.app = this; _base.slideCollection = slideCollection; this.children['slides'] = new CollectionView({ collection: slideCollection, el: $slides }, SlideView); this.children['fullscreen'] = new FullscreenSlideView({ el: this.$('[data-bind=fullscreen]'), model: new SlideModel() }); _base.openFullScreenPresentation = function(model){ $body.addClass('presentation-fix-body'); this.children['fullscreen'].$el.show(); this.children['fullscreen'].model.set(model.toJSON()); // TODO store vertical position }.bind(this); _base.hideFullScreenPresentation = function(){ this.children['fullscreen'].$el.hide(); $body.removeClass('presentation-fix-body'); }.bind(this); } }); var app = new PresentationApp({ el: '#app' }); }());
matraska23/m3-backbone-toolkit
demo_presentation/js/presentation.js
JavaScript
bsd-2-clause
22,354
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2013 ASMlover. 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 ofconditions 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 materialsprovided 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. import zmq import time if __name__ == '__main__': ctx = zmq.Context() worker = ctx.socket(zmq.PULL) worker.connect('tcp://localhost:5555') sinker = ctx.socket(zmq.PUSH) sinker.connect('tcp://localhost:6666') print 'all workers are ready ...' while True: try: msg = worker.recv() print 'begin to work on task use `%s ms`' % msg time.sleep(int(msg) * 0.001) print '\tfinished this task' sinker.send('finished task which used `%s ms`' % msg) except KeyboardInterrupt: break sinker.close() worker.close()
ASMlover/study
zeroMQ/python/push-pull/worker.py
Python
bsd-2-clause
1,961
class WireguardGo < Formula desc "Userspace Go implementation of WireGuard" homepage "https://www.wireguard.com/" url "https://git.zx2c4.com/wireguard-go/snapshot/wireguard-go-0.0.20200320.tar.xz" sha256 "c8262da949043976d092859843d3c0cdffe225ec6f1398ba119858b6c1b3552f" license "MIT" head "https://git.zx2c4.com/wireguard-go", using: :git livecheck do url :head regex(/href=.*?wireguard-go[._-]v?(\d+(?:\.\d+)+)\.t/i) end bottle do cellar :any_skip_relocation sha256 "783b1eeb0aba2c336e91fe59ef9e8d5d449e51ef3a5ed313f96666c7d055fb02" => :catalina sha256 "baf1cc2e7f0795747bcaed6856ce3a4075083356cc557497adf06ceaf28e0514" => :mojave sha256 "23d0d338dddebcecc58aa5f1e651fbde03494b0d49071937c4cff0b4d19961c2" => :high_sierra sha256 "168b97cf56b028ecf953768dcd06bd894aa1fc2daedb63a5074bfb5b60df99e5" => :x86_64_linux end depends_on "go" => :build def install ENV["GOPATH"] = HOMEBREW_CACHE/"go_cache" system "make", "PREFIX=#{prefix}", "install" end test do # ERROR: (notrealutun) Failed to create TUN device: no such file or directory return if ENV["CI"] assert_match "be utun", pipe_output("WG_PROCESS_FOREGROUND=1 #{bin}/wireguard-go notrealutun") end end
maxim-belkin/homebrew-core
Formula/wireguard-go.rb
Ruby
bsd-2-clause
1,241
#ifndef SOBER_NETWORK_HTTP_EXTRA_SUCCESS_HANDLER_HPP_ #define SOBER_NETWORK_HTTP_EXTRA_SUCCESS_HANDLER_HPP_ // Copyright (c) 2014, Ruslan Baratov // All rights reserved. #include <functional> // std::function namespace sober { namespace network { namespace http { using ExtraSuccessHandler = std::function<void()>; } // namespace http } // namespace network } // namespace sober #endif // SOBER_NETWORK_HTTP_EXTRA_SUCCESS_HANDLER_HPP_
ruslo/sober
Source/sober/network/http/ExtraSuccessHandler.hpp
C++
bsd-2-clause
441
/* * Copyright (c) 2012 Tom Denley * This file incorporates work covered by the following copyright and * permission notice: * * Copyright (c) 2003-2008, Franz-Josef Elmer, 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 OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.netmelody.neoclassycle.renderer; import org.netmelody.neoclassycle.graph.StrongComponent; /** * Interface for rendering a {@link StrongComponent}. * * @author Franz-Josef Elmer */ public interface StrongComponentRenderer { /** Renderes the specified {@link StrongComponent}. */ public String render(StrongComponent component); }
netmelody/neoclassycle
src/main/java/org/netmelody/neoclassycle/renderer/StrongComponentRenderer.java
Java
bsd-2-clause
1,856
from unittest import TestCase import pkg_resources from mock import patch from click import UsageError from click.testing import CliRunner class TestCli(TestCase): @patch('molo.core.cookiecutter.cookiecutter') def test_scaffold(self, mock_cookiecutter): from molo.core.scripts import cli package = pkg_resources.get_distribution('molo.core') runner = CliRunner() runner.invoke(cli.scaffold, ['foo']) [call] = mock_cookiecutter.call_args_list args, kwargs = call self.assertTrue(kwargs['extra_context'].pop('secret_key')) self.assertEqual(kwargs, { 'no_input': True, 'extra_context': { 'app_name': 'foo', 'directory': 'foo', 'author': 'Praekelt Foundation', 'author_email': 'dev@praekelt.com', 'url': None, 'license': 'BSD', 'molo_version': package.version, 'require': (), 'include': (), } }) @patch('molo.core.cookiecutter.cookiecutter') def test_scaffold_with_custom_dir(self, mock_cookiecutter): from molo.core.scripts import cli package = pkg_resources.get_distribution('molo.core') runner = CliRunner() runner.invoke(cli.scaffold, ['foo', 'bar']) [call] = mock_cookiecutter.call_args_list args, kwargs = call self.assertTrue(kwargs['extra_context'].pop('secret_key')) self.assertEqual(kwargs, { 'no_input': True, 'extra_context': { 'app_name': 'foo', 'directory': 'bar', 'author': 'Praekelt Foundation', 'author_email': 'dev@praekelt.com', 'url': None, 'license': 'BSD', 'molo_version': package.version, 'require': (), 'include': (), } }) @patch('molo.core.cookiecutter.cookiecutter') def test_scaffold_with_requirements(self, mock_cookiecutter): from molo.core.scripts import cli package = pkg_resources.get_distribution('molo.core') runner = CliRunner() runner.invoke(cli.scaffold, ['foo', '--require', 'bar']) [call] = mock_cookiecutter.call_args_list args, kwargs = call self.assertTrue(kwargs['extra_context'].pop('secret_key')) self.assertEqual(kwargs, { 'no_input': True, 'extra_context': { 'app_name': 'foo', 'directory': 'foo', 'author': 'Praekelt Foundation', 'author_email': 'dev@praekelt.com', 'url': None, 'license': 'BSD', 'molo_version': package.version, 'require': ('bar',), 'include': (), } }) @patch('molo.core.cookiecutter.cookiecutter') def test_scaffold_with_includes(self, mock_cookiecutter): from molo.core.scripts import cli package = pkg_resources.get_distribution('molo.core') runner = CliRunner() runner.invoke(cli.scaffold, ['foo', '--include', 'bar', 'baz']) [call] = mock_cookiecutter.call_args_list args, kwargs = call self.assertTrue(kwargs['extra_context'].pop('secret_key')) self.assertEqual(kwargs, { 'no_input': True, 'extra_context': { 'app_name': 'foo', 'directory': 'foo', 'author': 'Praekelt Foundation', 'author_email': 'dev@praekelt.com', 'url': None, 'license': 'BSD', 'molo_version': package.version, 'require': (), 'include': (('bar', 'baz'),), } }) @patch('molo.core.scripts.cli.get_package') @patch('molo.core.scripts.cli.get_template_dirs') @patch('shutil.copytree') def test_unpack(self, mock_copytree, mock_get_template_dirs, mock_get_package): package = pkg_resources.get_distribution('molo.core') mock_get_package.return_value = package mock_get_template_dirs.return_value = ['foo'] mock_copytree.return_value = True from molo.core.scripts import cli runner = CliRunner() runner.invoke(cli.unpack_templates, ['app1', 'app2']) mock_copytree.assert_called_with( pkg_resources.resource_filename('molo.core', 'templates/foo'), pkg_resources.resource_filename('molo.core', 'templates/foo')) def test_get_package(self): from molo.core.scripts.cli import get_package self.assertRaisesRegexp( UsageError, 'molo.foo is not installed.', get_package, 'molo.foo')
praekelt/molo
molo/core/scripts/tests/test_cli.py
Python
bsd-2-clause
4,820
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ItzWarty.RAF { public class RAFFileListEntry { private byte[] directoryFileContent = null; private UInt32 offsetEntry = 0; private RAF raf = null; public RAFFileListEntry(RAF raf, byte[] directoryFileContent, UInt32 offsetEntry) { this.raf = raf; this.directoryFileContent = directoryFileContent; this.offsetEntry = offsetEntry; } /// <summary> /// Hash of the string name /// </summary> public UInt32 StringNameHash { get { return BitConverter.ToUInt32(directoryFileContent, (int)offsetEntry); } } /// <summary> /// Offset to the start of the archived file in the data file /// </summary> public UInt32 FileOffset { get { return BitConverter.ToUInt32(directoryFileContent, (int)offsetEntry+4); } } /// <summary> /// Size of this archived file /// </summary> public UInt32 FileSize { get { return BitConverter.ToUInt32(directoryFileContent, (int)offsetEntry+8); } } /// <summary> /// Index of the name of the archvied file in the string table /// </summary> public UInt32 FileNameStringTableIndex { get { return BitConverter.ToUInt32(directoryFileContent, (int)offsetEntry+12); } } public String GetFileName { get { return this.raf.GetDirectoryFile().GetStringTable()[this.FileNameStringTableIndex]; } } } }
dargondevteam/raflib
RAFFileListEntry.cs
C#
bsd-2-clause
1,881
// Copyright (c) 2020 WNProject Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Intentionally left empty so that we can build a lib target for this library #include "hashing/inc/hash.h"
WNProject/WNFramework
Libraries/hashing/src/dummy.cpp
C++
bsd-2-clause
277
// // Copyright (c) 2015 CNRS // // This file is part of Pinocchio // Pinocchio is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // Pinocchio 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 // General Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // Pinocchio If not, see // <http://www.gnu.org/licenses/>. #ifndef __se3_se3_hpp__ #define __se3_se3_hpp__ #include <Eigen/Geometry> #include "pinocchio/spatial/fwd.hpp" #include "pinocchio/spatial/skew.hpp" namespace se3 { /* Type returned by the "se3Action" and "se3ActionInverse" functions. */ namespace internal { template<typename D> struct ActionReturn { typedef D Type; }; } /** The rigid transform aMb can be seen in two ways: * * - given a point p expressed in frame B by its coordinate vector Bp, aMb * computes its coordinates in frame A by Ap = aMb Bp. * - aMb displaces a solid S centered at frame A into the solid centered in * B. In particular, the origin of A is displaced at the origin of B: $^aM_b * ^aA = ^aB$. * The rigid displacement is stored as a rotation matrix and translation vector by: * aMb (x) = aRb*x + aAB * where aAB is the vector from origin A to origin B expressed in coordinates A. */ template< class Derived> class SE3Base { protected: typedef Derived Derived_t; SPATIAL_TYPEDEF_TEMPLATE(Derived_t); public: Derived_t & derived() { return *static_cast<Derived_t*>(this); } const Derived_t& derived() const { return *static_cast<const Derived_t*>(this); } const Angular_t & rotation() const { return derived().rotation_impl(); } const Linear_t & translation() const { return derived().translation_impl(); } Angular_t & rotation() { return derived().rotation_impl(); } Linear_t & translation() { return derived().translation_impl(); } void rotation(const Angular_t & R) { derived().rotation_impl(R); } void translation(const Linear_t & R) { derived().translation_impl(R); } Matrix4 toHomogeneousMatrix() const { return derived().toHomogeneousMatrix_impl(); } operator Matrix4() const { return toHomogeneousMatrix(); } Matrix6 toActionMatrix() const { return derived().toActionMatrix_impl(); } operator Matrix6() const { return toActionMatrix(); } void disp(std::ostream & os) const { static_cast<const Derived_t*>(this)->disp_impl(os); } Derived_t operator*(const Derived_t & m2) const { return derived().__mult__(m2); } /// ay = aXb.act(by) template<typename D> typename internal::ActionReturn<D>::Type act (const D & d) const { return derived().act_impl(d); } /// by = aXb.actInv(ay) template<typename D> typename internal::ActionReturn<D>::Type actInv(const D & d) const { return derived().actInv_impl(d); } Derived_t act (const Derived_t& m2) const { return derived().act_impl(m2); } Derived_t actInv(const Derived_t& m2) const { return derived().actInv_impl(m2); } bool operator == (const Derived_t & other) const { return derived().__equal__(other); } bool isApprox (const Derived_t & other) const { return derived().isApprox_impl(other); } friend std::ostream & operator << (std::ostream & os,const SE3Base<Derived> & X) { X.disp(os); return os; } }; // class SE3Base template<typename T, int U> struct traits< SE3Tpl<T, U> > { typedef T Scalar_t; typedef Eigen::Matrix<T,3,1,U> Vector3; typedef Eigen::Matrix<T,4,1,U> Vector4; typedef Eigen::Matrix<T,6,1,U> Vector6; typedef Eigen::Matrix<T,3,3,U> Matrix3; typedef Eigen::Matrix<T,4,4,U> Matrix4; typedef Eigen::Matrix<T,6,6,U> Matrix6; typedef Matrix3 Angular_t; typedef Vector3 Linear_t; typedef Matrix6 ActionMatrix_t; typedef Eigen::Quaternion<T,U> Quaternion_t; typedef SE3Tpl<T,U> SE3; typedef ForceTpl<T,U> Force; typedef MotionTpl<T,U> Motion; typedef Symmetric3Tpl<T,U> Symmetric3; enum { LINEAR = 0, ANGULAR = 3 }; }; // traits SE3Tpl template<typename _Scalar, int _Options> class SE3Tpl : public SE3Base< SE3Tpl< _Scalar, _Options > > { public: friend class SE3Base< SE3Tpl< _Scalar, _Options > >; SPATIAL_TYPEDEF_TEMPLATE(SE3Tpl); SE3Tpl(): rot(), trans() {}; template<typename M3,typename v3> SE3Tpl(const Eigen::MatrixBase<M3> & R, const Eigen::MatrixBase<v3> & p) : rot(R), trans(p) { } template<typename M4> SE3Tpl(const Eigen::MatrixBase<M4> & m) : rot(m.template block<3,3>(LINEAR,LINEAR)), trans(m.template block<3,1>(LINEAR,ANGULAR)) { } SE3Tpl(int) : rot(Matrix3::Identity()), trans(Vector3::Zero()) {} template<typename S2, int O2> SE3Tpl( const SE3Tpl<S2,O2> & clone ) : rot(clone.rotation()),trans(clone.translation()) {} template<typename S2, int O2> SE3Tpl & operator= (const SE3Tpl<S2,O2> & other) { rot = other.rotation (); trans = other.translation (); return *this; } static SE3Tpl Identity() { return SE3Tpl(1); } SE3Tpl & setIdentity () { rot.setIdentity (); trans.setZero (); return *this;} /// aXb = bXa.inverse() SE3Tpl inverse() const { return SE3Tpl(rot.transpose(), -rot.transpose()*trans); } static SE3Tpl Random() { Quaternion_t q(Vector4::Random()); q.normalize(); return SE3Tpl(q.matrix(),Vector3::Random()); } SE3Tpl & setRandom () { Quaternion_t q(Vector4::Random()); q.normalize (); rot = q.matrix (); trans.setRandom (); return *this; } public: Matrix4 toHomogeneousMatrix_impl() const { Matrix4 M; M.template block<3,3>(LINEAR,LINEAR) = rot; M.template block<3,1>(LINEAR,ANGULAR) = trans; M.template block<1,3>(ANGULAR,LINEAR).setZero(); M(3,3) = 1; return M; } /// Vb.toVector() = bXa.toMatrix() * Va.toVector() Matrix6 toActionMatrix_impl() const { Matrix6 M; M.template block<3,3>(ANGULAR,ANGULAR) = M.template block<3,3>(LINEAR,LINEAR) = rot; M.template block<3,3>(ANGULAR,LINEAR).setZero(); M.template block<3,3>(LINEAR,ANGULAR) = skew(trans) * M.template block<3,3>(ANGULAR,ANGULAR); return M; } void disp_impl(std::ostream & os) const { os << " R =\n" << rot << std::endl << " p = " << trans.transpose() << std::endl; } /// --- GROUP ACTIONS ON M6, F6 and I6 --- /// ay = aXb.act(by) template<typename D> typename internal::ActionReturn<D>::Type act_impl (const D & d) const { return d.se3Action(*this); } /// by = aXb.actInv(ay) template<typename D> typename internal::ActionReturn<D>::Type actInv_impl(const D & d) const { return d.se3ActionInverse(*this); } Vector3 act_impl (const Vector3& p) const { return (rot*p+trans).eval(); } Vector3 actInv_impl(const Vector3& p) const { return (rot.transpose()*(p-trans)).eval(); } SE3Tpl act_impl (const SE3Tpl& m2) const { return SE3Tpl( rot*m2.rot,trans+rot*m2.trans);} SE3Tpl actInv_impl (const SE3Tpl& m2) const { return SE3Tpl( rot.transpose()*m2.rot, rot.transpose()*(m2.trans-trans));} SE3Tpl __mult__(const SE3Tpl & m2) const { return this->act(m2);} bool __equal__( const SE3Tpl & m2 ) const { return (rotation_impl() == m2.rotation() && translation_impl() == m2.translation()); } bool isApprox_impl( const SE3Tpl & m2 ) const { Matrix4 diff( toHomogeneousMatrix_impl() - m2.toHomogeneousMatrix_impl()); return (diff.isMuchSmallerThan(toHomogeneousMatrix_impl(), 1e-14) && diff.isMuchSmallerThan(m2.toHomogeneousMatrix_impl(), 1e-14) ); } public: const Angular_t & rotation_impl() const { return rot; } Angular_t & rotation_impl() { return rot; } void rotation_impl(const Angular_t & R) { rot = R; } const Linear_t & translation_impl() const { return trans;} Linear_t & translation_impl() { return trans;} void translation_impl(const Linear_t & p) { trans=p; } protected: Angular_t rot; Linear_t trans; }; // class SE3Tpl typedef SE3Tpl<double,0> SE3; } // namespace se3 #endif // ifndef __se3_se3_hpp__
aelkhour/pinocchio
src/spatial/se3.hpp
C++
bsd-2-clause
8,904
import numpy as np from scipy.sparse import csr_matrix class AliasArray(np.ndarray): """An ndarray with a mapping of values to user-friendly names -- see example This ndarray subclass enables comparing sub_id and hop_id arrays directly with their friendly string identifiers. The mapping parameter translates sublattice or hopping names into their number IDs. Only the `==` and `!=` operators are overloaded to handle the aliases. Examples -------- >>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1}) >>> list(a == 0) [True, False, True] >>> list(a == "A") [True, False, True] >>> list(a != "A") [False, True, False] >>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2}) >>> list(a == "A") [True, False, True, True] >>> list(a != "A") [False, True, False, False] """ def __new__(cls, array, mapping): obj = np.asarray(array).view(cls) obj.mapping = {SplitName(k): v for k, v in mapping.items()} return obj def __array_finalize__(self, obj): if obj is None: return self.mapping = getattr(obj, "mapping", None) def _mapped_eq(self, other): if other in self.mapping: return super().__eq__(self.mapping[other]) else: result = np.zeros(len(self), dtype=np.bool) for k, v in self.mapping.items(): if k == other: result = np.logical_or(result, super().__eq__(v)) return result def __eq__(self, other): if isinstance(other, str): return self._mapped_eq(other) else: return super().__eq__(other) def __ne__(self, other): if isinstance(other, str): return np.logical_not(self._mapped_eq(other)) else: return super().__ne__(other) # noinspection PyAbstractClass class AliasCSRMatrix(csr_matrix): """Same as :class:`AliasArray` but for a CSR matrix Examples -------- >>> from scipy.sparse import spdiags >>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2}) >>> list(m.data == 'A') [True, False, True] >>> list(m.tocoo().data == 'A') [True, False, True] >>> list(m[:2].data == 'A') [True, False] """ def __init__(self, *args, **kwargs): mapping = kwargs.pop('mapping', {}) if not mapping: mapping = getattr(args[0], 'mapping', {}) super().__init__(*args, **kwargs) self.data = AliasArray(self.data, mapping) @property def format(self): return 'csr' @format.setter def format(self, _): pass @property def mapping(self): return self.data.mapping def tocoo(self, *args, **kwargs): coo = super().tocoo(*args, **kwargs) coo.data = AliasArray(coo.data, mapping=self.mapping) return coo def __getitem__(self, item): result = super().__getitem__(item) if getattr(result, 'format', '') == 'csr': return AliasCSRMatrix(result, mapping=self.mapping) else: return result class AliasIndex: """An all-or-nothing array index based on equality with a specific value The `==` and `!=` operators are overloaded to return a lazy array which is either all `True` or all `False`. See the examples below. This is useful for modifiers where the each call gets arrays with the same sub_id/hop_id for all elements. Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex` does the same all-or-nothing indexing. Examples -------- >>> l = np.array([1, 2, 3]) >>> ai = AliasIndex("A", len(l)) >>> list(l[ai == "A"]) [1, 2, 3] >>> list(l[ai == "B"]) [] >>> list(l[ai != "A"]) [] >>> list(l[ai != "B"]) [1, 2, 3] >>> np.logical_and([True, False, True], ai == "A") array([ True, False, True], dtype=bool) >>> np.logical_and([True, False, True], ai != "A") array([False, False, False], dtype=bool) >>> bool(ai == "A") True >>> bool(ai != "A") False >>> str(ai) 'A' >>> hash(ai) == hash("A") True >>> int(ai.eye) 1 >>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2)) True """ class LazyArray: def __init__(self, value, shape): self.value = value self.shape = shape def __bool__(self): return bool(self.value) def __array__(self): return np.full(self.shape, self.value) def __init__(self, name, shape, orbs=(1, 1)): self.name = name self.shape = shape self.orbs = orbs def __str__(self): return self.name def __eq__(self, other): return self.LazyArray(self.name == other, self.shape) def __ne__(self, other): return self.LazyArray(self.name != other, self.shape) def __hash__(self): return hash(self.name) @property def eye(self): return np.eye(*self.orbs) class SplitName(str): """String subclass with special support for strings of the form "first|second" Operators `==` and `!=` are overloaded to return `True` even if only the first part matches. Examples -------- >>> s = SplitName("first|second") >>> s == "first|second" True >>> s != "first|second" False >>> s == "first" True >>> s != "first" False >>> s == "second" False >>> s != "second" True """ @property def first(self): return self.split("|")[0] def __eq__(self, other): return super().__eq__(other) or self.first == other def __ne__(self, other): return super().__ne__(other) and self.first != other def __hash__(self): return super().__hash__()
MAndelkovic/pybinding
pybinding/support/alias.py
Python
bsd-2-clause
5,869
package org.mastodon.tracking.mamut.trackmate.wizard; import org.mastodon.mamut.model.Link; import org.mastodon.mamut.model.Model; import org.mastodon.mamut.model.Spot; import org.mastodon.model.AbstractModelImporter; public class CreateLargeModelExample { private static final int N_STARTING_CELLS = 6; private static final int N_DIVISIONS = 17; private static final int N_FRAMES_PER_DIVISION = 5; private static final double VELOCITY = 5; private static final double RADIUS = 3; private final Model model; public CreateLargeModelExample() { this.model = new Model(); } public Model run() { return run( N_STARTING_CELLS, N_DIVISIONS, N_FRAMES_PER_DIVISION ); } public Model run( final int nStartingCells, final int nDivisions, final int nFramesPerDivision ) { new AbstractModelImporter< Model >( model ){{ startImport(); }}; final Spot tmp = model.getGraph().vertexRef(); for ( int ic = 0; ic < nStartingCells; ic++ ) { final double angle = 2d * ic * Math.PI / N_STARTING_CELLS; final double vx = VELOCITY * Math.cos( angle ); final double vy = VELOCITY * Math.sin( angle ); // final int nframes = N_DIVISIONS * N_FRAMES_PER_DIVISION; final double x = 0.; // nframes * VELOCITY + vx; final double y = 0.; // nframes * VELOCITY + vy; final double z = N_DIVISIONS * VELOCITY; final double[] pos = new double[] { x, y, z }; final double[][] cov = new double[][] { { RADIUS, 0, 0 }, { 0, RADIUS, 0 }, { 0, 0, RADIUS } }; final Spot mother = model.getGraph().addVertex( tmp ).init( 0, pos, cov ); addBranch( mother, vx, vy, 1, nDivisions, nFramesPerDivision ); } model.getGraph().releaseRef( tmp ); new AbstractModelImporter< Model >( model ){{ finishImport(); }}; return model; } private void addBranch( final Spot start, final double vx, final double vy, final int iteration, final int nDivisions, final int nFramesPerDivision ) { if ( iteration >= nDivisions ) { return; } final Spot previousSpot = model.getGraph().vertexRef(); final Spot spot = model.getGraph().vertexRef(); final Spot daughter = model.getGraph().vertexRef(); final Link link = model.getGraph().edgeRef(); final double[] pos = new double[ 3 ]; final double[][] cov = new double[][] { { RADIUS, 0, 0 }, { 0, RADIUS, 0 }, { 0, 0, RADIUS } }; // Extend previousSpot.refTo( start ); for ( int it = 0; it < nFramesPerDivision; it++ ) { pos[ 0 ] = previousSpot.getDoublePosition( 0 ) + vx; pos[ 1 ] = previousSpot.getDoublePosition( 1 ) + vy; pos[ 2 ] = previousSpot.getDoublePosition( 2 ); final int frame = previousSpot.getTimepoint() + 1; model.getGraph().addVertex( spot ).init( frame, pos, cov ); model.getGraph().addEdge( previousSpot, spot, link ).init(); previousSpot.refTo( spot ); } // Divide for ( int id = 0; id < 2; id++ ) { final double sign = id == 0 ? 1 : -1; final double x; final double y; final double z; if ( iteration % 2 == 0 ) { x = previousSpot.getDoublePosition( 0 ); y = previousSpot.getDoublePosition( 1 ); z = previousSpot.getDoublePosition( 2 ) + sign * VELOCITY * ( 1 - 0.5d * iteration / nDivisions ) * 2; } else { x = previousSpot.getDoublePosition( 0 ) - sign * vy * ( 1 - 0.5d * iteration / nDivisions ) * 2; y = previousSpot.getDoublePosition( 1 ) + sign * vx * ( 1 - 0.5d * iteration / nDivisions ) * 2; z = previousSpot.getDoublePosition( 2 ); } final int frame = previousSpot.getTimepoint() + 1; pos[ 0 ] = x; pos[ 1 ] = y; pos[ 2 ] = z; model.getGraph().addVertex( daughter ).init( frame, pos, cov ); model.getGraph().addEdge( previousSpot, daughter, link ).init(); addBranch( daughter, vx, vy, iteration + 1, nDivisions, nFramesPerDivision ); } model.getGraph().releaseRef( previousSpot ); model.getGraph().releaseRef( spot ); model.getGraph().releaseRef( daughter ); model.getGraph().releaseRef( link ); } public static void main( final String[] args ) { final CreateLargeModelExample clme = new CreateLargeModelExample(); final long start = System.currentTimeMillis(); final Model model = clme.run(); final long end = System.currentTimeMillis(); System.out.println( "Model created in " + ( end - start ) + " ms." ); System.out.println( "Total number of spots: " + model.getGraph().vertices().size() ); System.out.println( String.format( "Total memory used by the model: %.1f MB", ( Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() ) / 1e6d ) ); } }
TrNdy/mastodon-tracking
src/test/java/org/mastodon/tracking/mamut/trackmate/wizard/CreateLargeModelExample.java
Java
bsd-2-clause
4,524
<?php /** * Class for XML output * * PHP versions 5 and 7 * * @category PEAR * @package PEAR_PackageFileManager * @author Greg Beaver <cellog@php.net> * @copyright 2003-2015 The PEAR Group * @license New BSD, Revised * @link http://pear.php.net/package/PEAR_PackageFileManager * @since File available since Release 1.2.0 */ /** * Class for XML output * * @category PEAR * @package PEAR_PackageFileManager * @author Greg Beaver <cellog@php.net> * @copyright 2003-2015 The PEAR Group * @license New BSD, Revised * @version Release: @PEAR-VER@ * @link http://pear.php.net/package/PEAR_PackageFileManager * @since Class available since Release 1.2.0 */ class PEAR_PackageFileManager_XMLOutput extends PEAR_Common { /** * Generate part of an XML description with release information. * * @param array $pkginfo array with release information * @param bool $changelog whether the result will be in a changelog element * * @return string XML data * @access private */ function _makeReleaseXml($pkginfo, $changelog = false) { $indent = $changelog ? " " : ""; $ret = "$indent <release>\n"; if (!empty($pkginfo['version'])) { $ret .= "$indent <version>$pkginfo[version]</version>\n"; } if (!empty($pkginfo['release_date'])) { $ret .= "$indent <date>$pkginfo[release_date]</date>\n"; } if (!empty($pkginfo['release_license'])) { $ret .= "$indent <license>$pkginfo[release_license]</license>\n"; } if (!empty($pkginfo['release_state'])) { $ret .= "$indent <state>$pkginfo[release_state]</state>\n"; } if (!empty($pkginfo['release_notes'])) { $ret .= "$indent <notes>".htmlspecialchars($pkginfo['release_notes'])."</notes>\n"; } if (!empty($pkginfo['release_warnings'])) { $ret .= "$indent <warnings>".htmlspecialchars($pkginfo['release_warnings'])."</warnings>\n"; } if (isset($pkginfo['release_deps']) && sizeof($pkginfo['release_deps']) > 0) { $ret .= "$indent <deps>\n"; foreach ($pkginfo['release_deps'] as $dep) { $ret .= "$indent <dep type=\"$dep[type]\" rel=\"$dep[rel]\""; if (isset($dep['version'])) { $ret .= " version=\"$dep[version]\""; } if (isset($dep['optional'])) { $ret .= " optional=\"$dep[optional]\""; } if (isset($dep['name'])) { $ret .= ">$dep[name]</dep>\n"; } else { $ret .= "/>\n"; } } $ret .= "$indent </deps>\n"; } if (isset($pkginfo['configure_options'])) { $ret .= "$indent <configureoptions>\n"; foreach ($pkginfo['configure_options'] as $c) { $ret .= "$indent <configureoption name=\"". htmlspecialchars($c['name']) . "\""; if (isset($c['default'])) { $ret .= " default=\"" . htmlspecialchars($c['default']) . "\""; } $ret .= " prompt=\"" . htmlspecialchars($c['prompt']) . "\""; $ret .= "/>\n"; } $ret .= "$indent </configureoptions>\n"; } if (isset($pkginfo['provides'])) { foreach ($pkginfo['provides'] as $key => $what) { $ret .= "$indent <provides type=\"$what[type]\" "; $ret .= "name=\"$what[name]\" "; if (isset($what['extends'])) { $ret .= "extends=\"$what[extends]\" "; } $ret .= "/>\n"; } } if (isset($pkginfo['filelist'])) { $ret .= "$indent <filelist>\n"; $ret .= $this->_doFileList($indent, $pkginfo['filelist'], '/'); $ret .= "$indent </filelist>\n"; } $ret .= "$indent </release>\n"; return $ret; } /** * Generate the <filelist> tag * * @param string $indent string to indent xml tag * @param array $filelist list of files included in release * @param string $curdir * * @access private * @return string XML data */ function _doFileList($indent, $filelist, $curdir) { $ret = ''; foreach ($filelist as $file => $fa) { if (isset($fa['##files'])) { $ret .= "$indent <dir"; } else { $ret .= "$indent <file"; } if (isset($fa['role'])) { $ret .= " role=\"$fa[role]\""; } if (isset($fa['baseinstalldir'])) { $ret .= ' baseinstalldir="' . htmlspecialchars($fa['baseinstalldir']) . '"'; } if (isset($fa['md5sum'])) { $ret .= " md5sum=\"$fa[md5sum]\""; } if (isset($fa['platform'])) { $ret .= " platform=\"$fa[platform]\""; } if (!empty($fa['install-as'])) { $ret .= ' install-as="' . htmlspecialchars($fa['install-as']) . '"'; } $ret .= ' name="' . htmlspecialchars($file) . '"'; if (isset($fa['##files'])) { $ret .= ">\n"; $recurdir = $curdir; if ($recurdir == '///') { $recurdir = ''; } $ret .= $this->_doFileList("$indent ", $fa['##files'], $recurdir . $file . '/'); $displaydir = $curdir; if ($displaydir == '///' || $displaydir == '/') { $displaydir = ''; } $ret .= "$indent </dir> <!-- $displaydir$file -->\n"; } else { if (empty($fa['replacements'])) { $ret .= "/>\n"; } else { $ret .= ">\n"; foreach ($fa['replacements'] as $r) { $ret .= "$indent <replace"; foreach ($r as $k => $v) { $ret .= " $k=\"" . htmlspecialchars($v) .'"'; } $ret .= "/>\n"; } $ret .= "$indent </file>\n"; } } } return $ret; } }
pear/PEAR_PackageFileManager
PEAR/PackageFileManager/XMLOutput.php
PHP
bsd-2-clause
6,592
// // ooSocket.c WJ112 // /* * Copyright (c) 2014, Walter de Jong * 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 "oo/Sock.h" #include "oo/print.h" #include <cerrno> #include <cstring> #include <netdb.h> #include <sys/types.h> namespace oo { int Sock::getprotobyname(const char *name) { if (name == nullptr) { name = "tcp"; } struct protoent *proto = ::getprotobyname(name); if (proto == nullptr) { return -1; } return proto->p_proto; } int Sock::getservbyname(const char *name, const char *proto) { if (name == nullptr) { throw ReferenceError(); } if (proto == nullptr) { proto = "tcp"; } struct servent *serv = ::getservbyname(name, proto); if (!serv) { // maybe it's just a numeric string int port; try { port = convert<int>(name); } catch(ValueError err) { return -1; } if (port <= 0) { // invalid port number return -1; // should we throw ValueError instead? } return port; } return ntohs(serv->s_port); } String Sock::getservbyport(int port, const char *proto) { if (proto == nullptr) { proto = "tcp"; } struct servent *serv = ::getservbyport(htons(port), proto); if (!serv) { return String(""); } return String(serv->s_proto); } bool Sock::listen(const char *serv) { int sock = ::socket(AF_INET, SOCK_STREAM, 0); if (sock == -1) { throw IOError("failed to create socket"); } // set option reuse bind address int on = 1; if (::setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(int)) == -1) { ::close(sock); throw IOError("failed to set socket option"); } #ifdef SO_REUSEPORT int on2 = 1; if (::setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &on2, sizeof(int)) == -1) { ::close(sock); throw IOError("failed to set socket option"); } #endif struct sockaddr_in sa; std::memset(&sa, 0, sizeof(struct sockaddr_in)); sa.sin_family = AF_INET; sa.sin_addr.s_addr = INADDR_ANY; int port = this->getservbyname(serv); if (port == -1) { ::close(sock); throw IOError("failed to listen, service unknown"); } sa.sin_port = htons(port); socklen_t sa_len = sizeof(struct sockaddr_in); if (::bind(sock, (struct sockaddr *)&sa, sa_len) == -1) { ::close(sock); throw IOError("failed to bind socket"); } if (::listen(sock, SOMAXCONN) == -1) { ::close(sock); throw IOError("failed to listen on socket"); } if (!f_.open(sock, "rw")) { ::close(sock); throw IOError("failed to tie socket to a stream"); } return true; } bool Sock::listen6(const char *serv) { int sock = ::socket(AF_INET6, SOCK_STREAM, 0); if (sock == -1) { throw IOError("failed to create socket"); } // set option reuse bind address int on = 1; if (::setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(int)) == -1) { ::close(sock); throw IOError("failed to set socket option"); } #ifdef SO_REUSEPORT int on2 = 1; if (::setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &on2, sizeof(int)) == -1) { ::close(sock); throw IOError("failed to set socket option"); } #endif struct sockaddr_in6 sa; std::memset(&sa, 0, sizeof(struct sockaddr_in6)); sa.sin6_family = AF_INET6; sa.sin6_addr = in6addr_any; int port = this->getservbyname(serv); if (port == -1) { ::close(sock); throw IOError("failed to listen, service unknown"); } sa.sin6_port = htons(port); socklen_t sa_len = sizeof(struct sockaddr_in6); if (::bind(sock, (struct sockaddr *)&sa, sa_len) == -1) { ::close(sock); throw IOError("failed to bind socket"); } if (::listen(sock, SOMAXCONN) == -1) { ::close(sock); throw IOError("failed to listen on socket"); } if (!f_.open(sock, "rw")) { ::close(sock); throw IOError("failed to tie socket to a stream"); } return true; } bool Sock::connect(const char *ipaddr, const char *serv) { if (ipaddr == nullptr) { throw ReferenceError(); } if (serv == nullptr) { throw ReferenceError(); } if (!this->isclosed()) { throw IOError("socket is already in use"); } struct addrinfo hints, *res; std::memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; // IPv4, IPv6, or any other protocol hints.ai_socktype = SOCK_STREAM; if (::getaddrinfo(ipaddr, serv, &hints, &res) != 0) { throw IOError("failed to get address info"); } int sock = -1; // try connecting, try out all protocols for(struct addrinfo *r = res; r != nullptr; r = r->ai_next) { if ((sock = ::socket(r->ai_family, r->ai_socktype, r->ai_protocol)) == -1) { continue; } if (::connect(sock, r->ai_addr, r->ai_addrlen) == -1) { ::close(sock); sock = -1; continue; } break; // successful connect } freeaddrinfo(res); if (sock == -1) { throw IOError("failed to connect to remote host"); } // tie it to a stream if (!f_.open(sock, "w+")) { ::close(sock); sock = -1; throw IOError("failed to open socket as a stream"); } return true; } Sock Sock::accept(void) const { if (this->isclosed()) { throw IOError("accept() called on a non-listening socket"); } Sock sock; struct sockaddr_storage addr; socklen_t addr_len = sizeof(struct sockaddr_storage); int sockfd; for(;;) { sockfd = ::accept(f_.fileno(), (struct sockaddr *)&addr, &addr_len); if (sockfd == -1) { if (errno == EINTR) { continue; } return Sock(); } break; } if (!sock.f_.open(sockfd, "w+")) { return Sock(); } return sock; } String Sock::remoteaddr(void) const { if (this->isclosed()) { throw IOError("can not get remote address of an unconnected socket"); } struct sockaddr_storage addr; socklen_t addr_len = sizeof(struct sockaddr_storage); if (::getpeername(f_.fileno(), (struct sockaddr *)&addr, &addr_len) == -1) { throw IOError("failed to get remote address of socket"); } char host[NI_MAXHOST]; if (::getnameinfo((struct sockaddr *)&addr, addr_len, host, sizeof(host), nullptr, 0, NI_NUMERICHOST|NI_NUMERICSERV) == -1) { throw IOError("failed to get numeric address of remote host"); } return String(host); } Sock listen(const char *serv) { Sock sock; if (!sock.listen(serv)) { return Sock(); } return sock; } Sock listen6(const char *serv) { Sock sock; if (!sock.listen6(serv)) { return Sock(); } return sock; } Sock connect(const char *ipaddr, const char *serv) { Sock sock; if (!sock.connect(ipaddr, serv)) { return Sock(); } return sock; } String resolv(const String& ipaddr) { if (ipaddr.empty()) { throw ValueError(); } struct addrinfo *res; if (::getaddrinfo(ipaddr.c_str(), nullptr, nullptr, &res) != 0) { // probably invalid IP address return ipaddr; } char host[NI_MAXHOST]; for(struct addrinfo *r = res; r != nullptr; r = r->ai_next) { if (::getnameinfo(r->ai_addr, r->ai_addrlen, host, sizeof(host), nullptr, 0, 0) == 0) { freeaddrinfo(res); return String(host); } } // some kind of error // print("TD error: %s", ::gai_strerror(err)); freeaddrinfo(res); return ipaddr; } void fprint(Sock& sock, const char *fmt, ...) { if (fmt == nullptr) { throw ReferenceError(); } if (!*fmt) { return; } std::va_list ap; va_start(ap, fmt); vfprint(sock, fmt, ap); va_end(ap); } void vfprint(Sock& sock, const char *fmt, std::va_list ap) { if (fmt == nullptr) { throw ReferenceError(); } std::stringstream ss; vssprint(ss, fmt, ap); sock.write(ss.str()); } } // namespace // EOB
walterdejong/oolib
src/Sock.cpp
C++
bsd-2-clause
8,549
// Copyright 2013 Yangqing Jia #include <algorithm> #include <cmath> #include <cfloat> #include <vector> #include "caffe/layer.hpp" #include "caffe/vision_layers.hpp" #include "caffe/util/math_functions.hpp" #include "caffe/util/io.hpp" #define C_ 1 using std::max; namespace caffe { const float kLOG_THRESHOLD = 1e-20; template <typename Dtype> void MultinomialLogisticLossLayer<Dtype>::SetUp( const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { CHECK_EQ(bottom.size(), 2) << "Loss Layer takes two blobs as input."; CHECK_EQ(top->size(), 0) << "Loss Layer takes no output."; CHECK_EQ(bottom[0]->num(), bottom[1]->num()) << "The data and label should have the same number."; CHECK_EQ(bottom[1]->channels(), 1); CHECK_EQ(bottom[1]->height(), 1); CHECK_EQ(bottom[1]->width(), 1); } template <typename Dtype> Dtype MultinomialLogisticLossLayer<Dtype>::Backward_cpu( const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom) { const Dtype* bottom_data = (*bottom)[0]->cpu_data(); const Dtype* bottom_label = (*bottom)[1]->cpu_data(); Dtype* bottom_diff = (*bottom)[0]->mutable_cpu_diff(); int num = (*bottom)[0]->num(); int dim = (*bottom)[0]->count() / (*bottom)[0]->num(); memset(bottom_diff, 0, sizeof(Dtype) * (*bottom)[0]->count()); Dtype loss = 0; for (int i = 0; i < num; ++i) { int label = static_cast<int>(bottom_label[i]); Dtype prob = max(bottom_data[i * dim + label], Dtype(kLOG_THRESHOLD)); loss -= log(prob); bottom_diff[i * dim + label] = - 1. / prob / num; } return loss / num; } // TODO: implement the GPU version for multinomial loss template <typename Dtype> void InfogainLossLayer<Dtype>::SetUp( const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { CHECK_EQ(bottom.size(), 2) << "Loss Layer takes two blobs as input."; CHECK_EQ(top->size(), 0) << "Loss Layer takes no output."; CHECK_EQ(bottom[0]->num(), bottom[1]->num()) << "The data and label should have the same number."; CHECK_EQ(bottom[1]->channels(), 1); CHECK_EQ(bottom[1]->height(), 1); CHECK_EQ(bottom[1]->width(), 1); BlobProto blob_proto; ReadProtoFromBinaryFile(this->layer_param_.source(), &blob_proto); infogain_.FromProto(blob_proto); CHECK_EQ(infogain_.num(), 1); CHECK_EQ(infogain_.channels(), 1); CHECK_EQ(infogain_.height(), infogain_.width()); } template <typename Dtype> Dtype InfogainLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom) { const Dtype* bottom_data = (*bottom)[0]->cpu_data(); const Dtype* bottom_label = (*bottom)[1]->cpu_data(); const Dtype* infogain_mat = infogain_.cpu_data(); Dtype* bottom_diff = (*bottom)[0]->mutable_cpu_diff(); int num = (*bottom)[0]->num(); int dim = (*bottom)[0]->count() / (*bottom)[0]->num(); CHECK_EQ(infogain_.height(), dim); Dtype loss = 0; for (int i = 0; i < num; ++i) { int label = static_cast<int>(bottom_label[i]); for (int j = 0; j < dim; ++j) { Dtype prob = max(bottom_data[i * dim + j], Dtype(kLOG_THRESHOLD)); loss -= infogain_mat[label * dim + j] * log(prob); bottom_diff[i * dim + j] = - infogain_mat[label * dim + j] / prob / num; } } return loss / num; } template <typename Dtype> void EuclideanLossLayer<Dtype>::SetUp( const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { CHECK_EQ(bottom.size(), 2) << "Loss Layer takes two blobs as input."; CHECK_EQ(top->size(), 0) << "Loss Layer takes no as output."; CHECK_EQ(bottom[0]->num(), bottom[1]->num()) << "The data and label should have the same number."; CHECK_EQ(bottom[0]->channels(), bottom[1]->channels()); CHECK_EQ(bottom[0]->height(), bottom[1]->height()); CHECK_EQ(bottom[0]->width(), bottom[1]->width()); difference_.Reshape(bottom[0]->num(), bottom[0]->channels(), bottom[0]->height(), bottom[0]->width()); } template <typename Dtype> Dtype EuclideanLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom) { int count = (*bottom)[0]->count(); int num = (*bottom)[0]->num(); caffe_sub(count, (*bottom)[0]->cpu_data(), (*bottom)[1]->cpu_data(), difference_.mutable_cpu_data()); Dtype loss = caffe_cpu_dot( count, difference_.cpu_data(), difference_.cpu_data()) / num / Dtype(2); // Compute the gradient caffe_axpby(count, Dtype(1) / num, difference_.cpu_data(), Dtype(0), (*bottom)[0]->mutable_cpu_diff()); return loss; } template <typename Dtype> void AccuracyLayer<Dtype>::SetUp( const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { CHECK_EQ(bottom.size(), 2) << "Accuracy Layer takes two blobs as input."; CHECK_EQ(top->size(), 1) << "Accuracy Layer takes 1 output."; CHECK_EQ(bottom[0]->num(), bottom[1]->num()) << "The data and label should have the same number."; CHECK_EQ(bottom[1]->channels(), 1); CHECK_EQ(bottom[1]->height(), 1); CHECK_EQ(bottom[1]->width(), 1); (*top)[0]->Reshape(1, 2, 1, 1); } template <typename Dtype> void AccuracyLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { Dtype accuracy = 0; Dtype logprob = 0; const Dtype* bottom_data = bottom[0]->cpu_data(); const Dtype* bottom_label = bottom[1]->cpu_data(); int num = bottom[0]->num(); int dim = bottom[0]->count() / bottom[0]->num(); for (int i = 0; i < num; ++i) { // Accuracy Dtype maxval = -FLT_MAX; int max_id = 0; for (int j = 0; j < dim; ++j) { if (bottom_data[i * dim + j] > maxval) { maxval = bottom_data[i * dim + j]; max_id = j; } } //LOG(INFO) << " max_id: " << max_id << " label: " << static_cast<int>(bottom_label[i]); if (max_id == static_cast<int>(bottom_label[i])) { ++accuracy; } Dtype prob = max(bottom_data[i * dim + static_cast<int>(bottom_label[i])], Dtype(kLOG_THRESHOLD)); logprob -= log(prob); } // LOG(INFO) << "classes: " << num; (*top)[0]->mutable_cpu_data()[0] = accuracy / num; (*top)[0]->mutable_cpu_data()[1] = logprob / num; } template <typename Dtype> void HingeLossLayer<Dtype>::SetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { CHECK_EQ(bottom.size(), 2) << "Hinge Loss Layer takes two blobs as input."; CHECK_EQ(top->size(), 0) << "Hinge Loss Layer takes no output."; } template <typename Dtype> void HingeLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { const Dtype* bottom_data = bottom[0]->cpu_data(); Dtype* bottom_diff = bottom[0]->mutable_cpu_diff(); const Dtype* label = bottom[1]->cpu_data(); int num = bottom[0]->num(); int count = bottom[0]->count(); int dim = count / num; caffe_copy(count, bottom_data, bottom_diff); if(0) { for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) LOG(INFO) << bottom_data[i * dim + j]; LOG(INFO) << "*************ONE PASS*****************"; } for (int i = 0; i < num; ++i) { bottom_diff[i * dim + static_cast<int>(label[i])] *= -1; //LOG(INFO) << bottom_diff[i * dim + static_cast<int>(label[i])]; } for (int i = 0; i < num; ++i) { for (int j = 0; j < dim; ++j) { //LOG(INFO) << bottom_diff[i * dim + j]; bottom_diff[i * dim + j] = max(Dtype(0), 1 + bottom_diff[i * dim + j]); //if(bottom_diff[i*dim+j] != 1) //LOG(INFO) << bottom_diff[i*dim+j]; } } } template <typename Dtype> Dtype HingeLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom) { Dtype* bottom_diff = (*bottom)[0]->mutable_cpu_diff(); const Dtype* label = (*bottom)[1]->cpu_data(); int num = (*bottom)[0]->num(); int count = (*bottom)[0]->count(); int dim = count / num; Dtype loss = caffe_cpu_asum(count, bottom_diff) / num; caffe_cpu_sign(count, bottom_diff, bottom_diff); for (int i = 0; i < num; ++i) { bottom_diff[i * dim + static_cast<int>(label[i])] *= -1; } caffe_scal(count, Dtype(1. / num), bottom_diff); //LOG(INFO) << "loss" << loss; return loss; } //**********************SquaredHingeLoss********************** template <typename Dtype> void SquaredHingeLossLayer<Dtype>::SetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { CHECK_EQ(bottom.size(), 2) << "Squared Hinge Loss Layer takes two blobs as input."; CHECK_EQ(top->size(), 0) << "Squared Hinge Loss Layer takes no output."; } template <typename Dtype> void SquaredHingeLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { const Dtype* bottom_data = bottom[0]->cpu_data(); Dtype* bottom_diff = bottom[0]->mutable_cpu_diff(); const Dtype* label = bottom[1]->cpu_data(); int num = bottom[0]->num(); int count = bottom[0]->count(); int dim = count / num; caffe_copy(count, bottom_data, bottom_diff); //Debug if(0) { for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) { LOG(INFO) << bottom_data[i * dim + j]; } LOG(INFO) << "*************ONE PASS*****************"; } for (int i = 0; i < num; ++i) { bottom_diff[i * dim + static_cast<int>(label[i])] *= -1; //LOG(INFO) << static_cast<int>(label[i]); } for (int i = 0; i < num; ++i) { for (int j = 0; j < dim; ++j) { //LOG(INFO) << bottom_diff[i * dim + j]; bottom_diff[i * dim + j] = max(Dtype(0), 1 + bottom_diff[i * dim + j]); //if(bottom_diff[i*dim+j] != 1) //LOG(INFO) << bottom_diff[i*dim+j]; } } } template <typename Dtype> Dtype SquaredHingeLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom) { Dtype* bottom_diff = (*bottom)[0]->mutable_cpu_diff(); const Dtype* label = (*bottom)[1]->cpu_data(); int num = (*bottom)[0]->num(); int count = (*bottom)[0]->count(); int dim = count / num; Dtype loss = caffe_cpu_dot(count, bottom_diff, bottom_diff) / num; for (int i = 0; i < num; ++i) { bottom_diff[i * dim + static_cast<int>(label[i])] *= -1; } caffe_scal(count, Dtype(2.* C_ / num), bottom_diff); //LOG(INFO) << "loss" << loss; return loss; } INSTANTIATE_CLASS(MultinomialLogisticLossLayer); INSTANTIATE_CLASS(InfogainLossLayer); INSTANTIATE_CLASS(EuclideanLossLayer); INSTANTIATE_CLASS(AccuracyLayer); INSTANTIATE_CLASS(HingeLossLayer); INSTANTIATE_CLASS(SquaredHingeLossLayer); } // namespace caffe
PeterPan1990/DSN
src/caffe/layers/loss_layer.cpp
C++
bsd-2-clause
10,973
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/profiles/profile.h" #include <string> #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "base/string_util.h" #include "build/build_config.h" #include "chrome/browser/background_contents_service_factory.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/content_settings/host_content_settings_map.h" #include "chrome/browser/download/download_manager.h" #include "chrome/browser/extensions/extension_message_service.h" #include "chrome/browser/extensions/extension_pref_store.h" #include "chrome/browser/extensions/extension_process_manager.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_special_storage_policy.h" #include "chrome/browser/net/pref_proxy_config_service.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/off_the_record_profile_io_data.h" #include "chrome/browser/profiles/profile_dependency_manager.h" #include "chrome/browser/ssl/ssl_host_state.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/themes/theme_service.h" #include "chrome/browser/transport_security_persister.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/find_bar/find_bar_state.h" #include "chrome/browser/ui/webui/chrome_url_data_manager.h" #include "chrome/browser/ui/webui/extension_icon_source.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/json_pref_store.h" #include "chrome/common/pref_names.h" #include "chrome/common/render_messages.h" #include "content/browser/appcache/chrome_appcache_service.h" #include "content/browser/browser_thread.h" #include "content/browser/chrome_blob_storage_context.h" #include "content/browser/file_system/browser_file_system_helper.h" #include "content/browser/host_zoom_map.h" #include "content/browser/in_process_webkit/webkit_context.h" #include "content/common/notification_service.h" #include "grit/locale_settings.h" #include "net/base/transport_security_state.h" #include "ui/base/resource/resource_bundle.h" #include "webkit/database/database_tracker.h" #include "webkit/quota/quota_manager.h" #if defined(TOOLKIT_USES_GTK) #include "chrome/browser/ui/gtk/gtk_theme_service.h" #endif #if defined(OS_WIN) #include "chrome/browser/password_manager/password_store_win.h" #elif defined(OS_MACOSX) #include "chrome/browser/keychain_mac.h" #include "chrome/browser/password_manager/password_store_mac.h" #elif defined(OS_POSIX) && !defined(OS_CHROMEOS) #include "chrome/browser/password_manager/native_backend_gnome_x.h" #include "chrome/browser/password_manager/native_backend_kwallet_x.h" #include "chrome/browser/password_manager/password_store_x.h" #elif defined(OS_CHROMEOS) #include "chrome/browser/chromeos/preferences.h" #endif using base::Time; using base::TimeDelta; // A pointer to the request context for the default profile. See comments on // Profile::GetDefaultRequestContext. net::URLRequestContextGetter* Profile::default_request_context_; namespace { } // namespace Profile::Profile() : restored_last_session_(false), accessibility_pause_level_(0) { } // static const char* Profile::kProfileKey = "__PROFILE__"; // static const ProfileId Profile::kInvalidProfileId = static_cast<ProfileId>(0); // static void Profile::RegisterUserPrefs(PrefService* prefs) { prefs->RegisterBooleanPref(prefs::kSearchSuggestEnabled, true); prefs->RegisterBooleanPref(prefs::kSessionExitedCleanly, true); prefs->RegisterBooleanPref(prefs::kSafeBrowsingEnabled, true); prefs->RegisterBooleanPref(prefs::kSafeBrowsingReportingEnabled, false); // TODO(estade): IDS_SPELLCHECK_DICTIONARY should be an ASCII string. prefs->RegisterLocalizedStringPref(prefs::kSpellCheckDictionary, IDS_SPELLCHECK_DICTIONARY); prefs->RegisterBooleanPref(prefs::kEnableSpellCheck, true); prefs->RegisterBooleanPref(prefs::kEnableAutoSpellCorrect, true); #if defined(TOOLKIT_USES_GTK) prefs->RegisterBooleanPref(prefs::kUsesSystemTheme, GtkThemeService::DefaultUsesSystemTheme()); #endif prefs->RegisterFilePathPref(prefs::kCurrentThemePackFilename, FilePath()); prefs->RegisterStringPref(prefs::kCurrentThemeID, ThemeService::kDefaultThemeID); prefs->RegisterDictionaryPref(prefs::kCurrentThemeImages); prefs->RegisterDictionaryPref(prefs::kCurrentThemeColors); prefs->RegisterDictionaryPref(prefs::kCurrentThemeTints); prefs->RegisterDictionaryPref(prefs::kCurrentThemeDisplayProperties); prefs->RegisterBooleanPref(prefs::kDisableExtensions, false); prefs->RegisterStringPref(prefs::kSelectFileLastDirectory, ""); #if defined(OS_CHROMEOS) // TODO(dilmah): For OS_CHROMEOS we maintain kApplicationLocale in both // local state and user's profile. For other platforms we maintain // kApplicationLocale only in local state. // In the future we may want to maintain kApplicationLocale // in user's profile for other platforms as well. prefs->RegisterStringPref(prefs::kApplicationLocale, ""); prefs->RegisterStringPref(prefs::kApplicationLocaleBackup, ""); prefs->RegisterStringPref(prefs::kApplicationLocaleAccepted, ""); #endif } // static net::URLRequestContextGetter* Profile::GetDefaultRequestContext() { return default_request_context_; } bool Profile::IsGuestSession() { #if defined(OS_CHROMEOS) static bool is_guest_session = CommandLine::ForCurrentProcess()->HasSwitch(switches::kGuestSession); return is_guest_session; #else return false; #endif } bool Profile::IsSyncAccessible() { ProfileSyncService* syncService = GetProfileSyncService(); return syncService && !syncService->IsManaged(); } //////////////////////////////////////////////////////////////////////////////// // // OffTheRecordProfileImpl is a profile subclass that wraps an existing profile // to make it suitable for the incognito mode. // //////////////////////////////////////////////////////////////////////////////// class OffTheRecordProfileImpl : public Profile, public BrowserList::Observer { public: explicit OffTheRecordProfileImpl(Profile* real_profile) : profile_(real_profile), prefs_(real_profile->GetOffTheRecordPrefs()), ALLOW_THIS_IN_INITIALIZER_LIST(io_data_(this)), start_time_(Time::Now()) { extension_process_manager_.reset(ExtensionProcessManager::Create(this)); BrowserList::AddObserver(this); BackgroundContentsServiceFactory::GetForProfile(this); DCHECK(real_profile->GetPrefs()->GetBoolean(prefs::kIncognitoEnabled)); // TODO(oshima): Remove the need to eagerly initialize the request context // getter. chromeos::OnlineAttempt is illegally trying to access this // Profile member from a thread other than the UI thread, so we need to // prevent a race. #if defined(OS_CHROMEOS) GetRequestContext(); #endif // defined(OS_CHROMEOS) // Make the chrome//extension-icon/ resource available. ExtensionIconSource* icon_source = new ExtensionIconSource(real_profile); GetChromeURLDataManager()->AddDataSource(icon_source); } virtual ~OffTheRecordProfileImpl() { NotificationService::current()->Notify(NotificationType::PROFILE_DESTROYED, Source<Profile>(this), NotificationService::NoDetails()); ProfileDependencyManager::GetInstance()->DestroyProfileServices(this); // Clean up all DB files/directories if (db_tracker_) BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, NewRunnableMethod( db_tracker_.get(), &webkit_database::DatabaseTracker::DeleteIncognitoDBDirectory)); BrowserList::RemoveObserver(this); if (pref_proxy_config_tracker_) pref_proxy_config_tracker_->DetachFromPrefService(); } virtual ProfileId GetRuntimeId() { return reinterpret_cast<ProfileId>(this); } virtual std::string GetProfileName() { // Incognito profile should not return the profile name. return std::string(); } virtual FilePath GetPath() { return profile_->GetPath(); } virtual bool IsOffTheRecord() { return true; } virtual Profile* GetOffTheRecordProfile() { return this; } virtual void DestroyOffTheRecordProfile() { // Suicide is bad! NOTREACHED(); } virtual bool HasOffTheRecordProfile() { return true; } virtual Profile* GetOriginalProfile() { return profile_; } virtual ChromeAppCacheService* GetAppCacheService() { if (!appcache_service_) { appcache_service_ = new ChromeAppCacheService; BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod( appcache_service_.get(), &ChromeAppCacheService::InitializeOnIOThread, IsOffTheRecord() ? FilePath() : GetPath().Append(chrome::kAppCacheDirname), make_scoped_refptr(GetHostContentSettingsMap()), make_scoped_refptr(GetExtensionSpecialStoragePolicy()), false)); } return appcache_service_; } virtual webkit_database::DatabaseTracker* GetDatabaseTracker() { if (!db_tracker_.get()) { db_tracker_ = new webkit_database::DatabaseTracker( GetPath(), IsOffTheRecord(), GetExtensionSpecialStoragePolicy()); } return db_tracker_; } virtual VisitedLinkMaster* GetVisitedLinkMaster() { // We don't provide access to the VisitedLinkMaster when we're OffTheRecord // because we don't want to leak the sites that the user has visited before. return NULL; } virtual ExtensionService* GetExtensionService() { return GetOriginalProfile()->GetExtensionService(); } virtual StatusTray* GetStatusTray() { return GetOriginalProfile()->GetStatusTray(); } virtual UserScriptMaster* GetUserScriptMaster() { return GetOriginalProfile()->GetUserScriptMaster(); } virtual ExtensionDevToolsManager* GetExtensionDevToolsManager() { // TODO(mpcomplete): figure out whether we should return the original // profile's version. return NULL; } virtual ExtensionProcessManager* GetExtensionProcessManager() { return extension_process_manager_.get(); } virtual ExtensionMessageService* GetExtensionMessageService() { return GetOriginalProfile()->GetExtensionMessageService(); } virtual ExtensionEventRouter* GetExtensionEventRouter() { return GetOriginalProfile()->GetExtensionEventRouter(); } virtual ExtensionSpecialStoragePolicy* GetExtensionSpecialStoragePolicy() { return GetOriginalProfile()->GetExtensionSpecialStoragePolicy(); } virtual SSLHostState* GetSSLHostState() { if (!ssl_host_state_.get()) ssl_host_state_.reset(new SSLHostState()); DCHECK(ssl_host_state_->CalledOnValidThread()); return ssl_host_state_.get(); } virtual net::TransportSecurityState* GetTransportSecurityState() { if (!transport_security_state_.get()) { transport_security_state_ = new net::TransportSecurityState( CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kHstsHosts)); transport_security_loader_ = new TransportSecurityPersister(true /* readonly */); transport_security_loader_->Initialize(transport_security_state_.get(), GetOriginalProfile()->GetPath()); } return transport_security_state_.get(); } virtual HistoryService* GetHistoryService(ServiceAccessType sat) { if (sat == EXPLICIT_ACCESS) return profile_->GetHistoryService(sat); NOTREACHED() << "This profile is OffTheRecord"; return NULL; } virtual HistoryService* GetHistoryServiceWithoutCreating() { return profile_->GetHistoryServiceWithoutCreating(); } virtual FaviconService* GetFaviconService(ServiceAccessType sat) { if (sat == EXPLICIT_ACCESS) return profile_->GetFaviconService(sat); NOTREACHED() << "This profile is OffTheRecord"; return NULL; } virtual AutocompleteClassifier* GetAutocompleteClassifier() { return profile_->GetAutocompleteClassifier(); } virtual WebDataService* GetWebDataService(ServiceAccessType sat) { if (sat == EXPLICIT_ACCESS) return profile_->GetWebDataService(sat); NOTREACHED() << "This profile is OffTheRecord"; return NULL; } virtual WebDataService* GetWebDataServiceWithoutCreating() { return profile_->GetWebDataServiceWithoutCreating(); } virtual PasswordStore* GetPasswordStore(ServiceAccessType sat) { if (sat == EXPLICIT_ACCESS) return profile_->GetPasswordStore(sat); NOTREACHED() << "This profile is OffTheRecord"; return NULL; } virtual PrefService* GetPrefs() { return prefs_; } virtual PrefService* GetOffTheRecordPrefs() { return prefs_; } virtual TemplateURLModel* GetTemplateURLModel() { return profile_->GetTemplateURLModel(); } virtual TemplateURLFetcher* GetTemplateURLFetcher() { return profile_->GetTemplateURLFetcher(); } virtual DownloadManager* GetDownloadManager() { if (!download_manager_.get()) { scoped_refptr<DownloadManager> dlm( new DownloadManager(g_browser_process->download_status_updater())); dlm->Init(this); download_manager_.swap(dlm); } return download_manager_.get(); } virtual bool HasCreatedDownloadManager() const { return (download_manager_.get() != NULL); } virtual PersonalDataManager* GetPersonalDataManager() { return NULL; } virtual fileapi::FileSystemContext* GetFileSystemContext() { if (!file_system_context_) file_system_context_ = CreateFileSystemContext( GetPath(), IsOffTheRecord(), GetExtensionSpecialStoragePolicy()); DCHECK(file_system_context_.get()); return file_system_context_.get(); } virtual net::URLRequestContextGetter* GetRequestContext() { return io_data_.GetMainRequestContextGetter(); } virtual quota::QuotaManager* GetQuotaManager() { if (!quota_manager_.get()) { quota_manager_ = new quota::QuotaManager( IsOffTheRecord(), GetPath(), BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO), BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB)); } return quota_manager_.get(); } virtual net::URLRequestContextGetter* GetRequestContextForRenderProcess( int renderer_child_id) { if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableExperimentalAppManifests)) { const Extension* installed_app = GetExtensionService()-> GetInstalledAppForRenderer(renderer_child_id); if (installed_app != NULL && installed_app->is_storage_isolated()) return GetRequestContextForIsolatedApp(installed_app->id()); } return GetRequestContext(); } virtual net::URLRequestContextGetter* GetRequestContextForMedia() { // In OTR mode, media request context is the same as the original one. return io_data_.GetMainRequestContextGetter(); } virtual net::URLRequestContextGetter* GetRequestContextForExtensions() { return io_data_.GetExtensionsRequestContextGetter(); } virtual net::URLRequestContextGetter* GetRequestContextForIsolatedApp( const std::string& app_id) { return io_data_.GetIsolatedAppRequestContextGetter(app_id); } virtual const content::ResourceContext& GetResourceContext() { return io_data_.GetResourceContext(); } virtual net::SSLConfigService* GetSSLConfigService() { return profile_->GetSSLConfigService(); } virtual HostContentSettingsMap* GetHostContentSettingsMap() { // Retrieve the host content settings map of the parent profile in order to // ensure the preferences have been migrated. profile_->GetHostContentSettingsMap(); if (!host_content_settings_map_.get()) host_content_settings_map_ = new HostContentSettingsMap(this); return host_content_settings_map_.get(); } virtual HostZoomMap* GetHostZoomMap() { if (!host_zoom_map_) host_zoom_map_ = new HostZoomMap(this); return host_zoom_map_.get(); } virtual GeolocationContentSettingsMap* GetGeolocationContentSettingsMap() { return profile_->GetGeolocationContentSettingsMap(); } virtual GeolocationPermissionContext* GetGeolocationPermissionContext() { return profile_->GetGeolocationPermissionContext(); } virtual UserStyleSheetWatcher* GetUserStyleSheetWatcher() { return profile_->GetUserStyleSheetWatcher(); } virtual FindBarState* GetFindBarState() { if (!find_bar_state_.get()) find_bar_state_.reset(new FindBarState()); return find_bar_state_.get(); } virtual bool HasProfileSyncService() const { // We never have a profile sync service. return false; } virtual bool DidLastSessionExitCleanly() { return profile_->DidLastSessionExitCleanly(); } virtual BookmarkModel* GetBookmarkModel() { return profile_->GetBookmarkModel(); } virtual ProtocolHandlerRegistry* GetProtocolHandlerRegistry() { return profile_->GetProtocolHandlerRegistry(); } virtual TokenService* GetTokenService() { return NULL; } virtual ProfileSyncService* GetProfileSyncService() { return NULL; } virtual ProfileSyncService* GetProfileSyncService( const std::string& cros_user) { return NULL; } virtual BrowserSignin* GetBrowserSignin() { return profile_->GetBrowserSignin(); } virtual CloudPrintProxyService* GetCloudPrintProxyService() { return NULL; } virtual bool IsSameProfile(Profile* profile) { return (profile == this) || (profile == profile_); } virtual Time GetStartTime() const { return start_time_; } virtual SpellCheckHost* GetSpellCheckHost() { return profile_->GetSpellCheckHost(); } virtual void ReinitializeSpellCheckHost(bool force) { profile_->ReinitializeSpellCheckHost(force); } virtual WebKitContext* GetWebKitContext() { if (!webkit_context_.get()) { webkit_context_ = new WebKitContext( IsOffTheRecord(), GetPath(), GetExtensionSpecialStoragePolicy(), false); } return webkit_context_.get(); } virtual history::TopSites* GetTopSitesWithoutCreating() { return NULL; } virtual history::TopSites* GetTopSites() { return NULL; } virtual void MarkAsCleanShutdown() { } virtual void InitExtensions(bool extensions_enabled) { NOTREACHED(); } virtual void InitPromoResources() { NOTREACHED(); } virtual void InitRegisteredProtocolHandlers() { NOTREACHED(); } virtual NTPResourceCache* GetNTPResourceCache() { // Just return the real profile resource cache. return profile_->GetNTPResourceCache(); } virtual FilePath last_selected_directory() { const FilePath& directory = last_selected_directory_; if (directory.empty()) { return profile_->last_selected_directory(); } return directory; } virtual void set_last_selected_directory(const FilePath& path) { last_selected_directory_ = path; } #if defined(OS_CHROMEOS) virtual void SetupChromeOSEnterpriseExtensionObserver() { profile_->SetupChromeOSEnterpriseExtensionObserver(); } virtual void InitChromeOSPreferences() { // The incognito profile shouldn't have Chrome OS's preferences. // The preferences are associated with the regular user profile. } #endif // defined(OS_CHROMEOS) virtual void ExitedOffTheRecordMode() { // DownloadManager is lazily created, so check before accessing it. if (download_manager_.get()) { // Drop our download manager so we forget about all the downloads made // in incognito mode. download_manager_->Shutdown(); download_manager_ = NULL; } } virtual void OnBrowserAdded(const Browser* browser) { } virtual void OnBrowserRemoved(const Browser* browser) { if (BrowserList::GetBrowserCount(this) == 0) ExitedOffTheRecordMode(); } virtual ChromeBlobStorageContext* GetBlobStorageContext() { if (!blob_storage_context_) { blob_storage_context_ = new ChromeBlobStorageContext(); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod( blob_storage_context_.get(), &ChromeBlobStorageContext::InitializeOnIOThread)); } return blob_storage_context_; } virtual ExtensionInfoMap* GetExtensionInfoMap() { return profile_->GetExtensionInfoMap(); } virtual ChromeURLDataManager* GetChromeURLDataManager() { if (!chrome_url_data_manager_.get()) chrome_url_data_manager_.reset(new ChromeURLDataManager(this)); return chrome_url_data_manager_.get(); } virtual PromoCounter* GetInstantPromoCounter() { return NULL; } #if defined(OS_CHROMEOS) virtual void ChangeAppLocale(const std::string& locale, AppLocaleChangedVia) { } virtual void OnLogin() { } #endif // defined(OS_CHROMEOS) virtual PrefProxyConfigTracker* GetProxyConfigTracker() { if (!pref_proxy_config_tracker_) pref_proxy_config_tracker_ = new PrefProxyConfigTracker(GetPrefs()); return pref_proxy_config_tracker_; } virtual prerender::PrerenderManager* GetPrerenderManager() { // We do not allow prerendering in OTR profiles at this point. // TODO(tburkard): Figure out if we want to support this, and how, at some // point in the future. return NULL; } private: NotificationRegistrar registrar_; // The real underlying profile. Profile* profile_; // Weak pointer owned by |profile_|. PrefService* prefs_; scoped_ptr<ExtensionProcessManager> extension_process_manager_; OffTheRecordProfileIOData::Handle io_data_; // The download manager that only stores downloaded items in memory. scoped_refptr<DownloadManager> download_manager_; // We use a non-writable content settings map for OTR. scoped_refptr<HostContentSettingsMap> host_content_settings_map_; // Use a separate zoom map for OTR. scoped_refptr<HostZoomMap> host_zoom_map_; // Use a special WebKit context for OTR browsing. scoped_refptr<WebKitContext> webkit_context_; // We don't want SSLHostState from the OTR profile to leak back to the main // profile because then the main profile would learn some of the host names // the user visited while OTR. scoped_ptr<SSLHostState> ssl_host_state_; // Use a separate FindBarState so search terms do not leak back to the main // profile. scoped_ptr<FindBarState> find_bar_state_; // The TransportSecurityState that only stores enabled sites in memory. scoped_refptr<net::TransportSecurityState> transport_security_state_; // Time we were started. Time start_time_; scoped_refptr<ChromeAppCacheService> appcache_service_; // The main database tracker for this profile. // Should be used only on the file thread. scoped_refptr<webkit_database::DatabaseTracker> db_tracker_; FilePath last_selected_directory_; scoped_refptr<ChromeBlobStorageContext> blob_storage_context_; // The file_system context for this profile. scoped_refptr<fileapi::FileSystemContext> file_system_context_; scoped_refptr<PrefProxyConfigTracker> pref_proxy_config_tracker_; scoped_ptr<ChromeURLDataManager> chrome_url_data_manager_; scoped_refptr<quota::QuotaManager> quota_manager_; // Used read-only. scoped_refptr<TransportSecurityPersister> transport_security_loader_; DISALLOW_COPY_AND_ASSIGN(OffTheRecordProfileImpl); }; #if defined(OS_CHROMEOS) // Special case of the OffTheRecordProfileImpl which is used while Guest // session in CrOS. class GuestSessionProfile : public OffTheRecordProfileImpl { public: explicit GuestSessionProfile(Profile* real_profile) : OffTheRecordProfileImpl(real_profile) { } virtual PersonalDataManager* GetPersonalDataManager() { return GetOriginalProfile()->GetPersonalDataManager(); } virtual void InitChromeOSPreferences() { chromeos_preferences_.reset(new chromeos::Preferences()); chromeos_preferences_->Init(GetPrefs()); } private: // The guest user should be able to customize Chrome OS preferences. scoped_ptr<chromeos::Preferences> chromeos_preferences_; }; #endif Profile* Profile::CreateOffTheRecordProfile() { #if defined(OS_CHROMEOS) if (Profile::IsGuestSession()) return new GuestSessionProfile(this); #endif return new OffTheRecordProfileImpl(this); }
Crystalnix/house-of-life-chromium
chrome/browser/profiles/profile.cc
C++
bsd-3-clause
24,938
/** * Layout Select UI * * @package zork * @subpackage form * @author Kristof Matos <kristof.matos@megaweb.hu> */ ( function ( global, $, js ) { "use strict"; if ( typeof js.layoutSelect !== "undefined" ) { return; } js.require( "jQuery.fn.vslider"); /** * Generates layout select user interface from radio inputs * * @memberOf Zork.Form.Element */ global.Zork.prototype.layoutSelect = function ( element ) { js.style('/styles/scripts/layoutselect.css'); element = $( element ); var defaultKey = element.data( "jsLayoutselectDefaultkey") || "paragraph.form.content.layout.default", descriptionKeyPattern = element.data( "jsLayoutselectDescriptionkey") || "paragraph.form.content.layout.default-description", imageSrcPattern = element.data( "jsLayoutselectImagesrc") || "", selectType = element.data( "jsLayoutselectType") || "locale", itemsPerRow = parseInt(element.data("jsLayoutselectItemsperrow"))>0 ? parseInt(element.data("jsLayoutselectItemsperrow")) : ( selectType == "local" ? 6 : 3 ); element.addClass( "layout-select "+selectType); element.find( "label" ).each( function(idx,eleRadioItem) { var input = $(eleRadioItem).find( ":radio" ), inner = $('<div class="inner"/>').append(input), title = $('<div class="title"/>').html( $(eleRadioItem).html() || js.core.translate(defaultKey) ), overlay = $('<div class="overlay"/>'), innerButtons = $('<div class="buttons"/>').appendTo(inner), innerDescription = $('<p class="description"/>').appendTo(inner), innerButtonsSelect = $('<span class="select"/>') .html( js.core.translate("default.select" ,js.core.userLocale) ) .appendTo(innerButtons), dateCreated = input.data("created") || '-', dateModified = input.data("lastModified") || '-'; $(eleRadioItem).html('') .append(inner) .append(title) .append(overlay); if( selectType == 'import' ) { innerDescription.html( js.core.translate( descriptionKeyPattern.replace("[value]", input.attr( "value")) ,js.core.userLocale)); var imageSrc = imageSrcPattern .replace("[value]",input.attr( "value")); inner.prepend( $( "<img alt='icon' />" ).attr( "src", imageSrc )); } else//selectType == 'locale' { if( input.attr( "value") ) { innerDescription .append( $('<div/>') .append( $('<span/>').html( js.core.translate("default.lastmodified", js.core.userLocale) +': ') ) .append( $('<span/>').html(dateModified) ) ) .append( $('<div/>') .append( $('<span/>').html( js.core.translate("default.created", js.core.userLocale) +': ') ) .append( $('<span/>').html(dateCreated) ) ); js.core.translate("default.created",js.core.userLocale) innerButtons.prepend( $('<a class="preview"/>') .html( js.core.translate("default.preview" ,js.core.userLocale) ) .attr('href','/app/'+js.core.userLocale +'/paragraph/render/'+input.attr( "value")) .attr('target','_blank') ); } } innerButtonsSelect.on( "click", function(evt) { element.find( "label" ).removeClass("selected"); $(evt.target.parentNode.parentNode.parentNode).addClass("selected"); } ); } ); var eleRow, eleRowsContainer = $('<div/>').appendTo(element); element.find( "label" ).each( function(idxItem,eleItem) { if( idxItem%itemsPerRow==0 ) { eleRow = $('<div />').appendTo(eleRowsContainer); } eleRow.append(eleItem); } ); $(eleRowsContainer).vslider({"items":"div", "itemheight":( selectType == 'local' ? 300 : 255 )}); { setTimeout( function(){ $('.ui-vslider').vslider('refresh') },100 ); } }; global.Zork.prototype.layoutSelect.isElementConstructor = true; } ( window, jQuery, zork ) );
webriq/core
module/Paragraph/public/scripts/zork/layoutselect.js
JavaScript
bsd-3-clause
5,515
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Bill */ public class BackRightAutonomous extends CommandBase { public BackRightAutonomous() { // Use requires() here to declare subsystem dependencies // eg. requires(chassis); } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
TeamSprocket/2013Robot
BackRightAutonomous.java
Java
bsd-3-clause
952
/** * Dialog to add a new visualization from any of your * existing tables. * */ cdb.admin.NewVisualizationDialogTableItem = cdb.core.View.extend({ events: { "click .remove" : "_onRemove" }, tagName: "li", className: "table", initialize: function() { _.bindAll(this, "_onRemove"); this.template = this.getTemplate('dashboard/views/new_visualization_dialog_table_item'); }, render: function() { this.$el.html(this.template(this.model.toJSON())); return this.$el; }, show: function() { this.$el.show(); }, _onRemove: function(e) { this.killEvent(e); this.clear(); this.trigger("remove", this); }, clear: function() { this.$el.hide(); } }); cdb.admin.NewVisualizationDialog = cdb.admin.BaseDialog.extend({ _MAX_LAYERS: 3, _TEXTS: { title: _t('Create visualization'), loading_data: _t('Loading data…'), description: _t('Select the layers you will use on this visualization (you will be able to add more later)'), new_vis_title: _t("Give a name to your visualization"), no_tables: _t("Looks like you don’t have any imported data in your account. To create your first \ visualization you will need to import at least a dataset.") }, events: cdb.core.View.extendEvents({ // do not remove "click .add" : "_onAddTableItem", }), initialize: function() { if (!this.options.user) { new Throw("No user specified when it is needed") } this.user = this.options.user; // Dialog options _.extend(this.options, { title: this._TEXTS.title, template_name: 'common/views/dialog_base', clean_on_hide: true, ok_button_classes: "button green hidden", ok_title: this._TEXTS.title, modal_type: "creation", modal_class: 'new_visualization_dialog', width: this.user.isInsideOrg() ? 502 : 464 }); // Set max layers if user has this parameter var max_user_layers = this.options.user.get('max_layers'); if (!isNaN(max_user_layers) && this._MAX_LAYERS != max_user_layers) { this._MAX_LAYERS = max_user_layers; } this.ok = this.options.ok; this.model = new cdb.core.Model(); this.model.bind("change:disabled", this._onToggleDisabled, this); // Collection to manage the tables this.table_items = new Backbone.Collection(); this.table_items.bind("add", this._addTableItem, this); this.table_items.bind("remove", this._onRemove, this); this.constructor.__super__.initialize.apply(this); this.setWizard(this.options.wizard_option); this.visualizations = new cdb.admin.Visualizations({ type: "derived" }); }, render_content: function() { this.$content = $("<div>"); var temp_content = this.getTemplate('dashboard/views/new_visualization_dialog'); this.$content.append(temp_content({ description: this._TEXTS.loading })); // Tables combo this.tableCombo = new cdb.ui.common.VisualizationsSelector({ model: this.visualizations, user: this.options.user }); this.$content.find('.tableListCombo').append(this.tableCombo.render().el); this.addView(this.tableCombo); this.disableOkButton(); this._loadTables(); return this.$content; }, _onToggleDisabled: function() { this.tableCombo[ this.model.get("disabled") ? "disable" : "enable" ]() this.$(".combo_wrapper")[( this.model.get("disabled") ? "addClass" : "removeClass" )]('disabled'); }, _loadTables: function() { this.visualizations.bind('reset', this._onReset, this); this.visualizations.options.set({ type: "table", per_page: 100000 }); var order = { data: { o: { updated_at: "desc" }, exclude_raster: true }}; this.visualizations.fetch(order); }, _onReset: function() { this.visualizations.unbind(null, null, this); // do this one time and one time only if (this.visualizations.size() == 0) { this.emptyState = true; this._showEmpyState(); } else { this.emptyState = false; this._showControls(); } }, _showEmpyState: function() { var self = this; this.$el.find(".loader").fadeOut(250, function() { $(this).addClass("hidden"); self.$el.find("p").html(self._TEXTS.no_tables); self.$el.find(".ok.button").removeClass("green").addClass("grey"); self.$el.find(".ok.button").html("Ok, let's import some data"); self.$el.find(".ok.button").fadeIn(250, function() { self.enableOkButton(); }); }); }, _showControls: function() { var self = this; this.$el.find(".loader").fadeOut(250, function() { $(this).addClass("hidden"); self.$el.find("p").html(self._TEXTS.description); self.$el.find(".combo_wrapper").addClass('active'); self.$el.find(".ok.button").fadeIn(250, function() { $(this).removeClass("hidden"); }); self.$el.find(".cancel").fadeIn(250); }); this._setupScroll(); }, _setupScroll: function() { this.$scrollPane = this.$el.find(".scrollpane"); this.$scrollPane.jScrollPane({ showArrows: true, animateScroll: true, animateDuration: 150 }); this.api = this.$scrollPane.data('jsp'); }, _cleanString: function(s, n) { if (s) { s = s.replace(/<(?:.|\n)*?>/gm, ''); // strip HTML tags s = s.substr(0, n-1) + (s.length > n ? '&hellip;' : ''); // truncate string } return s; }, _onAddTableItem: function(e) { this.killEvent(e); if (this.model.get("disabled")) return; var table = this.tableCombo.getSelected(); if (table) { var model = new cdb.core.Model(table); this.table_items.add(model); } }, _afterAddItem: function() { if (this.table_items.length >= this._MAX_LAYERS) { this.model.set("disabled", true); } }, _afterRemoveItem: function() { if (this.table_items.length < this._MAX_LAYERS) { this.model.set("disabled", false); } }, _addTableItem: function(model) { this.enableOkButton(); this._afterAddItem(); var view = new cdb.admin.NewVisualizationDialogTableItem({ model: model }); this.$(".tables").append(view.render()); view.bind("remove", this._onRemoveItem, this); view.show(); this._refreshScrollPane(); }, _onRemoveItem: function(item) { this.table_items.remove(item.model); this._refreshScrollPane(); this._afterRemoveItem(); }, _onRemove: function() { if (this.table_items.length == 0) this.disableOkButton(); }, _refreshScrollPane: function() { var self = this; this.$(".scrollpane").animate({ height: this.$(".tables").height() + 5 }, { duration: 150, complete: function() { self.api && self.api.reinitialise(); }}); }, _ok: function(ev) { this.killEvent(ev); if (this.emptyState) { this.hide(); this.trigger("navigate_tables", this); } else { if (this.table_items.length === 0) return; this.hide(); this._openNameVisualizationDialog(); } }, _openNameVisualizationDialog: function() { var selected_tables = this.table_items.pluck("vis_id"); var tables = _.compact( this.visualizations.map(function(m) { if (_.contains(selected_tables, m.get('id'))) { return m.get('table').name } return false; }) ); var dlg = new cdb.admin.NameVisualization({ msg: this._TEXTS.new_vis_title, onResponse: function(name) { var vis = new cdb.admin.Visualization(); vis.save({ name: name, tables: tables }).success(function() { window.location.href = vis.viewUrl(); }); } }); dlg.bind("will_open", function() { $("body").css({ overflow: "hidden" }); }, this); dlg.bind("was_removed", function() { $("body").css({ overflow: "auto" }); }, this); dlg.appendToBody().open(); }, clean: function() { $(".select2-drop.select2-drop-active").hide(); cdb.admin.BaseDialog.prototype.clean.call(this); } });
comilla/map
lib/assets/javascripts/cartodb/dashboard/visualizations/new_visualization_dialog.js
JavaScript
bsd-3-clause
8,143
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/public/common/page/content_to_visible_time_reporter.h" #include <utility> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/debug/dump_without_crashing.h" #include "base/feature_list.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/strings/strcat.h" #include "base/trace_event/trace_event.h" #include "third_party/blink/public/common/features.h" #include "third_party/blink/public/mojom/widget/record_content_to_visible_time_request.mojom.h" #include "ui/gfx/presentation_feedback.h" namespace blink { namespace { // Used to generate unique "TabSwitching::Latency" event ids. Note: The address // of ContentToVisibleTimeReporter can't be used as an id because a single // ContentToVisibleTimeReporter can generate multiple overlapping events. int g_num_trace_events_in_process = 0; const char* GetHistogramSuffix( bool has_saved_frames, const mojom::RecordContentToVisibleTimeRequest& start_state) { if (has_saved_frames) return "WithSavedFrames"; if (start_state.destination_is_loaded) { return "NoSavedFrames_Loaded"; } else { return "NoSavedFrames_NotLoaded"; } } void ReportUnOccludedMetric(const base::TimeTicks requested_time, const gfx::PresentationFeedback& feedback) { const base::TimeDelta delta = feedback.timestamp - requested_time; UMA_HISTOGRAM_TIMES("Aura.WebContentsWindowUnOccludedTime", delta); } void RecordBackForwardCacheRestoreMetric( const base::TimeTicks requested_time, const gfx::PresentationFeedback& feedback) { const base::TimeDelta delta = feedback.timestamp - requested_time; // Histogram to record the content to visible duration after restoring a page // from back-forward cache. Here min, max bucket size are same as the // "PageLoad.PaintTiming.NavigationToFirstContentfulPaint" metric. base::UmaHistogramCustomTimes( "BackForwardCache.Restore.NavigationToFirstPaint", delta, base::Milliseconds(10), base::Minutes(10), 100); } } // namespace void UpdateRecordContentToVisibleTimeRequest( mojom::RecordContentToVisibleTimeRequest const& from, mojom::RecordContentToVisibleTimeRequest& to) { to.event_start_time = std::min(to.event_start_time, from.event_start_time); to.destination_is_loaded |= from.destination_is_loaded; to.show_reason_tab_switching |= from.show_reason_tab_switching; to.show_reason_unoccluded |= from.show_reason_unoccluded; to.show_reason_bfcache_restore |= from.show_reason_bfcache_restore; } ContentToVisibleTimeReporter::ContentToVisibleTimeReporter() : is_tab_switch_metric2_feature_enabled_( base::FeatureList::IsEnabled(blink::features::kTabSwitchMetrics2)) {} ContentToVisibleTimeReporter::~ContentToVisibleTimeReporter() = default; base::OnceCallback<void(const gfx::PresentationFeedback&)> ContentToVisibleTimeReporter::TabWasShown( bool has_saved_frames, mojom::RecordContentToVisibleTimeRequestPtr start_state, base::TimeTicks widget_visibility_request_timestamp) { DCHECK(!start_state->event_start_time.is_null()); DCHECK(!widget_visibility_request_timestamp.is_null()); DCHECK(!tab_switch_start_state_); DCHECK(widget_visibility_request_timestamp_.is_null()); // Invalidate previously issued callbacks, to avoid accessing a null // |tab_switch_start_state_|. // // TODO(https://crbug.com/1121339): Make sure that TabWasShown() is never // called twice without a call to TabWasHidden() in-between, and remove this // mitigation. weak_ptr_factory_.InvalidateWeakPtrs(); has_saved_frames_ = has_saved_frames; tab_switch_start_state_ = std::move(start_state); widget_visibility_request_timestamp_ = widget_visibility_request_timestamp; // |tab_switch_start_state_| is only reset by RecordHistogramsAndTraceEvents // once the metrics have been emitted. return base::BindOnce( &ContentToVisibleTimeReporter::RecordHistogramsAndTraceEvents, weak_ptr_factory_.GetWeakPtr(), false /* is_incomplete */, tab_switch_start_state_->show_reason_tab_switching, tab_switch_start_state_->show_reason_unoccluded, tab_switch_start_state_->show_reason_bfcache_restore); } base::OnceCallback<void(const gfx::PresentationFeedback&)> ContentToVisibleTimeReporter::TabWasShown( bool has_saved_frames, base::TimeTicks event_start_time, bool destination_is_loaded, bool show_reason_tab_switching, bool show_reason_unoccluded, bool show_reason_bfcache_restore, base::TimeTicks widget_visibility_request_timestamp) { return TabWasShown( has_saved_frames, mojom::RecordContentToVisibleTimeRequest::New( event_start_time, destination_is_loaded, show_reason_tab_switching, show_reason_unoccluded, show_reason_bfcache_restore), widget_visibility_request_timestamp); } void ContentToVisibleTimeReporter::TabWasHidden() { if (tab_switch_start_state_) { RecordHistogramsAndTraceEvents(true /* is_incomplete */, true /* show_reason_tab_switching */, false /* show_reason_unoccluded */, false /* show_reason_bfcache_restore */, gfx::PresentationFeedback::Failure()); weak_ptr_factory_.InvalidateWeakPtrs(); } } void ContentToVisibleTimeReporter::RecordHistogramsAndTraceEvents( bool is_incomplete, bool show_reason_tab_switching, bool show_reason_unoccluded, bool show_reason_bfcache_restore, const gfx::PresentationFeedback& feedback) { DCHECK(tab_switch_start_state_); DCHECK(!widget_visibility_request_timestamp_.is_null()); // If the DCHECK fail, make sure RenderWidgetHostImpl::WasShown was triggered // for recording the event. DCHECK(show_reason_bfcache_restore || show_reason_unoccluded || show_reason_tab_switching); if (show_reason_bfcache_restore) { RecordBackForwardCacheRestoreMetric( tab_switch_start_state_->event_start_time, feedback); } if (show_reason_unoccluded) { ReportUnOccludedMetric(tab_switch_start_state_->event_start_time, feedback); } if (!show_reason_tab_switching) return; // Tab switching has occurred. auto tab_switch_result = TabSwitchResult::kSuccess; if (is_incomplete) tab_switch_result = TabSwitchResult::kIncomplete; else if (feedback.flags & gfx::PresentationFeedback::kFailure) tab_switch_result = TabSwitchResult::kPresentationFailure; const auto tab_switch_duration = feedback.timestamp - tab_switch_start_state_->event_start_time; // Record trace events. TRACE_EVENT_NESTABLE_ASYNC_BEGIN_WITH_TIMESTAMP0( "latency", "TabSwitching::Latency", TRACE_ID_LOCAL(g_num_trace_events_in_process), tab_switch_start_state_->event_start_time); TRACE_EVENT_NESTABLE_ASYNC_END_WITH_TIMESTAMP2( "latency", "TabSwitching::Latency", TRACE_ID_LOCAL(g_num_trace_events_in_process), feedback.timestamp, "result", tab_switch_result, "latency", tab_switch_duration.InMillisecondsF()); ++g_num_trace_events_in_process; const char* suffix = GetHistogramSuffix(has_saved_frames_, *tab_switch_start_state_); // Record result histogram. if (is_tab_switch_metric2_feature_enabled_) { base::UmaHistogramEnumeration( base::StrCat({"Browser.Tabs.TabSwitchResult2.", suffix}), tab_switch_result); } else { base::UmaHistogramEnumeration( base::StrCat({"Browser.Tabs.TabSwitchResult.", suffix}), tab_switch_result); } // Record latency histogram. switch (tab_switch_result) { case TabSwitchResult::kSuccess: { if (is_tab_switch_metric2_feature_enabled_) { base::UmaHistogramTimes( base::StrCat({"Browser.Tabs.TotalSwitchDuration2.", suffix}), tab_switch_duration); } else { base::UmaHistogramTimes( base::StrCat({"Browser.Tabs.TotalSwitchDuration.", suffix}), tab_switch_duration); } break; } case TabSwitchResult::kIncomplete: { if (is_tab_switch_metric2_feature_enabled_) { base::UmaHistogramTimes( base::StrCat( {"Browser.Tabs.TotalIncompleteSwitchDuration2.", suffix}), tab_switch_duration); } else { base::UmaHistogramTimes( base::StrCat( {"Browser.Tabs.TotalIncompleteSwitchDuration.", suffix}), tab_switch_duration); } break; } case TabSwitchResult::kPresentationFailure: { break; } } // Record legacy latency histogram. UMA_HISTOGRAM_TIMES( "MPArch.RWH_TabSwitchPaintDuration", feedback.timestamp - widget_visibility_request_timestamp_); // Reset tab switch information. has_saved_frames_ = false; tab_switch_start_state_.reset(); widget_visibility_request_timestamp_ = base::TimeTicks(); } } // namespace blink
nwjs/chromium.src
third_party/blink/common/page/content_to_visible_time_reporter.cc
C++
bsd-3-clause
9,156
#!/usr/bin/env python """ # Software License Agreement (BSD License) # # Copyright (c) 2012, University of California, Berkeley # All rights reserved. # Authors: Cameron Lee (cameronlee@berkeley.edu) and Dmitry Berenson ( berenson@eecs.berkeley.edu) # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of University of California, Berkeley nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ """ This node advertises an action which is used by the main lightning node (see run_lightning.py) to run the Retrieve and Repair portion of LightningROS. This node relies on a planner_stoppable type node to repair the paths, the PathTools library to retrieve paths from the library (this is not a separate node; just a python library that it calls), and the PathTools python library which calls the collision_checker service and advertises a topic for displaying stuff in RViz. """ import roslib import rospy import actionlib import threading from tools.PathTools import PlanTrajectoryWrapper, InvalidSectionWrapper, DrawPointsWrapper from pathlib.PathLibrary import * from lightning.msg import Float64Array, RRAction, RRResult from lightning.msg import StopPlanning, RRStats from lightning.srv import ManagePathLibrary, ManagePathLibraryResponse import sys import pickle import time # Name of this node. RR_NODE_NAME = "rr_node" # Name to use for stopping the repair planner. Published from this node. STOP_PLANNER_NAME = "stop_rr_planning" # Topic to subscribe to for stopping the whole node in the middle of processing. STOP_RR_NAME = "stop_all_rr" # Name of library managing service run from this node. MANAGE_LIBRARY = "manage_path_library" STATE_RETRIEVE, STATE_REPAIR, STATE_RETURN_PATH, STATE_FINISHED, STATE_FINISHED = (0, 1, 2, 3, 4) class RRNode: def __init__(self): # Retrieve ROS parameters and configuration and cosntruct various objects. self.robot_name = rospy.get_param("robot_name") self.planner_config_name = rospy.get_param("planner_config_name") self.current_joint_names = [] self.current_group_name = "" self.plan_trajectory_wrapper = PlanTrajectoryWrapper("rr", int(rospy.get_param("~num_rr_planners"))) self.invalid_section_wrapper = InvalidSectionWrapper() self.path_library = PathLibrary(rospy.get_param("~path_library_dir"), rospy.get_param("step_size"), node_size=int(rospy.get_param("~path_library_path_node_size")), sg_node_size=int(rospy.get_param("~path_library_sg_node_size")), dtw_dist=float(rospy.get_param("~dtw_distance"))) self.num_paths_checked = int(rospy.get_param("~num_paths_to_collision_check")) self.stop_lock = threading.Lock() self.stop = True self.rr_server = actionlib.SimpleActionServer(RR_NODE_NAME, RRAction, execute_cb=self._retrieve_repair, auto_start=False) self.rr_server.start() self.stop_rr_subscriber = rospy.Subscriber(STOP_RR_NAME, StopPlanning, self._stop_rr_planner) self.stop_rr_planner_publisher = rospy.Publisher(STOP_PLANNER_NAME, StopPlanning, queue_size=10) self.manage_library_service = rospy.Service(MANAGE_LIBRARY, ManagePathLibrary, self._do_manage_action) self.stats_pub = rospy.Publisher("rr_stats", RRStats, queue_size=10) self.repaired_sections_lock = threading.Lock() self.repaired_sections = [] self.working_lock = threading.Lock() #to ensure that node is not doing RR and doing a library management action at the same time #if draw_points is True, then display points in rviz self.draw_points = rospy.get_param("draw_points") if self.draw_points: self.draw_points_wrapper = DrawPointsWrapper() def _set_repaired_section(self, index, section): """ After you have done the path planning to repair a section, store the repaired path section. Args: index (int): the index corresponding to the section being repaired. section (path, list of list of float): A path to store. """ self.repaired_sections_lock.acquire() self.repaired_sections[index] = section self.repaired_sections_lock.release() def _call_planner(self, start, goal, planning_time): """ Calls a standard planner to plan between two points with an allowed planning time. Args: start (list of float): A joint configuration corresponding to the start position of the path. goal (list of float): The jount configuration corresponding to the goal position for the path. Returns: path: A list of joint configurations corresponding to the planned path. """ ret = None planner_number = self.plan_trajectory_wrapper.acquire_planner() if not self._need_to_stop(): ret = self.plan_trajectory_wrapper.plan_trajectory(start, goal, planner_number, self.current_joint_names, self.current_group_name, planning_time, self.planner_config_name) self.plan_trajectory_wrapper.release_planner(planner_number) return ret def _repair_thread(self, index, start, goal, start_index, goal_index, planning_time): """ Handles repairing a portion of the path. All that this function really does is to plan from scratch between the start and goal configurations and then store the planned path in the appropriate places and draws either the repaired path or, if the repair fails, the start and goal. Args: index (int): The index to pass to _set_repaired_section(), corresponding to which of the invalid sections of the path we are repairing. start (list of float): The start joint configuration to use. goal (list of float): The goal joint configuration to use. start_index (int): The index in the overall path corresponding to start. Only used for debugging info. goal_index (int): The index in the overall path corresponding to goal. Only used for debugging info. planning_time (float): Maximum allowed time to spend planning, in seconds. """ repaired_path = self._call_planner(start, goal, planning_time) if self.draw_points: if repaired_path is not None and len(repaired_path) > 0: rospy.loginfo("RR action server: got repaired section with start = %s, goal = %s" % (repaired_path[0], repaired_path[-1])) self.draw_points_wrapper.draw_points(repaired_path, self.current_group_name, "repaired"+str(start_index)+"_"+str(goal_index), DrawPointsWrapper.ANGLES, DrawPointsWrapper.GREENBLUE, 1.0, 0.01) else: if self.draw_points: rospy.loginfo("RR action server: path repair for section (%i, %i) failed, start = %s, goal = %s" % (start_index, goal_index, start, goal)) self.draw_points_wrapper.draw_points([start, goal], self.current_group_name, "failed_repair"+str(start_index)+"_"+str(goal_index), DrawPointsWrapper.ANGLES, DrawPointsWrapper.GREENBLUE, 1.0) if self._need_to_stop(): self._set_repaired_section(index, None) else: self._set_repaired_section(index, repaired_path) def _need_to_stop(self): self.stop_lock.acquire(); ret = self.stop; self.stop_lock.release(); return ret; def _set_stop_value(self, val): self.stop_lock.acquire(); self.stop = val; self.stop_lock.release(); def do_retrieved_path_drawing(self, projected, retrieved, invalid): """ Draws the points from the various paths involved in the planning in different colors in different namespaces. All of the arguments are lists of joint configurations, where each joint configuration is a list of joint angles. The only distinction between the different arguments being passed in are which color the points in question are being drawn in. Uses the DrawPointsWrapper to draw the points. Args: projected (list of list of float): List of points to draw as projected between the library path and the actual start/goal position. Will be drawn in blue. retrieved (list of list of float): The path retrieved straight from the path library. Will be drawn in white. invalid (list of list of float): List of points which were invalid. Will be drawn in red. """ if len(projected) > 0: if self.draw_points: self.draw_points_wrapper.draw_points(retrieved, self.current_group_name, "retrieved", DrawPointsWrapper.ANGLES, DrawPointsWrapper.WHITE, 0.1) projectionDisplay = projected[:projected.index(retrieved[0])]+projected[projected.index(retrieved[-1])+1:] self.draw_points_wrapper.draw_points(projectionDisplay, self.current_group_name, "projection", DrawPointsWrapper.ANGLES, DrawPointsWrapper.BLUE, 0.2) invalidDisplay = [] for invSec in invalid: invalidDisplay += projected[invSec[0]+1:invSec[-1]] self.draw_points_wrapper.draw_points(invalidDisplay, self.current_group_name, "invalid", DrawPointsWrapper.ANGLES, DrawPointsWrapper.RED, 0.2) def _retrieve_repair(self, action_goal): """ Callback which performs the full Retrieve and Repair for the path. """ self.working_lock.acquire() self.start_time = time.time() self.stats_msg = RRStats() self._set_stop_value(False) if self.draw_points: self.draw_points_wrapper.clear_points() rospy.loginfo("RR action server: RR got an action goal") s, g = action_goal.start, action_goal.goal res = RRResult() res.status.status = res.status.FAILURE self.current_joint_names = action_goal.joint_names self.current_group_name = action_goal.group_name projected, retrieved, invalid = [], [], [] repair_state = STATE_RETRIEVE self.stats_msg.init_time = time.time() - self.start_time # Go through the retrieve, repair, and return stages of the planning. # The while loop should only ever go through 3 iterations, one for each # stage. while not self._need_to_stop() and repair_state != STATE_FINISHED: if repair_state == STATE_RETRIEVE: start_retrieve = time.time() projected, retrieved, invalid = self.path_library.retrieve_path(s, g, self.num_paths_checked, self.robot_name, self.current_group_name, self.current_joint_names) self.stats_msg.retrieve_time.append(time.time() - start_retrieve) if len(projected) == 0: rospy.loginfo("RR action server: got an empty path for retrieve state") repair_state = STATE_FINISHED else: start_draw = time.time() if self.draw_points: self.do_retrieved_path_drawing(projected, retrieved, invalid) self.stats_msg.draw_time.append(time.time() - start_draw) repair_state = STATE_REPAIR elif repair_state == STATE_REPAIR: start_repair = time.time() repaired = self._path_repair(projected, action_goal.allowed_planning_time.to_sec(), invalid_sections=invalid) self.stats_msg.repair_time.append(time.time() - start_repair) if repaired is None: rospy.loginfo("RR action server: path repair didn't finish") repair_state = STATE_FINISHED else: repair_state = STATE_RETURN_PATH elif repair_state == STATE_RETURN_PATH: start_return = time.time() res.status.status = res.status.SUCCESS res.retrieved_path = [Float64Array(p) for p in retrieved] res.repaired_path = [Float64Array(p) for p in repaired] rospy.loginfo("RR action server: returning a path") repair_state = STATE_FINISHED self.stats_msg.return_time = time.time() - start_return if repair_state == STATE_RETRIEVE: rospy.loginfo("RR action server: stopped before it retrieved a path") elif repair_state == STATE_REPAIR: rospy.loginfo("RR action server: stopped before it could repair a retrieved path") elif repair_state == STATE_RETURN_PATH: rospy.loginfo("RR action server: stopped before it could return a repaired path") self.rr_server.set_succeeded(res) self.stats_msg.total_time = time.time() - self.start_time self.stats_pub.publish(self.stats_msg) self.working_lock.release() def _path_repair(self, original_path, planning_time, invalid_sections=None, use_parallel_repairing=True): """ Goes through each invalid section in a path and calls a planner to repair it, with the potential for multi-threading. Returns the repaired path. Args: original_path (path): The original path which needs repairing. planning_time (float): The maximum allowed planning time for each repair, in seconds. invalid_sections (list of pairs of indicies): The pairs of indicies describing the invalid sections. If None, then the invalid sections will be computed by this function. use_parallel_repairing (bool): Whether or not to use multi-threading. Returns: path: The repaired path. """ zeros_tuple = tuple([0 for i in xrange(len(self.current_joint_names))]) rospy.loginfo("RR action server: got path with %d points" % len(original_path)) if invalid_sections is None: invalid_sections = self.invalid_section_wrapper.getInvalidSectionsForPath(original_path, self.current_group_name) rospy.loginfo("RR action server: invalid sections: %s" % (str(invalid_sections))) if len(invalid_sections) > 0: if invalid_sections[0][0] == -1: rospy.loginfo("RR action server: Start is not a valid state...nothing can be done") return None if invalid_sections[-1][1] == len(original_path): rospy.loginfo("RR action server: Goal is not a valid state...nothing can be done") return None if use_parallel_repairing: #multi-threaded repairing self.repaired_sections = [None for i in xrange(len(invalid_sections))] #each thread replans an invalid section threadList = [] for i, sec in enumerate(invalid_sections): th = threading.Thread(target=self._repair_thread, args=(i, original_path[sec[0]], original_path[sec[-1]], sec[0], sec[-1], planning_time)) threadList.append(th) th.start() for th in threadList: th.join() #once all threads return, then the repaired sections can be combined for item in self.repaired_sections: if item is None: rospy.loginfo("RR action server: RR node was stopped during repair or repair failed") return None #replace invalid sections with replanned sections new_path = original_path[0:invalid_sections[0][0]] for i in xrange(len(invalid_sections)): new_path += self.repaired_sections[i] if i+1 < len(invalid_sections): new_path += original_path[invalid_sections[i][1]+1:invalid_sections[i+1][0]] new_path += original_path[invalid_sections[-1][1]+1:] self.repaired_sections = [] #reset repaired_sections else: #single-threaded repairing rospy.loginfo("RR action server: Got invalid sections: %s" % str(invalid_sections)) new_path = original_path[0:invalid_sections[0][0]] for i in xrange(len(invalid_sections)): if not self._need_to_stop(): #start_invalid and end_invalid must correspond to valid states when passed to the planner start_invalid, end_invalid = invalid_sections[i] rospy.loginfo("RR action server: Requesting path to replace from %d to %d" % (start_invalid, end_invalid)) repairedSection = self._call_planner(original_path[start_invalid], original_path[end_invalid]) if repairedSection is None: rospy.loginfo("RR action server: RR section repair was stopped or failed") return None rospy.loginfo("RR action server: Planner returned a trajectory of %d points for %d to %d" % (len(repairedSection), start_invalid, end_invalid)) new_path += repairedSection if i+1 < len(invalid_sections): new_path += original_path[end_invalid+1:invalid_sections[i+1][0]] else: rospy.loginfo("RR action server: RR was stopped while it was repairing the retrieved path") return None new_path += original_path[invalid_sections[-1][1]+1:] rospy.loginfo("RR action server: Trajectory after replan has %d points" % len(new_path)) else: new_path = original_path rospy.loginfo("RR action server: new trajectory has %i points" % (len(new_path))) return new_path def _stop_rr_planner(self, msg): self._set_stop_value(True) rospy.loginfo("RR action server: RR node got a stop message") self.stop_rr_planner_publisher.publish(msg) def _do_manage_action(self, request): """ Processes a ManagePathLibraryRequest as part of the ManagePathLibrary service. Basically, either stores a path in the library or deletes it. """ response = ManagePathLibraryResponse() response.result = response.FAILURE if request.robot_name == "" or len(request.joint_names) == 0: rospy.logerr("RR action server: robot name or joint names were not provided") return response self.working_lock.acquire() if request.action == request.ACTION_STORE: rospy.loginfo("RR action server: got a path to store in path library") if len(request.path_to_store) > 0: new_path = [p.positions for p in request.path_to_store] if len(request.retrieved_path) == 0: #PFS won so just store the path store_path_result = self.path_library.store_path(new_path, request.robot_name, request.joint_names) else: store_path_result = self.path_library.store_path(new_path, request.robot_name, request.joint_names, [p.positions for p in request.retrieved_path]) response.result = response.SUCCESS response.path_stored, response.num_library_paths = store_path_result else: response.message = "Path to store had no points" elif request.action == request.ACTION_DELETE_PATH: rospy.loginfo("RR action server: got a request to delete path %i in the path library" % (request.delete_id)) if self.path_library.delete_path_by_id(request.delete_id, request.robot_name, request.joint_names): response.result = response.SUCCESS else: response.message = "No path in the library had id %i" % (request.delete_id) elif request.action == request.ACTION_DELETE_LIBRARY: rospy.loginfo("RR action server: got a request to delete library corresponding to robot %s and joints %s" % (request.robot_name, request.joint_names)) if self.path_library.delete_library(request.robot_name, request.joint_names): response.result = response.SUCCESS else: response.message = "No library corresponding to robot %s and joint names %s exists" else: rospy.logerr("RR action server: manage path library request did not have a valid action set") self.working_lock.release() return response if __name__ == "__main__": try: rospy.init_node("rr_node") RRNode() rospy.loginfo("Retrieve-repair: ready") rospy.spin() except rospy.ROSInterruptException: pass
WPI-ARC/lightning_ros
scripts/RR_action_server.py
Python
bsd-3-clause
22,385
package de.uni.freiburg.iig.telematik.sewol.accesscontrol.rbac.lattice.graphic; import org.apache.commons.collections15.Factory; import edu.uci.ics.jung.graph.Graph; import edu.uci.ics.jung.graph.SparseMultigraph; public class RoleGraphViewer { Graph<Integer, String> g; int nodeCount, edgeCount; Factory<Integer> vertexFactory; Factory<String> edgeFactory; /** Creates a new instance of SimpleGraphView */ public RoleGraphViewer() { // Graph<V, E> where V is the type of the vertices and E is the type of // the edges g = new SparseMultigraph<Integer, String>(); nodeCount = 0; edgeCount = 0; vertexFactory = new Factory<Integer>() { // My vertex factory public Integer create() { return nodeCount++; } }; edgeFactory = new Factory<String>() { // My edge factory public String create() { return "E" + edgeCount++; } }; } }
iig-uni-freiburg/SEWOL
src/de/uni/freiburg/iig/telematik/sewol/accesscontrol/rbac/lattice/graphic/RoleGraphViewer.java
Java
bsd-3-clause
874
/** * @author */ imports("Controls.Composite.Carousel"); using("System.Fx.Marquee"); var Carousel = Control.extend({ onChange: function (e) { var ul = this.find('.x-carousel-header'), t; if (t = ul.first(e.from)) t.removeClass('x-carousel-header-selected'); if(t = ul.first(e.to)) t.addClass('x-carousel-header-selected'); }, init: function (options) { var me = this; me.marquee = new Marquee(me, options.direction, options.loop, options.deferUpdate); if (options.duration != null) me.marquee.duration = options.duration; if (options.delay != null) me.marquee.delay = options.delay; me.marquee.on('changing', me.onChange, me); me.query('.x-carousel-header > li').setWidth(me.getWidth() / me.marquee.length).on(options.event || 'mouseover', function (e) { me.marquee.moveTo(this.index()); }); me.onChange({to: 0}); me.marquee.start(); } }).defineMethods("marquee", "moveTo moveBy start stop");
jplusui/jplusui-en
src/Controls/Composite/assets/scripts/Carousel.js
JavaScript
bsd-3-clause
994
#!/usr/bin/env python from django.core.management import setup_environ import settings setup_environ(settings) import socket from trivia.models import * irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) irc.connect((settings.IRC_SERVER, settings.IRC_PORT)) def send(msg): irc.send(msg + "\r\n") print "{SENT} " + msg return def msg(user, msg): send("PRIVMSG " + user + " :" + msg) return def processline(line): parts = line.split(' :',1) args = parts[0].split(' ') if (len(parts) > 1): args.append(parts[1]) if args[0] == "PING": send("PONG :" + args[1]) return try: if args[3] == "!questions": questions = str(Question.objects.all()) msg(args[2], questions) return except IndexError: return # When we're done, remember to return. return send("USER " + (settings.IRC_NICKNAME + " ")*4) send("NICK " + settings.IRC_NICKNAME) for channel in settings.IRC_CHANNELS: send("JOIN " + channel) while True: # EXIST line = irc.recv(1024).rstrip() if "\r\n" in line: linesep = line.split() for l in linesep: processline(l) continue processline(line)
relrod/pib
bot.py
Python
bsd-3-clause
1,205
/// <reference path="../../src/CaseModel.ts" /> /// <reference path="../../src/CaseViewer.ts" /> /// <reference path="../../src/PlugInManager.ts" /> class AnnotationPlugIn extends AssureIt.PlugInSet { constructor(public plugInManager: AssureIt.PlugInManager) { super(plugInManager); this.HTMLRenderPlugIn = new AnnotationHTMLRenderPlugIn(plugInManager); } } class AnnotationHTMLRenderPlugIn extends AssureIt.HTMLRenderPlugIn { IsEnabled(caseViewer: AssureIt.CaseViewer, caseModel: AssureIt.NodeModel) : boolean { return true; } Delegate(caseViewer: AssureIt.CaseViewer, caseModel: AssureIt.NodeModel, element: JQuery) : boolean { if(caseModel.Annotations.length == 0) return; var text : string = ""; var p : {top: number; left: number} = element.position(); for(var i : number = 0; i < caseModel.Annotations.length; i++) { text += "@" + caseModel.Annotations[i].Name + "<br>"; } $('<div class="anno">' + '<p>' + text + '</p>' + '</div>') .css({position: 'absolute', 'font-size': 25, color: 'gray', top: p.top - 20, left: p.left + 80}).appendTo(element); return true; } }
assureit/AssureIt
plugins/Annotation/Annotation.ts
TypeScript
bsd-3-clause
1,118