repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
oTibia/UnderLight-AK47
|
data/actions/scripts/doors/window_open.lua
|
234
|
-- By Ricky Mesny
-- http://otfans.net/showthread.php?t=96955
function onUse(cid, item, frompos, item2, topos)
if not(House.getHouseByPos(frompos)) then
return false
end
doTransformItem(item.uid, item.itemid+2)
return true
end
|
gpl-2.0
|
DE-IBH/cmk_cisco-dom
|
perfometer/cisco_dom.py
|
1321
|
#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# cmk_cisco-dom - check-mk plugin for SNMP-based Cisco Digital-Optical-Monitoring monitoring
#
# Authors:
# Thomas Liske <liske@ibh.de>
#
# Copyright Holder:
# 2015 - 2016 (C) IBH IT-Service GmbH [http://www.ibh.de/]
#
# License:
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program 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 Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this package; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
def perfometer_cisco_dom(row, check_command, perf_data):
color = { 0: "#a4f", 1: "#ff2", 2: "#f22", 3: "#fa2" }[row["service_state"]]
return "%.1f dBm" % perf_data[0][1], perfometer_logarithmic(perf_data[0][1] + 20, 20, 2, color)
perfometers["check_mk-cisco_dom"] = perfometer_cisco_dom
|
gpl-2.0
|
Jamesits/Moegram
|
TMessagesProj/src/main/java/org/telegram/messenger/NotificationDismissReceiver.java
|
833
|
/*
* This is the source code of Telegram for Android v. 5.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2018.
*/
package org.telegram.messenger;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class NotificationDismissReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent == null) {
return;
}
int currentAccount = intent.getIntExtra("currentAccount", UserConfig.selectedAccount);
MessagesController.getNotificationsSettings(currentAccount).edit().putInt("dismissDate", intent.getIntExtra("messageDate", 0)).commit();
}
}
|
gpl-2.0
|
seppeduwe/cocct
|
src/main/java/sir/barchable/clash/protocol/ProtocolTool.java
|
3388
|
package sir.barchable.clash.protocol;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sir.barchable.clash.ResourceException;
import sir.barchable.util.Json;
import java.io.*;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
* Read and write Protocol json.
*
* @author Sir Barchable
* Date: 6/04/15
*/
public class ProtocolTool {
@Parameter(names = {"-d", "--definition-dir"}, required = true, description = "Directory to load the protocol definition from")
private File resourceDir;
@Parameter(names = {"-o", "--outfile"}, description = "Output file. Will write to stdout if not set")
private File outFile;
private static final Logger log = LoggerFactory.getLogger(ProtocolTool.class);
public static void main(String[] args) {
ProtocolTool tool = new ProtocolTool();
JCommander commander = new JCommander(tool);
try {
commander.parse(args);
tool.run();
} catch (ParameterException e) {
commander.usage();
} catch (Exception e) {
log.error("Oops: ", e);
}
}
ProtocolTool() { }
public ProtocolTool(File resourceDir) {
this.resourceDir = resourceDir;
}
private void run() throws IOException {
if (!resourceDir.exists() || !resourceDir.isDirectory()) {
throw new FileNotFoundException(resourceDir.toString());
} else {
OutputStreamWriter out;
if (outFile == null) {
out = new OutputStreamWriter(System.out);
} else {
out = new OutputStreamWriter(new FileOutputStream(outFile), UTF_8);
}
try {
write(read(), out);
} finally {
out.close();
}
}
}
/**
* Read a collection of message definitions from a directory.
*
* @return a protocol definition
*/
public Protocol read() throws IOException {
if (!resourceDir.exists()) {
throw new FileNotFoundException(resourceDir.toString());
}
List<Protocol.StructDefinition> definitions = new ArrayList<>();
log.info("Reading protocol definition from {}", resourceDir.getAbsolutePath());
Files.walk(resourceDir.toPath())
.filter(path -> path.toString().endsWith(".json"))
.forEach(path -> {
try {
definitions.add(Json.read(path.toFile(), Protocol.StructDefinition.class));
} catch (IOException e) {
throw new ResourceException("Could not read definition file " + path.getFileName(), e);
}
});
if (definitions.size() == 0) {
throw new IOException("Protocol definition not found in " + resourceDir);
}
return new Protocol(definitions);
}
/**
* Write a protocol definition out as json.
*
* @param protocol the definition
* @param out where to write the definition
*/
public void write(Protocol protocol, Writer out) throws IOException {
Json.writePretty(protocol, out);
}
}
|
gpl-2.0
|
openkm/document-management-system
|
src/main/java/com/openkm/frontend/client/extension/event/handler/WorkspaceHandlerExtension.java
|
1275
|
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2017 Paco Avila & Josep Llort
* <p>
* No bytes were intentionally harmed during the development of this application.
* <p>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* <p>
* This program 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 Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.frontend.client.extension.event.handler;
import com.openkm.frontend.client.extension.event.HasWorkspaceEvent.WorkspaceEventConstant;
/**
* WorkspaceHandlerExtension
*
* @author jllort
*
*/
public interface WorkspaceHandlerExtension {
public abstract void onChange(WorkspaceEventConstant event);
}
|
gpl-2.0
|
jameswatt2008/jameswatt2008.github.io
|
python/Pythonๆ ธๅฟ็ผ็จ/็ฝ็ป็ผ็จ/ๆชๅพๅไปฃ็ /ๆฆ่ฟฐใSOCKET/ๅค่ฟ็จcopyๆไปถ/test-ๅคไปถ/traceback.py
|
22194
|
"""Extract, format and print information about Python stack traces."""
import collections
import itertools
import linecache
import sys
__all__ = ['extract_stack', 'extract_tb', 'format_exception',
'format_exception_only', 'format_list', 'format_stack',
'format_tb', 'print_exc', 'format_exc', 'print_exception',
'print_last', 'print_stack', 'print_tb', 'clear_frames',
'FrameSummary', 'StackSummary', 'TracebackException',
'walk_stack', 'walk_tb']
#
# Formatting and printing lists of traceback lines.
#
def print_list(extracted_list, file=None):
"""Print the list of tuples as returned by extract_tb() or
extract_stack() as a formatted stack trace to the given file."""
if file is None:
file = sys.stderr
for item in StackSummary.from_list(extracted_list).format():
print(item, file=file, end="")
def format_list(extracted_list):
"""Format a list of traceback entry tuples for printing.
Given a list of tuples as returned by extract_tb() or
extract_stack(), return a list of strings ready for printing.
Each string in the resulting list corresponds to the item with the
same index in the argument list. Each string ends in a newline;
the strings may contain internal newlines as well, for those items
whose source text line is not None.
"""
return StackSummary.from_list(extracted_list).format()
#
# Printing and Extracting Tracebacks.
#
def print_tb(tb, limit=None, file=None):
"""Print up to 'limit' stack trace entries from the traceback 'tb'.
If 'limit' is omitted or None, all entries are printed. If 'file'
is omitted or None, the output goes to sys.stderr; otherwise
'file' should be an open file or file-like object with a write()
method.
"""
print_list(extract_tb(tb, limit=limit), file=file)
def format_tb(tb, limit=None):
"""A shorthand for 'format_list(extract_tb(tb, limit))'."""
return extract_tb(tb, limit=limit).format()
def extract_tb(tb, limit=None):
"""Return list of up to limit pre-processed entries from traceback.
This is useful for alternate formatting of stack traces. If
'limit' is omitted or None, all entries are extracted. A
pre-processed stack trace entry is a quadruple (filename, line
number, function name, text) representing the information that is
usually printed for a stack trace. The text is a string with
leading and trailing whitespace stripped; if the source is not
available it is None.
"""
return StackSummary.extract(walk_tb(tb), limit=limit)
#
# Exception formatting and output.
#
_cause_message = (
"\nThe above exception was the direct cause "
"of the following exception:\n\n")
_context_message = (
"\nDuring handling of the above exception, "
"another exception occurred:\n\n")
def print_exception(etype, value, tb, limit=None, file=None, chain=True):
"""Print exception up to 'limit' stack trace entries from 'tb' to 'file'.
This differs from print_tb() in the following ways: (1) if
traceback is not None, it prints a header "Traceback (most recent
call last):"; (2) it prints the exception type and value after the
stack trace; (3) if type is SyntaxError and value has the
appropriate format, it prints the line where the syntax error
occurred with a caret on the next line indicating the approximate
position of the error.
"""
# format_exception has ignored etype for some time, and code such as cgitb
# passes in bogus values as a result. For compatibility with such code we
# ignore it here (rather than in the new TracebackException API).
if file is None:
file = sys.stderr
for line in TracebackException(
type(value), value, tb, limit=limit).format(chain=chain):
print(line, file=file, end="")
def format_exception(etype, value, tb, limit=None, chain=True):
"""Format a stack trace and the exception information.
The arguments have the same meaning as the corresponding arguments
to print_exception(). The return value is a list of strings, each
ending in a newline and some containing internal newlines. When
these lines are concatenated and printed, exactly the same text is
printed as does print_exception().
"""
# format_exception has ignored etype for some time, and code such as cgitb
# passes in bogus values as a result. For compatibility with such code we
# ignore it here (rather than in the new TracebackException API).
return list(TracebackException(
type(value), value, tb, limit=limit).format(chain=chain))
def format_exception_only(etype, value):
"""Format the exception part of a traceback.
The arguments are the exception type and value such as given by
sys.last_type and sys.last_value. The return value is a list of
strings, each ending in a newline.
Normally, the list contains a single string; however, for
SyntaxError exceptions, it contains several lines that (when
printed) display detailed information about where the syntax
error occurred.
The message indicating which exception occurred is always the last
string in the list.
"""
return list(TracebackException(etype, value, None).format_exception_only())
# -- not official API but folk probably use these two functions.
def _format_final_exc_line(etype, value):
valuestr = _some_str(value)
if value == 'None' or value is None or not valuestr:
line = "%s\n" % etype
else:
line = "%s: %s\n" % (etype, valuestr)
return line
def _some_str(value):
try:
return str(value)
except:
return '<unprintable %s object>' % type(value).__name__
# --
def print_exc(limit=None, file=None, chain=True):
"""Shorthand for 'print_exception(*sys.exc_info(), limit, file)'."""
print_exception(*sys.exc_info(), limit=limit, file=file, chain=chain)
def format_exc(limit=None, chain=True):
"""Like print_exc() but return a string."""
return "".join(format_exception(*sys.exc_info(), limit=limit, chain=chain))
def print_last(limit=None, file=None, chain=True):
"""This is a shorthand for 'print_exception(sys.last_type,
sys.last_value, sys.last_traceback, limit, file)'."""
if not hasattr(sys, "last_type"):
raise ValueError("no last exception")
print_exception(sys.last_type, sys.last_value, sys.last_traceback,
limit, file, chain)
#
# Printing and Extracting Stacks.
#
def print_stack(f=None, limit=None, file=None):
"""Print a stack trace from its invocation point.
The optional 'f' argument can be used to specify an alternate
stack frame at which to start. The optional 'limit' and 'file'
arguments have the same meaning as for print_exception().
"""
if f is None:
f = sys._getframe().f_back
print_list(extract_stack(f, limit=limit), file=file)
def format_stack(f=None, limit=None):
"""Shorthand for 'format_list(extract_stack(f, limit))'."""
if f is None:
f = sys._getframe().f_back
return format_list(extract_stack(f, limit=limit))
def extract_stack(f=None, limit=None):
"""Extract the raw traceback from the current stack frame.
The return value has the same format as for extract_tb(). The
optional 'f' and 'limit' arguments have the same meaning as for
print_stack(). Each item in the list is a quadruple (filename,
line number, function name, text), and the entries are in order
from oldest to newest stack frame.
"""
if f is None:
f = sys._getframe().f_back
stack = StackSummary.extract(walk_stack(f), limit=limit)
stack.reverse()
return stack
def clear_frames(tb):
"Clear all references to local variables in the frames of a traceback."
while tb is not None:
try:
tb.tb_frame.clear()
except RuntimeError:
# Ignore the exception raised if the frame is still executing.
pass
tb = tb.tb_next
class FrameSummary:
"""A single frame from a traceback.
- :attr:`filename` The filename for the frame.
- :attr:`lineno` The line within filename for the frame that was
active when the frame was captured.
- :attr:`name` The name of the function or method that was executing
when the frame was captured.
- :attr:`line` The text from the linecache module for the
of code that was running when the frame was captured.
- :attr:`locals` Either None if locals were not supplied, or a dict
mapping the name to the repr() of the variable.
"""
__slots__ = ('filename', 'lineno', 'name', '_line', 'locals')
def __init__(self, filename, lineno, name, *, lookup_line=True,
locals=None, line=None):
"""Construct a FrameSummary.
:param lookup_line: If True, `linecache` is consulted for the source
code line. Otherwise, the line will be looked up when first needed.
:param locals: If supplied the frame locals, which will be captured as
object representations.
:param line: If provided, use this instead of looking up the line in
the linecache.
"""
self.filename = filename
self.lineno = lineno
self.name = name
self._line = line
if lookup_line:
self.line
self.locals = \
dict((k, repr(v)) for k, v in locals.items()) if locals else None
def __eq__(self, other):
if isinstance(other, FrameSummary):
return (self.filename == other.filename and
self.lineno == other.lineno and
self.name == other.name and
self.locals == other.locals)
if isinstance(other, tuple):
return (self.filename, self.lineno, self.name, self.line) == other
return NotImplemented
def __getitem__(self, pos):
return (self.filename, self.lineno, self.name, self.line)[pos]
def __iter__(self):
return iter([self.filename, self.lineno, self.name, self.line])
def __repr__(self):
return "<FrameSummary file {filename}, line {lineno} in {name}>".format(
filename=self.filename, lineno=self.lineno, name=self.name)
@property
def line(self):
if self._line is None:
self._line = linecache.getline(self.filename, self.lineno).strip()
return self._line
def walk_stack(f):
"""Walk a stack yielding the frame and line number for each frame.
This will follow f.f_back from the given frame. If no frame is given, the
current stack is used. Usually used with StackSummary.extract.
"""
if f is None:
f = sys._getframe().f_back.f_back
while f is not None:
yield f, f.f_lineno
f = f.f_back
def walk_tb(tb):
"""Walk a traceback yielding the frame and line number for each frame.
This will follow tb.tb_next (and thus is in the opposite order to
walk_stack). Usually used with StackSummary.extract.
"""
while tb is not None:
yield tb.tb_frame, tb.tb_lineno
tb = tb.tb_next
class StackSummary(list):
"""A stack of frames."""
@classmethod
def extract(klass, frame_gen, *, limit=None, lookup_lines=True,
capture_locals=False):
"""Create a StackSummary from a traceback or stack object.
:param frame_gen: A generator that yields (frame, lineno) tuples to
include in the stack.
:param limit: None to include all frames or the number of frames to
include.
:param lookup_lines: If True, lookup lines for each frame immediately,
otherwise lookup is deferred until the frame is rendered.
:param capture_locals: If True, the local variables from each frame will
be captured as object representations into the FrameSummary.
"""
if limit is None:
limit = getattr(sys, 'tracebacklimit', None)
if limit is not None and limit < 0:
limit = 0
if limit is not None:
if limit >= 0:
frame_gen = itertools.islice(frame_gen, limit)
else:
frame_gen = collections.deque(frame_gen, maxlen=-limit)
result = klass()
fnames = set()
for f, lineno in frame_gen:
co = f.f_code
filename = co.co_filename
name = co.co_name
fnames.add(filename)
linecache.lazycache(filename, f.f_globals)
# Must defer line lookups until we have called checkcache.
if capture_locals:
f_locals = f.f_locals
else:
f_locals = None
result.append(FrameSummary(
filename, lineno, name, lookup_line=False, locals=f_locals))
for filename in fnames:
linecache.checkcache(filename)
# If immediate lookup was desired, trigger lookups now.
if lookup_lines:
for f in result:
f.line
return result
@classmethod
def from_list(klass, a_list):
"""Create a StackSummary from a simple list of tuples.
This method supports the older Python API. Each tuple should be a
4-tuple with (filename, lineno, name, line) elements.
"""
# While doing a fast-path check for isinstance(a_list, StackSummary) is
# appealing, idlelib.run.cleanup_traceback and other similar code may
# break this by making arbitrary frames plain tuples, so we need to
# check on a frame by frame basis.
result = StackSummary()
for frame in a_list:
if isinstance(frame, FrameSummary):
result.append(frame)
else:
filename, lineno, name, line = frame
result.append(FrameSummary(filename, lineno, name, line=line))
return result
def format(self):
"""Format the stack ready for printing.
Returns a list of strings ready for printing. Each string in the
resulting list corresponds to a single frame from the stack.
Each string ends in a newline; the strings may contain internal
newlines as well, for those items with source text lines.
"""
result = []
for frame in self:
row = []
row.append(' File "{}", line {}, in {}\n'.format(
frame.filename, frame.lineno, frame.name))
if frame.line:
row.append(' {}\n'.format(frame.line.strip()))
if frame.locals:
for name, value in sorted(frame.locals.items()):
row.append(' {name} = {value}\n'.format(name=name, value=value))
result.append(''.join(row))
return result
class TracebackException:
"""An exception ready for rendering.
The traceback module captures enough attributes from the original exception
to this intermediary form to ensure that no references are held, while
still being able to fully print or format it.
Use `from_exception` to create TracebackException instances from exception
objects, or the constructor to create TracebackException instances from
individual components.
- :attr:`__cause__` A TracebackException of the original *__cause__*.
- :attr:`__context__` A TracebackException of the original *__context__*.
- :attr:`__suppress_context__` The *__suppress_context__* value from the
original exception.
- :attr:`stack` A `StackSummary` representing the traceback.
- :attr:`exc_type` The class of the original traceback.
- :attr:`filename` For syntax errors - the filename where the error
occurred.
- :attr:`lineno` For syntax errors - the linenumber where the error
occurred.
- :attr:`text` For syntax errors - the text where the error
occurred.
- :attr:`offset` For syntax errors - the offset into the text where the
error occurred.
- :attr:`msg` For syntax errors - the compiler error message.
"""
def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
lookup_lines=True, capture_locals=False, _seen=None):
# NB: we need to accept exc_traceback, exc_value, exc_traceback to
# permit backwards compat with the existing API, otherwise we
# need stub thunk objects just to glue it together.
# Handle loops in __cause__ or __context__.
if _seen is None:
_seen = set()
_seen.add(exc_value)
# Gracefully handle (the way Python 2.4 and earlier did) the case of
# being called with no type or value (None, None, None).
if (exc_value and exc_value.__cause__ is not None
and exc_value.__cause__ not in _seen):
cause = TracebackException(
type(exc_value.__cause__),
exc_value.__cause__,
exc_value.__cause__.__traceback__,
limit=limit,
lookup_lines=False,
capture_locals=capture_locals,
_seen=_seen)
else:
cause = None
if (exc_value and exc_value.__context__ is not None
and exc_value.__context__ not in _seen):
context = TracebackException(
type(exc_value.__context__),
exc_value.__context__,
exc_value.__context__.__traceback__,
limit=limit,
lookup_lines=False,
capture_locals=capture_locals,
_seen=_seen)
else:
context = None
self.exc_traceback = exc_traceback
self.__cause__ = cause
self.__context__ = context
self.__suppress_context__ = \
exc_value.__suppress_context__ if exc_value else False
# TODO: locals.
self.stack = StackSummary.extract(
walk_tb(exc_traceback), limit=limit, lookup_lines=lookup_lines,
capture_locals=capture_locals)
self.exc_type = exc_type
# Capture now to permit freeing resources: only complication is in the
# unofficial API _format_final_exc_line
self._str = _some_str(exc_value)
if exc_type and issubclass(exc_type, SyntaxError):
# Handle SyntaxError's specially
self.filename = exc_value.filename
self.lineno = str(exc_value.lineno)
self.text = exc_value.text
self.offset = exc_value.offset
self.msg = exc_value.msg
if lookup_lines:
self._load_lines()
@classmethod
def from_exception(self, exc, *args, **kwargs):
"""Create a TracebackException from an exception."""
return TracebackException(
type(exc), exc, exc.__traceback__, *args, **kwargs)
def _load_lines(self):
"""Private API. force all lines in the stack to be loaded."""
for frame in self.stack:
frame.line
if self.__context__:
self.__context__._load_lines()
if self.__cause__:
self.__cause__._load_lines()
def __eq__(self, other):
return self.__dict__ == other.__dict__
def __str__(self):
return self._str
def format_exception_only(self):
"""Format the exception part of the traceback.
The return value is a generator of strings, each ending in a newline.
Normally, the generator emits a single string; however, for
SyntaxError exceptions, it emites several lines that (when
printed) display detailed information about where the syntax
error occurred.
The message indicating which exception occurred is always the last
string in the output.
"""
if self.exc_type is None:
yield _format_final_exc_line(None, self._str)
return
stype = self.exc_type.__qualname__
smod = self.exc_type.__module__
if smod not in ("__main__", "builtins"):
stype = smod + '.' + stype
if not issubclass(self.exc_type, SyntaxError):
yield _format_final_exc_line(stype, self._str)
return
# It was a syntax error; show exactly where the problem was found.
filename = self.filename or "<string>"
lineno = str(self.lineno) or '?'
yield ' File "{}", line {}\n'.format(filename, lineno)
badline = self.text
offset = self.offset
if badline is not None:
yield ' {}\n'.format(badline.strip())
if offset is not None:
caretspace = badline.rstrip('\n')
offset = min(len(caretspace), offset) - 1
caretspace = caretspace[:offset].lstrip()
# non-space whitespace (likes tabs) must be kept for alignment
caretspace = ((c.isspace() and c or ' ') for c in caretspace)
yield ' {}^\n'.format(''.join(caretspace))
msg = self.msg or "<no detail available>"
yield "{}: {}\n".format(stype, msg)
def format(self, *, chain=True):
"""Format the exception.
If chain is not *True*, *__cause__* and *__context__* will not be formatted.
The return value is a generator of strings, each ending in a newline and
some containing internal newlines. `print_exception` is a wrapper around
this method which just prints the lines to a file.
The message indicating which exception occurred is always the last
string in the output.
"""
if chain:
if self.__cause__ is not None:
yield from self.__cause__.format(chain=chain)
yield _cause_message
elif (self.__context__ is not None and
not self.__suppress_context__):
yield from self.__context__.format(chain=chain)
yield _context_message
if self.exc_traceback is not None:
yield 'Traceback (most recent call last):\n'
yield from self.stack.format()
yield from self.format_exception_only()
|
gpl-2.0
|
carleton/reasoncms
|
reason_4.0/lib/core/classes/admin/modules/copy_borrowing.php
|
3483
|
<?php
/**
* @package reason
* @subpackage admin
*/
/**
* Include the default module and other needed utilities
*/
reason_include_once('classes/admin/modules/default.php');
include_once( DISCO_INC . 'disco.php');
/**
* An administrative module that allows a use to select a site to borrow a given item into
*/
class CopyBorrowingModule extends DefaultModule
{
/**
* Constructor
* @param object admin page
* @return void
*/
function CopyBorrowingModule( &$page )
{
$this->admin_page =& $page;
}
/**
* Initialize the module
* @return void
*/
function init()
{
$this->admin_page->title = 'Copy Borrowing';
}
function get_all_sites()
{
static $sites;
if(!isset($sites))
{
$es = new entity_selector(id_of('master_admin'));
$es->add_type(id_of('site'));
$sites = $es->run_one();
}
return $sites;
}
function get_all_types()
{
static $types;
if(!isset($types))
{
$es = new entity_selector(id_of('master_admin'));
$es->add_type(id_of('type'));
$types = $es->run_one();
}
return $types;
}
function entities_to_options($entities)
{
$ret = array();
foreach($entities as $e)
{
$ret[$e->id()] = $e->get_value('name');
}
return $ret;
}
/**
* Run the module & produce output
* @return void
*/
function run()
{
if ($this->admin_page->site_id != id_of('master_admin'))
{
echo 'This tool can be run only in the context of the master admin';
return;
}
$site_options = $this->entities_to_options($this->get_all_sites());
$type_options = $this->entities_to_options($this->get_all_types());
$d = new Disco();
$d->set_box_class( 'StackedBox' );
$copy_from = ( $_REQUEST['site_to_copy_from'] ) ? intval( $_REQUEST['site_to_copy_from'] ) : null;
$copy_to = ( $_REQUEST['site_to_copy_to'] ) ? intval( $_REQUEST['site_to_copy_to'] ) : null;
$type_to_copy = ( $_REQUEST['type_to_copy'] ) ? intval( $_REQUEST['type_to_copy'] ) : null;
$d->add_element( 'site_to_copy_from', 'select', array( 'options' => $site_options, 'default' => $copy_from ) );
$d->add_element( 'site_to_copy_to', 'select', array( 'options' => $site_options, 'default' => $copy_to ) );
$d->add_element( 'type_to_copy', 'select', array( 'options' => $type_options, 'default' => $type_to_copy ) );
$d->add_required('site_to_copy_from');
$d->add_required('site_to_copy_to');
$d->add_required('type_to_copy');
$d->set_actions(array('copy'=>'Copy Borrowing Relationships'));
$d->add_callback(array($this,'process_borrow_form'), 'process');
$d->run();
}
function process_borrow_form($d)
{
$allowable_relationship_id = get_borrows_relationship_id($d->get_value('type_to_copy'));
$es = new entity_selector($d->get_value('site_to_copy_from'));
$es->add_type($d->get_value('type_to_copy'));
$es->set_sharing( 'borrows' );
$es->limit_tables();
$es->limit_fields();
$entity_ids = $es->get_ids();
$successes = array();
$failures = array();
foreach($entity_ids as $entity_id)
{
if( create_relationship( $d->get_value('site_to_copy_to'), $entity_id, $allowable_relationship_id) )
{
$successes[] = $entity_id;
}
else
{
$failures = $entity_id;
}
}
echo '<h3>Successfully copied over ' . count($successes) .' borrow relationships</h3>';
echo '<h3>Failed to copy over ' . count($failures) . ' borrow relationships</h3>';
}
}
|
gpl-2.0
|
MTuner/RiaCrawler
|
owasp-proxy/src/main/java/org/owasp/proxy/ajp/AJPConstants.java
|
7406
|
/*
* This file is part of the OWASP Proxy, a free intercepting proxy library.
* Copyright (C) 2008-2010 Rogan Dawes <rogan@dawes.za.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to:
* The Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
package org.owasp.proxy.ajp;
import java.util.HashMap;
import java.util.Map;
/**
* Taken almost directly from org.apache.coyote.ajp.Constants
*
*/
public class AJPConstants {
// Prefix codes for message types from server to container
public static final byte JK_AJP13_FORWARD_REQUEST = 2;
public static final byte JK_AJP13_SHUTDOWN = 7;
public static final byte JK_AJP13_PING_REQUEST = 8;
public static final byte JK_AJP13_CPING_REQUEST = 10;
// Prefix codes for message types from container to server
public static final byte JK_AJP13_SEND_BODY_CHUNK = 3;
public static final byte JK_AJP13_SEND_HEADERS = 4;
public static final byte JK_AJP13_END_RESPONSE = 5;
public static final byte JK_AJP13_GET_BODY_CHUNK = 6;
public static final byte JK_AJP13_CPONG_REPLY = 9;
// Integer codes for common response header strings
public static final int SC_RESP_CONTENT_TYPE = 0xA001;
public static final int SC_RESP_CONTENT_LANGUAGE = 0xA002;
public static final int SC_RESP_CONTENT_LENGTH = 0xA003;
public static final int SC_RESP_DATE = 0xA004;
public static final int SC_RESP_LAST_MODIFIED = 0xA005;
public static final int SC_RESP_LOCATION = 0xA006;
public static final int SC_RESP_SET_COOKIE = 0xA007;
public static final int SC_RESP_SET_COOKIE2 = 0xA008;
public static final int SC_RESP_SERVLET_ENGINE = 0xA009;
public static final int SC_RESP_STATUS = 0xA00A;
public static final int SC_RESP_WWW_AUTHENTICATE = 0xA00B;
public static final int SC_RESP_AJP13_MAX = 11;
// Integer codes for common (optional) request attribute names
public static final byte SC_A_CONTEXT = 1; // XXX Unused
public static final byte SC_A_SERVLET_PATH = 2; // XXX Unused
public static final byte SC_A_REMOTE_USER = 3;
public static final byte SC_A_AUTH_TYPE = 4;
public static final byte SC_A_QUERY_STRING = 5;
public static final byte SC_A_JVM_ROUTE = 6;
public static final byte SC_A_SSL_CERT = 7;
public static final byte SC_A_SSL_CIPHER = 8;
public static final byte SC_A_SSL_SESSION = 9;
public static final byte SC_A_SSL_KEYSIZE = 11;
public static final byte SC_A_SECRET = 12;
public static final byte SC_A_STORED_METHOD = 13;
// AJP14 new header
public static final byte SC_A_SSL_KEY_SIZE = 11; // XXX ???
// Used for attributes which are not in the list above
public static final byte SC_A_REQ_ATTRIBUTE = 10;
// Terminates list of attributes
public static final byte SC_A_ARE_DONE = (byte) 0xFF;
// Ajp13 specific - needs refactoring for the new model
/**
* Default maximum total byte size for a AJP packet
*/
public static final int MAX_PACKET_SIZE = 8192;
/**
* Size of basic packet header
*/
public static final int H_SIZE = 4;
/**
* Size of the header metadata
*/
public static final int READ_HEAD_LEN = 6;
public static final int SEND_HEAD_LEN = 8;
/**
* Default maximum size of data that can be sent in one packet
*/
public static final int MAX_READ_SIZE = MAX_PACKET_SIZE - READ_HEAD_LEN;
public static final int MAX_SEND_SIZE = MAX_PACKET_SIZE - SEND_HEAD_LEN;
// Translates integer codes to names of HTTP methods
private static final String[] requestMethods = { "OPTIONS", "GET", "HEAD",
"POST", "PUT", "DELETE", "TRACE", "PROPFIND", "PROPPATCH", "MKCOL",
"COPY", "MOVE", "LOCK", "UNLOCK", "ACL", "REPORT",
"VERSION-CONTROL", "CHECKIN", "CHECKOUT", "UNCHECKOUT", "SEARCH",
"MKWORKSPACE", "UPDATE", "LABEL", "MERGE", "BASELINE-CONTROL",
"MKACTIVITY" };
private static final Map<String, Integer> requestMethodsHash = new HashMap<String, Integer>(
requestMethods.length);
static {
int i;
for (i = 0; i < requestMethods.length; i++) {
requestMethodsHash.put(requestMethods[i], Integer.valueOf(1 + i));
}
}
public static final int SC_M_JK_STORED = (byte) 0xFF;
// id's for common request headers
public static final int SC_REQ_ACCEPT = 1;
public static final int SC_REQ_ACCEPT_CHARSET = 2;
public static final int SC_REQ_ACCEPT_ENCODING = 3;
public static final int SC_REQ_ACCEPT_LANGUAGE = 4;
public static final int SC_REQ_AUTHORIZATION = 5;
public static final int SC_REQ_CONNECTION = 6;
public static final int SC_REQ_CONTENT_TYPE = 7;
public static final int SC_REQ_CONTENT_LENGTH = 8;
public static final int SC_REQ_COOKIE = 9;
public static final int SC_REQ_COOKIE2 = 10;
public static final int SC_REQ_HOST = 11;
public static final int SC_REQ_PRAGMA = 12;
public static final int SC_REQ_REFERER = 13;
public static final int SC_REQ_USER_AGENT = 14;
// Translates integer codes to request header names
private static final String[] requestHeaders = { "Accept",
"Accept-Charset", "Accept-Encoding", "Accept-Language",
"Authorization", "Connection", "Content-Type", "Content-Length",
"Cookie", "Cookie2", "Host", "Pragma", "Referer", "User-Agent" };
private static final Map<String, Integer> requestHeadersHash = new HashMap<String, Integer>(
requestHeaders.length);
static {
int i;
for (i = 0; i < requestHeaders.length; i++) {
requestHeadersHash.put(requestHeaders[i].toLowerCase(), Integer
.valueOf(0xA001 + i));
}
}
// Translates integer codes to response header names
private static final String[] responseHeaders = { "Content-Type",
"Content-Language", "Content-Length", "Date", "Last-Modified",
"Location", "Set-Cookie", "Set-Cookie2", "Servlet-Engine",
"Status", "WWW-Authenticate" };
private static final Map<String, Integer> responseHeadersHash = new HashMap<String, Integer>(
responseHeaders.length);
static {
int i;
for (i = 0; i < responseHeaders.length; i++) {
responseHeadersHash.put(responseHeaders[i], Integer
.valueOf(0xA001 + i));
}
}
public static final int getRequestMethodIndex(String method) {
Integer i = requestMethodsHash.get(method);
if (i == null)
return 0;
else
return i.intValue();
}
public static final String getRequestMethod(int index) {
return requestMethods[index - 1];
}
public static final int getRequestHeaderIndex(String header) {
Integer i = requestHeadersHash.get(header.toLowerCase());
if (i == null)
return 0;
else
return i.intValue();
}
public static final String getRequestHeader(int index) {
return requestHeaders[index - 0xA001];
}
public static final int getResponseHeaderIndex(String header) {
Integer i = responseHeadersHash.get(header);
if (i == null)
return 0;
else
return i.intValue();
}
public static final String getResponseHeader(int index) {
return responseHeaders[index - 0xA001];
}
}
|
gpl-2.0
|
iftekar007/pearlhealth-wp
|
wp-content/plugins/events-manager/multilingual/em-ml-admin.php
|
6386
|
<?php
class EM_ML_Admin{
public static function init(){
add_action('add_meta_boxes', 'EM_ML_Admin::meta_boxes',100);
if( !defined('EM_SETTINGS_TABS') && count(EM_ML::$langs) > 3 ) define('EM_SETTINGS_TABS',true);
}
public static function meta_boxes(){
global $EM_Event, $EM_Location;
//decide if it's a master event, if not then hide the meta boxes
if( !empty($EM_Event) && !EM_ML::is_original($EM_Event) ){
//remove meta boxes for events
remove_meta_box('em-event-when', EM_POST_TYPE_EVENT, 'side');
remove_meta_box('em-event-where', EM_POST_TYPE_EVENT, 'normal');
remove_meta_box('em-event-bookings', EM_POST_TYPE_EVENT, 'normal');
remove_meta_box('em-event-bookings-stats', EM_POST_TYPE_EVENT, 'side');
remove_meta_box('em-event-group', EM_POST_TYPE_EVENT, 'side');
if( get_option('dbem_attributes_enabled', true) ){
remove_meta_box('em-event-attributes', EM_POST_TYPE_EVENT, 'normal');
add_meta_box('em-event-attributes', __('Attributes','events-manager'), 'EM_ML_Admin::event_meta_box_attributes',EM_POST_TYPE_EVENT, 'normal','default');
}
//add translation-specific meta boxes
add_meta_box('em-event-translation', __('Translated Event Information','events-manager'), 'EM_ML_Admin::meta_box_translated_event',EM_POST_TYPE_EVENT, 'side','high');
$event = EM_ML::get_original_event($EM_Event);
if( $event->event_rsvp ){
add_meta_box('em-event-bookings-translation', __('Bookings/Registration','events-manager'), 'EM_ML_Admin::meta_box_bookings_translation',EM_POST_TYPE_EVENT, 'normal','high');
}
}
//locations, decide if it's a master location, if not then hide the meta boxes
if( !empty($EM_Location) && !EM_ML::is_original($EM_Location) ){
//add translation-specific meta boxes
add_meta_box('em-event-translation', __('Translated Event Information','events-manager'), 'EM_ML_Admin::meta_box_translated_location',EM_POST_TYPE_LOCATION, 'side','high');
//remove other meta boxes
remove_meta_box('em-location-where', EM_POST_TYPE_LOCATION, 'normal');
if( get_option('dbem_location_attributes_enabled') ){
remove_meta_box('em-location-attributes', EM_POST_TYPE_LOCATION, 'normal');
add_meta_box('em-location-attributes', __('Attributes','events-manager'), 'EM_ML_Admin::location_meta_box_attributes',EM_POST_TYPE_LOCATION, 'normal','default');
}
}
}
public static function meta_box_translated_event(){
global $EM_Event;
//output the _emnonce because it won't be output due to missing meta boxes
?>
<input type="hidden" name="_emnonce" value="<?php echo wp_create_nonce('edit_event'); ?>" />
<p>
<?php
$original_link = EM_ML::get_original_event($EM_Event)->get_edit_url();
$original_link = apply_filters('em_ml_admin_original_event_link',$original_link);
echo __('This is a translated event, therefore your time, location and booking information is handled by your original event translation.', 'events-manager');
echo ' <a href="'.esc_url($original_link).'">'.__('See original translation.','events-manager').'</a>';
?>
</p>
<?php
}
public static function meta_box_translated_location(){
global $EM_Location;
//output the _emnonce because it won't be output due to missing meta boxes
?>
<input type="hidden" name="_emnonce" value="<?php echo wp_create_nonce('edit_location'); ?>" />
<p>
<?php
$original_link = EM_ML::get_original_location($EM_Location)->get_edit_url();
$original_link = apply_filters('em_ml_admin_original_location_link',$original_link);
echo __('This is a translated event, therefore address information is handled by the original location translation.', 'events-manager');
echo ' <a href="'.esc_url($original_link).'">'.__('See original translation.','events-manager').'</a>';
?>
</p>
<?php
}
public static function meta_box_bookings_translation(){
global $EM_Event;
$event = EM_ML::get_original_event($EM_Event);
$lang = EM_ML::$current_language;
?>
<p><em><?php esc_html_e('Below are translations for your tickets. If left blank, the language of the original event will be used.','events-manager'); ?></em></p>
<table class="event-bookings-ticket-translation form-table">
<?php
foreach( $event->get_tickets()->tickets as $EM_Ticket ){ /* @var $EM_Ticket EM_Ticket */
$name = !empty($EM_Ticket->ticket_meta['langs'][$lang]['ticket_name']) ? $EM_Ticket->ticket_meta['langs'][$lang]['ticket_name'] : '';
$description = !empty($EM_Ticket->ticket_meta['langs'][$lang]['ticket_description']) ? $EM_Ticket->ticket_meta['langs'][$lang]['ticket_description']: '';
$desc_ph = !empty($EM_Ticket->ticket_description) ? $EM_Ticket->ticket_description:__('Description','events-manager');
?>
<tbody>
<tr>
<td><strong><?php echo esc_html($EM_Ticket->ticket_name); ?></strong></td>
<td>
<input placeholder="<?php echo esc_attr($EM_Ticket->ticket_name); ?>" type="text" name="ticket_translations[<?php echo $EM_Ticket->ticket_id ?>][ticket_name]" value="<?php echo esc_attr($name); ?>" />
<br/>
<textarea placeholder="<?php echo esc_attr($desc_ph); ?>" type="text" name="ticket_translations[<?php echo $EM_Ticket->ticket_id ?>][ticket_description]"><?php echo esc_html($description); ?></textarea>
</td>
</tr>
</tbody>
<?php
}
?>
</table>
<?php
}
public static function event_meta_box_attributes(){
global $EM_Event;
//get original location for attributes
$event = EM_ML::get_original_event($EM_Event);
EM_ML_IO::event_merge_original_attributes($EM_Event, $event);
em_locate_template('forms/event/attributes.php',true);
}
public static function location_meta_box_attributes(){
global $EM_Location;
//get original location for attributes
$location = EM_ML::get_original_location($EM_Location);
EM_ML_IO::location_merge_original_attributes($EM_Location, $location);
em_locate_template('forms/location/attributes.php',true);
}
}
EM_ML_Admin::init();
|
gpl-2.0
|
ppardalj/ServUO
|
Scripts/Mobiles/NPCs/WarriorGuard.cs
|
8241
|
#region Header
// **********
// ServUO - WarriorGuard.cs
// **********
#endregion
#region References
using System;
using Server.Items;
#endregion
namespace Server.Mobiles
{
public class WarriorGuard : BaseGuard
{
private Timer m_AttackTimer, m_IdleTimer;
private Mobile m_Focus;
[Constructable]
public WarriorGuard()
: this(null)
{ }
public WarriorGuard(Mobile target)
: base(target)
{
InitStats(1000, 1000, 1000);
Title = "the guard";
SpeechHue = Utility.RandomDyedHue();
Hue = Utility.RandomSkinHue();
if (Female = Utility.RandomBool())
{
Body = 0x191;
Name = NameList.RandomName("female");
switch (Utility.Random(2))
{
case 0:
AddItem(new LeatherSkirt());
break;
case 1:
AddItem(new LeatherShorts());
break;
}
switch (Utility.Random(5))
{
case 0:
AddItem(new FemaleLeatherChest());
break;
case 1:
AddItem(new FemaleStuddedChest());
break;
case 2:
AddItem(new LeatherBustierArms());
break;
case 3:
AddItem(new StuddedBustierArms());
break;
case 4:
AddItem(new FemalePlateChest());
break;
}
}
else
{
Body = 0x190;
Name = NameList.RandomName("male");
AddItem(new PlateChest());
AddItem(new PlateArms());
AddItem(new PlateLegs());
switch (Utility.Random(3))
{
case 0:
AddItem(new Doublet(Utility.RandomNondyedHue()));
break;
case 1:
AddItem(new Tunic(Utility.RandomNondyedHue()));
break;
case 2:
AddItem(new BodySash(Utility.RandomNondyedHue()));
break;
}
}
Utility.AssignRandomHair(this);
if (Utility.RandomBool())
{
Utility.AssignRandomFacialHair(this, HairHue);
}
Halberd weapon = new Halberd();
weapon.Movable = false;
weapon.Crafter = this;
weapon.Quality = ItemQuality.Exceptional;
AddItem(weapon);
Container pack = new Backpack();
pack.Movable = false;
pack.DropItem(new Gold(10, 25));
AddItem(pack);
Skills[SkillName.Anatomy].Base = 120.0;
Skills[SkillName.Tactics].Base = 120.0;
Skills[SkillName.Swords].Base = 120.0;
Skills[SkillName.MagicResist].Base = 120.0;
Skills[SkillName.DetectHidden].Base = 100.0;
NextCombatTime = Core.TickCount + 500;
Focus = target;
}
public WarriorGuard(Serial serial)
: base(serial)
{ }
[CommandProperty(AccessLevel.GameMaster)]
public override Mobile Focus
{
get { return m_Focus; }
set
{
if (Deleted)
{
return;
}
Mobile oldFocus = m_Focus;
if (oldFocus != value)
{
m_Focus = value;
if (value != null)
{
AggressiveAction(value);
}
Combatant = value;
if (oldFocus != null && !oldFocus.Alive)
{
Say("Thou hast suffered thy punishment, scoundrel.");
}
if (value != null)
{
Say(500131); // Thou wilt regret thine actions, swine!
}
if (m_AttackTimer != null)
{
m_AttackTimer.Stop();
m_AttackTimer = null;
}
if (m_IdleTimer != null)
{
m_IdleTimer.Stop();
m_IdleTimer = null;
}
if (m_Focus != null)
{
m_AttackTimer = new AttackTimer(this);
m_AttackTimer.Start();
((AttackTimer)m_AttackTimer).DoOnTick();
}
else
{
m_IdleTimer = new IdleTimer(this);
m_IdleTimer.Start();
}
}
else if (m_Focus == null && m_IdleTimer == null)
{
m_IdleTimer = new IdleTimer(this);
m_IdleTimer.Start();
}
}
}
public override bool OnBeforeDeath()
{
if (m_Focus != null && m_Focus.Alive)
{
new AvengeTimer(m_Focus).Start(); // If a guard dies, three more guards will spawn
}
return base.OnBeforeDeath();
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write(0); // version
writer.Write(m_Focus);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
switch (version)
{
case 0:
{
m_Focus = reader.ReadMobile();
if (m_Focus != null)
{
m_AttackTimer = new AttackTimer(this);
m_AttackTimer.Start();
}
else
{
m_IdleTimer = new IdleTimer(this);
m_IdleTimer.Start();
}
break;
}
}
}
public override void OnAfterDelete()
{
if (m_AttackTimer != null)
{
m_AttackTimer.Stop();
m_AttackTimer = null;
}
if (m_IdleTimer != null)
{
m_IdleTimer.Stop();
m_IdleTimer = null;
}
base.OnAfterDelete();
}
private class AvengeTimer : Timer
{
private readonly Mobile m_Focus;
public AvengeTimer(Mobile focus)
: base(TimeSpan.FromSeconds(2.5), TimeSpan.FromSeconds(1.0), 3)
{
m_Focus = focus;
}
protected override void OnTick()
{
Spawn(m_Focus, m_Focus, 1, true);
}
}
private class AttackTimer : Timer
{
private readonly WarriorGuard m_Owner;
public AttackTimer(WarriorGuard owner)
: base(TimeSpan.FromSeconds(0.25), TimeSpan.FromSeconds(0.1))
{
m_Owner = owner;
}
public void DoOnTick()
{
OnTick();
}
protected override void OnTick()
{
if (m_Owner.Deleted)
{
Stop();
return;
}
m_Owner.Criminal = false;
m_Owner.Kills = 0;
m_Owner.Stam = m_Owner.StamMax;
Mobile target = m_Owner.Focus;
if (target != null && (target.Deleted || !target.Alive || !m_Owner.CanBeHarmful(target)))
{
m_Owner.Focus = null;
Stop();
return;
}
else if (m_Owner.Weapon is Fists)
{
m_Owner.Kill();
Stop();
return;
}
if (target != null && m_Owner.Combatant != target)
{
m_Owner.Combatant = target;
}
if (target == null)
{
Stop();
}
else
{
// <instakill>
TeleportTo(target);
target.BoltEffect(0);
if (target is BaseCreature)
{
((BaseCreature)target).NoKillAwards = true;
}
target.Damage(target.HitsMax, m_Owner);
target.Kill(); // just in case, maybe Damage is overriden on some shard
if (target.Corpse != null && !target.Player)
{
target.Corpse.Delete();
}
m_Owner.Focus = null;
Stop();
} // </instakill>
/*else if ( !m_Owner.InRange( target, 20 ) )
{
m_Owner.Focus = null;
}
else if ( !m_Owner.InRange( target, 10 ) || !m_Owner.InLOS( target ) )
{
TeleportTo( target );
}
else if ( !m_Owner.InRange( target, 1 ) )
{
if ( !m_Owner.Move( m_Owner.GetDirectionTo( target ) | Direction.Running ) )
TeleportTo( target );
}
else if ( !m_Owner.CanSee( target ) )
{
if ( !m_Owner.UseSkill( SkillName.DetectHidden ) && Utility.Random( 50 ) == 0 )
m_Owner.Say( "Reveal!" );
}*/
}
private void TeleportTo(Mobile target)
{
Point3D from = m_Owner.Location;
Point3D to = target.Location;
m_Owner.Location = to;
Effects.SendLocationParticles(
EffectItem.Create(from, m_Owner.Map, EffectItem.DefaultDuration), 0x3728, 10, 10, 2023);
Effects.SendLocationParticles(EffectItem.Create(to, m_Owner.Map, EffectItem.DefaultDuration), 0x3728, 10, 10, 5023);
m_Owner.PlaySound(0x1FE);
}
}
private class IdleTimer : Timer
{
private readonly WarriorGuard m_Owner;
private int m_Stage;
public IdleTimer(WarriorGuard owner)
: base(TimeSpan.FromSeconds(2.0), TimeSpan.FromSeconds(2.5))
{
m_Owner = owner;
}
protected override void OnTick()
{
if (m_Owner.Deleted)
{
Stop();
return;
}
if ((m_Stage++ % 4) == 0 || !m_Owner.Move(m_Owner.Direction))
{
m_Owner.Direction = (Direction)Utility.Random(8);
}
if (m_Stage > 16)
{
Effects.SendLocationParticles(
EffectItem.Create(m_Owner.Location, m_Owner.Map, EffectItem.DefaultDuration), 0x3728, 10, 10, 2023);
m_Owner.PlaySound(0x1FE);
m_Owner.Delete();
}
}
}
}
}
|
gpl-2.0
|
IYEO/Sweettaste
|
administrator/components/com_hikashop/extensions/plg_hikashoppayment_sofort/library/helper/array_to_xml.php
|
4290
|
<?php
/**
* @package HikaShop for Joomla!
* @version 2.6.3
* @author hikashop.com
* @copyright (C) 2010-2016 HIKARI SOFTWARE. All rights reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
defined('_JEXEC') or die('Restricted access');
?><?php
require_once('array_to_xml_exception.php');
class ArrayToXml {
private $_maxDepth = 4;
private $_parsedData = null;
public function __construct(array $input, $maxDepth = 10, $trim = true) {
if ($maxDepth > 50) {
throw new ArrayToXmlException('Max depth too high.');
}
$this->_maxDepth = $maxDepth;
if (count($input) == 1) {
$tagName = key($input);
$SofortTag = new SofortTag($tagName, $this->_extractAttributesSection($input[$tagName]), $this->_extractDataSection($input[$tagName], $trim));
$this->_render($input[$tagName], $SofortTag, 1, $trim);
$this->_parsedData = $SofortTag->render();
} elseif(!$input) {
$this->_parsedData = '';
} else {
throw new ArrayToXmlException('No valid input.');
}
}
public function toXml($version = '1.0', $encoding = 'UTF-8') {
return !$version && !$encoding
? $this->_parsedData
: "<?xml version=\"{$version}\" encoding=\"{$encoding}\" ?>\n{$this->_parsedData}";
}
public static function render(array $input, array $options = array()) {
$options = array_merge(array(
'version' => '1.0',
'encoding' => 'UTF-8',
'trim' => true,
'depth' => 10,
),
$options
);
$Instance = new ArrayToXml($input, $options['depth'], $options['trim']);
return $Instance->toXml($options['version'], $options['encoding']);
}
private function _checkDepth($currentDepth) {
if ($this->_maxDepth && $currentDepth > $this->_maxDepth) {
throw new ArrayToXmlException("Max depth ({$this->_maxDepth}) exceeded");
}
}
private function _createNode($name, array $attributes, array $children) {
return new SofortTag($name, $attributes, $children);
}
private function _createTextNode($text, $trim) {
return new SofortText($text, true, $trim);
}
private function _extractAttributesSection(&$node) {
$attributes = array();
if (is_array($node) && isset($node['@attributes']) && $node['@attributes']) {
$attributes = is_array($node['@attributes']) ? $node['@attributes'] : array($node['@attributes']);
unset($node['@attributes']);
} elseif (is_array($node) && isset($node['@attributes'])) {
unset($node['@attributes']);
}
return $attributes;
}
private function _extractDataSection(&$node, $trim) {
$children = array();
if (is_array($node) && isset($node['@data']) && $node['@data']) {
$children = array($this->_createTextNode($node['@data'], $trim));
unset($node['@data']);
} elseif (is_array($node) && isset($node['@data'])) {
unset($node['@data']);
}
return $children;
}
private function _render($input, SofortTag $ParentTag, $currentDepth, $trim) {
$this->_checkDepth($currentDepth);
if (is_array($input)) {
foreach ($input as $tagName => $data) {
$attributes = $this->_extractAttributesSection($data);
if (is_array($data) && is_int(key($data))) {
$this->_checkDepth($currentDepth+1);
foreach ($data as $line) {
if (is_array($line)) {
$Tag = $this->_createNode($tagName, $this->_extractAttributesSection($line), $this->_extractDataSection($line, $trim));
$ParentTag->children[] = $Tag;
$this->_render($line, $Tag, $currentDepth+1, $trim);
} else {
$ParentTag->children[] = $this->_createNode($tagName, $attributes, array($this->_createTextNode($line, $trim)));
}
}
} elseif (is_array($data)) {
$Tag = $this->_createNode($tagName, $attributes, $this->_extractDataSection($data, $trim));
$ParentTag->children[] = $Tag;
$this->_render($data, $Tag, $currentDepth+1, $trim);
} elseif (is_numeric($tagName)) {
$ParentTag->children[] = $this->_createTextNode($data, $trim);
} else {
$ParentTag->children[] = $this->_createNode($tagName, $attributes, array($this->_createTextNode($data, $trim)));
}
}
return;
}
$ParentTag->children[] = $this->_createTextNode($input, $trim);
}
}
?>
|
gpl-2.0
|
md-5/jdk10
|
test/hotspot/jtreg/vmTestbase/nsk/jdi/EventSet/suspendPolicy/suspendpolicy016.java
|
18653
|
/*
* Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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 Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package nsk.jdi.EventSet.suspendPolicy;
import nsk.share.*;
import nsk.share.jpda.*;
import nsk.share.jdi.*;
import com.sun.jdi.*;
import com.sun.jdi.event.*;
import com.sun.jdi.request.*;
import java.util.*;
import java.io.*;
/**
* The test for the implementation of an object of the type <BR>
* EventSet. <BR>
* <BR>
* The test checks that results of the method <BR>
* <code>com.sun.jdi.EventSet.suspendPolicy()</code> <BR>
* complies with its spec. <BR>
* <BR>
* The test checks that for a VMDeathEvent set, <BR>
* the method returns values corresponding to one <BR>
* which suspends the most threads. <BR>
* The cases to check include event set containing two more <BR>
* VMDeathRequests with suspendPolicies <BR>
* SUSPEND_ALL and SUSPEND_EVENT_THREAD. <BR>
* <BR>
* The test has three phases and works as follows. <BR>
* <BR>
* In first phase, <BR>
* upon launching debuggee's VM which will be suspended, <BR>
* a debugger waits for the VMStartEvent within a predefined <BR>
* time interval. If no the VMStartEvent received, the test is FAILED. <BR>
* Upon getting the VMStartEvent, it makes the request for debuggee's <BR>
* ClassPrepareEvent with SUSPEND_EVENT_THREAD, resumes the VM, <BR>
* and waits for the event within the predefined time interval. <BR>
* If no the ClassPrepareEvent received, the test is FAILED. <BR>
* Upon getting the ClassPrepareEvent, <BR>
* the debugger sets up the breakpoint with SUSPEND_EVENT_THREAD <BR>
* within debuggee's special methodForCommunication(). <BR>
* <BR>
* In second phase to check the above, <BR>
* the debugger and the debuggee perform the following loop. <BR>
* - The debugger sets up VMDeathRequests, resumes <BR>
* the debuggee, and waits for the VMDeathEvent. <BR>
* - The debuggee ends to be resulting in the event. <BR>
* - Upon getting new event, the debugger <BR>
* performs the check corresponding to the event. <BR>
* <BR>
* Note. To inform each other of needed actions, the debugger and <BR>
* and the debuggee use debuggee's variable "instruction". <BR>
* In third phase, at the end, <BR>
* the debuggee changes the value of the "instruction" <BR>
* to inform the debugger of checks finished, and both end. <BR>
* <BR>
*/
public class suspendpolicy016 {
//----------------------------------------------------- templete section
static final int PASSED = 0;
static final int FAILED = 2;
static final int PASS_BASE = 95;
//----------------------------------------------------- templete parameters
static final String
sHeader1 = "\n==> nsk/jdi/EventSet/suspendPolicy/suspendpolicy016 ",
sHeader2 = "--> debugger: ",
sHeader3 = "##> debugger: ";
//----------------------------------------------------- main method
public static void main (String argv[]) {
int result = run(argv, System.out);
System.exit(result + PASS_BASE);
}
public static int run (String argv[], PrintStream out) {
int exitCode = new suspendpolicy016().runThis(argv, out);
if (exitCode != PASSED) {
System.out.println("TEST FAILED");
}
return testExitCode;
}
//-------------------------------------------------- log procedures
private static Log logHandler;
private static void log1(String message) {
logHandler.display(sHeader1 + message);
}
private static void log2(String message) {
logHandler.display(sHeader2 + message);
}
private static void log3(String message) {
logHandler.complain(sHeader3 + message);
}
// ************************************************ test parameters
private String debuggeeName =
"nsk.jdi.EventSet.suspendPolicy.suspendpolicy016a";
private String testedClassName =
"nsk.jdi.EventSet.suspendPolicy.TestClass";
//====================================================== test program
//------------------------------------------------------ common section
static Debugee debuggee;
static ArgumentHandler argsHandler;
static int waitTime;
static VirtualMachine vm = null;
static EventRequestManager eventRManager = null;
static EventQueue eventQueue = null;
static EventSet eventSet = null;
static EventIterator eventIterator = null;
static ReferenceType debuggeeClass = null;
static int testExitCode = PASSED;
int policyToCheck = 0;
//------------------------------------------------------ methods
private int runThis (String argv[], PrintStream out) {
argsHandler = new ArgumentHandler(argv);
logHandler = new Log(out, argsHandler);
Binder binder = new Binder(argsHandler, logHandler);
waitTime = argsHandler.getWaitTime() * 60000;
try {
log2("launching a debuggee :");
log2(" " + debuggeeName);
if (argsHandler.verbose()) {
debuggee = binder.bindToDebugee(debuggeeName + " -vbs");
} else {
debuggee = binder.bindToDebugee(debuggeeName);
}
if (debuggee == null) {
log3("ERROR: no debuggee launched");
return FAILED;
}
log2("debuggee launched");
} catch ( Exception e ) {
log3("ERROR: Exception : " + e);
log2(" test cancelled");
return FAILED;
}
debuggee.redirectOutput(logHandler);
vm = debuggee.VM();
eventQueue = vm.eventQueue();
if (eventQueue == null) {
log3("ERROR: eventQueue == null : TEST ABORTED");
vm.exit(PASS_BASE);
return FAILED;
}
log2("invocation of the method runTest()");
switch (runTest()) {
case 0 : log2("test phase has finished normally");
log2(" waiting for the debuggee to finish ...");
debuggee.waitFor();
log2("......getting the debuggee's exit status");
int status = debuggee.getStatus();
if (status != PASS_BASE) {
log3("ERROR: debuggee returned UNEXPECTED exit status: " +
status + " != PASS_BASE");
testExitCode = FAILED;
} else {
log2("......debuggee returned expected exit status: " +
status + " == PASS_BASE");
}
break;
default : log3("ERROR: runTest() returned unexpected value");
case 1 : log3("test phase has not finished normally: debuggee is still alive");
log2("......forcing: vm.exit();");
testExitCode = FAILED;
try {
vm.exit(PASS_BASE);
} catch ( Exception e ) {
log3("ERROR: Exception : e");
}
break;
case 2 : log3("test cancelled due to VMDisconnectedException");
log2("......trying: vm.process().destroy();");
testExitCode = FAILED;
try {
Process vmProcess = vm.process();
if (vmProcess != null) {
vmProcess.destroy();
}
} catch ( Exception e ) {
log3("ERROR: Exception : e");
}
break;
}
return testExitCode;
}
/*
* Return value: 0 - normal end of the test
* 1 - ubnormal end of the test
* 2 - VMDisconnectedException while test phase
*/
private int runTest() {
try {
testRun();
log2("waiting for VMDeathEvent");
getEventSet();
if ( !(eventIterator.nextEvent() instanceof VMDeathEvent) ) {
log3("ERROR: last event is not the VMDeathEvent");
return 1;
}
check();
log2("waiting for VMDisconnectEvent");
getEventSet();
if ( !(eventIterator.nextEvent() instanceof VMDisconnectEvent) ) {
log3("ERROR: last event is not the VMDisconnectEvent");
return 1;
}
return 0;
} catch ( VMDisconnectedException e ) {
log3("ERROR: VMDisconnectedException : " + e);
return 2;
} catch ( Exception e ) {
log3("ERROR: Exception : " + e);
return 1;
}
}
private void testRun()
throws JDITestRuntimeException, Exception {
if ( !vm.canRequestVMDeathEvent() ) {
log2("......vm.canRequestVMDeathEvent == false :: test cancelled");
vm.exit(PASS_BASE);
return;
}
eventRManager = vm.eventRequestManager();
log2("......getting ClassPrepareEvent for debuggee's class");
ClassPrepareRequest cpRequest = eventRManager.createClassPrepareRequest();
cpRequest.setSuspendPolicy( EventRequest.SUSPEND_EVENT_THREAD);
cpRequest.addClassFilter(debuggeeName);
cpRequest.enable();
vm.resume();
getEventSet();
cpRequest.disable();
ClassPrepareEvent event = (ClassPrepareEvent) eventIterator.next();
debuggeeClass = event.referenceType();
if (!debuggeeClass.name().equals(debuggeeName))
throw new JDITestRuntimeException("** Unexpected ClassName for ClassPrepareEvent **");
log2(" received: ClassPrepareEvent for debuggeeClass");
log2("......setting up ClassPrepareEvent for breakpointForCommunication");
String bPointMethod = "methodForCommunication";
String lineForComm = "lineForComm";
BreakpointRequest bpRequest;
ThreadReference mainThread = debuggee.threadByNameOrThrow("main");
bpRequest = settingBreakpoint(mainThread,
debuggeeClass,
bPointMethod, lineForComm, "zero");
bpRequest.enable();
vm.resume();
//------------------------------------------------------ testing section
log1(" TESTING BEGINS");
EventRequest eventRequest1 = null;
EventRequest eventRequest2 = null;
EventRequest eventRequest3 = null;
final int SUSPEND_POLICY = EventRequest.SUSPEND_NONE;
final int SUSPEND_NONE = EventRequest.SUSPEND_NONE;
final int SUSPEND_THREAD = EventRequest.SUSPEND_EVENT_THREAD;
final int SUSPEND_ALL = EventRequest.SUSPEND_ALL;
int policyExpected[] = { SUSPEND_NONE,
SUSPEND_THREAD,
SUSPEND_ALL,
SUSPEND_THREAD,
SUSPEND_ALL,
SUSPEND_ALL,
SUSPEND_ALL };
int policy = 0;
breakpointForCommunication();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ variable part
eventRequest2 = settingVMDeathRequest (SUSPEND_THREAD, "VMDeathRequest2");
eventRequest2.enable();
eventRequest3 = settingVMDeathRequest (SUSPEND_ALL, "VMDeathRequest3");
eventRequest3.enable();
policyToCheck = policyExpected[5];
mainThread.resume();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
log1(" TESTING ENDS");
return;
}
/*
* private BreakpointRequest settingBreakpoint(ThreadReference, ReferenceType,
* String, String, String)
*
* It sets up a breakpoint at given line number within a given method in a given class
* for a given thread.
*
* Return value: BreakpointRequest object in case of success
*
* JDITestRuntimeException in case of an Exception thrown within the method
*/
private BreakpointRequest settingBreakpoint ( ThreadReference thread,
ReferenceType testedClass,
String methodName,
String bpLine,
String property)
throws JDITestRuntimeException {
log2("......setting up a breakpoint:");
log2(" thread: " + thread + "; class: " + testedClass +
"; method: " + methodName + "; line: " + bpLine);
List alllineLocations = null;
Location lineLocation = null;
BreakpointRequest breakpRequest = null;
try {
Method method = (Method) testedClass.methodsByName(methodName).get(0);
alllineLocations = method.allLineLocations();
int n =
( (IntegerValue) testedClass.getValue(testedClass.fieldByName(bpLine) ) ).value();
if (n > alllineLocations.size()) {
log3("ERROR: TEST_ERROR_IN_settingBreakpoint(): number is out of bound of method's lines");
} else {
lineLocation = (Location) alllineLocations.get(n);
try {
breakpRequest = eventRManager.createBreakpointRequest(lineLocation);
breakpRequest.putProperty("number", property);
breakpRequest.addThreadFilter(thread);
breakpRequest.setSuspendPolicy( EventRequest.SUSPEND_EVENT_THREAD);
} catch ( Exception e1 ) {
log3("ERROR: inner Exception within settingBreakpoint() : " + e1);
breakpRequest = null;
}
}
} catch ( Exception e2 ) {
log3("ERROR: ATTENTION: outer Exception within settingBreakpoint() : " + e2);
breakpRequest = null;
}
if (breakpRequest == null) {
log2(" A BREAKPOINT HAS NOT BEEN SET UP");
throw new JDITestRuntimeException("**FAILURE to set up a breakpoint**");
}
log2(" a breakpoint has been set up");
return breakpRequest;
}
private void getEventSet()
throws JDITestRuntimeException {
try {
// log2(" eventSet = eventQueue.remove(waitTime);");
eventSet = eventQueue.remove(waitTime);
if (eventSet == null) {
throw new JDITestRuntimeException("** TIMEOUT while waiting for event **");
}
// log2(" eventIterator = eventSet.eventIterator;");
eventIterator = eventSet.eventIterator();
} catch ( Exception e ) {
throw new JDITestRuntimeException("** EXCEPTION while waiting for event ** : " + e);
}
}
private void breakpointForCommunication()
throws JDITestRuntimeException {
log2("breakpointForCommunication");
getEventSet();
if (eventIterator.nextEvent() instanceof BreakpointEvent)
return;
throw new JDITestRuntimeException("** event IS NOT a breakpoint **");
}
// ============================== test's additional methods
private VMDeathRequest settingVMDeathRequest( int suspendPolicy,
String property )
throws JDITestRuntimeException {
try {
log2("......setting up VMDeathRequest:");
log2(" suspendPolicy: " + suspendPolicy + "; property: " + property);
VMDeathRequest
vmdr = eventRManager.createVMDeathRequest();
vmdr.putProperty("number", property);
vmdr.setSuspendPolicy(suspendPolicy);
return vmdr;
} catch ( Exception e ) {
log3("ERROR: ATTENTION: Exception within settingVMDeathRequest() : " + e);
log3(" VMDeathRequest HAS NOT BEEN SET UP");
throw new JDITestRuntimeException("** FAILURE to set up a VMDeathRequest **");
}
}
void check() {
log2("......checking up on eventSet.suspendPolicy()");
int policy = eventSet.suspendPolicy();
if (policy != policyToCheck) {
log3("ERROR: eventSet.suspendPolicy() != policyExpected");
log3(" eventSet.suspendPolicy() == " + policy);
log3(" policyExpected == " + policyToCheck);
testExitCode = FAILED;
}
vm.resume();
}
}
|
gpl-2.0
|
famelo/TYPO3-Base
|
typo3/sysext/core/Classes/Page/PageRenderer.php
|
81662
|
<?php
namespace TYPO3\CMS\Core\Page;
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Localization\LocalizationFactory;
use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* TYPO3 pageRender class (new in TYPO3 4.3.0)
* This class render the HTML of a webpage, usable for BE and FE
*/
class PageRenderer implements \TYPO3\CMS\Core\SingletonInterface {
// Constants for the part to be rendered
const PART_COMPLETE = 0;
const PART_HEADER = 1;
const PART_FOOTER = 2;
// jQuery Core version that is shipped with TYPO3
const JQUERY_VERSION_LATEST = '1.11.3';
// jQuery namespace options
const JQUERY_NAMESPACE_NONE = 'none';
const JQUERY_NAMESPACE_DEFAULT = 'jQuery';
const JQUERY_NAMESPACE_DEFAULT_NOCONFLICT = 'defaultNoConflict';
/**
* @var bool
*/
protected $compressJavascript = FALSE;
/**
* @var bool
*/
protected $compressCss = FALSE;
/**
* @var bool
*/
protected $removeLineBreaksFromTemplate = FALSE;
/**
* @var bool
*/
protected $concatenateFiles = FALSE;
/**
* @var bool
*/
protected $concatenateJavascript = FALSE;
/**
* @var bool
*/
protected $concatenateCss = FALSE;
/**
* @var bool
*/
protected $moveJsFromHeaderToFooter = FALSE;
/**
* @var \TYPO3\CMS\Core\Charset\CharsetConverter
*/
protected $csConvObj;
/**
* @var \TYPO3\CMS\Core\Localization\Locales
*/
protected $locales;
/**
* The language key
* Two character string or 'default'
*
* @var string
*/
protected $lang;
/**
* List of language dependencies for actual language. This is used for local variants of a language
* that depend on their "main" language, like Brazilian Portuguese or Canadian French.
*
* @var array
*/
protected $languageDependencies = array();
/**
* @var \TYPO3\CMS\Core\Resource\ResourceCompressor
*/
protected $compressor;
// Arrays containing associative array for the included files
/**
* @var array
*/
protected $jsFiles = array();
/**
* @var array
*/
protected $jsFooterFiles = array();
/**
* @var array
*/
protected $jsLibs = array();
/**
* @var array
*/
protected $jsFooterLibs = array();
/**
* @var array
*/
protected $cssFiles = array();
/**
* @var array
*/
protected $cssLibs = array();
/**
* The title of the page
*
* @var string
*/
protected $title;
/**
* Charset for the rendering
*
* @var string
*/
protected $charSet;
/**
* @var string
*/
protected $favIcon;
/**
* @var string
*/
protected $baseUrl;
/**
* @var bool
*/
protected $renderXhtml = TRUE;
// Static header blocks
/**
* @var string
*/
protected $xmlPrologAndDocType = '';
/**
* @var array
*/
protected $metaTags = array();
/**
* @var array
*/
protected $inlineComments = array();
/**
* @var array
*/
protected $headerData = array();
/**
* @var array
*/
protected $footerData = array();
/**
* @var string
*/
protected $titleTag = '<title>|</title>';
/**
* @var string
*/
protected $metaCharsetTag = '<meta http-equiv="Content-Type" content="text/html; charset=|" />';
/**
* @var string
*/
protected $htmlTag = '<html>';
/**
* @var string
*/
protected $headTag = '<head>';
/**
* @var string
*/
protected $baseUrlTag = '<base href="|" />';
/**
* @var string
*/
protected $iconMimeType = '';
/**
* @var string
*/
protected $shortcutTag = '<link rel="shortcut icon" href="%1$s"%2$s />';
// Static inline code blocks
/**
* @var array
*/
protected $jsInline = array();
/**
* @var array
*/
protected $jsFooterInline = array();
/**
* @var array
*/
protected $extOnReadyCode = array();
/**
* @var array
*/
protected $cssInline = array();
/**
* @var string
*/
protected $bodyContent;
/**
* @var string
*/
protected $templateFile;
/**
* @var array
*/
protected $jsLibraryNames = array('extjs');
// Paths to contibuted libraries
/**
* default path to the requireJS library, relative to the typo3/ directory
* @var string
*/
protected $requireJsPath = 'sysext/core/Resources/Public/JavaScript/Contrib/';
/**
* @var string
*/
protected $extJsPath = 'sysext/core/Resources/Public/JavaScript/Contrib/extjs/';
/**
* The local directory where one can find jQuery versions and plugins
*
* @var string
*/
protected $jQueryPath = 'sysext/core/Resources/Public/JavaScript/Contrib/jquery/';
// Internal flags for JS-libraries
/**
* This array holds all jQuery versions that should be included in the
* current page.
* Each version is described by "source", "version" and "namespace"
*
* The namespace of every particular version is the key
* of that array, because only one version per namespace can exist.
*
* The type "source" describes where the jQuery core should be included from
* currently, TYPO3 supports "local" (make use of jQuery path), "google",
* "jquery" and "msn".
* Currently there are downsides to "local" and "jquery", as "local" only
* supports the latest/shipped jQuery core out of the box, and
* "jquery" does not have SSL support.
*
* @var array
*/
protected $jQueryVersions = array();
/**
* Array of jQuery version numbers shipped with the core
*
* @var array
*/
protected $availableLocalJqueryVersions = array(
self::JQUERY_VERSION_LATEST
);
/**
* Array of jQuery CDNs with placeholders
*
* @var array
*/
protected $jQueryCdnUrls = array(
'google' => '//ajax.googleapis.com/ajax/libs/jquery/%1$s/jquery%2$s.js',
'msn' => '//ajax.aspnetcdn.com/ajax/jQuery/jquery-%1$s%2$s.js',
'jquery' => 'http://code.jquery.com/jquery-%1$s%2$s.js'
);
/**
* if set, the requireJS library is included
* @var bool
*/
protected $addRequireJs = FALSE;
/**
* inline configuration for requireJS
* @var array
*/
protected $requireJsConfig = array();
/**
* @var bool
*/
protected $addExtJS = FALSE;
/**
* @var bool
*/
protected $extDirectCodeAdded = FALSE;
/**
* @var bool
*/
protected $enableExtJsDebug = FALSE;
/**
* @var bool
*/
protected $enableJqueryDebug = FALSE;
/**
* @var bool
*/
protected $extJStheme = TRUE;
/**
* @var bool
*/
protected $extJScss = TRUE;
/**
* @var array
*/
protected $inlineLanguageLabels = array();
/**
* @var array
*/
protected $inlineLanguageLabelFiles = array();
/**
* @var array
*/
protected $inlineSettings = array();
/**
* @var array
*/
protected $inlineJavascriptWrap = array();
/**
* Saves error messages generated during compression
*
* @var string
*/
protected $compressError = '';
/**
* Is empty string for HTML and ' /' for XHTML rendering
*
* @var string
*/
protected $endingSlash = '';
/**
* Used by BE modules
*
* @var null|string
*/
public $backPath;
/**
* @param string $templateFile Declare the used template file. Omit this parameter will use default template
* @param string $backPath Relative path to typo3-folder. It varies for BE modules, in FE it will be typo3/
*/
public function __construct($templateFile = '', $backPath = NULL) {
$this->reset();
$this->csConvObj = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Charset\CharsetConverter::class);
$this->locales = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Localization\Locales::class);
if ($templateFile !== '') {
$this->templateFile = $templateFile;
}
$this->backPath = isset($backPath) ? $backPath : $GLOBALS['BACK_PATH'];
$this->inlineJavascriptWrap = array(
'<script type="text/javascript">' . LF . '/*<![CDATA[*/' . LF,
'/*]]>*/' . LF . '</script>' . LF
);
$this->inlineCssWrap = array(
'<style type="text/css">' . LF . '/*<![CDATA[*/' . LF . '<!-- ' . LF,
'-->' . LF . '/*]]>*/' . LF . '</style>' . LF
);
}
/**
* Reset all vars to initial values
*
* @return void
*/
protected function reset() {
$this->templateFile = 'EXT:core/Resources/Private/Templates/PageRenderer.html';
$this->jsFiles = array();
$this->jsFooterFiles = array();
$this->jsInline = array();
$this->jsFooterInline = array();
$this->jsLibs = array();
$this->cssFiles = array();
$this->cssInline = array();
$this->metaTags = array();
$this->inlineComments = array();
$this->headerData = array();
$this->footerData = array();
$this->extOnReadyCode = array();
$this->jQueryVersions = array();
}
/*****************************************************/
/* */
/* Public Setters */
/* */
/* */
/*****************************************************/
/**
* Sets the title
*
* @param string $title title of webpage
* @return void
*/
public function setTitle($title) {
$this->title = $title;
}
/**
* Enables/disables rendering of XHTML code
*
* @param bool $enable Enable XHTML
* @return void
*/
public function setRenderXhtml($enable) {
$this->renderXhtml = $enable;
}
/**
* Sets xml prolog and docType
*
* @param string $xmlPrologAndDocType Complete tags for xml prolog and docType
* @return void
*/
public function setXmlPrologAndDocType($xmlPrologAndDocType) {
$this->xmlPrologAndDocType = $xmlPrologAndDocType;
}
/**
* Sets meta charset
*
* @param string $charSet Used charset
* @return void
*/
public function setCharSet($charSet) {
$this->charSet = $charSet;
}
/**
* Sets language
*
* @param string $lang Used language
* @return void
*/
public function setLanguage($lang) {
$this->lang = $lang;
$this->languageDependencies = array();
// Language is found. Configure it:
if (in_array($this->lang, $this->locales->getLocales())) {
$this->languageDependencies[] = $this->lang;
foreach ($this->locales->getLocaleDependencies($this->lang) as $language) {
$this->languageDependencies[] = $language;
}
}
}
/**
* Set the meta charset tag
*
* @param string $metaCharsetTag
* @return void
*/
public function setMetaCharsetTag($metaCharsetTag) {
$this->metaCharsetTag = $metaCharsetTag;
}
/**
* Sets html tag
*
* @param string $htmlTag Html tag
* @return void
*/
public function setHtmlTag($htmlTag) {
$this->htmlTag = $htmlTag;
}
/**
* Sets HTML head tag
*
* @param string $headTag HTML head tag
* @return void
*/
public function setHeadTag($headTag) {
$this->headTag = $headTag;
}
/**
* Sets favicon
*
* @param string $favIcon
* @return void
*/
public function setFavIcon($favIcon) {
$this->favIcon = $favIcon;
}
/**
* Sets icon mime type
*
* @param string $iconMimeType
* @return void
*/
public function setIconMimeType($iconMimeType) {
$this->iconMimeType = $iconMimeType;
}
/**
* Sets HTML base URL
*
* @param string $baseUrl HTML base URL
* @return void
*/
public function setBaseUrl($baseUrl) {
$this->baseUrl = $baseUrl;
}
/**
* Sets template file
*
* @param string $file
* @return void
*/
public function setTemplateFile($file) {
$this->templateFile = $file;
}
/**
* Sets back path
*
* @param string $backPath
* @return void
*/
public function setBackPath($backPath) {
$this->backPath = $backPath;
}
/**
* Sets Content for Body
*
* @param string $content
* @return void
*/
public function setBodyContent($content) {
$this->bodyContent = $content;
}
/**
* Sets path to requireJS library (relative to typo3 directory)
*
* @param string $path Path to requireJS library
* @return void
*/
public function setRequireJsPath($path) {
$this->requireJsPath = $path;
}
/**
* Sets Path for ExtJs library (relative to typo3 directory)
*
* @param string $path
* @return void
*/
public function setExtJsPath($path) {
$this->extJsPath = $path;
}
/*****************************************************/
/* */
/* Public Enablers / Disablers */
/* */
/* */
/*****************************************************/
/**
* Enables MoveJsFromHeaderToFooter
*
* @return void
*/
public function enableMoveJsFromHeaderToFooter() {
$this->moveJsFromHeaderToFooter = TRUE;
}
/**
* Disables MoveJsFromHeaderToFooter
*
* @return void
*/
public function disableMoveJsFromHeaderToFooter() {
$this->moveJsFromHeaderToFooter = FALSE;
}
/**
* Enables compression of javascript
*
* @return void
*/
public function enableCompressJavascript() {
$this->compressJavascript = TRUE;
}
/**
* Disables compression of javascript
*
* @return void
*/
public function disableCompressJavascript() {
$this->compressJavascript = FALSE;
}
/**
* Enables compression of css
*
* @return void
*/
public function enableCompressCss() {
$this->compressCss = TRUE;
}
/**
* Disables compression of css
*
* @return void
*/
public function disableCompressCss() {
$this->compressCss = FALSE;
}
/**
* Enables concatenation of js and css files
*
* @return void
*/
public function enableConcatenateFiles() {
$this->concatenateFiles = TRUE;
}
/**
* Disables concatenation of js and css files
*
* @return void
*/
public function disableConcatenateFiles() {
$this->concatenateFiles = FALSE;
}
/**
* Enables concatenation of js files
*
* @return void
*/
public function enableConcatenateJavascript() {
$this->concatenateJavascript = TRUE;
}
/**
* Disables concatenation of js files
*
* @return void
*/
public function disableConcatenateJavascript() {
$this->concatenateJavascript = FALSE;
}
/**
* Enables concatenation of css files
*
* @return void
*/
public function enableConcatenateCss() {
$this->concatenateCss = TRUE;
}
/**
* Disables concatenation of css files
*
* @return void
*/
public function disableConcatenateCss() {
$this->concatenateCss = FALSE;
}
/**
* Sets removal of all line breaks in template
*
* @return void
*/
public function enableRemoveLineBreaksFromTemplate() {
$this->removeLineBreaksFromTemplate = TRUE;
}
/**
* Unsets removal of all line breaks in template
*
* @return void
*/
public function disableRemoveLineBreaksFromTemplate() {
$this->removeLineBreaksFromTemplate = FALSE;
}
/**
* Enables Debug Mode
* This is a shortcut to switch off all compress/concatenate features to enable easier debug
*
* @return void
*/
public function enableDebugMode() {
$this->compressJavascript = FALSE;
$this->compressCss = FALSE;
$this->concatenateFiles = FALSE;
$this->removeLineBreaksFromTemplate = FALSE;
$this->enableExtJsDebug = TRUE;
$this->enableJqueryDebug = TRUE;
}
/*****************************************************/
/* */
/* Public Getters */
/* */
/* */
/*****************************************************/
/**
* Gets the title
*
* @return string $title Title of webpage
*/
public function getTitle() {
return $this->title;
}
/**
* Gets the charSet
*
* @return string $charSet
*/
public function getCharSet() {
return $this->charSet;
}
/**
* Gets the language
*
* @return string $lang
*/
public function getLanguage() {
return $this->lang;
}
/**
* Returns rendering mode XHTML or HTML
*
* @return bool TRUE if XHTML, FALSE if HTML
*/
public function getRenderXhtml() {
return $this->renderXhtml;
}
/**
* Gets html tag
*
* @return string $htmlTag Html tag
*/
public function getHtmlTag() {
return $this->htmlTag;
}
/**
* Get meta charset
*
* @return string
*/
public function getMetaCharsetTag() {
return $this->metaCharsetTag;
}
/**
* Gets head tag
*
* @return string $tag Head tag
*/
public function getHeadTag() {
return $this->headTag;
}
/**
* Gets favicon
*
* @return string $favIcon
*/
public function getFavIcon() {
return $this->favIcon;
}
/**
* Gets icon mime type
*
* @return string $iconMimeType
*/
public function getIconMimeType() {
return $this->iconMimeType;
}
/**
* Gets HTML base URL
*
* @return string $url
*/
public function getBaseUrl() {
return $this->baseUrl;
}
/**
* Gets template file
*
* @return string
*/
public function getTemplateFile() {
return $this->templateFile;
}
/**
* Gets MoveJsFromHeaderToFooter
*
* @return bool
*/
public function getMoveJsFromHeaderToFooter() {
return $this->moveJsFromHeaderToFooter;
}
/**
* Gets compress of javascript
*
* @return bool
*/
public function getCompressJavascript() {
return $this->compressJavascript;
}
/**
* Gets compress of css
*
* @return bool
*/
public function getCompressCss() {
return $this->compressCss;
}
/**
* Gets concatenate of js and css files
*
* @return bool
*/
public function getConcatenateFiles() {
return $this->concatenateFiles;
}
/**
* Gets concatenate of js files
*
* @return bool
*/
public function getConcatenateJavascript() {
return $this->concatenateJavascript;
}
/**
* Gets concatenate of css files
*
* @return bool
*/
public function getConcatenateCss() {
return $this->concatenateCss;
}
/**
* Gets remove of empty lines from template
*
* @return bool
*/
public function getRemoveLineBreaksFromTemplate() {
return $this->removeLineBreaksFromTemplate;
}
/**
* Gets content for body
*
* @return string
*/
public function getBodyContent() {
return $this->bodyContent;
}
/**
* Gets Path for ExtJs library (relative to typo3 directory)
*
* @return string
*/
public function getExtJsPath() {
return $this->extJsPath;
}
/**
* Gets the inline language labels.
*
* @return array The inline language labels
*/
public function getInlineLanguageLabels() {
return $this->inlineLanguageLabels;
}
/**
* Gets the inline language files
*
* @return array
*/
public function getInlineLanguageLabelFiles() {
return $this->inlineLanguageLabelFiles;
}
/*****************************************************/
/* */
/* Public Functions to add Data */
/* */
/* */
/*****************************************************/
/**
* Adds meta data
*
* @param string $meta Meta data (complete metatag)
* @return void
*/
public function addMetaTag($meta) {
if (!in_array($meta, $this->metaTags)) {
$this->metaTags[] = $meta;
}
}
/**
* Adds inline HTML comment
*
* @param string $comment
* @return void
*/
public function addInlineComment($comment) {
if (!in_array($comment, $this->inlineComments)) {
$this->inlineComments[] = $comment;
}
}
/**
* Adds header data
*
* @param string $data Free header data for HTML header
* @return void
*/
public function addHeaderData($data) {
if (!in_array($data, $this->headerData)) {
$this->headerData[] = $data;
}
}
/**
* Adds footer data
*
* @param string $data Free header data for HTML header
* @return void
*/
public function addFooterData($data) {
if (!in_array($data, $this->footerData)) {
$this->footerData[] = $data;
}
}
/**
* Adds JS Library. JS Library block is rendered on top of the JS files.
*
* @param string $name Arbitrary identifier
* @param string $file File name
* @param string $type Content Type
* @param bool $compress Flag if library should be compressed
* @param bool $forceOnTop Flag if added library should be inserted at begin of this block
* @param string $allWrap
* @param bool $excludeFromConcatenation
* @param string $splitChar The char used to split the allWrap value, default is "|"
* @param bool $async Flag if property 'async="async"' should be added to JavaScript tags
* @param string $integrity Subresource Integrity (SRI)
* @return void
*/
public function addJsLibrary($name, $file, $type = 'text/javascript', $compress = FALSE, $forceOnTop = FALSE, $allWrap = '', $excludeFromConcatenation = FALSE, $splitChar = '|', $async = FALSE, $integrity = '') {
if (!$type) {
$type = 'text/javascript';
}
if (!in_array(strtolower($name), $this->jsLibs)) {
$this->jsLibs[strtolower($name)] = array(
'file' => $file,
'type' => $type,
'section' => self::PART_HEADER,
'compress' => $compress,
'forceOnTop' => $forceOnTop,
'allWrap' => $allWrap,
'excludeFromConcatenation' => $excludeFromConcatenation,
'splitChar' => $splitChar,
'async' => $async,
'integrity' => $integrity,
);
}
}
/**
* Adds JS Library to Footer. JS Library block is rendered on top of the Footer JS files.
*
* @param string $name Arbitrary identifier
* @param string $file File name
* @param string $type Content Type
* @param bool $compress Flag if library should be compressed
* @param bool $forceOnTop Flag if added library should be inserted at begin of this block
* @param string $allWrap
* @param bool $excludeFromConcatenation
* @param string $splitChar The char used to split the allWrap value, default is "|"
* @param bool $async Flag if property 'async="async"' should be added to JavaScript tags
* @param string $integrity Subresource Integrity (SRI)
* @return void
*/
public function addJsFooterLibrary($name, $file, $type = 'text/javascript', $compress = FALSE, $forceOnTop = FALSE, $allWrap = '', $excludeFromConcatenation = FALSE, $splitChar = '|', $async = FALSE, $integrity = '') {
if (!$type) {
$type = 'text/javascript';
}
if (!in_array(strtolower($name), $this->jsLibs)) {
$this->jsLibs[strtolower($name)] = array(
'file' => $file,
'type' => $type,
'section' => self::PART_FOOTER,
'compress' => $compress,
'forceOnTop' => $forceOnTop,
'allWrap' => $allWrap,
'excludeFromConcatenation' => $excludeFromConcatenation,
'splitChar' => $splitChar,
'async' => $async,
'integrity' => $integrity,
);
}
}
/**
* Adds JS file
*
* @param string $file File name
* @param string $type Content Type
* @param bool $compress
* @param bool $forceOnTop
* @param string $allWrap
* @param bool $excludeFromConcatenation
* @param string $splitChar The char used to split the allWrap value, default is "|"
* @param bool $async Flag if property 'async="async"' should be added to JavaScript tags
* @param string $integrity Subresource Integrity (SRI)
* @return void
*/
public function addJsFile($file, $type = 'text/javascript', $compress = TRUE, $forceOnTop = FALSE, $allWrap = '', $excludeFromConcatenation = FALSE, $splitChar = '|', $async = FALSE, $integrity = '') {
if (!$type) {
$type = 'text/javascript';
}
if (!isset($this->jsFiles[$file])) {
$this->jsFiles[$file] = array(
'file' => $file,
'type' => $type,
'section' => self::PART_HEADER,
'compress' => $compress,
'forceOnTop' => $forceOnTop,
'allWrap' => $allWrap,
'excludeFromConcatenation' => $excludeFromConcatenation,
'splitChar' => $splitChar,
'async' => $async,
'integrity' => $integrity,
);
}
}
/**
* Adds JS file to footer
*
* @param string $file File name
* @param string $type Content Type
* @param bool $compress
* @param bool $forceOnTop
* @param string $allWrap
* @param bool $excludeFromConcatenation
* @param string $splitChar The char used to split the allWrap value, default is "|"
* @param bool $async Flag if property 'async="async"' should be added to JavaScript tags
* @param string $integrity Subresource Integrity (SRI)
* @return void
*/
public function addJsFooterFile($file, $type = 'text/javascript', $compress = TRUE, $forceOnTop = FALSE, $allWrap = '', $excludeFromConcatenation = FALSE, $splitChar = '|', $async = FALSE, $integrity = '') {
if (!$type) {
$type = 'text/javascript';
}
if (!isset($this->jsFiles[$file])) {
$this->jsFiles[$file] = array(
'file' => $file,
'type' => $type,
'section' => self::PART_FOOTER,
'compress' => $compress,
'forceOnTop' => $forceOnTop,
'allWrap' => $allWrap,
'excludeFromConcatenation' => $excludeFromConcatenation,
'splitChar' => $splitChar,
'async' => $async,
'integrity' => $integrity,
);
}
}
/**
* Adds JS inline code
*
* @param string $name
* @param string $block
* @param bool $compress
* @param bool $forceOnTop
* @return void
*/
public function addJsInlineCode($name, $block, $compress = TRUE, $forceOnTop = FALSE) {
if (!isset($this->jsInline[$name]) && !empty($block)) {
$this->jsInline[$name] = array(
'code' => $block . LF,
'section' => self::PART_HEADER,
'compress' => $compress,
'forceOnTop' => $forceOnTop
);
}
}
/**
* Adds JS inline code to footer
*
* @param string $name
* @param string $block
* @param bool $compress
* @param bool $forceOnTop
* @return void
*/
public function addJsFooterInlineCode($name, $block, $compress = TRUE, $forceOnTop = FALSE) {
if (!isset($this->jsInline[$name]) && !empty($block)) {
$this->jsInline[$name] = array(
'code' => $block . LF,
'section' => self::PART_FOOTER,
'compress' => $compress,
'forceOnTop' => $forceOnTop
);
}
}
/**
* Adds Ext.onready code, which will be wrapped in Ext.onReady(function() {...});
*
* @param string $block Javascript code
* @param bool $forceOnTop Position of the javascript code (TRUE for putting it on top, default is FALSE = bottom)
* @return void
*/
public function addExtOnReadyCode($block, $forceOnTop = FALSE) {
if (!in_array($block, $this->extOnReadyCode)) {
if ($forceOnTop) {
array_unshift($this->extOnReadyCode, $block);
} else {
$this->extOnReadyCode[] = $block;
}
}
}
/**
* Adds the ExtDirect code
*
* @param array $filterNamespaces Limit the output to defined namespaces. If empty, all namespaces are generated
* @return void
*/
public function addExtDirectCode(array $filterNamespaces = array()) {
if ($this->extDirectCodeAdded) {
return;
}
$this->extDirectCodeAdded = TRUE;
if (empty($filterNamespaces)) {
$filterNamespaces = array('TYPO3');
}
// @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
// add compatibility mapping for the old flashmessage API
$this->addJsFile(GeneralUtility::resolveBackPath($this->backPath .
'sysext/backend/Resources/Public/JavaScript/flashmessage_compatibility.js'));
// Add language labels for ExtDirect
if (TYPO3_MODE === 'FE') {
$this->addInlineLanguageLabelArray(array(
'extDirect_timeoutHeader' => $GLOBALS['TSFE']->sL('LLL:EXT:lang/locallang_misc.xlf:extDirect_timeoutHeader'),
'extDirect_timeoutMessage' => $GLOBALS['TSFE']->sL('LLL:EXT:lang/locallang_misc.xlf:extDirect_timeoutMessage')
));
} else {
$this->addInlineLanguageLabelArray(array(
'extDirect_timeoutHeader' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xlf:extDirect_timeoutHeader'),
'extDirect_timeoutMessage' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xlf:extDirect_timeoutMessage')
));
}
$token = ($api = '');
if (TYPO3_MODE === 'BE') {
$formprotection = \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get();
$token = $formprotection->generateToken('extDirect');
// Debugger Console strings
$this->addInlineLanguageLabelFile('EXT:core/Resources/Private/Language/debugger.xlf');
}
/** @var $extDirect \TYPO3\CMS\Core\ExtDirect\ExtDirectApi */
$extDirect = GeneralUtility::makeInstance(\TYPO3\CMS\Core\ExtDirect\ExtDirectApi::class);
$api = $extDirect->getApiPhp($filterNamespaces);
if ($api) {
$this->addJsInlineCode('TYPO3ExtDirectAPI', $api, FALSE);
}
// Note: we need to iterate thru the object, because the addProvider method
// does this only with multiple arguments
$this->addExtOnReadyCode('
(function() {
TYPO3.ExtDirectToken = "' . $token . '";
for (var api in Ext.app.ExtDirectAPI) {
var provider = Ext.Direct.addProvider(Ext.app.ExtDirectAPI[api]);
provider.on("beforecall", function(provider, transaction, meta) {
if (transaction.data) {
transaction.data[transaction.data.length] = TYPO3.ExtDirectToken;
} else {
transaction.data = [TYPO3.ExtDirectToken];
}
});
provider.on("call", function(provider, transaction, meta) {
if (transaction.isForm) {
transaction.params.securityToken = TYPO3.ExtDirectToken;
}
});
}
})();
var extDirectDebug = function(message, header, group) {
var TYPO3ViewportInstance = null;
if (top && top.TYPO3 && typeof top.TYPO3.Backend === "object") {
TYPO3ViewportInstance = top.TYPO3.Backend;
} else if (typeof TYPO3 === "object" && typeof TYPO3.Backend === "object") {
TYPO3ViewportInstance = TYPO3.Backend;
}
if (TYPO3ViewportInstance !== null) {
TYPO3ViewportInstance.DebugConsole.addTab(message, header, group);
} else if (typeof console === "object") {
console.log(message);
} else {
document.write(message);
}
};
Ext.Direct.on("exception", function(event) {
if (event.code === Ext.Direct.exceptions.TRANSPORT && !event.where) {
top.TYPO3.Notification.error(
TYPO3.l10n.localize("extDirect_timeoutHeader"),
TYPO3.l10n.localize("extDirect_timeoutMessage")
);
} else {
var backtrace = "";
if (event.code === "parse") {
extDirectDebug(
"<p>" + event.xhr.responseText + "<\\/p>",
event.type,
"ExtDirect - Exception"
);
} else if (event.code === "router") {
top.TYPO3.Notification.error(
event.code,
event.message
);
} else if (event.where) {
backtrace = "<p style=\\"margin-top: 20px;\\">" +
"<strong>Backtrace:<\\/strong><br \\/>" +
event.where.replace(/#/g, "<br \\/>#") +
"<\\/p>";
extDirectDebug(
"<p>" + event.message + "<\\/p>" + backtrace,
event.method,
"ExtDirect - Exception"
);
}
}
});
Ext.Direct.on("event", function(event, provider) {
if (typeof event.debug !== "undefined" && event.debug !== "") {
extDirectDebug(event.debug, event.method, "ExtDirect - Debug");
}
});
', TRUE);
}
/**
* Adds CSS file
*
* @param string $file
* @param string $rel
* @param string $media
* @param string $title
* @param bool $compress
* @param bool $forceOnTop
* @param string $allWrap
* @param bool $excludeFromConcatenation
* @param string $splitChar The char used to split the allWrap value, default is "|"
* @return void
*/
public function addCssFile($file, $rel = 'stylesheet', $media = 'all', $title = '', $compress = TRUE, $forceOnTop = FALSE, $allWrap = '', $excludeFromConcatenation = FALSE, $splitChar = '|') {
if (!isset($this->cssFiles[$file])) {
$this->cssFiles[$file] = array(
'file' => $file,
'rel' => $rel,
'media' => $media,
'title' => $title,
'compress' => $compress,
'forceOnTop' => $forceOnTop,
'allWrap' => $allWrap,
'excludeFromConcatenation' => $excludeFromConcatenation,
'splitChar' => $splitChar
);
}
}
/**
* Adds CSS file
*
* @param string $file
* @param string $rel
* @param string $media
* @param string $title
* @param bool $compress
* @param bool $forceOnTop
* @param string $allWrap
* @param bool $excludeFromConcatenation
* @param string $splitChar The char used to split the allWrap value, default is "|"
* @return void
*/
public function addCssLibrary($file, $rel = 'stylesheet', $media = 'all', $title = '', $compress = TRUE, $forceOnTop = FALSE, $allWrap = '', $excludeFromConcatenation = FALSE, $splitChar = '|') {
if (!isset($this->cssLibs[$file])) {
$this->cssLibs[$file] = array(
'file' => $file,
'rel' => $rel,
'media' => $media,
'title' => $title,
'compress' => $compress,
'forceOnTop' => $forceOnTop,
'allWrap' => $allWrap,
'excludeFromConcatenation' => $excludeFromConcatenation,
'splitChar' => $splitChar
);
}
}
/**
* Adds CSS inline code
*
* @param string $name
* @param string $block
* @param bool $compress
* @param bool $forceOnTop
* @return void
*/
public function addCssInlineBlock($name, $block, $compress = FALSE, $forceOnTop = FALSE) {
if (!isset($this->cssInline[$name]) && !empty($block)) {
$this->cssInline[$name] = array(
'code' => $block,
'compress' => $compress,
'forceOnTop' => $forceOnTop
);
}
}
/**
* Call this function if you need to include the jQuery library
*
* @param null|string $version The jQuery version that should be included, either "latest" or any available version
* @param null|string $source The location of the jQuery source, can be "local", "google", "msn", "jquery" or just an URL to your jQuery lib
* @param string $namespace The namespace in which the jQuery object of the specific version should be stored.
* @return void
* @throws \UnexpectedValueException
*/
public function loadJquery($version = NULL, $source = NULL, $namespace = self::JQUERY_NAMESPACE_DEFAULT) {
// Set it to the version that is shipped with the TYPO3 core
if ($version === NULL || $version === 'latest') {
$version = self::JQUERY_VERSION_LATEST;
}
// Check if the source is set, otherwise set it to "default"
if ($source === NULL) {
$source = 'local';
}
if ($source === 'local' && !in_array($version, $this->availableLocalJqueryVersions)) {
throw new \UnexpectedValueException('The requested jQuery version is not available in the local filesystem.', 1341505305);
}
if (!preg_match('/^[a-zA-Z0-9]+$/', $namespace)) {
throw new \UnexpectedValueException('The requested namespace contains non alphanumeric characters.', 1341571604);
}
$this->jQueryVersions[$namespace] = array(
'version' => $version,
'source' => $source
);
}
/**
* Call function if you need the requireJS library
* this automatically adds the JavaScript path of all loaded extensions in the requireJS path option
* so it resolves names like TYPO3/CMS/MyExtension/MyJsFile to EXT:MyExtension/Resources/Public/JavaScript/MyJsFile.js
* when using requireJS
*
* @return void
*/
public function loadRequireJs() {
// load all paths to map to package names / namespaces
if (empty($this->requireJsConfig)) {
// In order to avoid browser caching of JS files, adding a GET parameter to the files loaded via requireJS
if (GeneralUtility::getApplicationContext()->isDevelopment()) {
$this->requireJsConfig['urlArgs'] = 'bust=' . $GLOBALS['EXEC_TIME'];
} else {
$this->requireJsConfig['urlArgs'] = 'bust=' . GeneralUtility::hmac(TYPO3_version . PATH_site);
}
// first, load all paths for the namespaces, and configure contrib libs.
$this->requireJsConfig['paths'] = array(
'jquery-ui' => $this->backPath . 'sysext/core/Resources/Public/JavaScript/Contrib/jquery-ui',
'datatables' => $this->backPath . 'sysext/core/Resources/Public/JavaScript/Contrib/jquery.dataTables',
'nprogress' => $this->backPath . 'sysext/core/Resources/Public/JavaScript/Contrib/nprogress',
'moment' => $this->backPath . 'sysext/core/Resources/Public/JavaScript/Contrib/moment',
'cropper' => $this->backPath . 'sysext/core/Resources/Public/JavaScript/Contrib/cropper.min',
'imagesloaded' => $this->backPath . 'sysext/core/Resources/Public/JavaScript/Contrib/imagesloaded.pkgd.min',
'bootstrap' => $this->backPath . 'sysext/core/Resources/Public/JavaScript/Contrib/bootstrap/bootstrap',
'twbs/bootstrap-datetimepicker' => $this->backPath . 'sysext/core/Resources/Public/JavaScript/Contrib/bootstrap-datetimepicker',
'autosize' => $this->backPath . 'sysext/core/Resources/Public/JavaScript/Contrib/autosize',
'taboverride' => $this->backPath . 'sysext/core/Resources/Public/JavaScript/Contrib/taboverride.min',
'twbs/bootstrap-slider' => $this->backPath . 'sysext/core/Resources/Public/JavaScript/Contrib/bootstrap-slider.min',
'jquery/autocomplete' => $this->backPath . 'sysext/core/Resources/Public/JavaScript/Contrib/jquery.autocomplete',
);
// get all extensions that are loaded
$loadedExtensions = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::getLoadedExtensionListArray();
foreach ($loadedExtensions as $packageName) {
$fullJsPath = 'EXT:' . $packageName . '/Resources/Public/JavaScript/';
$fullJsPath = GeneralUtility::getFileAbsFileName($fullJsPath);
$fullJsPath = \TYPO3\CMS\Core\Utility\PathUtility::getRelativePath(PATH_typo3, $fullJsPath);
$fullJsPath = rtrim($fullJsPath, '/');
if ($fullJsPath) {
$this->requireJsConfig['paths']['TYPO3/CMS/' . GeneralUtility::underscoredToUpperCamelCase($packageName)] = $this->backPath . $fullJsPath;
}
}
// check if additional AMD modules need to be loaded if a single AMD module is initialized
if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['RequireJS']['postInitializationModules'])) {
$this->addInlineSettingArray('RequireJS.PostInitializationModules', $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['RequireJS']['postInitializationModules']);
}
}
$this->addRequireJs = TRUE;
}
/**
* Add additional configuration to require js.
*
* Configuration will be merged recursive with overrule.
*
* To add another path mapping deliver the following configuration:
* 'paths' => array(
* 'EXTERN/mybootstrapjs' => 'sysext/.../twbs/bootstrap.min',
* ),
*
* @param array $configuration The configuration that will be merged with existing one.
* @return void
*/
public function addRequireJsConfiguration(array $configuration) {
\TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($this->requireJsConfig, $configuration);
}
/**
* includes an AMD-compatible JS file by resolving the ModuleName, and then requires the file via a requireJS request,
* additionally allowing to execute JavaScript code afterwards
*
* this function only works for AMD-ready JS modules, used like "define('TYPO3/CMS/Backend/FormEngine..."
* in the JS file
*
* TYPO3/CMS/Backend/FormEngine =>
* "TYPO3": Vendor Name
* "CMS": Product Name
* "Backend": Extension Name
* "FormEngine": FileName in the Resources/Public/JavaScript folder
*
* @param string $mainModuleName Must be in the form of "TYPO3/CMS/PackageName/ModuleName" e.g. "TYPO3/CMS/Backend/FormEngine"
* @param string $callBackFunction loaded right after the requireJS loading, must be wrapped in function() {}
* @return void
*/
public function loadRequireJsModule($mainModuleName, $callBackFunction = NULL) {
$inlineCodeKey = $mainModuleName;
// make sure requireJS is initialized
$this->loadRequireJs();
// execute the main module, and load a possible callback function
$javaScriptCode = 'require(["' . $mainModuleName . '"]';
if ($callBackFunction !== NULL) {
$inlineCodeKey .= sha1($callBackFunction);
$javaScriptCode .= ', ' . $callBackFunction;
}
$javaScriptCode .= ');';
$this->addJsInlineCode('RequireJS-Module-' . $inlineCodeKey, $javaScriptCode);
}
/**
* call this function if you need the extJS library
*
* @param bool $css Flag, if set the ext-css will be loaded
* @param bool $theme Flag, if set the ext-theme "grey" will be loaded
* @return void
*/
public function loadExtJS($css = TRUE, $theme = TRUE) {
$this->addExtJS = TRUE;
$this->extJStheme = $theme;
$this->extJScss = $css;
}
/**
* Call this function to load debug version of ExtJS. Use this for development only
*
* @return void
*/
public function enableExtJsDebug() {
$this->enableExtJsDebug = TRUE;
}
/**
* Adds Javascript Inline Label. This will occur in TYPO3.lang - object
* The label can be used in scripts with TYPO3.lang.<key>
* Need extJs loaded
*
* @param string $key
* @param string $value
* @return void
*/
public function addInlineLanguageLabel($key, $value) {
$this->inlineLanguageLabels[$key] = $value;
}
/**
* Adds Javascript Inline Label Array. This will occur in TYPO3.lang - object
* The label can be used in scripts with TYPO3.lang.<key>
* Array will be merged with existing array.
* Need extJs loaded
*
* @param array $array
* @param bool $parseWithLanguageService
* @return void
*/
public function addInlineLanguageLabelArray(array $array, $parseWithLanguageService = FALSE) {
if ($parseWithLanguageService === TRUE) {
foreach ($array as $key => $value) {
$array[$key] = $this->getLanguageService()->sL($value);
}
}
$this->inlineLanguageLabels = array_merge($this->inlineLanguageLabels, $array);
}
/**
* Gets labels to be used in JavaScript fetched from a locallang file.
*
* @param string $fileRef Input is a file-reference (see GeneralUtility::getFileAbsFileName). That file is expected to be a 'locallang.xlf' file containing a valid XML TYPO3 language structure.
* @param string $selectionPrefix Prefix to select the correct labels (default: '')
* @param string $stripFromSelectionName Sub-prefix to be removed from label names in the result (default: '')
* @param int $errorMode Error mode (when file could not be found): 0 - syslog entry, 1 - do nothing, 2 - throw an exception
* @return void
*/
public function addInlineLanguageLabelFile($fileRef, $selectionPrefix = '', $stripFromSelectionName = '', $errorMode = 0) {
$index = md5($fileRef . $selectionPrefix . $stripFromSelectionName);
if ($fileRef && !isset($this->inlineLanguageLabelFiles[$index])) {
$this->inlineLanguageLabelFiles[$index] = array(
'fileRef' => $fileRef,
'selectionPrefix' => $selectionPrefix,
'stripFromSelectionName' => $stripFromSelectionName,
'errorMode' => $errorMode
);
}
}
/**
* Adds Javascript Inline Setting. This will occur in TYPO3.settings - object
* The label can be used in scripts with TYPO3.setting.<key>
* Need extJs loaded
*
* @param string $namespace
* @param string $key
* @param string $value
* @return void
*/
public function addInlineSetting($namespace, $key, $value) {
if ($namespace) {
if (strpos($namespace, '.')) {
$parts = explode('.', $namespace);
$a = &$this->inlineSettings;
foreach ($parts as $part) {
$a = &$a[$part];
}
$a[$key] = $value;
} else {
$this->inlineSettings[$namespace][$key] = $value;
}
} else {
$this->inlineSettings[$key] = $value;
}
}
/**
* Adds Javascript Inline Setting. This will occur in TYPO3.settings - object
* The label can be used in scripts with TYPO3.setting.<key>
* Array will be merged with existing array.
* Need extJs loaded
*
* @param string $namespace
* @param array $array
* @return void
*/
public function addInlineSettingArray($namespace, array $array) {
if ($namespace) {
if (strpos($namespace, '.')) {
$parts = explode('.', $namespace);
$a = &$this->inlineSettings;
foreach ($parts as $part) {
$a = &$a[$part];
}
$a = array_merge((array)$a, $array);
} else {
$this->inlineSettings[$namespace] = array_merge((array)$this->inlineSettings[$namespace], $array);
}
} else {
$this->inlineSettings = array_merge($this->inlineSettings, $array);
}
}
/**
* Adds content to body content
*
* @param string $content
* @return void
*/
public function addBodyContent($content) {
$this->bodyContent .= $content;
}
/*****************************************************/
/* */
/* Render Functions */
/* */
/*****************************************************/
/**
* Render the section (Header or Footer)
*
* @param int $part Section which should be rendered: self::PART_COMPLETE, self::PART_HEADER or self::PART_FOOTER
* @return string Content of rendered section
*/
public function render($part = self::PART_COMPLETE) {
$this->prepareRendering();
list($jsLibs, $jsFiles, $jsFooterFiles, $cssLibs, $cssFiles, $jsInline, $cssInline, $jsFooterInline, $jsFooterLibs) = $this->renderJavaScriptAndCss();
$metaTags = implode(LF, $this->metaTags);
$markerArray = $this->getPreparedMarkerArray($jsLibs, $jsFiles, $jsFooterFiles, $cssLibs, $cssFiles, $jsInline, $cssInline, $jsFooterInline, $jsFooterLibs, $metaTags);
$template = $this->getTemplateForPart($part);
// The page renderer needs a full reset, even when only rendering one part of the page
// This means that you can only register footer files *after* the header has been already rendered.
// In case you render the footer part first, header files can only be added *after* the footer has been rendered
$this->reset();
return trim(\TYPO3\CMS\Core\Html\HtmlParser::substituteMarkerArray($template, $markerArray, '###|###'));
}
/**
* Render the page but not the JavaScript and CSS Files
*
* @param string $substituteHash The hash that is used for the placehoder markers
* @access private
* @return string Content of rendered section
*/
public function renderPageWithUncachedObjects($substituteHash) {
$this->prepareRendering();
$markerArray = $this->getPreparedMarkerArrayForPageWithUncachedObjects($substituteHash);
$template = $this->getTemplateForPart(self::PART_COMPLETE);
return trim(\TYPO3\CMS\Core\Html\HtmlParser::substituteMarkerArray($template, $markerArray, '###|###'));
}
/**
* Renders the JavaScript and CSS files that have been added during processing
* of uncached content objects (USER_INT, COA_INT)
*
* @param string $cachedPageContent
* @param string $substituteHash The hash that is used for the placehoder markers
* @access private
* @return string
*/
public function renderJavaScriptAndCssForProcessingOfUncachedContentObjects($cachedPageContent, $substituteHash) {
$this->prepareRendering();
list($jsLibs, $jsFiles, $jsFooterFiles, $cssLibs, $cssFiles, $jsInline, $cssInline, $jsFooterInline, $jsFooterLibs) = $this->renderJavaScriptAndCss();
$title = $this->title ? str_replace('|', htmlspecialchars($this->title), $this->titleTag) : '';
$markerArray = array(
'<!-- ###TITLE' . $substituteHash . '### -->' => $title,
'<!-- ###CSS_LIBS' . $substituteHash . '### -->' => $cssLibs,
'<!-- ###CSS_INCLUDE' . $substituteHash . '### -->' => $cssFiles,
'<!-- ###CSS_INLINE' . $substituteHash . '### -->' => $cssInline,
'<!-- ###JS_INLINE' . $substituteHash . '### -->' => $jsInline,
'<!-- ###JS_INCLUDE' . $substituteHash . '### -->' => $jsFiles,
'<!-- ###JS_LIBS' . $substituteHash . '### -->' => $jsLibs,
'<!-- ###HEADERDATA' . $substituteHash . '### -->' => implode(LF, $this->headerData),
'<!-- ###FOOTERDATA' . $substituteHash . '### -->' => implode(LF, $this->footerData),
'<!-- ###JS_LIBS_FOOTER' . $substituteHash . '### -->' => $jsFooterLibs,
'<!-- ###JS_INCLUDE_FOOTER' . $substituteHash . '### -->' => $jsFooterFiles,
'<!-- ###JS_INLINE_FOOTER' . $substituteHash . '### -->' => $jsFooterInline
);
foreach ($markerArray as $placeHolder => $content) {
$cachedPageContent = str_replace($placeHolder, $content, $cachedPageContent);
}
$this->reset();
return $cachedPageContent;
}
/**
* Remove ending slashes from static header block
* if the page is beeing rendered as html (not xhtml)
* and define property $this->endingSlash for further use
*
* @return void
*/
protected function prepareRendering() {
if ($this->getRenderXhtml()) {
$this->endingSlash = ' /';
} else {
$this->metaCharsetTag = str_replace(' />', '>', $this->metaCharsetTag);
$this->baseUrlTag = str_replace(' />', '>', $this->baseUrlTag);
$this->shortcutTag = str_replace(' />', '>', $this->shortcutTag);
$this->endingSlash = '';
}
}
/**
* Renders all JavaScript and CSS
*
* @return array<string>
*/
protected function renderJavaScriptAndCss() {
$this->executePreRenderHook();
$mainJsLibs = $this->renderMainJavaScriptLibraries();
if ($this->concatenateFiles || $this->concatenateJavascript || $this->concatenateCss) {
// Do the file concatenation
$this->doConcatenate();
}
if ($this->compressCss || $this->compressJavascript) {
// Do the file compression
$this->doCompress();
}
$this->executeRenderPostTransformHook();
$cssLibs = $this->renderCssLibraries();
$cssFiles = $this->renderCssFiles();
$cssInline = $this->renderCssInline();
list($jsLibs, $jsFooterLibs) = $this->renderAdditionalJavaScriptLibraries();
list($jsFiles, $jsFooterFiles) = $this->renderJavaScriptFiles();
list($jsInline, $jsFooterInline) = $this->renderInlineJavaScript();
$jsLibs = $mainJsLibs . $jsLibs;
if ($this->moveJsFromHeaderToFooter) {
$jsFooterLibs = $jsLibs . LF . $jsFooterLibs;
$jsLibs = '';
$jsFooterFiles = $jsFiles . LF . $jsFooterFiles;
$jsFiles = '';
$jsFooterInline = $jsInline . LF . $jsFooterInline;
$jsInline = '';
}
$this->executePostRenderHook($jsLibs, $jsFiles, $jsFooterFiles, $cssLibs, $cssFiles, $jsInline, $cssInline, $jsFooterInline, $jsFooterLibs);
return array($jsLibs, $jsFiles, $jsFooterFiles, $cssLibs, $cssFiles, $jsInline, $cssInline, $jsFooterInline, $jsFooterLibs);
}
/**
* Fills the marker array with the given strings and trims each value
*
* @param $jsLibs string
* @param $jsFiles string
* @param $jsFooterFiles string
* @param $cssLibs string
* @param $cssFiles string
* @param $jsInline string
* @param $cssInline string
* @param $jsFooterInline string
* @param $jsFooterLibs string
* @param $metaTags string
* @return array Marker array
*/
protected function getPreparedMarkerArray($jsLibs, $jsFiles, $jsFooterFiles, $cssLibs, $cssFiles, $jsInline, $cssInline, $jsFooterInline, $jsFooterLibs, $metaTags) {
$markerArray = array(
'XMLPROLOG_DOCTYPE' => $this->xmlPrologAndDocType,
'HTMLTAG' => $this->htmlTag,
'HEADTAG' => $this->headTag,
'METACHARSET' => $this->charSet ? str_replace('|', htmlspecialchars($this->charSet), $this->metaCharsetTag) : '',
'INLINECOMMENT' => $this->inlineComments ? LF . LF . '<!-- ' . LF . implode(LF, $this->inlineComments) . '-->' . LF . LF : '',
'BASEURL' => $this->baseUrl ? str_replace('|', $this->baseUrl, $this->baseUrlTag) : '',
'SHORTCUT' => $this->favIcon ? sprintf($this->shortcutTag, htmlspecialchars($this->favIcon), $this->iconMimeType) : '',
'CSS_LIBS' => $cssLibs,
'CSS_INCLUDE' => $cssFiles,
'CSS_INLINE' => $cssInline,
'JS_INLINE' => $jsInline,
'JS_INCLUDE' => $jsFiles,
'JS_LIBS' => $jsLibs,
'TITLE' => $this->title ? str_replace('|', htmlspecialchars($this->title), $this->titleTag) : '',
'META' => $metaTags,
'HEADERDATA' => $this->headerData ? implode(LF, $this->headerData) : '',
'FOOTERDATA' => $this->footerData ? implode(LF, $this->footerData) : '',
'JS_LIBS_FOOTER' => $jsFooterLibs,
'JS_INCLUDE_FOOTER' => $jsFooterFiles,
'JS_INLINE_FOOTER' => $jsFooterInline,
'BODY' => $this->bodyContent
);
$markerArray = array_map('trim', $markerArray);
return $markerArray;
}
/**
* Fills the marker array with the given strings and trims each value
*
* @param string $substituteHash The hash that is used for the placehoder markers
* @return array Marker array
*/
protected function getPreparedMarkerArrayForPageWithUncachedObjects($substituteHash) {
$markerArray = array(
'XMLPROLOG_DOCTYPE' => $this->xmlPrologAndDocType,
'HTMLTAG' => $this->htmlTag,
'HEADTAG' => $this->headTag,
'METACHARSET' => $this->charSet ? str_replace('|', htmlspecialchars($this->charSet), $this->metaCharsetTag) : '',
'INLINECOMMENT' => $this->inlineComments ? LF . LF . '<!-- ' . LF . implode(LF, $this->inlineComments) . '-->' . LF . LF : '',
'BASEURL' => $this->baseUrl ? str_replace('|', $this->baseUrl, $this->baseUrlTag) : '',
'SHORTCUT' => $this->favIcon ? sprintf($this->shortcutTag, htmlspecialchars($this->favIcon), $this->iconMimeType) : '',
'META' => implode(LF, $this->metaTags),
'BODY' => $this->bodyContent,
'TITLE' => '<!-- ###TITLE' . $substituteHash . '### -->',
'CSS_LIBS' => '<!-- ###CSS_LIBS' . $substituteHash . '### -->',
'CSS_INCLUDE' => '<!-- ###CSS_INCLUDE' . $substituteHash . '### -->',
'CSS_INLINE' => '<!-- ###CSS_INLINE' . $substituteHash . '### -->',
'JS_INLINE' => '<!-- ###JS_INLINE' . $substituteHash . '### -->',
'JS_INCLUDE' => '<!-- ###JS_INCLUDE' . $substituteHash . '### -->',
'JS_LIBS' => '<!-- ###JS_LIBS' . $substituteHash . '### -->',
'HEADERDATA' => '<!-- ###HEADERDATA' . $substituteHash . '### -->',
'FOOTERDATA' => '<!-- ###FOOTERDATA' . $substituteHash . '### -->',
'JS_LIBS_FOOTER' => '<!-- ###JS_LIBS_FOOTER' . $substituteHash . '### -->',
'JS_INCLUDE_FOOTER' => '<!-- ###JS_INCLUDE_FOOTER' . $substituteHash . '### -->',
'JS_INLINE_FOOTER' => '<!-- ###JS_INLINE_FOOTER' . $substituteHash . '### -->'
);
$markerArray = array_map('trim', $markerArray);
return $markerArray;
}
/**
* Reads the template file and returns the requested part as string
*
* @param int $part
* @return string
*/
protected function getTemplateForPart($part) {
$templateFile = GeneralUtility::getFileAbsFileName($this->templateFile, TRUE);
$template = GeneralUtility::getUrl($templateFile);
if ($this->removeLineBreaksFromTemplate) {
$template = strtr($template, array(LF => '', CR => ''));
}
if ($part !== self::PART_COMPLETE) {
$templatePart = explode('###BODY###', $template);
$template = $templatePart[$part - 1];
}
return $template;
}
/**
* Helper function for render the main JavaScript libraries,
* currently: RequireJS, jQuery, ExtJS
*
* @return string Content with JavaScript libraries
*/
protected function renderMainJavaScriptLibraries() {
$out = '';
// Include RequireJS
if ($this->addRequireJs) {
// load the paths of the requireJS configuration
$out .= GeneralUtility::wrapJS('var require = ' . json_encode($this->requireJsConfig)) . LF;
// directly after that, include the require.js file
$out .= '<script src="' . $this->processJsFile(($this->backPath . $this->requireJsPath . 'require.js')) . '" type="text/javascript"></script>' . LF;
}
// Include jQuery Core for each namespace, depending on the version and source
if (!empty($this->jQueryVersions)) {
foreach ($this->jQueryVersions as $namespace => $jQueryVersion) {
$out .= $this->renderJqueryScriptTag($jQueryVersion['version'], $jQueryVersion['source'], $namespace);
}
}
// Include extJS
if ($this->addExtJS) {
// Use the base adapter all the time
$out .= '<script src="' . $this->processJsFile(($this->backPath . $this->extJsPath . 'adapter/ext-base' . ($this->enableExtJsDebug ? '-debug' : '') . '.js')) . '" type="text/javascript"></script>' . LF;
$out .= '<script src="' . $this->processJsFile(($this->backPath . $this->extJsPath . 'ext-all' . ($this->enableExtJsDebug ? '-debug' : '') . '.js')) . '" type="text/javascript"></script>' . LF;
// Add extJS localization
// Load standard ISO mapping and modify for use with ExtJS
$localeMap = $this->locales->getIsoMapping();
$localeMap[''] = 'en';
$localeMap['default'] = 'en';
// Greek
$localeMap['gr'] = 'el_GR';
// Norwegian Bokmaal
$localeMap['no'] = 'no_BO';
// Swedish
$localeMap['se'] = 'se_SV';
$extJsLang = isset($localeMap[$this->lang]) ? $localeMap[$this->lang] : $this->lang;
// @todo autoconvert file from UTF8 to current BE charset if necessary!!!!
$extJsLocaleFile = $this->extJsPath . 'locale/ext-lang-' . $extJsLang . '.js';
if (file_exists(PATH_typo3 . $extJsLocaleFile)) {
$out .= '<script src="' . $this->processJsFile(($this->backPath . $extJsLocaleFile)) . '" type="text/javascript" charset="utf-8"></script>' . LF;
}
// Remove extjs from JScodeLibArray
unset($this->jsFiles[$this->backPath . $this->extJsPath . 'ext-all.js'], $this->jsFiles[$this->backPath . $this->extJsPath . 'ext-all-debug.js']);
}
$this->loadJavaScriptLanguageStrings();
if (TYPO3_MODE === 'BE') {
$this->addAjaxUrlsToInlineSettings();
}
$inlineSettings = $this->inlineLanguageLabels ? 'TYPO3.lang = ' . json_encode($this->inlineLanguageLabels) . ';' : '';
$inlineSettings .= $this->inlineSettings ? 'TYPO3.settings = ' . json_encode($this->inlineSettings) . ';' : '';
if ($this->addExtJS) {
// Set clear.gif, move it on top, add handler code
$code = '';
if (!empty($this->extOnReadyCode)) {
foreach ($this->extOnReadyCode as $block) {
$code .= $block;
}
}
$out .= $this->inlineJavascriptWrap[0] . '
Ext.ns("TYPO3");
Ext.BLANK_IMAGE_URL = "' . htmlspecialchars(GeneralUtility::locationHeaderUrl(($this->backPath . 'gfx/clear.gif'))) . '";
Ext.SSL_SECURE_URL = "' . htmlspecialchars(GeneralUtility::locationHeaderUrl(($this->backPath . 'gfx/clear.gif'))) . '";' . LF
. $inlineSettings
. 'Ext.onReady(function() {'
. $code
. ' });'
. $this->inlineJavascriptWrap[1];
$this->extOnReadyCode = array();
// Include TYPO3.l10n object
if (TYPO3_MODE === 'BE') {
$out .= '<script src="' . $this->processJsFile(($this->backPath . 'sysext/lang/Resources/Public/JavaScript/Typo3Lang.js')) . '" type="text/javascript" charset="utf-8"></script>' . LF;
}
if ($this->extJScss) {
if (isset($GLOBALS['TBE_STYLES']['extJS']['all'])) {
$this->addCssLibrary($this->backPath . $GLOBALS['TBE_STYLES']['extJS']['all'], 'stylesheet', 'all', '', TRUE);
} else {
$this->addCssLibrary($this->backPath . $this->extJsPath . 'resources/css/ext-all-notheme.css', 'stylesheet', 'all', '', TRUE);
}
}
if ($this->extJStheme) {
if (isset($GLOBALS['TBE_STYLES']['extJS']['theme'])) {
$this->addCssLibrary($this->backPath . $GLOBALS['TBE_STYLES']['extJS']['theme'], 'stylesheet', 'all', '', TRUE);
} else {
$this->addCssLibrary($this->backPath . $this->extJsPath . 'resources/css/xtheme-blue.css', 'stylesheet', 'all', '', TRUE);
}
}
} else {
// no extJS loaded, but still inline settings
if ($inlineSettings !== '') {
// make sure the global TYPO3 is available
$inlineSettings = 'var TYPO3 = TYPO3 || {};' . CRLF . $inlineSettings;
$out .= $this->inlineJavascriptWrap[0] . $inlineSettings . $this->inlineJavascriptWrap[1];
// Add language module only if also jquery is guaranteed to be there
if (TYPO3_MODE === 'BE' && !empty($this->jQueryVersions)) {
$this->loadRequireJsModule('TYPO3/CMS/Lang/Lang');
}
}
}
return $out;
}
/**
* Load the language strings into JavaScript
*/
protected function loadJavaScriptLanguageStrings() {
if (!empty($this->inlineLanguageLabelFiles)) {
foreach ($this->inlineLanguageLabelFiles as $languageLabelFile) {
$this->includeLanguageFileForInline($languageLabelFile['fileRef'], $languageLabelFile['selectionPrefix'], $languageLabelFile['stripFromSelectionName'], $languageLabelFile['errorMode']);
}
}
$this->inlineLanguageLabelFiles = array();
// Convert labels/settings back to UTF-8 since json_encode() only works with UTF-8:
if (TYPO3_MODE === 'FE' && $this->getCharSet() !== 'utf-8') {
if ($this->inlineLanguageLabels) {
$this->csConvObj->convArray($this->inlineLanguageLabels, $this->getCharSet(), 'utf-8');
}
if ($this->inlineSettings) {
$this->csConvObj->convArray($this->inlineSettings, $this->getCharSet(), 'utf-8');
}
}
}
/**
* Make URLs to all backend ajax handlers available as inline setting.
*/
protected function addAjaxUrlsToInlineSettings() {
$ajaxUrls = array();
foreach ($GLOBALS['TYPO3_CONF_VARS']['BE']['AJAX'] as $ajaxHandler => $_) {
$ajaxUrls[$ajaxHandler] = BackendUtility::getAjaxUrl($ajaxHandler);
}
$this->inlineSettings['ajaxUrls'] = $ajaxUrls;
}
/**
* Renders the HTML script tag for the given jQuery version.
*
* @param string $version The jQuery version that should be included, either "latest" or any available version
* @param string $source The location of the jQuery source, can be "local", "google", "msn" or "jquery
* @param string $namespace The namespace in which the jQuery object of the specific version should be stored
* @return string
*/
protected function renderJqueryScriptTag($version, $source, $namespace) {
switch (TRUE) {
case isset($this->jQueryCdnUrls[$source]):
if ($this->enableJqueryDebug) {
$minifyPart = '';
} else {
$minifyPart = '.min';
}
$jQueryFileName = sprintf($this->jQueryCdnUrls[$source], $version, $minifyPart);
break;
case $source === 'local':
$jQueryFileName = $this->backPath . $this->jQueryPath . 'jquery-' . rawurlencode($version);
if ($this->enableJqueryDebug) {
$jQueryFileName .= '.js';
} else {
$jQueryFileName .= '.min.js';
}
break;
default:
$jQueryFileName = $source;
}
// Include the jQuery Core
$scriptTag = '<script src="' . htmlspecialchars($jQueryFileName) . '" type="text/javascript"></script>' . LF;
// Set the noConflict mode to be available via "TYPO3.jQuery" in all installations
switch ($namespace) {
case self::JQUERY_NAMESPACE_DEFAULT_NOCONFLICT:
$scriptTag .= GeneralUtility::wrapJS('jQuery.noConflict();') . LF;
break;
case self::JQUERY_NAMESPACE_NONE:
break;
case self::JQUERY_NAMESPACE_DEFAULT:
default:
$scriptTag .= GeneralUtility::wrapJS('var TYPO3 = TYPO3 || {}; TYPO3.' . $namespace . ' = jQuery.noConflict(true);') . LF;
}
return $scriptTag;
}
/**
* Render CSS library files
*
* @return string
*/
protected function renderCssLibraries() {
$cssFiles = '';
if (!empty($this->cssLibs)) {
foreach ($this->cssLibs as $file => $properties) {
$file = GeneralUtility::resolveBackPath($file);
$file = GeneralUtility::createVersionNumberedFilename($file);
$tag = '<link rel="' . htmlspecialchars($properties['rel'])
. '" type="text/css" href="' . htmlspecialchars($file)
. '" media="' . htmlspecialchars($properties['media']) . '"'
. ($properties['title'] ? ' title="' . htmlspecialchars($properties['title']) . '"' : '')
. $this->endingSlash . '>';
if ($properties['allWrap']) {
$wrapArr = explode($properties['splitChar'] ?: '|', $properties['allWrap'], 2);
$tag = $wrapArr[0] . $tag . $wrapArr[1];
}
$tag .= LF;
if ($properties['forceOnTop']) {
$cssFiles = $tag . $cssFiles;
} else {
$cssFiles .= $tag;
}
}
}
return $cssFiles;
}
/**
* Render CSS files
*
* @return string
*/
protected function renderCssFiles() {
$cssFiles = '';
if (!empty($this->cssFiles)) {
foreach ($this->cssFiles as $file => $properties) {
$file = GeneralUtility::resolveBackPath($file);
$file = GeneralUtility::createVersionNumberedFilename($file);
$tag = '<link rel="' . htmlspecialchars($properties['rel'])
. '" type="text/css" href="' . htmlspecialchars($file)
. '" media="' . htmlspecialchars($properties['media']) . '"'
. ($properties['title'] ? ' title="' . htmlspecialchars($properties['title']) . '"' : '')
. $this->endingSlash . '>';
if ($properties['allWrap']) {
$wrapArr = explode($properties['splitChar'] ?: '|', $properties['allWrap'], 2);
$tag = $wrapArr[0] . $tag . $wrapArr[1];
}
$tag .= LF;
if ($properties['forceOnTop']) {
$cssFiles = $tag . $cssFiles;
} else {
$cssFiles .= $tag;
}
}
}
return $cssFiles;
}
/**
* Render inline CSS
*
* @return string
*/
protected function renderCssInline() {
$cssInline = '';
if (!empty($this->cssInline)) {
foreach ($this->cssInline as $name => $properties) {
$cssCode = '/*' . htmlspecialchars($name) . '*/' . LF . $properties['code'] . LF;
if ($properties['forceOnTop']) {
$cssInline = $cssCode . $cssInline;
} else {
$cssInline .= $cssCode;
}
}
$cssInline = $this->inlineCssWrap[0] . $cssInline . $this->inlineCssWrap[1];
}
return $cssInline;
}
/**
* Render JavaScipt libraries
*
* @return array<string> jsLibs and jsFooterLibs strings
*/
protected function renderAdditionalJavaScriptLibraries() {
$jsLibs = '';
$jsFooterLibs = '';
if (!empty($this->jsLibs)) {
foreach ($this->jsLibs as $properties) {
$properties['file'] = GeneralUtility::resolveBackPath($properties['file']);
$properties['file'] = GeneralUtility::createVersionNumberedFilename($properties['file']);
$async = ($properties['async']) ? ' async="async"' : '';
$integrity = ($properties['integrity']) ? ' integrity="' . htmlspecialchars($properties['integrity']) . '"' : '';
$tag = '<script src="' . htmlspecialchars($properties['file']) . '" type="' . htmlspecialchars($properties['type']) . '"' . $async . $integrity . '></script>';
if ($properties['allWrap']) {
$wrapArr = explode($properties['splitChar'] ?: '|', $properties['allWrap'], 2);
$tag = $wrapArr[0] . $tag . $wrapArr[1];
}
$tag .= LF;
if ($properties['forceOnTop']) {
if ($properties['section'] === self::PART_HEADER) {
$jsLibs = $tag . $jsLibs;
} else {
$jsFooterLibs = $tag . $jsFooterLibs;
}
} else {
if ($properties['section'] === self::PART_HEADER) {
$jsLibs .= $tag;
} else {
$jsFooterLibs .= $tag;
}
}
}
}
if ($this->moveJsFromHeaderToFooter) {
$jsFooterLibs = $jsLibs . LF . $jsFooterLibs;
$jsLibs = '';
}
return array($jsLibs, $jsFooterLibs);
}
/**
* Render JavaScript files
*
* @return array<string> jsFiles and jsFooterFiles strings
*/
protected function renderJavaScriptFiles() {
$jsFiles = '';
$jsFooterFiles = '';
if (!empty($this->jsFiles)) {
foreach ($this->jsFiles as $file => $properties) {
$file = GeneralUtility::resolveBackPath($file);
$file = GeneralUtility::createVersionNumberedFilename($file);
$async = ($properties['async']) ? ' async="async"' : '';
$integrity = ($properties['integrity']) ? ' integrity="' . htmlspecialchars($properties['integrity']) . '"' : '';
$tag = '<script src="' . htmlspecialchars($file) . '" type="' . htmlspecialchars($properties['type']) . '"' . $async . $integrity . '></script>';
if ($properties['allWrap']) {
$wrapArr = explode($properties['splitChar'] ?: '|', $properties['allWrap'], 2);
$tag = $wrapArr[0] . $tag . $wrapArr[1];
}
$tag .= LF;
if ($properties['forceOnTop']) {
if ($properties['section'] === self::PART_HEADER) {
$jsFiles = $tag . $jsFiles;
} else {
$jsFooterFiles = $tag . $jsFooterFiles;
}
} else {
if ($properties['section'] === self::PART_HEADER) {
$jsFiles .= $tag;
} else {
$jsFooterFiles .= $tag;
}
}
}
}
if ($this->moveJsFromHeaderToFooter) {
$jsFooterFiles = $jsFiles . $jsFooterFiles;
$jsFiles = '';
}
return array($jsFiles, $jsFooterFiles);
}
/**
* Render inline JavaScript
*
* @return array<string> jsInline and jsFooterInline string
*/
protected function renderInlineJavaScript() {
$jsInline = '';
$jsFooterInline = '';
if (!empty($this->jsInline)) {
foreach ($this->jsInline as $name => $properties) {
$jsCode = '/*' . htmlspecialchars($name) . '*/' . LF . $properties['code'] . LF;
if ($properties['forceOnTop']) {
if ($properties['section'] === self::PART_HEADER) {
$jsInline = $jsCode . $jsInline;
} else {
$jsFooterInline = $jsCode . $jsFooterInline;
}
} else {
if ($properties['section'] === self::PART_HEADER) {
$jsInline .= $jsCode;
} else {
$jsFooterInline .= $jsCode;
}
}
}
}
if ($jsInline) {
$jsInline = $this->inlineJavascriptWrap[0] . $jsInline . $this->inlineJavascriptWrap[1];
}
if ($jsFooterInline) {
$jsFooterInline = $this->inlineJavascriptWrap[0] . $jsFooterInline . $this->inlineJavascriptWrap[1];
}
if ($this->moveJsFromHeaderToFooter) {
$jsFooterInline = $jsInline . $jsFooterInline;
$jsInline = '';
}
return array($jsInline, $jsFooterInline);
}
/**
* Include language file for inline usage
*
* @param string $fileRef
* @param string $selectionPrefix
* @param string $stripFromSelectionName
* @param int $errorMode
* @return void
* @throws \RuntimeException
*/
protected function includeLanguageFileForInline($fileRef, $selectionPrefix = '', $stripFromSelectionName = '', $errorMode = 0) {
if (!isset($this->lang) || !isset($this->charSet)) {
throw new \RuntimeException('Language and character encoding are not set.', 1284906026);
}
$labelsFromFile = array();
$allLabels = $this->readLLfile($fileRef, $errorMode);
// Regular expression to strip the selection prefix and possibly something from the label name:
$labelPattern = '#^' . preg_quote($selectionPrefix, '#') . '(' . preg_quote($stripFromSelectionName, '#') . ')?#';
if ($allLabels !== FALSE) {
// Merge language specific translations:
if ($this->lang !== 'default' && isset($allLabels[$this->lang])) {
$labels = array_merge($allLabels['default'], $allLabels[$this->lang]);
} else {
$labels = $allLabels['default'];
}
// Iterate through all locallang labels:
foreach ($labels as $label => $value) {
if ($selectionPrefix === '') {
$labelsFromFile[$label] = $value;
} elseif (strpos($label, $selectionPrefix) === 0) {
preg_replace($labelPattern, '', $label);
$labelsFromFile[$label] = $value;
}
}
$this->inlineLanguageLabels = array_merge($this->inlineLanguageLabels, $labelsFromFile);
}
}
/**
* Reads a locallang file.
*
* @param string $fileRef Reference to a relative filename to include.
* @param int $errorMode Error mode (when file could not be found): 0 - syslog entry, 1 - do nothing, 2 - throw an exception
* @return array Returns the $LOCAL_LANG array found in the file. If no array found, returns empty array.
*/
protected function readLLfile($fileRef, $errorMode = 0) {
/** @var $languageFactory LocalizationFactory */
$languageFactory = GeneralUtility::makeInstance(LocalizationFactory::class);
if ($this->lang !== 'default') {
$languages = array_reverse($this->languageDependencies);
// At least we need to have English
if (empty($languages)) {
$languages[] = 'default';
}
} else {
$languages = array('default');
}
$localLanguage = array();
foreach ($languages as $language) {
$tempLL = $languageFactory->getParsedData($fileRef, $language, $this->charSet, $errorMode);
$localLanguage['default'] = $tempLL['default'];
if (!isset($localLanguage[$this->lang])) {
$localLanguage[$this->lang] = $localLanguage['default'];
}
if ($this->lang !== 'default' && isset($tempLL[$language])) {
// Merge current language labels onto labels from previous language
// This way we have a labels with fall back applied
\TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($localLanguage[$this->lang], $tempLL[$language], TRUE, FALSE);
}
}
return $localLanguage;
}
/*****************************************************/
/* */
/* Tools */
/* */
/*****************************************************/
/**
* Concatenate files into one file
* registered handler
*
* @return void
*/
protected function doConcatenate() {
$this->doConcatenateCss();
$this->doConcatenateJavaScript();
}
/**
* Concatenate JavaScript files according to the configuration.
*
* @return void
*/
protected function doConcatenateJavaScript() {
if ($this->concatenateFiles || $this->concatenateJavascript) {
if (!empty($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['jsConcatenateHandler'])) {
// use external concatenation routine
$params = array(
'jsLibs' => &$this->jsLibs,
'jsFiles' => &$this->jsFiles,
'jsFooterFiles' => &$this->jsFooterFiles,
'headerData' => &$this->headerData,
'footerData' => &$this->footerData
);
GeneralUtility::callUserFunction($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['jsConcatenateHandler'], $params, $this);
} else {
$this->jsLibs = $this->getCompressor()->concatenateJsFiles($this->jsLibs);
$this->jsFiles = $this->getCompressor()->concatenateJsFiles($this->jsFiles);
$this->jsFooterFiles = $this->getCompressor()->concatenateJsFiles($this->jsFooterFiles);
}
}
}
/**
* Concatenate CSS files according to configuration.
*
* @return void
*/
protected function doConcatenateCss() {
if ($this->concatenateFiles || $this->concatenateCss) {
if (!empty($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['cssConcatenateHandler'])) {
// use external concatenation routine
$params = array(
'cssFiles' => &$this->cssFiles,
'cssLibs' => &$this->cssLibs,
'headerData' => &$this->headerData,
'footerData' => &$this->footerData
);
GeneralUtility::callUserFunction($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['cssConcatenateHandler'], $params, $this);
} else {
$cssOptions = array();
if (TYPO3_MODE === 'BE') {
$cssOptions = array('baseDirectories' => $GLOBALS['TBE_TEMPLATE']->getSkinStylesheetDirectories());
}
$this->cssLibs = $this->getCompressor()->concatenateCssFiles($this->cssLibs, $cssOptions);
$this->cssFiles = $this->getCompressor()->concatenateCssFiles($this->cssFiles, $cssOptions);
}
}
}
/**
* Compresses inline code
*
* @return void
*/
protected function doCompress() {
$this->doCompressJavaScript();
$this->doCompressCss();
}
/**
* Compresses CSS according to configuration.
*
* @return void
*/
protected function doCompressCss() {
if ($this->compressCss) {
if (!empty($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['cssCompressHandler'])) {
// Use external compression routine
$params = array(
'cssInline' => &$this->cssInline,
'cssFiles' => &$this->cssFiles,
'cssLibs' => &$this->cssLibs,
'headerData' => &$this->headerData,
'footerData' => &$this->footerData
);
GeneralUtility::callUserFunction($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['cssCompressHandler'], $params, $this);
} else {
$this->cssLibs = $this->getCompressor()->compressCssFiles($this->cssLibs);
$this->cssFiles = $this->getCompressor()->compressCssFiles($this->cssFiles);
}
}
}
/**
* Compresses JavaScript according to configuration.
*
* @return void
*/
protected function doCompressJavaScript() {
if ($this->compressJavascript) {
if (!empty($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['jsCompressHandler'])) {
// Use external compression routine
$params = array(
'jsInline' => &$this->jsInline,
'jsFooterInline' => &$this->jsFooterInline,
'jsLibs' => &$this->jsLibs,
'jsFiles' => &$this->jsFiles,
'jsFooterFiles' => &$this->jsFooterFiles,
'headerData' => &$this->headerData,
'footerData' => &$this->footerData
);
GeneralUtility::callUserFunction($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['jsCompressHandler'], $params, $this);
} else {
// Traverse the arrays, compress files
if (!empty($this->jsInline)) {
foreach ($this->jsInline as $name => $properties) {
if ($properties['compress']) {
$error = '';
$this->jsInline[$name]['code'] = GeneralUtility::minifyJavaScript($properties['code'], $error);
if ($error) {
$this->compressError .= 'Error with minify JS Inline Block "' . $name . '": ' . $error . LF;
}
}
}
}
$this->jsLibs = $this->getCompressor()->compressJsFiles($this->jsLibs);
$this->jsFiles = $this->getCompressor()->compressJsFiles($this->jsFiles);
$this->jsFooterFiles = $this->getCompressor()->compressJsFiles($this->jsFooterFiles);
}
}
}
/**
* Returns instance of \TYPO3\CMS\Core\Resource\ResourceCompressor
*
* @return \TYPO3\CMS\Core\Resource\ResourceCompressor
*/
protected function getCompressor() {
if ($this->compressor === NULL) {
$this->compressor = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\ResourceCompressor::class);
}
return $this->compressor;
}
/**
* Processes a Javascript file dependent on the current context
*
* Adds the version number for Frontend, compresses the file for Backend
*
* @param string $filename Filename
* @return string New filename
*/
protected function processJsFile($filename) {
switch (TYPO3_MODE) {
case 'FE':
if ($this->compressJavascript) {
$filename = $this->getCompressor()->compressJsFile($filename);
} else {
$filename = GeneralUtility::createVersionNumberedFilename($filename);
}
break;
case 'BE':
if ($this->compressJavascript) {
$filename = $this->getCompressor()->compressJsFile($filename);
}
break;
}
return $filename;
}
/**
* Returns global language service instance
*
* @return \TYPO3\CMS\Lang\LanguageService
*/
protected function getLanguageService() {
return $GLOBALS['LANG'];
}
/*****************************************************/
/* */
/* Hooks */
/* */
/*****************************************************/
/**
* Execute PreRenderHook for possible manipulation
*
* @return void
*/
protected function executePreRenderHook() {
if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_pagerenderer.php']['render-preProcess'])) {
$params = array(
'jsLibs' => &$this->jsLibs,
'jsFooterLibs' => &$this->jsFooterLibs,
'jsFiles' => &$this->jsFiles,
'jsFooterFiles' => &$this->jsFooterFiles,
'cssFiles' => &$this->cssFiles,
'headerData' => &$this->headerData,
'footerData' => &$this->footerData,
'jsInline' => &$this->jsInline,
'jsFooterInline' => &$this->jsFooterInline,
'cssInline' => &$this->cssInline
);
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_pagerenderer.php']['render-preProcess'] as $hook) {
GeneralUtility::callUserFunction($hook, $params, $this);
}
}
}
/**
* PostTransform for possible manipulation of concatenated and compressed files
*
* @return void
*/
protected function executeRenderPostTransformHook() {
if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_pagerenderer.php']['render-postTransform'])) {
$params = array(
'jsLibs' => &$this->jsLibs,
'jsFooterLibs' => &$this->jsFooterLibs,
'jsFiles' => &$this->jsFiles,
'jsFooterFiles' => &$this->jsFooterFiles,
'cssFiles' => &$this->cssFiles,
'headerData' => &$this->headerData,
'footerData' => &$this->footerData,
'jsInline' => &$this->jsInline,
'jsFooterInline' => &$this->jsFooterInline,
'cssInline' => &$this->cssInline
);
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_pagerenderer.php']['render-postTransform'] as $hook) {
GeneralUtility::callUserFunction($hook, $params, $this);
}
}
}
/**
* Execute postRenderHook for possible manipulation
*
* @param $jsLibs string
* @param $jsFiles string
* @param $jsFooterFiles string
* @param $cssLibs string
* @param $cssFiles string
* @param $jsInline string
* @param $cssInline string
* @param $jsFooterInline string
* @param $jsFooterLibs string
* @return void
*/
protected function executePostRenderHook(&$jsLibs, &$jsFiles, &$jsFooterFiles, &$cssLibs, &$cssFiles, &$jsInline, &$cssInline, &$jsFooterInline, &$jsFooterLibs) {
if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_pagerenderer.php']['render-postProcess'])) {
$params = array(
'jsLibs' => &$jsLibs,
'jsFiles' => &$jsFiles,
'jsFooterFiles' => &$jsFooterFiles,
'cssLibs' => &$cssLibs,
'cssFiles' => &$cssFiles,
'headerData' => &$this->headerData,
'footerData' => &$this->footerData,
'jsInline' => &$jsInline,
'cssInline' => &$cssInline,
'xmlPrologAndDocType' => &$this->xmlPrologAndDocType,
'htmlTag' => &$this->htmlTag,
'headTag' => &$this->headTag,
'charSet' => &$this->charSet,
'metaCharsetTag' => &$this->metaCharsetTag,
'shortcutTag' => &$this->shortcutTag,
'inlineComments' => &$this->inlineComments,
'baseUrl' => &$this->baseUrl,
'baseUrlTag' => &$this->baseUrlTag,
'favIcon' => &$this->favIcon,
'iconMimeType' => &$this->iconMimeType,
'titleTag' => &$this->titleTag,
'title' => &$this->title,
'metaTags' => &$this->metaTags,
'jsFooterInline' => &$jsFooterInline,
'jsFooterLibs' => &$jsFooterLibs,
'bodyContent' => &$this->bodyContent
);
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_pagerenderer.php']['render-postProcess'] as $hook) {
GeneralUtility::callUserFunction($hook, $params, $this);
}
}
}
}
|
gpl-2.0
|
srgg6701/WebApps
|
components/com_collector1/models/_options_beyond_sides.php
|
2044
|
<?php
/**
* @version 2.1.0
* @package com_collector1
* @copyright Copyright (C) webapps 2012. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
* @author srgg <srgg67@gmail.com> - http://www.facebook.com/srgg67
*/
defined('_JEXEC') or die;
jimport('joomla.application.component.modellist');
/**
* Methods supporting a list of Collector1 records.
*/
class Collector1Model_options_beyond_sides extends JModelList {
/**
* Constructor.
*
* @param array An optional associative array of configuration settings.
* @see JController
* @since 1.6
*/
public function __construct($config = array()) {
parent::__construct($config);
}
/**
* Method to auto-populate the model state.
*
* Note. Calling getState in this method will result in recursion.
*
* @since 1.6
*/
protected function populateState($ordering = null, $direction = null) {
// Initialise variables.
$app = JFactory::getApplication();
// List state information
$limit = $app->getUserStateFromRequest('global.list.limit', 'limit', $app->getCfg('list_limit'));
$this->setState('list.limit', $limit);
$limitstart = JRequest::getVar('limitstart', 0, '', 'int');
$this->setState('list.start', $limitstart);
// List state information.
parent::populateState();
}
/**
* Build an SQL query to load the list data.
*
* @return JDatabaseQuery
* @since 1.6
*/
protected function getListQuery() {
// Create a new query object.
$db = $this->getDbo();
$query = $db->getQuery(true);
// Select the required fields from the table.
$query->select(
$this->getState(
'list.select', 'a.*'
)
);
$query->from('`#__webapps_site_options_beyond_sides` AS a');
return $query;
}
}
|
gpl-2.0
|
ahsparrow/xcsoar_orig
|
src/Event/Linux/TTYKeyboard.hpp
|
2091
|
/*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2015 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program 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 Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
*/
#ifndef XCSOAR_EVENT_LINUX_TTY_KEYBOARD_HPP
#define XCSOAR_EVENT_LINUX_TTY_KEYBOARD_HPP
#include "IO/Async/FileEventHandler.hpp"
#include "Compiler.h"
#include <stdint.h>
class EventQueue;
class IOLoop;
/**
* A keyboard driver reading key presses from the TTY.
*/
class TTYKeyboard final : private FileEventHandler {
EventQueue &queue;
IOLoop &io_loop;
/**
* The current state of the multi-byte key code parser.
*/
enum class InputState : uint8_t {
/** Not currently parsing a multi-byte key code. */
NONE,
/** The "ESC" ASCII code was seen. */
ESCAPE,
/** "ESC" plus a square bracket was seen. */
ESCAPE_BRACKET,
/**
* "ESC" plus one or more digits was seen. See #input_number.
*/
ESCAPE_NUMBER,
/** "ESC" plus two square brackets were seen. */
ESCAPE_BRACKET2,
} input_state;
/**
* The number currently being parsed by #ESCAPE_NUMBER.
*/
unsigned input_number;
public:
TTYKeyboard(EventQueue &queue, IOLoop &io_loop);
~TTYKeyboard();
private:
void HandleInputByte(char ch);
/* virtual methods from FileEventHandler */
virtual bool OnFileEvent(int fd, unsigned mask) override;
};
#endif
|
gpl-2.0
|
tectronics/scummvm-for-sally
|
engines/m4/converse.cpp
|
40723
|
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program 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 Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* $URL: https://scummvm.svn.sourceforge.net/svnroot/scummvm/scummvm/tags/release-1-1-1/engines/m4/converse.cpp $
* $Id: converse.cpp 48172 2010-03-07 05:06:58Z dreammaster $
*
*/
#include "common/array.h"
#include "common/hashmap.h"
#include "m4/converse.h"
#include "m4/resource.h"
#include "m4/globals.h"
#include "m4/m4_views.h"
#include "m4/compression.h"
namespace M4 {
#define CONV_ENTRIES_X_OFFSET 20
#define CONV_ENTRIES_Y_OFFSET 4
#define CONV_ENTRIES_HEIGHT 20
#define CONV_MAX_SHOWN_ENTRIES 5
#define CONVERSATION_ENTRY_HIGHLIGHTED 22
#define CONVERSATION_ENTRY_NORMAL 3
// Conversation chunks
// Header
#define HEAD_CONV MKID_BE('CONV') // conversation
#define CHUNK_DECL MKID_BE('DECL') // declaration
#define CHUNK_NODE MKID_BE('NODE') // node
#define CHUNK_LNOD MKID_BE('LNOD') // linear node
#define CHUNK_ETRY MKID_BE('ETRY') // entry
#define CHUNK_TEXT MKID_BE('TEXT') // text
#define CHUNK_MESG MKID_BE('MESG') // message
// Conversation chunks - entry related (unconditional)
#define CHUNK_RPLY MKID_BE('RPLY') // reply
#define CHUNK_HIDE MKID_BE('HIDE') // hide entry
#define CHUNK_UHID MKID_BE('UHID') // unhide entry
#define CHUNK_DSTR MKID_BE('DSTR') // destroy entry
// Conversation chunks - entry related (conditional)
#define CHUNK_CRPL MKID_BE('CRPL') // reply
#define CHUNK_CHDE MKID_BE('CHDE') // hide entry
#define CHUNK_CUHD MKID_BE('CUHD') // unhide entry
#define CHUNK_CDST MKID_BE('DDTS') // destroy entry
// Conversation chunks - branching and logic (unconditional)
#define CHUNK_ASGN MKID_BE('ASGN') // assign
#define CHUNK_GOTO MKID_BE('GOTO') // goto chunk
#define CHUNK_EXIT MKID_BE('EXIT') // exit/return from goto
// Conversation chunks - branching and logic (conditional)
#define CHUNK_CASN MKID_BE('CASN') // assign
#define CHUNK_CCGO MKID_BE('CCGO') // goto chunk
#define CHUNK_CEGO MKID_BE('CEGO') // exit/return from goto
// Others
#define CHUNK_FALL MKID_BE('FALL') // fallthrough
#define CHUNK_WRPL MKID_BE('WRPL') // weighted reply chunk
#define CHUNK_WPRL MKID_BE('WPRL') // weighted preply chunk
ConversationView::ConversationView(MadsM4Engine *vm): View(vm, Common::Rect(0,
vm->_screen->height() - INTERFACE_HEIGHT, vm->_screen->width(), vm->_screen->height())) {
_screenType = VIEWID_CONVERSATION;
_screenFlags.layer = LAYER_INTERFACE;
_screenFlags.visible = false;
_screenFlags.get = SCREVENT_MOUSE;
_conversationState = kNoConversation;
_currentHandle = NULL;
}
ConversationView::~ConversationView() {
_activeItems.clear();
}
void ConversationView::setNode(int32 nodeIndex) {
_highlightedIndex = -1;
_xEnd = CONV_ENTRIES_X_OFFSET;
_vm->_font->setFont(FONT_CONVERSATION);
// TODO: Conversation styles and colors
_vm->_font->setColors(2, 1, 3);
_currentNodeIndex = nodeIndex;
_activeItems.clear();
if (nodeIndex != -1) {
ConvEntry *node = _m4Vm->_converse->getNode(nodeIndex);
for (uint i = 0; i < node->entries.size(); ++i) {
if (!node->entries[i]->visible)
continue;
if ((int)_activeItems.size() > CONV_MAX_SHOWN_ENTRIES) {
warning("TODO: scrolling. Max shown entries are %i, skipping entry %i",
CONV_MAX_SHOWN_ENTRIES, i);
}
// Add node to active items list
_activeItems.push_back(node->entries[i]);
if (node->entries[i]->autoSelect || strlen(node->entries[i]->text) == 0) {
//printf("Auto selecting entry %i of node %i\n", i, nodeIndex);
selectEntry(i);
return;
}
// Figure out the longest string to determine where option highlighting ends
int tempX = _vm->_font->getWidth(node->entries[i]->text, 0) +
CONV_ENTRIES_X_OFFSET + 10;
_xEnd = MAX(_xEnd, tempX);
}
// Make sure that there aren't too many entries
//assert((int)_activeItems.size() < (height() - CONV_ENTRIES_Y_OFFSET) / CONV_ENTRIES_HEIGHT);
// Fallthrough
if (node->fallthroughMinEntries >= 0 && node->fallthroughOffset >= 0) {
//printf("Current node falls through node at offset %i when entries are less or equal than %i\n",
// node->fallthroughOffset, node->fallthroughMinEntries);
if (_activeItems.size() <= (uint32)node->fallthroughMinEntries) {
const EntryInfo *entryInfo = _m4Vm->_converse->getEntryInfo(node->fallthroughOffset);
//printf("Entries are less than or equal to %i, falling through to node at offset %i, index %i\n",
// node->fallthroughMinEntries, node->fallthroughOffset, entryInfo->nodeIndex);
setNode(entryInfo->nodeIndex);
return;
}
}
_entriesShown = true;
_conversationState = kConversationOptionsShown;
}
}
void ConversationView::onRefresh(RectList *rects, M4Surface *destSurface) {
//if (!this->isVisible())
// return;
clear();
if (_entriesShown) {
// Write out the conversation options
_vm->_font->setFont(FONT_CONVERSATION);
for (int i = 0; i < (int)_activeItems.size(); ++i) {
// TODO: scrolling
if (i > CONV_MAX_SHOWN_ENTRIES - 1)
break;
_vm->_font->setColor((_highlightedIndex == i) ? CONVERSATION_ENTRY_HIGHLIGHTED :
CONVERSATION_ENTRY_NORMAL);
_vm->_font->writeString(this, _activeItems[i]->text, CONV_ENTRIES_X_OFFSET,
CONV_ENTRIES_Y_OFFSET + CONV_ENTRIES_HEIGHT * i, 0, 0);
}
}
View::onRefresh(rects, destSurface);
}
bool ConversationView::onEvent(M4EventType eventType, int32 param, int x, int y, bool &captureEvents) {
//if (!this->isVisible())
// return false;
if (!_entriesShown)
return false;
if (eventType == KEVENT_KEY)
return false;
int localY = y - _coords.top;
int selectedIndex = _highlightedIndex;
switch (eventType) {
case MEVENT_MOVE:
if ((x < CONV_ENTRIES_X_OFFSET) || (x >= _xEnd) || (localY < CONV_ENTRIES_Y_OFFSET))
_highlightedIndex = -1;
else {
int index = (localY - CONV_ENTRIES_Y_OFFSET) / CONV_ENTRIES_HEIGHT;
_highlightedIndex = (index >= (int)_activeItems.size()) ? -1 : index;
}
break;
case MEVENT_LEFT_RELEASE:
if (_highlightedIndex != -1) {
selectEntry(selectedIndex);
}
break;
default:
break;
}
return true;
}
void ConversationView::selectEntry(int entryIndex) {
char buffer[20];
sprintf(buffer, "%s.raw", _activeItems[entryIndex]->voiceFile);
_entriesShown = false;
_conversationState = kEntryIsActive;
_vm->_player->setCommandsAllowed(false);
// Necessary, as entries can be selected programmatically
_highlightedIndex = entryIndex;
// Play the selected entry's voice
if (strlen(_activeItems[entryIndex]->voiceFile) > 0) {
_currentHandle = _vm->_sound->getHandle();
_vm->_sound->playVoice(buffer, 255);
} else {
_currentHandle = NULL;
}
// Hide selected entry, unless it has a persistent flag set
if (!(_activeItems[entryIndex]->flags & kEntryPersists)) {
//printf("Hiding selected entry\n");
_m4Vm->_converse->getNode(_currentNodeIndex)->entries[entryIndex]->visible = false;
} else {
//printf("Selected entry is persistent, not hiding it\n");
}
}
void ConversationView::updateState() {
switch (_conversationState) {
case kConversationOptionsShown:
return;
case kEntryIsActive:
case kReplyIsActive:
// FIXME: for now, we determine whether a conversation entry is
// finished by waiting for its associated speech file to finish playing
if (_currentHandle != NULL && _vm->_sound->isHandleActive(_currentHandle)) {
return;
} else {
playNextReply();
} // end else
break;
case kNoConversation:
return;
default:
error("Unknown converstation state");
break;
}
}
void ConversationView::playNextReply() {
char buffer[20];
assert(_highlightedIndex >= 0);
// Start playing the first reply
for (uint32 i = 0; i < _activeItems[_highlightedIndex]->entries.size(); i++) {
ConvEntry *currentEntry = _activeItems[_highlightedIndex]->entries[i];
if (currentEntry->isConditional) {
if (!_m4Vm->_converse->evaluateCondition(
_m4Vm->_converse->getValue(currentEntry->condition.offset),
currentEntry->condition.op, currentEntry->condition.val))
continue; // don't play this reply
}
if (currentEntry->entryType != kWeightedReply) {
sprintf(buffer, "%s.raw", currentEntry->voiceFile);
if (strlen(currentEntry->voiceFile) > 0) {
_currentHandle = _vm->_sound->getHandle();
_vm->_sound->playVoice(buffer, 255);
// Remove reply from the list of replies
_activeItems[_highlightedIndex]->entries.remove_at(i);
_conversationState = kReplyIsActive;
return;
} else {
_currentHandle = NULL;
}
} else {
int selectedWeight = _vm->_random->getRandomNumber(currentEntry->totalWeight - 1) + 1;
//printf("Selected weight: %i\n", selectedWeight);
int previousWeight = 1;
int currentWeight = 0;
for (uint32 j = 0; j < currentEntry->entries.size(); j++) {
currentWeight += currentEntry->entries[j]->weight;
if (selectedWeight >= previousWeight && selectedWeight <= currentWeight) {
sprintf(buffer, "%s.raw", currentEntry->entries[j]->voiceFile);
if (strlen(currentEntry->entries[j]->voiceFile) > 0) {
_currentHandle = _vm->_sound->getHandle();
_vm->_sound->playVoice(buffer, 255);
// Remove reply from the list of replies
_activeItems[_highlightedIndex]->entries.remove_at(i);
_conversationState = kReplyIsActive;
return;
} else {
_currentHandle = NULL;
}
break;
}
previousWeight += currentWeight;
} // end for j
} // end if
} // end for i
// If we reached here, there are no more replies, so perform the active entry's actions
//printf("Current selection does %i actions\n", _activeItems[entryIndex]->actions.size());
for (uint32 i = 0; i < _activeItems[_highlightedIndex]->actions.size(); i++) {
if (!_m4Vm->_converse->performAction(_activeItems[_highlightedIndex]->actions[i]))
break;
} // end for
// Refresh the conversation node, in case it hasn't changed
setNode(_currentNodeIndex);
_entriesShown = true;
_vm->_player->setCommandsAllowed(true);
// Check if the conversation has been ended
if (_currentNodeIndex == -1) {
_conversationState = kNoConversation;
}
}
//--------------------------------------------------------------------------
void Converse::startConversation(const char *convName, bool showConverseBox, ConverseStyle style) {
if (_vm->isM4())
loadConversation(convName);
else
loadConversationMads(convName);
if (!_vm->isM4()) showConverseBox = false; // TODO: remove
_playerCommandsAllowed = _vm->_player->commandsAllowed;
if (_vm->isM4()) // TODO: remove (interface not implemented yet in MADS games)
_interfaceWasVisible = _m4Vm->scene()->getInterface()->isVisible();
_vm->_player->setCommandsAllowed(false);
_style = style;
if (showConverseBox) {
_vm->_conversationView->show();
_vm->_mouse->lockCursor(CURSOR_ARROW);
if (_interfaceWasVisible)
_m4Vm->scene()->getInterface()->hide();
_vm->_conversationView->setNode(0);
_vm->_conversationView->show();
}
}
void Converse::endConversation() {
_vm->_conversationView->setNode(-1);
_vm->_conversationView->hide();
// TODO: do a more proper cleanup here
_convNodes.clear();
_variables.clear();
_offsetMap.clear();
_vm->_player->setCommandsAllowed(_playerCommandsAllowed);
if (_interfaceWasVisible)
_m4Vm->scene()->getInterface()->show();
}
void Converse::loadConversation(const char *convName) {
char name[40];
char buffer[256];
sprintf(name, "%s.chk", convName);
Common::SeekableReadStream *convS = _vm->res()->get(name);
uint32 header = convS->readUint32LE();
uint32 size;
uint32 chunk;
uint32 data = 0;
uint32 i = 0;
ConvEntry* curEntry = NULL;
ConvEntry* replyEntry = NULL;
int32 currentWeightedEntry = -1;
EntryAction* curAction = NULL;
uint32 curNode = 0;
uint32 chunkPos = 0;
uint32 val;
int32 autoSelectIndex = -1;
int returnAddress = -1;
bool debugFlag = false; // set to true for debug messages
// Conversation *.chk files contain a 'CONV' header in LE format
if (header != HEAD_CONV) {
warning("Unexpected conversation file external header");
return;
}
size = convS->readUint32LE(); // is this used at all?
if (debugFlag) printf("Conv chunk size (external header): %i\n", size);
// Conversation name, which is the conversation file's name
// without the extension
convS->read(buffer, 8);
if (debugFlag) printf("Conversation name: %s\n", buffer);
while (true) {
chunkPos = convS->pos();
chunk = convS->readUint32LE(); // read chunk
if (convS->eos()) break;
if (debugFlag) printf("***** Pos: %i -> ", chunkPos);
switch (chunk) {
case CHUNK_DECL: // Declare
if (debugFlag) printf("DECL chunk\n");
data = convS->readUint32LE();
if (debugFlag) printf("Tag: %i\n", data);
if (data > 0)
warning("Tag > 0 in DECL chunk, value is: %i", data); // TODO
val = convS->readUint32LE();
if (debugFlag) printf("Value: %i\n", val);
data = convS->readUint32LE();
if (debugFlag) printf("Flags: %i\n", data);
if (data > 0)
warning("Flags != 0 in DECL chunk, value is %i", data); // TODO
setValue(chunkPos, val);
break;
// ----------------------------------------------------------------------------
case CHUNK_NODE: // Node
case CHUNK_LNOD: // Linear node
// Create new node
curEntry = new ConvEntry();
curEntry->offset = chunkPos;
curEntry->entryType = (chunk == CHUNK_NODE) ? kNode : kLinearNode;
curEntry->fallthroughMinEntries = -1;
curEntry->fallthroughOffset = -1;
if (chunk == CHUNK_NODE) {
if (debugFlag) printf("NODE chunk\n");
} else {
if (debugFlag) printf("LNOD chunk\n");
}
curNode = convS->readUint32LE();
if (debugFlag) printf("Node number: %i\n", curNode);
data = convS->readUint32LE();
if (debugFlag) printf("Tag: %i\n", data);
if (chunk == CHUNK_LNOD) {
autoSelectIndex = convS->readUint32LE();
if (debugFlag) printf("Autoselect entry number: %i\n", autoSelectIndex);
}
size = convS->readUint32LE();
if (debugFlag) printf("Number of entries: %i\n", size);
for (i = 0; i < size; i++) {
data = convS->readUint32LE();
if (debugFlag) printf("Entry %i: %i\n", i + 1, data);
}
_convNodes.push_back(curEntry);
setEntryInfo(curEntry->offset, curEntry->entryType, curNode, -1);
break;
case CHUNK_ETRY: // Entry
// Create new entry
curEntry = new ConvEntry();
curEntry->offset = chunkPos;
curEntry->entryType = kEntry;
strcpy(curEntry->voiceFile, "");
strcpy(curEntry->text, "");
if (debugFlag) printf("ETRY chunk\n");
data = convS->readUint32LE();
if (debugFlag) printf("Unknown (attributes perhaps?): %i\n", data);
data = convS->readUint32LE();
if (debugFlag) printf("Entry flags: ");
if (debugFlag) if (data & kEntryInitial) printf ("Initial ");
if (debugFlag) if (data & kEntryPersists) printf ("Persists ");
if (debugFlag) printf("\n");
curEntry->flags = data;
curEntry->visible = (curEntry->flags & kEntryInitial) ? true : false;
if (autoSelectIndex >= 0) {
if (_convNodes[curNode]->entries.size() == (uint32)autoSelectIndex) {
curEntry->autoSelect = true;
autoSelectIndex = -1;
} else {
curEntry->autoSelect = false;
}
} else {
curEntry->autoSelect = false;
}
_convNodes[curNode]->entries.push_back(curEntry);
setEntryInfo(curEntry->offset, curEntry->entryType,
curNode, _convNodes[curNode]->entries.size() - 1);
replyEntry = NULL;
break;
case CHUNK_WPRL: // Weighted preply
// WPRL chunks are random entries that the character would say, not an NPC
// They don't seem to be used in Orion Burger
warning("WPRL chunk - treating as WRPL chunk");
case CHUNK_WRPL: // Weighted reply
case CHUNK_CRPL: // Conditional reply
case CHUNK_RPLY: // Reply
{
ConvEntry* weightedEntry = NULL;
// Create new reply
replyEntry = new ConvEntry();
replyEntry->offset = chunkPos;
strcpy(replyEntry->voiceFile, "");
// Conditional part
if (chunk == CHUNK_CRPL) {
replyEntry->isConditional = true;
replyEntry->condition.offset = convS->readUint32LE();
replyEntry->condition.op = convS->readUint32LE();
replyEntry->condition.val = convS->readUint32LE();
} else {
replyEntry->isConditional = false;
}
if (chunk == CHUNK_WPRL || chunk == CHUNK_WRPL) {
replyEntry->entryType = kWeightedReply;
replyEntry->totalWeight = 0;
if (debugFlag) printf("WRPL chunk\n");
size = convS->readUint32LE();
if (debugFlag) printf("Weighted reply %i - %i entries:\n", i, size);
for (i = 0; i < size; i++) {
weightedEntry = new ConvEntry();
weightedEntry->offset = chunkPos;
strcpy(weightedEntry->voiceFile, "");
weightedEntry->entryType = kWeightedReply;
data = convS->readUint32LE();
if (debugFlag) printf("- Weight: %i ", data);
weightedEntry->weight = data;
replyEntry->totalWeight += weightedEntry->weight;
data = convS->readUint32LE();
if (debugFlag) printf("offset: %i\n", data);
replyEntry->entries.push_back(weightedEntry);
}
currentWeightedEntry = 0;
} else {
replyEntry->entryType = kReply;
if (debugFlag) printf("RPLY chunk\n");
data = convS->readUint32LE();
if (debugFlag) printf("Reply data offset: %i\n", data);
}
curEntry->entries.push_back(replyEntry);
setEntryInfo(replyEntry->offset, replyEntry->entryType,
curNode, _convNodes[curNode]->entries.size() - 1);
// Seek to chunk data (i.e. TEXT/MESG tag, which is usually right
// after this chunk but it can be further on in conditional reply chunks
assert((int)data >= convS->pos());
// If the entry's data is not right after the entry, remember the position
// to return to after the data is read
if (chunk == CHUNK_CRPL && (int)data != convS->pos())
returnAddress = convS->pos();
convS->seek(data, SEEK_SET);
}
break;
// ----------------------------------------------------------------------------
case CHUNK_TEXT: // Text (contains text and voice)
case CHUNK_MESG: // Message (contains voice only)
{
ConvEntry* parentEntry = NULL;
if (chunk == CHUNK_TEXT) {
if (debugFlag) printf("TEXT chunk\n");
} else {
if (debugFlag) printf("MESG chunk\n");
}
if (replyEntry == NULL) {
parentEntry = curEntry;
} else if (replyEntry != NULL && replyEntry->entryType != kWeightedReply) {
parentEntry = replyEntry;
} else if (replyEntry != NULL && replyEntry->entryType == kWeightedReply) {
parentEntry = replyEntry->entries[currentWeightedEntry];
currentWeightedEntry++;
}
size = convS->readUint32LE();
if (debugFlag) printf("Entry data size: %i\n", size);
convS->read(buffer, 8);
size -= 8; // subtract maximum length of voice file name
// If the file name is 8 characters, it will not be 0-terminated, so use strncpy
strncpy(parentEntry->voiceFile, buffer, 8);
parentEntry->voiceFile[8] = '\0';
if (debugFlag) printf("Voice file: %s\n", parentEntry->voiceFile);
if (chunk == CHUNK_TEXT) {
convS->read(buffer, size);
if (debugFlag) printf("Text: %s\n", buffer);
sprintf(parentEntry->text, "%s", buffer);
} else {
while (size > 0) {
data = convS->readUint32LE();
if (debugFlag) printf("Unknown: %i\n", data); // TODO
size -= 4;
}
}
// Now that the data chunk has been read, if we skipped a reply node,
// jump back to it
if (returnAddress != -1) {
convS->seek(returnAddress, SEEK_SET);
returnAddress = -1;
}
}
break;
// ----------------------------------------------------------------------------
// Entry action chunks
case CHUNK_CASN: // Conditional assign
case CHUNK_ASGN: // Assign
curAction = new EntryAction();
if (debugFlag) printf("ASGN chunk\n");
curAction->actionType = kAssignValue;
// Conditional part
if (chunk == CHUNK_CASN) {
curAction->isConditional = true;
curAction->condition.offset = convS->readUint32LE();
curAction->condition.op = convS->readUint32LE();
curAction->condition.val = convS->readUint32LE();
} else {
curAction->isConditional = false;
}
curAction->targetOffset = convS->readUint32LE();
assert(convS->readUint32LE() == kOpAssign);
curAction->value = convS->readUint32LE();
break;
case CHUNK_CCGO: // Conditional go to entry
case CHUNK_CHDE: // Conditional hide entry
case CHUNK_CUHD: // Conditional unhide entry
case CHUNK_CDST: // Conditional destroy entry
case CHUNK_CEGO: // Conditional exit conversation / go to
case CHUNK_GOTO: // Go to entry
case CHUNK_HIDE: // Hide entry
case CHUNK_UHID: // Unhide entry
case CHUNK_DSTR: // Destroy entry
case CHUNK_EXIT: // Exit conversation
curAction = new EntryAction();
// Conditional part
if (chunk == CHUNK_CCGO || chunk == CHUNK_CHDE || chunk == CHUNK_CUHD ||
chunk == CHUNK_CDST || chunk == CHUNK_CEGO) {
curAction->isConditional = true;
curAction->condition.offset = convS->readUint32LE();
curAction->condition.op = convS->readUint32LE();
curAction->condition.val = convS->readUint32LE();
} else {
curAction->isConditional = false;
}
if (chunk == CHUNK_GOTO || chunk == CHUNK_CCGO) {
curAction->actionType = kGotoEntry;
if (debugFlag) printf("GOTO chunk\n");
} else if (chunk == CHUNK_HIDE || chunk == CHUNK_CHDE) {
curAction->actionType = kHideEntry;
if (debugFlag) printf("HIDE chunk\n");
} else if (chunk == CHUNK_UHID || chunk == CHUNK_CUHD) {
curAction->actionType = kUnhideEntry;
if (debugFlag) printf("UHID chunk\n");
} else if (chunk == CHUNK_DSTR || chunk == CHUNK_CDST) {
curAction->actionType = kDestroyEntry;
if (debugFlag) printf("DSTR chunk\n");
} else if (chunk == CHUNK_EXIT || chunk == CHUNK_CEGO) {
curAction->actionType = kExitConv;
if (debugFlag) printf("EXIT chunk\n");
}
data = convS->readUint32LE();
if (debugFlag) printf("Offset: %i\n", data);
curAction->targetOffset = data;
curEntry->actions.push_back(curAction);
break;
case CHUNK_FALL: // Fallthrough
if (debugFlag) printf("FALL chunk\n");
size = convS->readUint32LE();
if (debugFlag) printf("Minimum nodes: %i\n", size);
_convNodes[curNode]->fallthroughMinEntries = size;
data = convS->readUint32LE();
if (debugFlag) printf("Offset: %i\n", data);
_convNodes[curNode]->fallthroughOffset = data;
break;
// ----------------------------------------------------------------------------
default:
// Should never happen
error("Unknown conversation chunk");
break;
}
}
_vm->res()->toss(name);
}
void Converse::loadConversationMads(const char *convName) {
char name[40];
char buffer[256];
char *buf;
Common::SeekableReadStream *convS;
int curPos = 0;
int unk = 0;
uint32 stringIndex = 0;
uint32 stringCount = 0;
int flags = 0;
int count = 0;
uint32 i, j;
ConvEntry* curEntry = NULL;
MessageEntry *curMessage;
Common::Array<char *> messageList;
// TODO
// CND file
sprintf(name, "%s.cnd", convName);
MadsPack convDataD(name, _vm);
// ------------------------------------------------------------
// Chunk 0
convS = convDataD.getItemStream(0);
printf("Chunk 0\n");
printf("Conv stream size: %i\n", convS->size());
while (!convS->eos()) { // FIXME (eos changed)
printf("%i ", convS->readByte());
}
printf("\n");
// ------------------------------------------------------------
// Chunk 1
convS = convDataD.getItemStream(1);
printf("Chunk 1\n");
printf("Conv stream size: %i\n", convS->size());
while (!convS->eos()) { // FIXME (eos changed)
printf("%i ", convS->readByte());
}
printf("\n");
// ------------------------------------------------------------
// Chunk 2
convS = convDataD.getItemStream(2);
printf("Chunk 2\n");
printf("Conv stream size: %i\n", convS->size());
while (!convS->eos()) { // FIXME (eos changed)
printf("%i ", convS->readByte());
}
printf("\n");
// ------------------------------------------------------------
// CNV file
sprintf(name, "%s.cnv", convName);
MadsPack convData(name, _vm);
// *.cnv files have 7 chunks
// Here is the chunk output of conv001.cnv (from the dump_file command)
/*
Dumping conv001.cnv, size: 3431
Dumping compressed chunk 1 of 7, size is 150
Dumping compressed chunk 2 of 7, size is 130
Dumping compressed chunk 3 of 7, size is 224
Dumping compressed chunk 4 of 7, size is 92
Dumping compressed chunk 5 of 7, size is 168
Dumping compressed chunk 6 of 7, size is 4064
Dumping compressed chunk 7 of 7, size is 2334
*/
// ------------------------------------------------------------
// TODO: finish this
// Chunk 0
convS = convData.getItemStream(0);
printf("Chunk 0\n");
printf("Conv stream size: %i\n", convS->size());
printf("%i ", convS->readUint16LE());
printf("%i ", convS->readUint16LE());
printf("%i ", convS->readUint16LE());
printf("%i ", convS->readUint16LE());
printf("%i ", convS->readUint16LE());
printf("%i ", convS->readUint16LE());
printf("\n");
count = convS->readUint16LE(); // conversation face count (usually 2)
printf("Conversation faces: %i\n", count);
for (i = 0; i < 5; i++) {
convS->read(buffer, 16);
printf("Face %i: %s ", i + 1, buffer);
}
printf("\n");
// 5 face slots
// 1 = face slot has a face (with the filename specified above)
// 0 = face slot doesn't contain face data
for (i = 0; i < 5; i++) {
printf("%i ", convS->readUint16LE());
}
printf("\n");
convS->read(buffer, 14); // speech file
printf("Speech file: %s\n", buffer);
while (!convS->eos()) { // FIXME: eos changed
printf("%i ", convS->readByte());
}
printf("\n");
delete convS;
// ------------------------------------------------------------
// Chunk 1: Conversation nodes
convS = convData.getItemStream(1);
printf("Chunk 1: conversation nodes\n");
printf("Conv stream size: %i\n", convS->size());
while (true) {
uint16 id = convS->readUint16LE();
if (convS->eos()) break;
curEntry = new ConvEntry();
curEntry->id = id;
curEntry->entryCount = convS->readUint16LE();
curEntry->flags = convS->readUint16LE();
if (curEntry->entryCount == 1 && curEntry->flags != 65535) {
warning("Entry count is 1 and flags is not 65535 (it's %i)", flags);
} else if (curEntry->entryCount != 1 && flags != 0) {
warning("Entry count > 1 and flags is not 0 (it's %i)", flags);
}
unk = convS->readUint16LE();
assert (unk == 65535);
unk = convS->readUint16LE();
assert (unk == 65535);
_convNodes.push_back(curEntry);
printf("Node %i, ID %i, entries %i\n", _convNodes.size(), curEntry->id, curEntry->entryCount);
// flags = 0: node has more than 1 entry
// flags = 65535: node has 1 entry
}
printf("Conversation has %i nodes\n", _convNodes.size());
printf("\n");
delete convS;
// ------------------------------------------------------------
// Chunk 4 contains the conversation string offsets of chunk 5
// (unused, as it's unneeded - we find the offsets ourselves)
// ------------------------------------------------------------
// Chunk 5 contains the conversation strings
convS = convData.getItemStream(5);
//printf("Chunk 5: conversation strings\n");
//printf("Conv stream size: %i\n", convS->size());
*buffer = 0;
while (true) {
//if (curPos == 0)
// printf("%i: Offset %i: ", _convStrings.size(), convS->pos());
uint8 b = convS->readByte();
if (convS->eos()) break;
buffer[curPos++] = b;
if (buffer[curPos - 1] == '~') { // filter out special characters
curPos--;
continue;
}
if (buffer[curPos - 1] == '\0') {
// end of string
//printf("%s\n", buffer);
buf = new char[strlen(buffer)];
sprintf(buf, "%s", buffer);
_convStrings.push_back(buf);
curPos = 0;
*buffer = 0;
}
}
delete convS;
// ------------------------------------------------------------
// Chunk 2: entry data
convS = convData.getItemStream(2);
//printf("Chunk 2 - entry data\n");
//printf("Conv stream size: %i\n", convS->size());
for (i = 0; i < _convNodes.size(); i++) {
for (j = 0; j < _convNodes[i]->entryCount; j++) {
curEntry = new ConvEntry();
stringIndex = convS->readUint16LE();
if (stringIndex != 65535)
sprintf(curEntry->text, "%s", _convStrings[stringIndex]);
else
*curEntry->text = 0;
curEntry->id = convS->readUint16LE();
curEntry->offset = convS->readUint16LE();
curEntry->size = convS->readUint16LE();
_convNodes[i]->entries.push_back(curEntry);
//printf("Node %i, entry %i, id %i, offset %i, size %i, text: %s\n",
// i, j, curEntry->id, curEntry->offset, curEntry->size, curEntry->text);
}
}
delete convS;
// ------------------------------------------------------------
// Chunk 3: message (MESG) chunks, created from the strings of chunk 5
convS = convData.getItemStream(3);
//printf("Chunk 3 - MESG chunk data\n");
//printf("Conv stream size: %i\n", convS->size());
while (true) {
uint16 index = convS->readUint16LE();
if (convS->eos()) break;
curMessage = new MessageEntry();
stringIndex = index;
stringCount = convS->readUint16LE();
*buffer = 0;
//printf("Message: %i\n", _madsMessageList.size());
for (i = stringIndex; i < stringIndex + stringCount; i++) {
//printf("%i: %s\n", i, _convStrings[i]);
curMessage->messageStrings.push_back(_convStrings[i]);
}
_madsMessageList.push_back(curMessage);
//printf("----------\n");
}
//printf("\n");
delete convS;
// ------------------------------------------------------------
// TODO: finish this
// Chunk 6: conversation script
convS = convData.getItemStream(6);
printf("Chunk 6\n");
printf("Conv stream size: %i\n", convS->size());
/*while (!convS->eos()) { // FIXME (eos changed)
printf("%i ", convS->readByte());
printf("%i ", convS->readByte());
printf("%i ", convS->readByte());
printf("%i ", convS->readByte());
printf("%i ", convS->readByte());
printf("%i ", convS->readByte());
printf("%i ", convS->readByte());
printf("%i ", convS->readByte());
printf("%i ", convS->readByte());
printf("%i ", convS->readByte());
printf("\n");
}
return;*/
for (i = 0; i < _convNodes.size(); i++) {
for (j = 0; j < _convNodes[i]->entryCount; j++) {
printf("*** Node %i entry %i data size %i\n", i, j, _convNodes[i]->entries[j]->size);
printf("Entry ID %i, text %s\n", _convNodes[i]->entries[j]->id, _convNodes[i]->entries[j]->text);
Common::SubReadStream *entryStream = new Common::SubReadStream(convS, _convNodes[i]->entries[j]->size);
readConvEntryActions(entryStream, _convNodes[i]->entries[j]);
delete entryStream;
printf("--------------------\n");
}
}
delete convS;
}
void Converse::readConvEntryActions(Common::SubReadStream *convS, ConvEntry *curEntry) {
uint8 chunk;
uint8 type; // 255: normal, 11: conditional
uint8 hasText1, hasText2;
int target;
int count = 0;
int var, val;
int messageIndex = 0;
int unk = 0;
while (true) {
chunk = convS->readByte();
if (convS->eos()) break;
type = convS->readByte();
switch (chunk) {
case 1:
printf("TODO: chunk type %i\n", chunk);
break;
case 2:
printf("HIDE\n");
convS->readByte();
count = convS->readByte();
printf("%i entries: ", count);
for (int i = 0; i < count; i++)
printf("%i %d", i, convS->readUint16LE());
printf("\n");
break;
case 3:
printf("UNHIDE\n");
convS->readByte();
count = convS->readByte();
printf("%i entries: ", count);
for (int i = 0; i < count; i++)
printf("%i %d", i, convS->readUint16LE());
printf("\n");
break;
case 4: // MESSAGE
printf("MESSAGE\n");
if (type == 255) {
//printf("unconditional\n");
} else if (type == 11) {
//printf("conditional\n");
} else {
printf("unknown type: %i\n", type);
}
// Conditional part
if (type == 11) {
unk = convS->readUint16LE(); // 1
if (unk != 1)
printf("Message: unk != 1 (it's %i)\n", unk);
var = convS->readUint16LE();
val = convS->readUint16LE();
printf("Var %i == %i\n", var, val);
}
unk = convS->readUint16LE(); // 256
if (unk != 256)
printf("Message: unk != 256 (it's %i)\n", unk);
// it seems that the first text entry is set when the message
// chunk is supposed to be shown unconditionally, whereas the second text
// entry is set when the message is supposed to be shown conditionally
hasText1 = convS->readByte();
hasText2 = convS->readByte();
if (hasText1 == 1) {
messageIndex = convS->readUint16LE();
printf("Message 1 index: %i, text:\n", messageIndex);
for (uint32 i = 0; i < _madsMessageList[messageIndex]->messageStrings.size(); i++) {
printf("%s\n", _madsMessageList[messageIndex]->messageStrings[i]);
}
}
if (hasText2 == 1) {
messageIndex = convS->readUint16LE();
if (hasText1 == 0) {
printf("Message 2 index: %i, text:\n", messageIndex);
for (uint32 i = 0; i < _madsMessageList[messageIndex]->messageStrings.size(); i++) {
printf("%s\n", _madsMessageList[messageIndex]->messageStrings[i]);
}
}
}
break;
case 5: // AUTO
printf("AUTO\n");
for (int k = 0; k < 4; k++)
convS->readByte();
messageIndex = convS->readUint16LE();
printf("Message index: %i, text:\n", messageIndex);
for (uint32 i = 0; i < _madsMessageList[messageIndex]->messageStrings.size(); i++) {
printf("%s\n", _madsMessageList[messageIndex]->messageStrings[i]);
}
convS->readUint16LE();
break;
case 6:
printf("TODO: chunk type %i\n", chunk);
break;
case 7: // GOTO
unk = convS->readUint32LE(); // 0
if (unk != 0 && unk != 1)
printf("Goto: unk != 0 or 1 (it's %i)\n", unk);
target = convS->readUint16LE();
convS->readUint16LE(); // 255
if (unk != 0)
printf("Goto: unk != 0 (it's %i)\n", unk);
if (target != 65535)
printf("GOTO node %i\n", target);
else
printf("GOTO exit\n");
break;
case 8:
printf("TODO: chunk type %i\n", chunk);
break;
case 9: // ASSIGN
//printf("ASSIGN\n");
unk = convS->readUint32LE(); // 0
if (unk != 0)
printf("Assign: unk != 0 (it's %i)\n", unk);
val = convS->readUint16LE();
var = convS->readUint16LE();
//printf("Var %i = %i\n", var, val);
break;
default:
printf ("Unknown chunk type! (%i)\n", chunk);
break;
}
}
printf("\n");
}
void Converse::setEntryInfo(int32 offset, EntryType type, int32 nodeIndex, int32 entryIndex) {
char hashOffset[10];
sprintf(hashOffset, "%i", offset);
EntryInfo info;
info.targetType = type;
info.nodeIndex = nodeIndex;
info.entryIndex = entryIndex;
_offsetMap[hashOffset] = info;
//printf("Set entry info: offset %i, type %i, node %i, entry %i\n", offset, type, nodeIndex, entryIndex);
}
const EntryInfo* Converse::getEntryInfo(int32 offset) {
char hashOffset[10];
sprintf(hashOffset, "%i", offset);
OffsetHashMap::const_iterator entry = _offsetMap.find(hashOffset);
if (entry != _offsetMap.end())
return &(entry->_value);
else
error("Undeclared entry offset: %i", offset);
}
void Converse::setValue(int32 offset, int32 value) {
char hashOffset[10];
sprintf(hashOffset, "%i", offset);
_variables[hashOffset] = value;
}
int32 Converse::getValue(int32 offset) {
char hashOffset[10];
sprintf(hashOffset, "%i", offset);
ConvVarHashMap::const_iterator entry = _variables.find(hashOffset);
if (entry != _variables.end())
return entry->_value;
else
error("Undeclared variable offset: %i", offset);
}
bool Converse::evaluateCondition(int32 leftVal, int32 op, int32 rightVal) {
switch (op) {
case kOpPercent:
return (leftVal % rightVal == 0);
case kOpGreaterOrEqual:
return leftVal >= rightVal;
case kOpLessOrEqual:
return leftVal <= rightVal;
case kOpGreaterThan:
return leftVal > rightVal;
case kOpLessThan:
return leftVal < rightVal;
case kOpNotEqual:
case kOpCondNotEqual:
return leftVal != rightVal;
case kOpAssign:
return leftVal == rightVal;
case kOpAnd:
return leftVal && rightVal;
case kOpOr:
return leftVal || rightVal;
default:
error("Unknown conditional operator: %i", op);
}
}
bool Converse::performAction(EntryAction *action) {
if (action->isConditional) {
if (!evaluateCondition(getValue(action->condition.offset),
action->condition.op, action->condition.val))
return true; // don't perform this action
}
if (action->actionType == kAssignValue) {
//printf("Assigning variable at offset %i to value %i\n",
// action->targetOffset, action->value);
setValue(action->targetOffset, action->value);
return true; // nothing else to do in an assignment action
}
const EntryInfo *entryInfo = getEntryInfo(action->targetOffset);
ConvEntry *targetEntry;
if (entryInfo->nodeIndex >= 0 && entryInfo->entryIndex >= 0)
targetEntry = getNode(entryInfo->nodeIndex)->entries[entryInfo->entryIndex];
else if (entryInfo->nodeIndex >= 0)
targetEntry = getNode(entryInfo->nodeIndex);
else
error("Target node id is negative");
switch (action->actionType) {
case kGotoEntry:
//printf("Goto entry at offset %i. Associated node is %i, entry %i\n",
// action->targetOffset, entryInfo->nodeIndex, entryInfo->entryIndex);
_vm->_conversationView->setNode(entryInfo->nodeIndex);
if (entryInfo->entryIndex >= 0)
_vm->_conversationView->selectEntry(entryInfo->entryIndex);
return false;
case kHideEntry:
//printf("Hide entry at offset %i. Associated node is %i, entry %i\n",
// targetEntry->offset, entryInfo->nodeIndex, entryInfo->entryIndex);
targetEntry->visible = false;
return true;
case kUnhideEntry:
//printf("Show entry at offset %i. Associated node is %i, entry %i\n",
// targetEntry->offset, entryInfo->nodeIndex, entryInfo->entryIndex);
targetEntry->visible = true;
return true;
case kDestroyEntry:
//printf("Destroy entry at offset %i. Associated node is %i, entry %i\n",
// targetEntry->offset, entryInfo->nodeIndex, entryInfo->entryIndex);
if (entryInfo->entryIndex >= 0)
getNode(entryInfo->nodeIndex)->entries.remove_at(entryInfo->entryIndex);
else
warning("Target entry is a node, not destroying it");
targetEntry->visible = true;
return true;
case kExitConv:
//printf("Exit conversation\n");
endConversation();
return false;
default:
warning("Unknown entry action");
return false;
} // end switch
}
/*--------------------------------------------------------------------------*/
MadsConversation::MadsConversation() {
for (int i = 0; i < MADS_TALK_SIZE; ++i) {
_talkList[i].desc = NULL;
_talkList[i].id = 0;
}
}
} // End of namespace M4
|
gpl-2.0
|
PKRoma/Git-Source-Control-Provider
|
GitUI/ICSharpCode.AvalonEdit/Rendering/VisualYPosition.cs
|
1008
|
๏ปฟ// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
namespace ICSharpCode.AvalonEdit.Rendering
{
/// <summary>
/// An enum that specifies the possible Y positions that can be returned by VisualLine.GetVisualPosition.
/// </summary>
public enum VisualYPosition
{
/// <summary>
/// Returns the top of the TextLine.
/// </summary>
LineTop,
/// <summary>
/// Returns the top of the text. If the line contains inline UI elements larger than the text, TextTop
/// will be below LineTop.
/// </summary>
TextTop,
/// <summary>
/// Returns the bottom of the TextLine. This is the same as the bottom of the text (the text is always
/// aligned at the bottom border).
/// </summary>
LineBottom,
/// <summary>
/// The middle between LineTop and LineBottom.
/// </summary>
LineMiddle
}
}
|
gpl-2.0
|
hernancmartinez/dibbler
|
Options/OptInteger.cpp
|
2071
|
/*
* Dibbler - a portable DHCPv6
*
* authors: Tomasz Mrugalski <thomson@klub.com.pl>
* Marek Senderski <msend@o2.pl>
*
* released under GNU GPL v2 licence
*
*/
#include <stdlib.h>
#include <sstream>
#include <iostream>
#include "Portable.h"
#include "OptInteger.h"
#include "DHCPConst.h"
using namespace std;
TOptInteger::TOptInteger(uint16_t type, unsigned int integerLen, unsigned int value, TMsg* parent)
:TOpt(type, parent) {
this->Value = value;
this->Valid = true;
this->Len = integerLen;
}
TOptInteger::TOptInteger(uint16_t type, unsigned int len, const char *buf, size_t bufsize, TMsg* parent)
:TOpt(type, parent)
{
if ((unsigned int)bufsize<len) {
this->Valid = false;
return;
}
this->Len = len;
this->Valid = true;
switch (len) {
case 0:
this->Value = 0;
break;
case 1:
this->Value = (unsigned char)(*buf);
break;
case 2:
this->Value = readUint16(buf);
break;
case 3:
this->Value = ((long)buf[0])<<16 | ((long)buf[1])<<8 | (long)buf[2]; /* no ntoh3, eh? */
break;
case 4:
this->Value = readUint32(buf);
break;
default:
this->Valid = false;
return;
}
}
char * TOptInteger::storeSelf(char* buf)
{
buf = writeUint16(buf, OptType);
buf = writeUint16(buf, this->Len);
switch (this->Len) {
case 0:
break;
case 1:
*buf = (char)this->Value;
break;
case 2:
buf = writeUint16(buf, this->Value);
break;
case 3:
{
int tmp = this->Value;
buf[0] = tmp%256; tmp = tmp/256;
buf[1] = tmp%256; tmp = tmp/256;
buf[2] = tmp%256; tmp = tmp/256;
break;
}
case 4:
buf = writeUint32(buf, this->Value);
break;
default:
/* this should never happen */
break;
}
return buf+this->Len;
}
size_t TOptInteger::getSize() {
return 4 /*option header length*/ + this->Len;
}
unsigned int TOptInteger::getValue() {
return this->Value;
}
std::string TOptInteger::getPlain() {
stringstream tmp;
tmp << Value;
return tmp.str();
}
bool TOptInteger::isValid() const {
return this->Valid;
}
|
gpl-2.0
|
ashwinmt/wp-ny
|
wp-content/plugins/cornerstone/includes/shortcodes/share.php
|
5693
|
<?php
// Share
// =============================================================================
function x_shortcode_share( $atts ) {
extract( shortcode_atts( array(
'id' => '',
'class' => '',
'style' => '',
'title' => '',
'share_title' => '',
'facebook' => '',
'twitter' => '',
'google_plus' => '',
'linkedin' => '',
'pinterest' => '',
'reddit' => '',
'email' => '',
'email_subject' => ''
), $atts, 'x_share' ) );
$share_url = urlencode( get_permalink() );
if ( is_singular() ) {
$share_url = urlencode( get_permalink() );
} else {
global $wp;
$share_url = urlencode( home_url( ($wp->request) ? $wp->request : '' ) );
}
if ( is_singular() ) {
$share_title = ( $share_title != '' ) ? esc_attr( $share_title ) : urlencode( get_the_title() );
} else {
$share_title = ( $share_title != '' ) ? esc_attr( $share_title ) : urlencode( apply_filters( 'the_title', get_page( get_option( 'page_for_posts' ) )->post_title) );
}
$share_source = urlencode( get_bloginfo( 'name' ) );
$share_image_info = wp_get_attachment_image_src( get_post_thumbnail_id(), 'full' );
$share_image = ( function_exists( 'x_get_featured_image_with_fallback_url' ) ) ? urlencode( x_get_featured_image_with_fallback_url() ) : urlencode( $share_image_info[0] );
if ( $linkedin == 'true' ) {
$share_content = urlencode( cs_get_raw_excerpt() );
}
$tooltip_attr = cs_generate_data_attributes_extra( 'tooltip', 'hover', 'bottom' );
$id = ( $id != '' ) ? 'id="' . esc_attr( $id ) . '"' : '';
$class = ( $class != '' ) ? 'x-entry-share ' . esc_attr( $class ) : 'x-entry-share';
$style = ( $style != '' ) ? 'style="' . $style . '"' : '';
$title = ( $title != '' ) ? $title : __( 'Share this Post', 'cornerstone' );
$facebook = ( $facebook == 'true' ) ? "<a href=\"#share\" {$tooltip_attr} class=\"x-share\" title=\"" . __( 'Share on Facebook', 'cornerstone' ) . "\" onclick=\"window.open('http://www.facebook.com/sharer.php?u={$share_url}&t={$share_title}', 'popupFacebook', 'width=650, height=270, resizable=0, toolbar=0, menubar=0, status=0, location=0, scrollbars=0'); return false;\"><i class=\"x-icon-facebook-square\" data-x-icon=\"\"></i></a>" : '';
$twitter = ( $twitter == 'true' ) ? "<a href=\"#share\" {$tooltip_attr} class=\"x-share\" title=\"" . __( 'Share on Twitter', 'cornerstone' ) . "\" onclick=\"window.open('https://twitter.com/intent/tweet?text={$share_title}&url={$share_url}', 'popupTwitter', 'width=500, height=370, resizable=0, toolbar=0, menubar=0, status=0, location=0, scrollbars=0'); return false;\"><i class=\"x-icon-twitter-square\" data-x-icon=\"\"></i></a>" : '';
$google_plus = ( $google_plus == 'true' ) ? "<a href=\"#share\" {$tooltip_attr} class=\"x-share\" title=\"" . __( 'Share on Google+', 'cornerstone' ) . "\" onclick=\"window.open('https://plus.google.com/share?url={$share_url}', 'popupGooglePlus', 'width=650, height=226, resizable=0, toolbar=0, menubar=0, status=0, location=0, scrollbars=0'); return false;\"><i class=\"x-icon-google-plus-square\" data-x-icon=\"\"></i></a>" : '';
$linkedin = ( $linkedin == 'true' ) ? "<a href=\"#share\" {$tooltip_attr} class=\"x-share\" title=\"" . __( 'Share on LinkedIn', 'cornerstone' ) . "\" onclick=\"window.open('http://www.linkedin.com/shareArticle?mini=true&url={$share_url}&title={$share_title}&summary={$share_content}&source={$share_source}', 'popupLinkedIn', 'width=610, height=480, resizable=0, toolbar=0, menubar=0, status=0, location=0, scrollbars=0'); return false;\"><i class=\"x-icon-linkedin-square\" data-x-icon=\"\"></i></a>" : '';
$pinterest = ( $pinterest == 'true' ) ? "<a href=\"#share\" {$tooltip_attr} class=\"x-share\" title=\"" . __( 'Share on Pinterest', 'cornerstone' ) . "\" onclick=\"window.open('http://pinterest.com/pin/create/button/?url={$share_url}&media={$share_image}&description={$share_title}', 'popupPinterest', 'width=750, height=265, resizable=0, toolbar=0, menubar=0, status=0, location=0, scrollbars=0'); return false;\"><i class=\"x-icon-pinterest-square\" data-x-icon=\"\"></i></a>" : '';
$reddit = ( $reddit == 'true' ) ? "<a href=\"#share\" {$tooltip_attr} class=\"x-share\" title=\"" . __( 'Share on Reddit', 'cornerstone' ) . "\" onclick=\"window.open('http://www.reddit.com/submit?url={$share_url}', 'popupReddit', 'width=875, height=450, resizable=0, toolbar=0, menubar=0, status=0, location=0, scrollbars=0'); return false;\"><i class=\"x-icon-reddit-square\" data-x-icon=\"\"></i></a>" : '';
$email_subject = ( $email_subject != '' ) ? esc_attr( $email_subject ) : __( 'Hey, thought you might enjoy this! Check it out when you have a chance:', 'cornerstone' );
$mail_to = esc_url( "mailto:?subject=" . get_the_title() . "&body=" . $email_subject . " " . get_permalink() . "" );
$email = ( $email == 'true' ) ? "<a href=\"{$mail_to}\" {$tooltip_attr} class=\"x-share email\" title=\"" . __( 'Share via Email', 'cornerstone' ) . "\"><span><i class=\"x-icon-envelope-square\" data-x-icon=\"\"></i></span></a>" : '';
$output = "<div {$id} class=\"{$class}\" {$style}>"
. '<p>' . $title . '</p>'
. '<div class="x-share-options">'
. $facebook . $twitter . $google_plus . $linkedin . $pinterest . $reddit . $email
. '</div>'
. '</div>';
return $output;
}
add_shortcode( 'x_share', 'x_shortcode_share' );
|
gpl-2.0
|
durilka/MeditationTracker
|
dootil/src/doo/util/functional/Folder.java
|
132
|
package doo.util.functional;
public interface Folder<TSource, TResult> {
TResult fold(TResult accumulator, TSource current);
}
|
gpl-2.0
|
jtulach/truffle
|
truffle/com.oracle.truffle.dsl.processor/src/com/oracle/truffle/dsl/processor/interop/InteropDSLProcessor.java
|
14081
|
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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 Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.truffle.dsl.processor.interop;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.FilerException;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.NestingKind;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.MirroredTypeException;
import javax.tools.Diagnostic.Kind;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.interop.CanResolve;
import com.oracle.truffle.api.interop.Message;
import com.oracle.truffle.api.interop.MessageResolution;
import com.oracle.truffle.api.interop.Resolve;
import com.oracle.truffle.api.interop.TruffleObject;
import com.oracle.truffle.dsl.processor.ExpectError;
import com.oracle.truffle.dsl.processor.ProcessorContext;
import com.oracle.truffle.dsl.processor.java.ElementUtils;
/**
* THIS IS NOT PUBLIC API.
*/
public final class InteropDSLProcessor extends AbstractProcessor {
static final List<Message> KNOWN_MESSAGES = Arrays.asList(new Message[]{Message.READ, Message.WRITE, Message.IS_NULL, Message.IS_EXECUTABLE, Message.IS_BOXED, Message.HAS_SIZE,
Message.GET_SIZE, Message.UNBOX, Message.createExecute(0), Message.createInvoke(0), Message.createNew(0)});
@Override
public Set<String> getSupportedAnnotationTypes() {
Set<String> annotations = new HashSet<>();
annotations.add("com.oracle.truffle.api.interop.MessageResolution");
return annotations;
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latest();
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
return false;
}
process0(roundEnv);
return true;
}
private void process0(RoundEnvironment roundEnv) {
for (Element e : roundEnv.getElementsAnnotatedWith(MessageResolution.class)) {
try {
processElement(e);
} catch (Throwable ex) {
ex.printStackTrace();
String message = "Uncaught error in " + this.getClass();
ProcessorContext.getInstance().getEnvironment().getMessager().printMessage(Kind.ERROR, message + ": " + ElementUtils.printException(ex));
}
}
}
private void processElement(Element e) throws IOException {
if (e.getKind() != ElementKind.CLASS) {
return;
}
MessageResolution messageImplementations = e.getAnnotation(MessageResolution.class);
if (messageImplementations == null) {
return;
}
// Check the receiver
final String receiverTypeFullClassName = Utils.getReceiverTypeFullClassName(messageImplementations);
if (isReceiverNonStaticInner(messageImplementations)) {
emitError(receiverTypeFullClassName + " cannot be used as a receiver as it is not a static inner class.", e);
return;
}
// check if there is a @LanguageCheck class
Element curr = e;
List<TypeElement> receiverChecks = new ArrayList<>();
for (Element innerClass : curr.getEnclosedElements()) {
if (innerClass.getKind() != ElementKind.CLASS) {
continue;
}
if (innerClass.getAnnotation(CanResolve.class) != null) {
receiverChecks.add((TypeElement) innerClass);
}
}
if (receiverChecks.size() == 0 && isInstanceMissing(receiverTypeFullClassName)) {
emitError("Missing isInstance method in class " + receiverTypeFullClassName, e);
return;
}
if (receiverChecks.size() == 0 && isInstanceHasWrongSignature(receiverTypeFullClassName)) {
emitError("Method isInstance in class " + receiverTypeFullClassName + " has an invalid signature: expected signature (object: TruffleObject).", e);
return;
}
if (receiverChecks.size() > 1) {
emitError("Only one @LanguageCheck element allowed", e);
return;
}
// Collect all inner classes with an @Resolve annotation
curr = e;
List<TypeElement> elements = new ArrayList<>();
for (Element innerClass : curr.getEnclosedElements()) {
if (innerClass.getKind() != ElementKind.CLASS) {
continue;
}
if (innerClass.getAnnotation(Resolve.class) != null) {
elements.add((TypeElement) innerClass);
}
}
ForeignAccessFactoryGenerator factoryGenerator = new ForeignAccessFactoryGenerator(processingEnv, messageImplementations, (TypeElement) e);
// Process inner classes with an @Resolve annotation
boolean generationSuccessfull = true;
for (TypeElement elem : elements) {
generationSuccessfull &= processResolveClass(elem.getAnnotation(Resolve.class), messageImplementations, elem, factoryGenerator);
}
if (!generationSuccessfull) {
return;
}
if (!receiverChecks.isEmpty()) {
generationSuccessfull &= processLanguageCheck(messageImplementations, receiverChecks.get(0), factoryGenerator);
}
if (!generationSuccessfull) {
return;
}
try {
factoryGenerator.generate();
} catch (FilerException ex) {
emitError("Foreign factory class with same name already exists", e);
return;
}
}
private boolean processLanguageCheck(MessageResolution messageResolutionAnnotation, TypeElement element, ForeignAccessFactoryGenerator factoryGenerator)
throws IOException {
LanguageCheckGenerator generator = new LanguageCheckGenerator(processingEnv, messageResolutionAnnotation, element);
if (!ElementUtils.typeEquals(element.getSuperclass(), Utils.getTypeMirror(processingEnv, com.oracle.truffle.api.nodes.Node.class))) {
emitError(ElementUtils.getQualifiedName(element) + " must extend com.oracle.truffle.api.nodes.Node.", element);
return false;
}
if (!element.getModifiers().contains(Modifier.ABSTRACT)) {
emitError("Class must be abstract", element);
return false;
}
if (!element.getModifiers().contains(Modifier.STATIC)) {
emitError("Class must be static", element);
return false;
}
List<ExecutableElement> methods = generator.getTestMethods();
if (methods.isEmpty() || methods.size() > 1) {
emitError("There needs to be exactly one test method.", element);
return false;
}
ExecutableElement m = methods.get(0);
String errorMessage = generator.checkSignature(m);
if (errorMessage != null) {
emitError(errorMessage, m);
return false;
}
try {
generator.generate();
} catch (FilerException ex) {
emitError("Language check class with same name already exists", element);
return false;
}
factoryGenerator.addLanguageCheckHandler(generator.getRootNodeFactoryInvokation());
return true;
}
private boolean processResolveClass(Resolve resolveAnnotation, MessageResolution messageResolutionAnnotation, TypeElement element, ForeignAccessFactoryGenerator factoryGenerator)
throws IOException {
MessageGenerator currentGenerator = MessageGenerator.getGenerator(processingEnv, resolveAnnotation, messageResolutionAnnotation, element);
if (currentGenerator == null) {
emitError("Unknown message type: " + resolveAnnotation.message(), element);
return false;
}
if (!ElementUtils.typeEquals(element.getSuperclass(), Utils.getTypeMirror(processingEnv, com.oracle.truffle.api.nodes.Node.class))) {
emitError(ElementUtils.getQualifiedName(element) + " must extend com.oracle.truffle.api.nodes.Node.", element);
return false;
}
if (!element.getModifiers().contains(Modifier.ABSTRACT)) {
emitError("Class must be abstract", element);
return false;
}
if (!element.getModifiers().contains(Modifier.STATIC)) {
emitError("Class must be static", element);
return false;
}
List<ExecutableElement> methods = currentGenerator.getAccessMethods();
if (methods.isEmpty()) {
emitError("There needs to be at least one access method.", element);
return false;
}
List<? extends VariableElement> params = methods.get(0).getParameters();
int argumentSize = params.size();
if (params.size() > 0 && ElementUtils.typeEquals(params.get(0).asType(), Utils.getTypeMirror(processingEnv, VirtualFrame.class))) {
argumentSize -= 1;
}
for (ExecutableElement m : methods) {
params = m.getParameters();
int paramsSize = params.size();
if (params.size() > 0 && ElementUtils.typeEquals(params.get(0).asType(), Utils.getTypeMirror(processingEnv, VirtualFrame.class))) {
paramsSize -= 1;
}
if (argumentSize != paramsSize) {
emitError("Inconsistent argument length.", element);
return false;
}
}
for (ExecutableElement m : methods) {
String errorMessage = currentGenerator.checkSignature(m);
if (errorMessage != null) {
emitError(errorMessage, m);
return false;
}
}
try {
currentGenerator.generate();
} catch (FilerException ex) {
emitError("Message resolution class with same name already exists", element);
return false;
}
Object currentMessage = Utils.getMessage(processingEnv, resolveAnnotation.message());
factoryGenerator.addMessageHandler(currentMessage, currentGenerator.getRootNodeFactoryInvokation());
return true;
}
private static boolean isReceiverNonStaticInner(MessageResolution message) {
try {
message.receiverType();
throw new AssertionError();
} catch (MirroredTypeException mte) {
// This exception is always thrown: use the mirrors to inspect the class
DeclaredType type = (DeclaredType) mte.getTypeMirror();
TypeElement element = (TypeElement) type.asElement();
if (element.getNestingKind() == NestingKind.MEMBER || element.getNestingKind() == NestingKind.LOCAL) {
for (Modifier modifier : element.getModifiers()) {
if (modifier.compareTo(Modifier.STATIC) == 0) {
return false;
}
}
return true;
} else {
return false;
}
}
}
private boolean isInstanceMissing(String receiverTypeFullClassName) {
for (Element elem : this.processingEnv.getElementUtils().getTypeElement(receiverTypeFullClassName).getEnclosedElements()) {
if (elem.getKind().equals(ElementKind.METHOD)) {
ExecutableElement method = (ExecutableElement) elem;
if (method.getSimpleName().toString().equals("isInstance")) {
return false;
}
}
}
return true;
}
private boolean isInstanceHasWrongSignature(String receiverTypeFullClassName) {
for (Element elem : this.processingEnv.getElementUtils().getTypeElement(receiverTypeFullClassName).getEnclosedElements()) {
if (elem.getKind().equals(ElementKind.METHOD)) {
ExecutableElement method = (ExecutableElement) elem;
if (method.getSimpleName().toString().equals("isInstance") && method.getParameters().size() == 1 &&
ElementUtils.typeEquals(method.getParameters().get(0).asType(), Utils.getTypeMirror(processingEnv, TruffleObject.class))) {
return false;
}
}
}
return true;
}
private void emitError(String msg, Element e) {
if (ExpectError.isExpectedError(processingEnv, e, msg)) {
return;
}
processingEnv.getMessager().printMessage(Kind.ERROR, msg, e);
}
}
|
gpl-2.0
|
SkidJava/BaseClient
|
lucid_1.8.8/net/minecraft/block/BlockStoneSlab.java
|
7170
|
package net.minecraft.block;
import java.util.List;
import java.util.Random;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.BlockPos;
import net.minecraft.util.IStringSerializable;
import net.minecraft.world.World;
public abstract class BlockStoneSlab extends BlockSlab
{
public static final PropertyBool SEAMLESS = PropertyBool.create("seamless");
public static final PropertyEnum<BlockStoneSlab.EnumType> VARIANT = PropertyEnum.<BlockStoneSlab.EnumType>create("variant", BlockStoneSlab.EnumType.class);
public BlockStoneSlab()
{
super(Material.rock);
IBlockState iblockstate = this.blockState.getBaseState();
if (this.isDouble())
{
iblockstate = iblockstate.withProperty(SEAMLESS, Boolean.valueOf(false));
}
else
{
iblockstate = iblockstate.withProperty(HALF, BlockSlab.EnumBlockHalf.BOTTOM);
}
this.setDefaultState(iblockstate.withProperty(VARIANT, BlockStoneSlab.EnumType.STONE));
this.setCreativeTab(CreativeTabs.tabBlock);
}
/**
* Get the Item that this Block should drop when harvested.
*/
public Item getItemDropped(IBlockState state, Random rand, int fortune)
{
return Item.getItemFromBlock(Blocks.stone_slab);
}
public Item getItem(World worldIn, BlockPos pos)
{
return Item.getItemFromBlock(Blocks.stone_slab);
}
/**
* Returns the slab block name with the type associated with it
*/
public String getUnlocalizedName(int meta)
{
return super.getUnlocalizedName() + "." + BlockStoneSlab.EnumType.byMetadata(meta).getUnlocalizedName();
}
public IProperty<?> getVariantProperty()
{
return VARIANT;
}
public Object getVariant(ItemStack stack)
{
return BlockStoneSlab.EnumType.byMetadata(stack.getMetadata() & 7);
}
/**
* returns a list of blocks with the same ID, but different meta (eg: wood returns 4 blocks)
*/
public void getSubBlocks(Item itemIn, CreativeTabs tab, List<ItemStack> list)
{
if (itemIn != Item.getItemFromBlock(Blocks.double_stone_slab))
{
for (BlockStoneSlab.EnumType blockstoneslab$enumtype : BlockStoneSlab.EnumType.values())
{
if (blockstoneslab$enumtype != BlockStoneSlab.EnumType.WOOD)
{
list.add(new ItemStack(itemIn, 1, blockstoneslab$enumtype.getMetadata()));
}
}
}
}
/**
* Convert the given metadata into a BlockState for this Block
*/
public IBlockState getStateFromMeta(int meta)
{
IBlockState iblockstate = this.getDefaultState().withProperty(VARIANT, BlockStoneSlab.EnumType.byMetadata(meta & 7));
if (this.isDouble())
{
iblockstate = iblockstate.withProperty(SEAMLESS, Boolean.valueOf((meta & 8) != 0));
}
else
{
iblockstate = iblockstate.withProperty(HALF, (meta & 8) == 0 ? BlockSlab.EnumBlockHalf.BOTTOM : BlockSlab.EnumBlockHalf.TOP);
}
return iblockstate;
}
/**
* Convert the BlockState into the correct metadata value
*/
public int getMetaFromState(IBlockState state)
{
int i = 0;
i = i | ((BlockStoneSlab.EnumType)state.getValue(VARIANT)).getMetadata();
if (this.isDouble())
{
if (((Boolean)state.getValue(SEAMLESS)).booleanValue())
{
i |= 8;
}
}
else if (state.getValue(HALF) == BlockSlab.EnumBlockHalf.TOP)
{
i |= 8;
}
return i;
}
protected BlockState createBlockState()
{
return this.isDouble() ? new BlockState(this, new IProperty[] {SEAMLESS, VARIANT}): new BlockState(this, new IProperty[] {HALF, VARIANT});
}
/**
* Gets the metadata of the item this Block can drop. This method is called when the block gets destroyed. It
* returns the metadata of the dropped item based on the old metadata of the block.
*/
public int damageDropped(IBlockState state)
{
return ((BlockStoneSlab.EnumType)state.getValue(VARIANT)).getMetadata();
}
/**
* Get the MapColor for this Block and the given BlockState
*/
public MapColor getMapColor(IBlockState state)
{
return ((BlockStoneSlab.EnumType)state.getValue(VARIANT)).func_181074_c();
}
public static enum EnumType implements IStringSerializable
{
STONE(0, MapColor.stoneColor, "stone"),
SAND(1, MapColor.sandColor, "sandstone", "sand"),
WOOD(2, MapColor.woodColor, "wood_old", "wood"),
COBBLESTONE(3, MapColor.stoneColor, "cobblestone", "cobble"),
BRICK(4, MapColor.redColor, "brick"),
SMOOTHBRICK(5, MapColor.stoneColor, "stone_brick", "smoothStoneBrick"),
NETHERBRICK(6, MapColor.netherrackColor, "nether_brick", "netherBrick"),
QUARTZ(7, MapColor.quartzColor, "quartz");
private static final BlockStoneSlab.EnumType[] META_LOOKUP = new BlockStoneSlab.EnumType[values().length];
private final int meta;
private final MapColor field_181075_k;
private final String name;
private final String unlocalizedName;
private EnumType(int p_i46381_3_, MapColor p_i46381_4_, String p_i46381_5_)
{
this(p_i46381_3_, p_i46381_4_, p_i46381_5_, p_i46381_5_);
}
private EnumType(int p_i46382_3_, MapColor p_i46382_4_, String p_i46382_5_, String p_i46382_6_)
{
this.meta = p_i46382_3_;
this.field_181075_k = p_i46382_4_;
this.name = p_i46382_5_;
this.unlocalizedName = p_i46382_6_;
}
public int getMetadata()
{
return this.meta;
}
public MapColor func_181074_c()
{
return this.field_181075_k;
}
public String toString()
{
return this.name;
}
public static BlockStoneSlab.EnumType byMetadata(int meta)
{
if (meta < 0 || meta >= META_LOOKUP.length)
{
meta = 0;
}
return META_LOOKUP[meta];
}
public String getName()
{
return this.name;
}
public String getUnlocalizedName()
{
return this.unlocalizedName;
}
static {
for (BlockStoneSlab.EnumType blockstoneslab$enumtype : values())
{
META_LOOKUP[blockstoneslab$enumtype.getMetadata()] = blockstoneslab$enumtype;
}
}
}
}
|
gpl-2.0
|
Pasha-G/icms1
|
templates/_default_/admin/autoform.php
|
1670
|
<?php
global $tpl_data, $_LANG;
extract($tpl_data);
?>
<input type="hidden" name="do" value="save_auto_config" />
<input type="hidden" name="csrf_token" value="<?php echo cmsUser::getCsrfToken(); ?>" />
<div class="params-form">
<table width="100%" cellpadding="3" cellspacing="0" border="0">
<?php foreach($fields as $fid=>$field){ ?>
<tr id="f<?php echo $fid; ?>">
<td class="param-name">
<div class="label"><strong><?php echo $field['title']; ?></strong></div>
<?php if ($field['hint']) { ?>
<div class="hinttext"><?php echo $field['hint']; ?></div>
<?php } ?>
<?php if ($field['type']=='list_db' && $field['multiple']) { ?>
<div class="param-links">
<a href="javascript:void(0);" onclick="$('tr#f<?php echo $fid; ?> td input:checkbox').prop('checked', true)"><?php echo $_LANG['SELECT_ALL']; ?></a> |
<a href="javascript:void(0);" onclick="$('tr#f<?php echo $fid; ?> td input:checkbox').prop('checked', false)"><?php echo $_LANG['REMOVE_ALL']; ?></a>
</div>
<?php } ?>
</td>
<td class="param-value">
<?php echo $field['html']; ?>
</td>
</tr>
<?php } ?>
</table>
</div>
<div class="params-buttons">
<input type="submit" name="save" class="button" value="<?php echo $_LANG['SAVE']; ?>" />
</div>
<script type="text/javascript">
function submitModuleConfig(){
$('#optform').submit();
}
</script>
|
gpl-2.0
|
lamsfoundation/lams
|
3rdParty_sources/xmltooling/org/opensaml/xml/encryption/impl/EncryptedTypeImpl.java
|
5355
|
/*
* Licensed to the University Corporation for Advanced Internet Development,
* Inc. (UCAID) under one or more contributor license agreements. See the
* NOTICE file distributed with this work for additional information regarding
* copyright ownership. The UCAID licenses this file to You under the Apache
* License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opensaml.xml.encryption.impl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.opensaml.xml.XMLObject;
import org.opensaml.xml.encryption.CipherData;
import org.opensaml.xml.encryption.EncryptedType;
import org.opensaml.xml.encryption.EncryptionMethod;
import org.opensaml.xml.encryption.EncryptionProperties;
import org.opensaml.xml.signature.KeyInfo;
import org.opensaml.xml.validation.AbstractValidatingXMLObject;
/**
* Abstract implementation of {@link org.opensaml.xml.encryption.EncryptedType}.
*/
public abstract class EncryptedTypeImpl extends AbstractValidatingXMLObject implements EncryptedType {
/** id attribute value. */
private String id;
/** Type attribute value. */
private String type;
/** MimeType attribute value. */
private String mimeType;
/** Encoding attribute value. */
private String encoding;
/** EncryptionMethod child element. */
private EncryptionMethod encryptionMethod;
/** EncryptionMethod child element. */
private KeyInfo keyInfo;
/** CipherData child element. */
private CipherData cipherData;
/** EncryptionProperties child element. */
private EncryptionProperties encryptionProperties;
/**
* Constructor
*
* @param namespaceURI
* @param elementLocalName
* @param namespacePrefix
*/
protected EncryptedTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) {
super(namespaceURI, elementLocalName, namespacePrefix);
}
/** {@inheritDoc} */
public String getID() {
return this.id;
}
/** {@inheritDoc} */
public void setID(String newID) {
String oldID = this.id;
this.id = prepareForAssignment(this.id, newID);
registerOwnID(oldID, this.id);
}
/** {@inheritDoc} */
public String getType() {
return this.type;
}
/** {@inheritDoc} */
public void setType(String newType) {
this.type = prepareForAssignment(this.type, newType);
}
/** {@inheritDoc} */
public String getMimeType() {
return this.mimeType;
}
/** {@inheritDoc} */
public void setMimeType(String newMimeType) {
this.mimeType = prepareForAssignment(this.mimeType, newMimeType);
}
/** {@inheritDoc} */
public String getEncoding() {
return this.encoding;
}
/** {@inheritDoc} */
public void setEncoding(String newEncoding) {
this.encoding = prepareForAssignment(this.encoding, newEncoding);
}
/** {@inheritDoc} */
public EncryptionMethod getEncryptionMethod() {
return this.encryptionMethod;
}
/** {@inheritDoc} */
public void setEncryptionMethod(EncryptionMethod newEncryptionMethod) {
this.encryptionMethod = prepareForAssignment(this.encryptionMethod, newEncryptionMethod);
}
/** {@inheritDoc} */
public KeyInfo getKeyInfo() {
return this.keyInfo;
}
/** {@inheritDoc} */
public void setKeyInfo(KeyInfo newKeyInfo) {
this.keyInfo = prepareForAssignment(this.keyInfo, newKeyInfo);
}
/** {@inheritDoc} */
public CipherData getCipherData() {
return this.cipherData;
}
/** {@inheritDoc} */
public void setCipherData(CipherData newCipherData) {
this.cipherData = prepareForAssignment(this.cipherData, newCipherData);
}
/** {@inheritDoc} */
public EncryptionProperties getEncryptionProperties() {
return this.encryptionProperties;
}
/** {@inheritDoc} */
public void setEncryptionProperties(EncryptionProperties newEncryptionProperties) {
this.encryptionProperties = prepareForAssignment(this.encryptionProperties, newEncryptionProperties);
}
/** {@inheritDoc} */
public List<XMLObject> getOrderedChildren() {
ArrayList<XMLObject> children = new ArrayList<XMLObject>();
if (encryptionMethod != null) {
children.add(encryptionMethod);
}
if (keyInfo != null) {
children.add(keyInfo);
}
if (cipherData != null) {
children.add(cipherData);
}
if (encryptionProperties!= null) {
children.add(encryptionProperties);
}
if (children.size() == 0) {
return null;
}
return Collections.unmodifiableList(children);
}
}
|
gpl-2.0
|
FeiZhu/Physika
|
Projects/TESTS/matrix4x4_test.cpp
|
2549
|
/*
* @file matrix4x4_test.cpp
* @brief Test the Matrix4x4 class.
* @author Sheng Yang, Liyou Xu
*
* This file is part of Physika, a versatile physics simulation library.
* Copyright (C) 2013- Physika Group.
*
* This Source Code Form is subject to the terms of the GNU General Public License v2.0.
* If a copy of the GPL was not distributed with this file, you can obtain one at:
* http://www.gnu.org/licenses/gpl-2.0.html
*
*/
#include <iostream>
#include "Physika_Core/Matrices/matrix_4x4.h"
using namespace std;
int main()
{
cout<<"Matrix4x4 Test"<<endl;
Physika::SquareMatrix<double,4> mat_double(3.0,1.0,1.0,1.0, 3.0,3.0,1.0,1.0, 3.0,3.0,3.0,1.0, 3.0,3.0,3.0,3.0);
cout<<"A 4x4 matrix of double numbers:"<<endl;
cout<<mat_double;
cout<<"Rows: "<<mat_double.rows()<<" Cols: "<<mat_double.cols()<<endl;
Physika::SquareMatrix<double,4> mat_double3(1.0,1.0,1.0,1.0, 0.0,3.0,3.0,0.0, 3.0,2.0,3.0,1.0, 1.0,1.0,0.0,0.0);
cout<<"Another 4x4 matrix of double numbers:"<<endl;
cout<<mat_double3<<endl;
cout<<"matrix2[1][1]:"<<mat_double3(1,1)<<endl;
cout<<"matrix2's trace:"<<mat_double3.trace()<<endl;
cout<<"matrix1 and matrix2's double contraction:"<<mat_double.doubleContraction(mat_double3)<<endl;
cout<<"matrix1 add matrix3: (+)"<<endl;
cout<<mat_double+mat_double3<<endl;
cout<<"matrix1 add matrix3: (+=)"<<endl;
cout<<(mat_double+=mat_double3)<<endl;
cout<<"matrix1 sub matrix3: (-)"<<endl;
cout<<mat_double-mat_double3<<endl;
cout<<"matrix1 sub matrix3: (-=)"<<endl;
cout<<(mat_double-=mat_double3)<<endl;
cout<<"equal test: (matrix1 == matrix3)?"<<endl;
if(mat_double==mat_double3)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
cout<<"matrix1 copy to matrix3:"<<endl;
mat_double3=mat_double;
cout<<mat_double3<<endl;
cout<<"matrix1 mult scalar(3): (*)"<<endl;
cout<<mat_double*3.0f<<endl;
cout<<"matrix1 mult scalar(3): (*=)"<<endl;
cout<<(mat_double*=3.0f)<<endl;
cout<<"matrix1 div scalar(4): (/)"<<endl;
cout<<mat_double/4.0f<<endl;
cout<<"matrix1 div scalar(4): (/=)"<<endl;
cout<<(mat_double/=4.0f)<<endl;
cout<<"matrix1 transpose:"<<endl;
cout<<mat_double.transpose()<<endl;
cout<<"copy matrix2 to matrix1:"<<endl;
mat_double = mat_double3;
cout<<mat_double<<endl;
cout<<"matrix1 inverse:"<<endl;
cout<<mat_double.inverse()<<endl;
cout<<"matrix1 determinant:"<<endl;
cout<<mat_double.determinant()<<endl;
cout<<"matrix1^(-1) mult matrix2:"<<endl;
cout<<mat_double.inverse()*mat_double3<<endl;
int a;
cin>>a;
return 0;
}
|
gpl-2.0
|
snorrelo/plugin.image.500px
|
resources/lib/fivehundredpxutils/xbmc.py
|
1545
|
import os
import sys
import urllib
import urlparse
import string
import xbmcgui
import xbmcplugin
import xbmcaddon
__addon__ = xbmcaddon.Addon()
addon_path = __addon__.getAddonInfo('path')
addon_url = sys.argv[0]
addon_handle = int(sys.argv[1])
addon_params = dict(urlparse.parse_qsl(sys.argv[2][1:]))
def encode_child_url(mode, **kwargs):
params = {
'mode': mode
}
params.update(kwargs)
return "%s?&%s" % (addon_url, urllib.urlencode(params))
def add_dir(name, url, thumb=None):
def enhance_name(value):
return string.capwords(value.replace('_', ' '))
name = enhance_name(name)
item = xbmcgui.ListItem(name)
item.setInfo(type="Image", infoLabels={"Title": name})
if thumb:
item.setArt({'thumb': thumb})
xbmcplugin.addDirectoryItem(addon_handle, url, item, True)
def add_image(image):
item = xbmcgui.ListItem(image.name)
item.setArt({'thumb': image.thumb_url})
item.setInfo(
type='pictures',
infoLabels={
"title": image.name,
"picturepath": image.url,
"exif:path": image.url
}
)
if not 'ctxsearch' in addon_params:
label = "More from %s" % image.userfullname # i18n
url = encode_child_url('search', term=image.username, ctxsearch=True)
action = "XBMC.Container.Update(%s)" % url
item.addContextMenuItems([(label, action,)])
xbmcplugin.addDirectoryItem(addon_handle, image.url, item)
def end_of_directory():
xbmcplugin.endOfDirectory(addon_handle)
|
gpl-2.0
|
YesWiki/yeswiki-extensions-deprecated
|
wysiwyg/libs/tiny_mce/plugins/table/js/table.js
|
14125
|
tinyMCEPopup.requireLangPack();
var action, orgTableWidth, orgTableHeight, dom = tinyMCEPopup.editor.dom;
function insertTable() {
var formObj = document.forms[0];
var inst = tinyMCEPopup.editor, dom = inst.dom;
var cols = 2, rows = 2, border = 0, cellpadding = -1, cellspacing = -1, align, width, height, className, caption, frame, rules;
var html = '', capEl, elm;
var cellLimit, rowLimit, colLimit;
tinyMCEPopup.restoreSelection();
if (!AutoValidator.validate(formObj)) {
tinyMCEPopup.alert(inst.getLang('invalid_data'));
return false;
}
elm = dom.getParent(inst.selection.getNode(), 'table');
// Get form data
cols = formObj.elements['cols'].value;
rows = formObj.elements['rows'].value;
border = formObj.elements['border'].value != "" ? formObj.elements['border'].value : 0;
cellpadding = formObj.elements['cellpadding'].value != "" ? formObj.elements['cellpadding'].value : "";
cellspacing = formObj.elements['cellspacing'].value != "" ? formObj.elements['cellspacing'].value : "";
align = getSelectValue(formObj, "align");
frame = getSelectValue(formObj, "tframe");
rules = getSelectValue(formObj, "rules");
width = formObj.elements['width'].value;
height = formObj.elements['height'].value;
bordercolor = formObj.elements['bordercolor'].value;
bgcolor = formObj.elements['bgcolor'].value;
className = getSelectValue(formObj, "class");
id = formObj.elements['id'].value;
summary = formObj.elements['summary'].value;
style = formObj.elements['style'].value;
dir = formObj.elements['dir'].value;
lang = formObj.elements['lang'].value;
background = formObj.elements['backgroundimage'].value;
caption = formObj.elements['caption'].checked;
cellLimit = tinyMCEPopup.getParam('table_cell_limit', false);
rowLimit = tinyMCEPopup.getParam('table_row_limit', false);
colLimit = tinyMCEPopup.getParam('table_col_limit', false);
// Validate table size
if (colLimit && cols > colLimit) {
tinyMCEPopup.alert(inst.getLang('table_dlg.col_limit').replace(/\{\$cols\}/g, colLimit));
return false;
} else if (rowLimit && rows > rowLimit) {
tinyMCEPopup.alert(inst.getLang('table_dlg.row_limit').replace(/\{\$rows\}/g, rowLimit));
return false;
} else if (cellLimit && cols * rows > cellLimit) {
tinyMCEPopup.alert(inst.getLang('table_dlg.cell_limit').replace(/\{\$cells\}/g, cellLimit));
return false;
}
// Update table
if (action == "update") {
inst.execCommand('mceBeginUndoLevel');
dom.setAttrib(elm, 'cellPadding', cellpadding, true);
dom.setAttrib(elm, 'cellSpacing', cellspacing, true);
dom.setAttrib(elm, 'border', border);
dom.setAttrib(elm, 'align', align);
dom.setAttrib(elm, 'frame', frame);
dom.setAttrib(elm, 'rules', rules);
dom.setAttrib(elm, 'class', className);
dom.setAttrib(elm, 'style', style);
dom.setAttrib(elm, 'id', id);
dom.setAttrib(elm, 'summary', summary);
dom.setAttrib(elm, 'dir', dir);
dom.setAttrib(elm, 'lang', lang);
capEl = inst.dom.select('caption', elm)[0];
if (capEl && !caption)
capEl.parentNode.removeChild(capEl);
if (!capEl && caption) {
capEl = elm.ownerDocument.createElement('caption');
if (!tinymce.isIE)
capEl.innerHTML = '<br data-mce-bogus="1"/>';
elm.insertBefore(capEl, elm.firstChild);
}
if (width && inst.settings.inline_styles) {
dom.setStyle(elm, 'width', width);
dom.setAttrib(elm, 'width', '');
} else {
dom.setAttrib(elm, 'width', width, true);
dom.setStyle(elm, 'width', '');
}
// Remove these since they are not valid XHTML
dom.setAttrib(elm, 'borderColor', '');
dom.setAttrib(elm, 'bgColor', '');
dom.setAttrib(elm, 'background', '');
if (height && inst.settings.inline_styles) {
dom.setStyle(elm, 'height', height);
dom.setAttrib(elm, 'height', '');
} else {
dom.setAttrib(elm, 'height', height, true);
dom.setStyle(elm, 'height', '');
}
if (background != '')
elm.style.backgroundImage = "url('" + background + "')";
else
elm.style.backgroundImage = '';
/* if (tinyMCEPopup.getParam("inline_styles")) {
if (width != '')
elm.style.width = getCSSSize(width);
}*/
if (bordercolor != "") {
elm.style.borderColor = bordercolor;
elm.style.borderStyle = elm.style.borderStyle == "" ? "solid" : elm.style.borderStyle;
elm.style.borderWidth = border == "" ? "1px" : border;
} else
elm.style.borderColor = '';
elm.style.backgroundColor = bgcolor;
elm.style.height = getCSSSize(height);
inst.addVisual();
// Fix for stange MSIE align bug
//elm.outerHTML = elm.outerHTML;
inst.nodeChanged();
inst.execCommand('mceEndUndoLevel');
// Repaint if dimensions changed
if (formObj.width.value != orgTableWidth || formObj.height.value != orgTableHeight)
inst.execCommand('mceRepaint');
tinyMCEPopup.close();
return true;
}
// Create new table
html += '<table';
html += makeAttrib('id', id);
html += makeAttrib('border', border);
html += makeAttrib('cellpadding', cellpadding);
html += makeAttrib('cellspacing', cellspacing);
html += makeAttrib('data-mce-new', '1');
if (width && inst.settings.inline_styles) {
if (style)
style += '; ';
// Force px
if (/^[0-9\.]+$/.test(width))
width += 'px';
style += 'width: ' + width;
} else
html += makeAttrib('width', width);
/* if (height) {
if (style)
style += '; ';
style += 'height: ' + height;
}*/
//html += makeAttrib('height', height);
//html += makeAttrib('bordercolor', bordercolor);
//html += makeAttrib('bgcolor', bgcolor);
html += makeAttrib('align', align);
html += makeAttrib('frame', frame);
html += makeAttrib('rules', rules);
html += makeAttrib('class', className);
html += makeAttrib('style', style);
html += makeAttrib('summary', summary);
html += makeAttrib('dir', dir);
html += makeAttrib('lang', lang);
html += '>';
if (caption) {
if (!tinymce.isIE)
html += '<caption><br data-mce-bogus="1"/></caption>';
else
html += '<caption></caption>';
}
for (var y=0; y<rows; y++) {
html += "<tr>";
for (var x=0; x<cols; x++) {
if (!tinymce.isIE)
html += '<td><br data-mce-bogus="1"/></td>';
else
html += '<td></td>';
}
html += "</tr>";
}
html += "</table>";
inst.execCommand('mceBeginUndoLevel');
// Move table
if (inst.settings.fix_table_elements) {
var patt = '';
inst.focus();
inst.selection.setContent('<br class="_mce_marker" />');
tinymce.each('h1,h2,h3,h4,h5,h6,p'.split(','), function(n) {
if (patt)
patt += ',';
patt += n + ' ._mce_marker';
});
tinymce.each(inst.dom.select(patt), function(n) {
inst.dom.split(inst.dom.getParent(n, 'h1,h2,h3,h4,h5,h6,p'), n);
});
dom.setOuterHTML(dom.select('br._mce_marker')[0], html);
} else
inst.execCommand('mceInsertContent', false, html);
tinymce.each(dom.select('table[data-mce-new]'), function(node) {
var td = dom.select('td', node);
try {
// IE9 might fail to do this selection
inst.selection.select(td[0], true);
inst.selection.collapse();
} catch (ex) {
// Ignore
}
dom.setAttrib(node, 'data-mce-new', '');
});
inst.addVisual();
inst.execCommand('mceEndUndoLevel');
tinyMCEPopup.close();
}
function makeAttrib(attrib, value) {
var formObj = document.forms[0];
var valueElm = formObj.elements[attrib];
if (typeof(value) == "undefined" || value == null) {
value = "";
if (valueElm)
value = valueElm.value;
}
if (value == "")
return "";
// XML encode it
value = value.replace(/&/g, '&');
value = value.replace(/\"/g, '"');
value = value.replace(/</g, '<');
value = value.replace(/>/g, '>');
return ' ' + attrib + '="' + value + '"';
}
function init() {
tinyMCEPopup.resizeToInnerSize();
document.getElementById('backgroundimagebrowsercontainer').innerHTML = getBrowserHTML('backgroundimagebrowser','backgroundimage','image','table');
document.getElementById('backgroundimagebrowsercontainer').innerHTML = getBrowserHTML('backgroundimagebrowser','backgroundimage','image','table');
document.getElementById('bordercolor_pickcontainer').innerHTML = getColorPickerHTML('bordercolor_pick','bordercolor');
document.getElementById('bgcolor_pickcontainer').innerHTML = getColorPickerHTML('bgcolor_pick','bgcolor');
var cols = 2, rows = 2, border = tinyMCEPopup.getParam('table_default_border', '0'), cellpadding = tinyMCEPopup.getParam('table_default_cellpadding', ''), cellspacing = tinyMCEPopup.getParam('table_default_cellspacing', '');
var align = "", width = "", height = "", bordercolor = "", bgcolor = "", className = "";
var id = "", summary = "", style = "", dir = "", lang = "", background = "", bgcolor = "", bordercolor = "", rules = "", frame = "";
var inst = tinyMCEPopup.editor, dom = inst.dom;
var formObj = document.forms[0];
var elm = dom.getParent(inst.selection.getNode(), "table");
action = tinyMCEPopup.getWindowArg('action');
if (!action)
action = elm ? "update" : "insert";
if (elm && action != "insert") {
var rowsAr = elm.rows;
var cols = 0;
for (var i=0; i<rowsAr.length; i++)
if (rowsAr[i].cells.length > cols)
cols = rowsAr[i].cells.length;
cols = cols;
rows = rowsAr.length;
st = dom.parseStyle(dom.getAttrib(elm, "style"));
border = trimSize(getStyle(elm, 'border', 'borderWidth'));
cellpadding = dom.getAttrib(elm, 'cellpadding', "");
cellspacing = dom.getAttrib(elm, 'cellspacing', "");
width = trimSize(getStyle(elm, 'width', 'width'));
height = trimSize(getStyle(elm, 'height', 'height'));
bordercolor = convertRGBToHex(getStyle(elm, 'bordercolor', 'borderLeftColor'));
bgcolor = convertRGBToHex(getStyle(elm, 'bgcolor', 'backgroundColor'));
align = dom.getAttrib(elm, 'align', align);
frame = dom.getAttrib(elm, 'frame');
rules = dom.getAttrib(elm, 'rules');
className = tinymce.trim(dom.getAttrib(elm, 'class').replace(/mceItem.+/g, ''));
id = dom.getAttrib(elm, 'id');
summary = dom.getAttrib(elm, 'summary');
style = dom.serializeStyle(st);
dir = dom.getAttrib(elm, 'dir');
lang = dom.getAttrib(elm, 'lang');
background = getStyle(elm, 'background', 'backgroundImage').replace(new RegExp("url\\(['\"]?([^'\"]*)['\"]?\\)", 'gi'), "$1");
formObj.caption.checked = elm.getElementsByTagName('caption').length > 0;
orgTableWidth = width;
orgTableHeight = height;
action = "update";
formObj.insert.value = inst.getLang('update');
}
addClassesToList('class', "table_styles");
TinyMCE_EditableSelects.init();
// Update form
selectByValue(formObj, 'align', align);
selectByValue(formObj, 'tframe', frame);
selectByValue(formObj, 'rules', rules);
selectByValue(formObj, 'class', className, true, true);
formObj.cols.value = cols;
formObj.rows.value = rows;
formObj.border.value = border;
formObj.cellpadding.value = cellpadding;
formObj.cellspacing.value = cellspacing;
formObj.width.value = width;
formObj.height.value = height;
formObj.bordercolor.value = bordercolor;
formObj.bgcolor.value = bgcolor;
formObj.id.value = id;
formObj.summary.value = summary;
formObj.style.value = style;
formObj.dir.value = dir;
formObj.lang.value = lang;
formObj.backgroundimage.value = background;
updateColor('bordercolor_pick', 'bordercolor');
updateColor('bgcolor_pick', 'bgcolor');
// Resize some elements
if (isVisible('backgroundimagebrowser'))
document.getElementById('backgroundimage').style.width = '180px';
// Disable some fields in update mode
if (action == "update") {
formObj.cols.disabled = true;
formObj.rows.disabled = true;
}
}
function changedSize() {
var formObj = document.forms[0];
var st = dom.parseStyle(formObj.style.value);
/* var width = formObj.width.value;
if (width != "")
st['width'] = tinyMCEPopup.getParam("inline_styles") ? getCSSSize(width) : "";
else
st['width'] = "";*/
var height = formObj.height.value;
if (height != "")
st['height'] = getCSSSize(height);
else
st['height'] = "";
formObj.style.value = dom.serializeStyle(st);
}
function changedBackgroundImage() {
var formObj = document.forms[0];
var st = dom.parseStyle(formObj.style.value);
st['background-image'] = "url('" + formObj.backgroundimage.value + "')";
formObj.style.value = dom.serializeStyle(st);
}
function changedBorder() {
var formObj = document.forms[0];
var st = dom.parseStyle(formObj.style.value);
// Update border width if the element has a color
if (formObj.border.value != "" && formObj.bordercolor.value != "")
st['border-width'] = formObj.border.value + "px";
formObj.style.value = dom.serializeStyle(st);
}
function changedColor() {
var formObj = document.forms[0];
var st = dom.parseStyle(formObj.style.value);
st['background-color'] = formObj.bgcolor.value;
if (formObj.bordercolor.value != "") {
st['border-color'] = formObj.bordercolor.value;
// Add border-width if it's missing
if (!st['border-width'])
st['border-width'] = formObj.border.value == "" ? "1px" : formObj.border.value + "px";
}
formObj.style.value = dom.serializeStyle(st);
}
function changedStyle() {
var formObj = document.forms[0];
var st = dom.parseStyle(formObj.style.value);
if (st['background-image'])
formObj.backgroundimage.value = st['background-image'].replace(new RegExp("url\\(['\"]?([^'\"]*)['\"]?\\)", 'gi'), "$1");
else
formObj.backgroundimage.value = '';
if (st['width'])
formObj.width.value = trimSize(st['width']);
if (st['height'])
formObj.height.value = trimSize(st['height']);
if (st['background-color']) {
formObj.bgcolor.value = st['background-color'];
updateColor('bgcolor_pick','bgcolor');
}
if (st['border-color']) {
formObj.bordercolor.value = st['border-color'];
updateColor('bordercolor_pick','bordercolor');
}
}
tinyMCEPopup.onInit.add(init);
|
gpl-2.0
|
LauraRey/oacfdc
|
components/com_comment/helpers/tree.php
|
3543
|
<?php
/***************************************************************
*
* Copyright notice
*
* Copyright 2013 Daniel Dimitrov. (http://compojoom.com)
* All rights reserved
*
* This script is part of the CompojoomComment project. The CompojoomComment project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
* A copy is found in the textfile GPL.txt and important notices to the license
* from the author is found in LICENSE.txt distributed with these scripts.
*
*
* This script 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 Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
class ccommentHelperTree
{
private static $_counter;
private static $_new;
/**
* @param $data
* @param $seed
*/
private static function getSeed($data, $seed)
{
self::$_counter++;
if ($seed) {
foreach ($seed as $item) {
$data[$item]->wrapnum = self::$_counter;
self::$_new[] = $data[$item];
if (isset($data[$item]->seed) && $data[$item]->seed) {
self::getSeed($data, $data[$item]->seed);
$data[$item] = null;
}
}
}
self::$_counter--;
}
/**
* @static
* @param $data
* @return mixed
*/
public static function build($data)
{
$index = 0;
self::$_new = null;
self::$_counter = 0;
/*
* TREE :
* parents can have several direct children
* their children can have also their own children etc...
*
* parent
* |_ child1
* | |_ child1.1
* | | |_ child1.1.1
* | | |...
* | |_ child1.2
* | ...
* |_ child2
* ...
*
* SEED for one parent is the CHILDS ARRAY
*/
/*
* FIRST LOOP : prepare datas
*
* $index is $data key (we call it: INDEX)
*
* $old[] : key = comment_id / value = INDEX
*
* - save INDEX in a new 'treeid' column
*
* - for all children: replace parentid value by PARENT INDEX value
* -> sort must be with parents first !! (means already set in old)
*
*/
foreach ($data as $item) {
$old[$item->id] = $index;
$data[$index]->treeid = $index;
$data[$index]->parent = $item->parentid;
if ($data[$index]->parent != -1) {
$data[$index]->parent = isset($old[$item->parentid]) ? $old[$item->parentid] : -2;
}
$data[$index]->wrapnum = 0;
$index++;
}
/*
* 2ND LOOP : construct SEED
*
* - for all childrens : construct 1st level 'seed'[]
*/
foreach ($data as $item) {
/* IS CHILD -> PARENT[SEED][] = CHILD INDEX */
if ($item->parent >= 0) {
$data[$item->parent]->seed[] = $item->treeid;
}
}
foreach ($data as $item) {
/* IS NOT A CHILD -> DATA[] */
if ($item->parent == -1) {
self::$_new[] = $item;
if (isset($item->seed)) {
self::getSeed($data, $item->seed);
}
}
}
return self::$_new;
}
}
|
gpl-2.0
|
kadircet/HackMETU-15
|
Pwnable/500/clear.py
|
190
|
#!/usr/bin/python
from os import popen
from os import mkdir
from sys import argv
N = int(argv[1])
popen('killall p500')
popen('rm -rf team*')
for t in range(N):
popen('userdel p500t%d'%t)
|
gpl-2.0
|
bharcode/MachineLearning
|
commons_ml/Logistic_Regression/Logistic_Binary_Classification/Scripts/logistic_regression.py
|
5789
|
#!/usr/bin/env python
# logistic_regression.py
# Author : Saimadhu
# Date: 19-March-2017
# About: Implementing Logistic Regression Classifier to predict to whom the voter will vote.
# Required Python Packages
import pandas as pd
import numpy as np
import pdb
import plotly.plotly as py
import plotly.graph_objs as go
# import plotly.plotly as py
# from plotly.graph_objs import *
py.sign_in('dataaspirant', 'RhJdlA1OsXsTjcRA0Kka')
from sklearn.cross_validation import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
# Files
DATA_SET_PATH = "../Inputs/anes_dataset.csv"
def dataset_headers(dataset):
"""
To get the dataset header names
:param dataset: loaded dataset into pandas DataFrame
:return: list of header names
"""
return list(dataset.columns.values)
def unique_observations(dataset, header, method=1):
"""
To get unique observations in the loaded pandas DataFrame column
:param dataset:
:param header:
:param method: Method to perform the unique (default method=1 for pandas and method=0 for numpy )
:return:
"""
try:
if method == 0:
# With Numpy
observations = np.unique(dataset[[header]])
elif method == 1:
# With Pandas
observations = pd.unique(dataset[header].values.ravel())
else:
observations = None
print "Wrong method type, Use 1 for pandas and 0 for numpy"
except Exception as e:
observations = None
print "Error: {error_msg} /n Please check the inputs once..!".format(error_msg=e.message)
return observations
def feature_target_frequency_relation(dataset, f_t_headers):
"""
To get the frequency relation between targets and the unique feature observations
:param dataset:
:param f_t_headers: feature and target header
:return: feature unique observations dictionary of frequency count dictionary
"""
feature_unique_observations = unique_observations(dataset, f_t_headers[0])
unique_targets = unique_observations(dataset, f_t_headers[1])
frequencies = {}
for feature in feature_unique_observations:
frequencies[feature] = {unique_targets[0]: len(
dataset[(dataset[f_t_headers[0]] == feature) & (dataset[f_t_headers[1]] == unique_targets[0])]),
unique_targets[1]: len(
dataset[(dataset[f_t_headers[0]] == feature) & (dataset[f_t_headers[1]] == unique_targets[1])])}
return frequencies
def feature_target_histogram(feature_target_frequencies, feature_header):
"""
:param feature_target_frequencies:
:param feature_header:
:return:
"""
keys = feature_target_frequencies.keys()
y0 = [feature_target_frequencies[key][0] for key in keys]
y1 = [feature_target_frequencies[key][1] for key in keys]
trace1 = go.Bar(
x=keys,
y=y0,
name='Clinton'
)
trace2 = go.Bar(
x=keys,
y=y1,
name='Dole'
)
data = [trace1, trace2]
layout = go.Layout(
barmode='group',
title='Feature :: ' + feature_header + ' Clinton Vs Dole votes Frequency',
xaxis=dict(title="Feature :: " + feature_header + " classes"),
yaxis=dict(title="Votes Frequency")
)
fig = go.Figure(data=data, layout=layout)
# plot_url = py.plot(fig, filename=feature_header + ' - Target - Histogram')
py.image.save_as(fig, filename=feature_header + '_Target_Histogram.png')
def train_logistic_regression(train_x, train_y):
"""
Training logistic regression model with train dataset features(train_x) and target(train_y)
:param train_x:
:param train_y:
:return:
"""
logistic_regression_model = LogisticRegression()
logistic_regression_model.fit(train_x, train_y)
return logistic_regression_model
def model_accuracy(trained_model, features, targets):
"""
Get the accuracy score of the model
:param trained_model:
:param features:
:param targets:
:return:
"""
accuracy_score = trained_model.score(features, targets)
return accuracy_score
def main():
"""
Logistic Regression classifier main
:return:
"""
# Load the data set for training and testing the logistic regression classifier
dataset = pd.read_csv(DATA_SET_PATH)
print "Number of Observations :: ", len(dataset)
# Get the first observation
print dataset.head()
headers = dataset_headers(dataset)
print "Data set headers :: {headers}".format(headers=headers)
training_features = ['TVnews', 'PID', 'age', 'educ', 'income']
target = 'vote'
# Train , Test data split
train_x, test_x, train_y, test_y = train_test_split(dataset[training_features], dataset[target], train_size=0.7)
print "train_x size :: ", train_x.shape
print "train_y size :: ", train_y.shape
print "test_x size :: ", test_x.shape
print "test_y size :: ", test_y.shape
print "edu_target_frequencies :: ", feature_target_frequency_relation(dataset, [training_features[3], target])
for feature in training_features:
feature_target_frequencies = feature_target_frequency_relation(dataset, [feature, target])
feature_target_histogram(feature_target_frequencies, feature)
# Training Logistic regression model
trained_logistic_regression_model = train_logistic_regression(train_x, train_y)
train_accuracy = model_accuracy(trained_logistic_regression_model, train_x, train_y)
# Testing the logistic regression model
test_accuracy = model_accuracy(trained_logistic_regression_model, test_x, test_y)
print "Train Accuracy :: ", train_accuracy
print "Test Accuracy :: ", test_accuracy
if __name__ == "__main__":
main()
|
gpl-2.0
|
iarna/joe-editor
|
tests/joefx/controller.py
|
7787
|
import array
import atexit
import collections
import fcntl
import os
import pty
import select
import shutil
import signal
import tempfile
import termios
import time
import pyte
from . import exceptions
from . import keys
coord = collections.namedtuple('coord', ['X', 'Y'])
class JoeController(object):
"""Controller class for JOE program. Manages child process and sends/receives interaction. Nothing specific to JOE here, really"""
def __init__(self, joeexe, joeargs, joeenv, startup, pid, fd):
self.joeexe = joeexe
self.joeargs = joeargs
self.joeenv = joeenv
self.pid = pid
self.fd = fd
self.exited = None
self.term = pyte.Screen(startup.columns, startup.lines)
self.stream = pyte.ByteStream()
self.stream.attach(self.term)
self.timeout = 1
def expect(self, func):
"""Waits for data from the child process and runs func until it returns true or a timeout has elapsed"""
if not self.checkProcess():
raise exceptions.ProcessExitedException
if func(): return True
timeout = self.timeout
deadline = time.time() + timeout
while timeout > 0:
rready, wready, xready = select.select([self.fd], [], [self.fd], timeout)
timeout = deadline - time.time()
if len(rready) == 0:
# Timeout expired.
return False
res = self._readData()
if res <= 0:
raise exceptions.ProcessExitedException
if func():
return True
# Timeout expired.
return False
def write(self, b):
"""Writes specified data (string or bytes) to the process"""
self.flushin()
if hasattr(b, 'encode'):
return os.write(self.fd, b.encode('utf-8'))
else:
return os.write(self.fd, b)
def writectl(self, ctlstr):
"""Writes specified control sequences to the process"""
return self.write(keys.toctl(ctlstr))
def flushin(self):
"""Reads all pending input and processes through the terminal emulator"""
if self.fd is None: return
while True:
ready, jnk, jnk = select.select([self.fd], [], [], 0)
if len(ready) > 0:
if self._readData() <= 0:
return
else:
return
def _readData(self):
"""Reads bytes from program and sends them to the terminal"""
try:
result = os.read(self.fd, 1024)
except OSError:
return -1
self.stream.feed(result)
return len(result)
def checkProcess(self):
"""Checks whether the process is still running"""
if self.exited is not None:
return True
result = os.waitpid(self.pid, os.WNOHANG)
if result == (0, 0):
return True
else:
self.exited = result
return False
def getExitCode(self):
"""Get exit code of program, if it has exited"""
if self.exited is not None:
result = self.exited
else:
result = os.waitpid(self.pid, os.WNOHANG)
if result != (0, 0):
self.exited = result
return result[1] >> 8
else:
return None
def kill(self, code=9):
"""Kills the child process with the specified signal"""
os.kill(self.pid, code)
def close(self):
"""Waits for process to exit and close down open handles"""
self.wait()
os.close(self.fd)
self.fd = None
def readLine(self, line, col, length):
"""Reads the text found at the specified screen location"""
def getChar(y, x):
if len(self.term.buffer) <= y: return ''
if len(self.term.buffer[y]) <= x: return ''
return self.term.buffer[y][x].data
return ''.join(getChar(line, i + col) for i in range(length))
def checkText(self, line, col, text):
"""Checks whether the text at the specified position matches the input"""
return self.readLine(line, col, len(text)) == text
def wait(self):
"""Waits for child process to exit or timeout to expire"""
if self.exited is not None:
return self.exited[1] >> 8
def ontimeout(signum, frame):
raise exceptions.TimeoutException()
signal.signal(signal.SIGALRM, ontimeout)
signal.alarm(int(self.timeout))
try:
result = os.waitpid(self.pid, 0)
except exceptions.TimeoutException:
return None
signal.alarm(0)
self.exited = result
return result[1] >> 8
def resize(self, width, height):
"""Resizes terminal"""
self.flushin()
self.term.resize(height, width)
buf = array.array('h', [height, width, 0, 0])
fcntl.ioctl(self.fd, termios.TIOCSWINSZ, buf)
@property
def screen(self):
"""Returns contents of screen as a string"""
return '\n'.join([self.readLine(i, 0, self.term.columns) for i in range(self.term.lines)])
@property
def cursor(self):
"""Returns cursor position"""
return coord(self.term.cursor.x, self.term.cursor.y)
@property
def size(self):
"""Returns size of terminal"""
return coord(self.term.columns, self.term.lines)
class StartupArgs(object):
"""Startup arguments for JOE"""
def __init__(self):
self.args = ()
self.env = {}
self.lines = 25
self.columns = 80
class TempFiles:
"""Temporary file manager. Creates temp location and ensures it's deleted at exit"""
def __init__(self):
self.tmp = None
def _cleanup(self):
if os.path.exists(self.tmp):
# Make sure we're not in it.
os.chdir('/')
shutil.rmtree(self.tmp)
def getDir(self, path):
"""Get or create temporary directory 'path', under root temporary directory"""
if self.tmp is None:
self.tmp = tempfile.mkdtemp()
atexit.register(self._cleanup)
fullpath = os.path.join(self.tmp, path)
if not os.path.exists(fullpath):
os.makedirs(fullpath)
return fullpath
@property
def homedir(self):
"""Temporary directory pointed to by HOME"""
return self.getDir("home")
@property
def workdir(self):
"""Temporary directory where JOE will be started"""
return self.getDir("work")
tmpfiles = TempFiles()
def startJoe(joeexe, args=None):
"""Starts JOE in a pty, returns a handle to controller"""
if not joeexe.startswith('/'):
joeexepath = os.path.join(os.getcwd(), joeexe)
else:
joeexepath = joeexe
if args is None:
args = StartupArgs()
env = {}
#env.update(os.environ)
env['HOME'] = tmpfiles.homedir
env['LINES'] = str(args.lines)
env['COLUMNS'] = str(args.columns)
env['TERM'] = 'ansi'
env['LANG'] = 'en_US.UTF-8'
env['SHELL'] = os.environ['SHELL']
env.update(args.env)
cmdline = ('joe',) + args.args
pid, fd = pty.fork()
if pid == 0:
os.chdir(tmpfiles.workdir)
os.execve(joeexepath, cmdline, env)
os._exit(1)
else:
buf = array.array('h', [args.lines, args.columns, 0, 0])
fcntl.ioctl(fd, termios.TIOCSWINSZ, buf)
return JoeController(joeexepath, cmdline, env, args, pid, fd)
|
gpl-2.0
|
JIMyungSik/uftrace
|
tests/t025_report_s_call.py
|
1023
|
#!/usr/bin/env python
from runtest import TestBase
import subprocess as sp
TDIR='xxx'
class TestCase(TestBase):
def __init__(self):
TestBase.__init__(self, 'sort', """
Total time Self time Nr. called Function
========== ========== ========== ====================================
36.388 us 36.388 us 6 loop
37.525 us 1.137 us 2 foo
1.078 ms 1.078 ms 1 usleep
1.152 ms 71.683 us 1 main
70.176 us 70.176 us 1 __monstartup # ignore this
1.080 ms 1.813 us 1 bar
1.200 us 1.200 us 1 __cxa_atexit # and this too
""", sort='report')
def pre(self):
record_cmd = '%s record -d %s %s' % (TestBase.ftrace, TDIR, 't-sort')
sp.call(record_cmd.split())
return TestBase.TEST_SUCCESS
def runcmd(self):
return '%s report -d %s -s call,self' % (TestBase.ftrace, TDIR)
def post(self, ret):
sp.call(['rm', '-rf', TDIR])
return ret
|
gpl-2.0
|
cakeside/cakeside
|
app/services/infrastructure/queued_job.rb
|
468
|
class QueuedJob < Struct.new(:event, :payload)
def perform
handlers_for(event).each { |handler| handler.handle(payload) }
end
def error(job, exception)
ExceptionNotifier.notify_exception(exception) unless Rails.env.test?
end
private
def handlers_for(event)
container.resolve_all(:message_handler).find_all do |handler|
handler.handles?(event)
end
end
def container
@container ||= Spank::IOC.resolve(:container)
end
end
|
gpl-2.0
|
KDE/calligra-history
|
filters/kspread/xlsx/NumberFormatParser.cpp
|
30203
|
/*
* This file is part of Office 2007 Filters for KOffice
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
*
* Contact: Christoph Schleifenbaum christoph@kdab.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "NumberFormatParser.h"
#include <KoGenStyle.h>
#include <KoGenStyles.h>
#include <KoXmlWriter.h>
#include <MsooXmlUtils.h>
#include <QtCore/QBuffer>
#include <QtCore/QLocale>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtGui/QColor>
#include <QtGui/QPalette>
KoGenStyles* NumberFormatParser::styles = 0;
QColor NumberFormatParser::color(const QString& name)
{
if (name.toUpper().startsWith(QLatin1String("COLOR"))) {
bool ok = false;
const int index = name.mid(5).toInt(&ok) + 7;
return MSOOXML::Utils::defaultIndexedColor(index);
} else {
return QColor(name);
}
}
QLocale NumberFormatParser::locale(int langid)
{
return MSOOXML::Utils::localeForLangId(langid);
}
void NumberFormatParser::setStyles(KoGenStyles* styles)
{
NumberFormatParser::styles = styles;
}
#define SET_TYPE_OR_RETURN( TYPE ) { \
if( type == KoGenStyle::NumericDateStyle && TYPE == KoGenStyle::NumericTimeStyle ) \
{ \
} \
else if( type == KoGenStyle::NumericTimeStyle && TYPE == KoGenStyle::NumericDateStyle ) \
{ \
type = TYPE; \
} \
else if( type == KoGenStyle::NumericPercentageStyle && TYPE == KoGenStyle::NumericNumberStyle ) \
{ \
} \
else if( type == KoGenStyle::NumericNumberStyle && TYPE == KoGenStyle::NumericPercentageStyle ) \
{ \
type = TYPE; \
} \
else if( type == KoGenStyle::NumericCurrencyStyle && TYPE == KoGenStyle::NumericNumberStyle ) \
{ \
} \
else if( type == KoGenStyle::NumericNumberStyle && TYPE == KoGenStyle::NumericCurrencyStyle ) \
{ \
type = TYPE; \
} \
else if( type == KoGenStyle::NumericFractionStyle && TYPE == KoGenStyle::NumericNumberStyle ) \
{ \
} \
else if( type == KoGenStyle::NumericNumberStyle && TYPE == KoGenStyle::NumericFractionStyle ) \
{ \
type = TYPE; \
} \
else if( type == KoGenStyle::NumericScientificStyle && TYPE == KoGenStyle::NumericNumberStyle ) \
{ \
} \
else if( type == KoGenStyle::NumericNumberStyle && TYPE == KoGenStyle::NumericScientificStyle ) \
{ \
type = TYPE; \
} \
else if( type != KoGenStyle::ParagraphAutoStyle && type != TYPE ) \
{ \
return KoGenStyle( KoGenStyle::ParagraphAutoStyle ); \
} \
else \
{ \
type = TYPE; \
} \
}
#define FINISH_PLAIN_TEXT_PART { \
if( !plainText.isEmpty() ) \
{ \
hadPlainText = true; \
xmlWriter.startElement( "number:text" ); \
xmlWriter.addTextNode( plainText ); \
xmlWriter.endElement(); \
plainText.clear(); \
} \
}
static KoGenStyle styleFromTypeAndBuffer(KoGenStyle::Type type, const QBuffer& buffer)
{
KoGenStyle result(type);
const QString elementContents = QString::fromUtf8(buffer.buffer(), buffer.buffer().size());
result.addChildElement("number", elementContents);
return result;
}
KoGenStyle NumberFormatParser::parse(const QString& numberFormat)
{
QBuffer buffer;
buffer.open(QIODevice::WriteOnly);
KoXmlWriter xmlWriter(&buffer);
KoGenStyle::Type type = KoGenStyle::ParagraphAutoStyle;
QString plainText;
QMap< QString, QString > conditions;
QString condition;
// this is for the month vs. minutes-context
bool justHadHours = false;
bool hadPlainText = false;
for (int i = 0; i < numberFormat.length(); ++i) {
const char c = numberFormat[ i ].toLatin1();
bool isSpecial = true;
const bool isLong = i < numberFormat.length() - 1 && numberFormat[ i + 1 ] == c;
const bool isLonger = isLong && i < numberFormat.length() - 2 && numberFormat[ i + 2 ] == c;
const bool isLongest = isLonger && i < numberFormat.length() - 3 && numberFormat[ i + 3 ] == c;
const bool isWayTooLong = isLongest && i < numberFormat.length() - 4 && numberFormat[ i + 4 ] == c;
switch (c) {
// condition or color or locale...
case '[': {
const char ch = i < numberFormat.length() - 1 ? numberFormat[ ++i ].toLatin1() : ']';
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
// color code
QString colorName;
while (i < numberFormat.length() && numberFormat[ i ] != QLatin1Char(']'))
colorName += numberFormat[ i++ ];
const QColor color = NumberFormatParser::color(colorName);
if (color.isValid()) {
xmlWriter.startElement("style:text-properties");
xmlWriter.addAttribute("fo:color", color.name());
xmlWriter.endElement();
}
} else if (ch == '$' && i < numberFormat.length() - 2 && numberFormat[ i + 1 ].toLatin1() != '-') {
SET_TYPE_OR_RETURN(KoGenStyle::NumericCurrencyStyle);
++i;
// currency code
QString currency;
while (i < numberFormat.length() && numberFormat[ i ] != QLatin1Char(']') && numberFormat[ i ] != QLatin1Char('-'))
currency += numberFormat[ i++ ];
QString language;
QString country;
if (numberFormat[ i ] == QLatin1Char('-')) {
++i;
QString localeId;
while (i < numberFormat.length() && numberFormat[ i ] != QLatin1Char(']'))
localeId += numberFormat[ i++ ];
const QLocale locale = NumberFormatParser::locale(localeId.toInt(0, 16));
language = locale.name();
language = language.left(language.indexOf(QLatin1String("_")));
country = locale.name();
country = country.mid(country.indexOf(QLatin1String("_")) + 1);
}
xmlWriter.startElement("number:currency-symbol");
if (!language.isEmpty()) {
xmlWriter.addAttribute("number:language", language);
}
if (!country.isEmpty()) {
xmlWriter.addAttribute("number:country", country);
}
xmlWriter.addTextSpan(currency);
xmlWriter.endElement();
} else {
// unknown - no idea, skip
while (i < numberFormat.length() && numberFormat[ i ] != QLatin1Char(']'))
++i;
}
}
break;
// underscore: ignore the next char
case '_':
plainText += QLatin1Char(' ');
++i;
break;
// asterisk: ignore
case '*':
case '(':
case ')':
break;
// percentage
case '%':
SET_TYPE_OR_RETURN(KoGenStyle::NumericPercentageStyle);
FINISH_PLAIN_TEXT_PART
xmlWriter.startElement("number:text");
xmlWriter.addTextNode("%");
xmlWriter.endElement();
break;
// a number
case '.':
case ',':
case '#':
case '0':
case '?':
SET_TYPE_OR_RETURN(KoGenStyle::NumericNumberStyle)
FINISH_PLAIN_TEXT_PART {
bool grouping = false;
bool gotDot = false;
bool gotE = false;
bool gotFraction = false;
int decimalPlaces = 0;
int integerDigits = 0;
int exponentDigits = 0;
int numeratorDigits = 0;
int denominatorDigits = 0;
char ch = numberFormat[ i ].toLatin1();
do {
if (ch == '.') {
gotDot = true;
} else if (ch == ',') {
grouping = true;
} else if (ch == 'E' || ch == 'e') {
SET_TYPE_OR_RETURN(KoGenStyle::NumericScientificStyle);
if (i >= numberFormat.length() - 1) break;
const char chN = numberFormat[ i + 1 ].toLatin1();
if (chN == '-' || chN == '+') {
gotE = true;
++i;
}
} else if (ch == '0' && gotE) {
++exponentDigits;
} else if (ch == '0' && !gotDot && !gotFraction) {
++integerDigits;
} else if (ch == '0' && gotDot && !gotFraction) {
++decimalPlaces;
} else if (ch == '?' && !gotFraction) {
++numeratorDigits;
} else if (ch == '?' && gotFraction) {
++denominatorDigits;
} else if (ch == '/') {
SET_TYPE_OR_RETURN(KoGenStyle::NumericFractionStyle);
if (gotDot)
return KoGenStyle();
gotFraction = true;
}
if (i >= numberFormat.length() - 1) break;
ch = numberFormat[ ++i ].toLatin1();
if (ch == ' ') {
// spaces are not allowed - but there's an exception: if this is a fraction. Let's check for '?' or '/'
const char c = numberFormat[ i + 1 ].toLatin1();
if (c == '?' || c == '/')
ch = numberFormat[ ++i ].toLatin1();
}
} while (i < numberFormat.length() && (ch == '.' || ch == ',' || ch == '#' || ch == '0' || ch == 'E' || ch == 'e' || ch == '?' || ch == '/'));
if (!(ch == '.' || ch == ',' || ch == '#' || ch == '0' || ch == 'E' || ch == 'e' || ch == '?' || ch == '/')) {
--i;
}
if (gotFraction) {
xmlWriter.startElement("number:fraction");
} else if (exponentDigits > 0) {
xmlWriter.startElement("number:scientific-number");
} else {
xmlWriter.startElement("number:number");
}
xmlWriter.addAttribute("number:decimal-places", decimalPlaces);
xmlWriter.addAttribute("number:min-integer-digits", integerDigits);
if (exponentDigits > 0) {
xmlWriter.addAttribute("number:min-exponent-digits", exponentDigits);
}
if (grouping) {
xmlWriter.addAttribute("number:grouping", grouping ? "true" : "false");
}
if (gotFraction) {
xmlWriter.addAttribute("number:min-numerator-digits", numeratorDigits);
xmlWriter.addAttribute("number:min-denominator-digits", denominatorDigits);
}
xmlWriter.endElement();
}
break;
// Everything related to date/time
// AM/PM
case 'A':
case 'a':
if (numberFormat.mid(i, 5).toLower() == QLatin1String("am/pm") ||
numberFormat.mid(i, 3).toLower() == QLatin1String("a/p")) {
SET_TYPE_OR_RETURN(KoGenStyle::NumericTimeStyle)
FINISH_PLAIN_TEXT_PART;
xmlWriter.startElement("number:am-pm");
xmlWriter.endElement();
if (numberFormat.mid(i, 5).toLower() == QLatin1String("am/pm"))
i += 2;
i += 2;
}
break;
// hours, long or short
case 'H':
case 'h':
SET_TYPE_OR_RETURN(KoGenStyle::NumericTimeStyle)
FINISH_PLAIN_TEXT_PART;
xmlWriter.startElement("number:hours");
if (isLong) {
xmlWriter.addAttribute("number:style", "long");
++i;
}
xmlWriter.endElement();
break;
// minutes or months, depending on context
case 'M':
case 'm':
// must be month, then, at least three M
if (isLonger) {
SET_TYPE_OR_RETURN(KoGenStyle::NumericDateStyle)
FINISH_PLAIN_TEXT_PART;
xmlWriter.startElement("number:month");
const bool isReallyReallyLong = isWayTooLong && i < numberFormat.length() - 4 && numberFormat[ i + 4 ] == c;
if (isLongest && !isReallyReallyLong)
xmlWriter.addAttribute("number:style", "long");
if (isWayTooLong) { // the month format is "mmmmm" then it's the extra-short format of month
xmlWriter.addAttribute("koffice:number-length", "extra-short");
}
xmlWriter.addAttribute("number:textual", "true");
xmlWriter.endElement();
i += isLongest ? (isWayTooLong ? 4 : 3) : 2;
if (isReallyReallyLong ) {
++i;
}
}
// depends on the context. After hours and before seconds, it's minutes
// otherwise it's the month
else {
if (justHadHours) {
SET_TYPE_OR_RETURN(KoGenStyle::NumericTimeStyle)
FINISH_PLAIN_TEXT_PART;
xmlWriter.startElement("number:minutes");
if (isLong)
xmlWriter.addAttribute("number:style", "long");
xmlWriter.endElement();
} else {
// on the next iteration, we might see wheter there're seconds or something else
bool minutes = true; // let's just default to minutes, if there's nothing more...
// so let's look ahead:
for (int j = i + 1; j < numberFormat.length(); ++j) {
const char ch = numberFormat[ i ].toLatin1();
if (ch == 's' || ch == 'S') { // minutes
break;
}
if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))) { // months
continue;
}
minutes = false;
break;
}
if (minutes) {
SET_TYPE_OR_RETURN(KoGenStyle::NumericTimeStyle)
} else {
SET_TYPE_OR_RETURN(KoGenStyle::NumericDateStyle)
FINISH_PLAIN_TEXT_PART;
}
if (minutes) {
xmlWriter.startElement("number:minutes");
} else {
xmlWriter.startElement("number:month");
}
if (isLong) {
xmlWriter.addAttribute("number:style", "long");
}
xmlWriter.endElement();
}
if (isLong) {
++i;
}
}
break;
// day (of week)
case 'D':
case 'd':
SET_TYPE_OR_RETURN(KoGenStyle::NumericDateStyle)
FINISH_PLAIN_TEXT_PART;
if (!isLonger) {
xmlWriter.startElement("number:day");
if (isLong) {
xmlWriter.addAttribute("number:style", "long");
}
xmlWriter.endElement();
} else {
xmlWriter.startElement("number:day-of-week");
if (isLongest) {
xmlWriter.addAttribute("number:style", "long");
}
xmlWriter.endElement();
}
if (isLong) {
++i;
}
if (isLonger) {
++i;
}
if (isLongest) {
++i;
}
break;
// seconds, long or short
case 'S':
case 's':
SET_TYPE_OR_RETURN(KoGenStyle::NumericTimeStyle)
FINISH_PLAIN_TEXT_PART;
xmlWriter.startElement("number:seconds");
if (isLong) {
xmlWriter.addAttribute("number:style", "long");
++i;
}
xmlWriter.endElement();
break;
// year, long or short
case 'Y':
case 'y':
SET_TYPE_OR_RETURN(KoGenStyle::NumericDateStyle)
FINISH_PLAIN_TEXT_PART;
xmlWriter.startElement("number:year");
if (isLongest) {
xmlWriter.addAttribute("number:style", "long");
i += 3;
} else if (isLong) {
++i;
}
xmlWriter.endElement();
break;
// now it's getting really scarry: semi-colon:
case ';': {
FINISH_PLAIN_TEXT_PART;
buffer.close();
// conditional style with the current format
KoGenStyle result = styleFromTypeAndBuffer(type, buffer);
result.addAttribute("style:volatile", "true");
const QString styleName = NumberFormatParser::styles->insert(result, "N");
// start a new style
buffer.setData(QByteArray());
buffer.open(QIODevice::WriteOnly);
conditions.insertMulti(condition, styleName);
condition.clear();
}
break;
// text-content
case '@':
FINISH_PLAIN_TEXT_PART;
hadPlainText = true;
xmlWriter.startElement("number:text-content");
xmlWriter.endElement();
break;
// quote - plain text block
case '"':
isSpecial = false;
while (i < numberFormat.length() - 1 && numberFormat[ ++i ] != QLatin1Char('"'))
plainText += numberFormat[ i ];
break;
// backslash escapes the next char
case '\\':
isSpecial = false;
if (i < numberFormat.length() - 1) {
plainText += numberFormat[ ++i ];
}
break;
// every other char is just passed
default:
isSpecial = false;
plainText += c;
break;
}
// for the context-sensitive 'M' which can mean either minutes or months
if (isSpecial) {
justHadHours = (c == 'h' || c == 'H');
}
}
FINISH_PLAIN_TEXT_PART;
if (type == KoGenStyle::ParagraphAutoStyle && hadPlainText) {
SET_TYPE_OR_RETURN(KoGenStyle::NumericTextStyle)
}
if (!condition.isEmpty()) {
// conditional style with the current format
KoGenStyle result = styleFromTypeAndBuffer(type, buffer);
result.addAttribute("style:volatile", "true");
const QString styleName = NumberFormatParser::styles->insert(result, "N");
// start a new style
buffer.setData(QByteArray());
buffer.open(QIODevice::WriteOnly);
conditions.insertMulti(condition, styleName);
condition.clear();
}
// if conditions w/o explicit expressions where added, we create the expressions
QStringList autoConditions;
if (conditions.count(QString()) == 1) {
autoConditions.push_back(QLatin1String("value()>=0"));
} else {
autoConditions.push_back(QLatin1String("value()>0"));
autoConditions.push_back(QLatin1String("value()<0"));
autoConditions.push_back(QLatin1String("value()=0"));
}
// add conditional styles:
for (QMap< QString, QString >::const_iterator it = conditions.constBegin(); it != conditions.constEnd(); ++it) {
// conditional styles are always numbers
type = KoGenStyle::NumericNumberStyle;
xmlWriter.startElement("style:map");
xmlWriter.addAttribute("style:condition", it.key().isEmpty() ? autoConditions.takeLast() : it.key());
xmlWriter.addAttribute("style:apply-style-name", it.value());
xmlWriter.endElement();
}
buffer.close();
// conditional style with the current format
return styleFromTypeAndBuffer(conditions.isEmpty() ? type : KoGenStyle::NumericTextStyle, buffer);
}
bool NumberFormatParser::isDateFormat(const QString& numberFormat)
{
// this is for the month vs. minutes-context
bool justHadHours = false;
bool hadPlainText = false;
for (int i = 0; i < numberFormat.length(); ++i) {
const char c = numberFormat[ i ].toLatin1();
bool isSpecial = true;
const bool isLong = i < numberFormat.length() - 1 && numberFormat[ i + 1 ] == c;
const bool isLonger = isLong && i < numberFormat.length() - 2 && numberFormat[ i + 2 ] == c;
const bool isLongest = isLonger && i < numberFormat.length() - 3 && numberFormat[ i + 3 ] == c;
const bool isWayTooLong = isLongest && i < numberFormat.length() - 4 && numberFormat[ i + 4 ] == c;
switch (c) {
// condition or color or locale...
case '[': {
//don't care, skip
while (i < numberFormat.length() && numberFormat[ i ] != QLatin1Char(']'))
++i;
}
break;
// underscore: ignore the next char
case '_':
++i;
break;
// asterisk: ignore
case '*':
case '(':
case ')':
break;
// percentage
case '%':
//SET_TYPE_OR_RETURN(KoGenStyle::NumericPercentageStyle);
break;
// a number
case '.':
case ',':
case '#':
case '0':
case '?': {
//SET_TYPE_OR_RETURN(KoGenStyle::NumericNumberStyle)
char ch = numberFormat[ i ].toLatin1();
do {
if (i >= numberFormat.length() - 1) break;
ch = numberFormat[ ++i ].toLatin1();
if (ch == ' ') {
// spaces are not allowed - but there's an exception: if this is a fraction. Let's check for '?' or '/'
const char c = numberFormat[ i + 1 ].toLatin1();
if (c == '?' || c == '/')
ch = numberFormat[ ++i ].toLatin1();
}
} while (i < numberFormat.length() && (ch == '.' || ch == ',' || ch == '#' || ch == '0' || ch == 'E' || ch == 'e' || ch == '?' || ch == '/'));
if (!(ch == '.' || ch == ',' || ch == '#' || ch == '0' || ch == 'E' || ch == 'e' || ch == '?' || ch == '/')) {
--i;
}
}
break;
// Everything related to date/time
// AM/PM
case 'A':
case 'a':
if (numberFormat.mid(i, 5).toLower() == QLatin1String("am/pm") ||
numberFormat.mid(i, 3).toLower() == QLatin1String("a/p")) {
// SET_TYPE_OR_RETURN(KoGenStyle::NumericTimeStyle)
if (numberFormat.mid(i, 5).toLower() == QLatin1String("am/pm"))
i += 2;
i += 2;
}
break;
// hours, long or short
case 'H':
case 'h':
//SET_TYPE_OR_RETURN(KoGenStyle::NumericTimeStyle)
if (isLong) {
++i;
}
break;
// minutes or months, depending on context
case 'M':
case 'm':
// must be month, then, at least three M
if (isLonger) {
return true;
}
// depends on the context. After hours and before seconds, it's minutes
// otherwise it's the month
else {
if (justHadHours) {
//SET_TYPE_OR_RETURN(KoGenStyle::NumericTimeStyle)
} else {
// on the next iteration, we might see wheter there're seconds or something else
bool minutes = true; // let's just default to minutes, if there's nothing more...
// so let's look ahead:
for (int j = i + 1; j < numberFormat.length(); ++j) {
const char ch = numberFormat[ i ].toLatin1();
if (ch == 's' || ch == 'S') { // minutes
break;
}
if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))) { // months
continue;
}
minutes = false;
break;
}
if (minutes) {
//SET_TYPE_OR_RETURN(KoGenStyle::NumericTimeStyle)
} else {
return true;
}
}
if (isLong) {
++i;
}
}
break;
// day (of week)
case 'D':
case 'd':
return true;
// seconds, long or short
case 'S':
case 's':
// SET_TYPE_OR_RETURN(KoGenStyle::NumericTimeStyle)
if (isLong) {
++i;
}
break;
// year, long or short
case 'Y':
case 'y':
return true;
// now it's getting really scarry: semi-colon:
case ';':
break;
// text-content
case '@':
break;
// quote - plain text block
case '"':
isSpecial = false;
while (i < numberFormat.length() - 1 && numberFormat[ ++i ] != QLatin1Char('"'))
/* empty */;
break;
// backslash escapes the next char
case '\\':
isSpecial = false;
if (i < numberFormat.length() - 1) {
++i;
}
break;
// every other char is just passed
default:
isSpecial = false;
break;
}
// for the context-sensitive 'M' which can mean either minutes or months
if (isSpecial) {
justHadHours = (c == 'h' || c == 'H');
}
}
return false;
}
|
gpl-2.0
|
bundocba/applied-metaphysics
|
plugins/system/nnframework/fields/hr.php
|
1888
|
<?php
/**
* Element: HR
* Displays a line
*
* @package NoNumber Framework
* @version 12.4.2
*
* @author Peter van Westen <peter@nonumber.nl>
* @link http://www.nonumber.nl
* @copyright Copyright ยฉ 2012 NoNumber All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
// No direct access
defined('_JEXEC') or die;
/**
* HR Element
*/
class nnFieldHR
{
var $_version = '12.4.2';
function getInput($name, $id, $value, $params, $children, $j15 = 0)
{
$document = JFactory::getDocument();
$document->addStyleSheet(JURI::root(true).'/plugins/system/nnframework/css/style.css?v='.$this->_version);
return '<div class="panel nn_panel nn_hr'.($j15 ? ' nn_panel_15' : '').'"></div>';
}
private function def($val, $default = '')
{
return (isset($this->params[$val]) && (string) $this->params[$val] != '') ? (string) $this->params[$val] : $default;
}
}
if (version_compare(JVERSION, '1.6.0', 'l')) {
// For Joomla 1.5
class JElementNN_HR extends JElement
{
/**
* Element name
*
* @access protected
* @var string
*/
var $_name = 'HR';
function fetchTooltip($label, $description, &$node, $control_name, $name)
{
$this->_nnfield = new nnFieldHR();
return;
}
function fetchElement($name, $value, &$node, $control_name)
{
return $this->_nnfield->getInput($control_name.'['.$name.']', $control_name.$name, $value, $node->attributes(), $node->children(), 1);
}
}
} else {
// For Joomla 1.6
class JFormFieldNN_HR extends JFormField
{
/**
* The form field type
*
* @var string
*/
public $type = 'HR';
protected function getLabel()
{
$this->_nnfield = new nnFieldHR();
return;
}
protected function getInput()
{
return $this->_nnfield->getInput($this->name, $this->id, $this->value, $this->element->attributes(), $this->element->children());
}
}
}
|
gpl-2.0
|
hardvain/mono-compiler
|
errors/cs1690-3.cs
|
469
|
// CS1690: Cannot call methods, properties, or indexers on `A.point' because it is a value type member of a marshal-by-reference class
// Line: 22
// Compiler options: -warn:1 -warnaserror
using System;
public struct Point
{
public bool this [int i] { set { } }
}
public class A : MarshalByRefObject
{
public Point point = new Point ();
}
public class Test
{
public static void Main ()
{
A a = new A ();
a.point [3] = false;
}
}
|
gpl-2.0
|
gabeshaughnessy/timothy-woodworking
|
wp-content/plugins/codepress-admin-columns/classes/column/media/exif-data.php
|
2543
|
<?php
/**
* CPAC_Column_Media_File_Size
*
* @since 2.0
*/
class CPAC_Column_Media_Exif_Data extends CPAC_Column {
/**
* @see CPAC_Column::init()
* @since 2.3
*/
public function init() {
parent::init();
// Properties
$this->properties['type'] = 'column-exif_data';
$this->properties['label'] = __( 'EXIF data', 'cpac' );
$this->properties['is_cloneable'] = true;
// Options
$this->options['exif_datatype'] = '';
}
/**
* Get EXIF data
*
* Get extended image metadata
*
* @since 2.0
*
* @return array EXIF data types
*/
private function get_exif_types() {
$exif_types = array(
'aperture' => __( 'Aperture', 'cpac' ),
'credit' => __( 'Credit', 'cpac' ),
'camera' => __( 'Camera', 'cpac' ),
'caption' => __( 'Caption', 'cpac' ),
'created_timestamp' => __( 'Timestamp', 'cpac' ),
'copyright' => __( 'Copyright EXIF', 'cpac' ),
'focal_length' => __( 'Focal Length', 'cpac' ),
'iso' => __( 'ISO', 'cpac' ),
'shutter_speed' => __( 'Shutter Speed', 'cpac' ),
'title' => __( 'Title', 'cpac' ),
);
return $exif_types;
}
/**
* @see CPAC_Column::get_value()
* @since 2.0
*/
function get_value( $id ) {
$value = '';
$data = $this->options->exif_datatype;
$meta = get_post_meta( $id, '_wp_attachment_metadata', true );
if ( isset( $meta['image_meta'][ $data ] ) ) {
$value = $meta['image_meta'][ $data ];
if ( 'created_timestamp' == $data ) {
$value = date_i18n( get_option('date_format') . ' ' . get_option('time_format') , strtotime( $value ) );
}
}
return $value;
}
/**
* @see CPAC_Column::apply_conditional()
* @since 2.0
*/
function apply_conditional() {
if ( function_exists( 'exif_read_data' ) )
return true;
return false;
}
/**
* Display Settings
*
* @see CPAC_Column::display_settings()
* @since 2.0
*/
function display_settings() {
?>
<tr class="column-exif-data">
<?php $this->label_view( $this->properties->label, '', 'exif_datatype' ); ?>
<td class="input">
<select name="<?php $this->attr_name( 'exif_datatype' ); ?>" id="<?php $this->attr_id( 'exif_datatype' ); ?>">
<?php foreach ( $this->get_exif_types() as $key => $label ) : ?>
<option value="<?php echo $key; ?>"<?php selected( $key, $this->options->exif_datatype ) ?>><?php echo $label; ?></option>
<?php endforeach; ?>
</select>
</td>
</tr>
<?php
}
}
|
gpl-2.0
|
SamGraber/Robo-Rumble
|
server/config/routes.js
|
514
|
var express = require('express');
module.exports = function(app, config) {
app.use(express.static(config.rootPath + '/public'));
app.get('/partials/*', function(req, res) {
res.render('../../public/app/' + req.params[0]);
});
app.get('/new/*', function(req, res) {
res.render('new');
});
app.get('/continue/*', function(req, res) {
res.render('continue');
});
app.get('/watch/*', function(req, res) {
res.render('watch');
});
app.get('*', function(req, res) {
res.render('index');
});
};
|
gpl-2.0
|
tntrung/youCVML
|
demo_pca.py
|
1083
|
# The demo of PCA algorithm
import numpy as np
import matplotlib.pyplot as plt
from ml.manifolds.unsupervised.pca import pca
from misc import zero_mean as zm
# Load data
data = np.loadtxt("data/pcaData.txt").transpose()
data,mean = zm.zero_mean(data)
# Display the size of loaded data
# print data.shape
# Visualizing 2D points
plt.figure(1)
plt.scatter(data[:,0], data[:,1])
# Computing PCA
(U, s, mean) = pca.pca(data)
plt.scatter(mean[0], mean[1], c='r')
# Displaying basis vectors
ax = plt.axes()
ax.arrow(mean[0], mean[1], U[0,0]*np.sqrt(s[0]), U[1,0]*np.sqrt(s[0]), head_width=0.05, head_length=0.1, fc='k', ec='k')
ax.arrow(mean[0], mean[1], U[0,1]*np.sqrt(s[1]), U[1,1]*np.sqrt(s[1]), head_width=0.05, head_length=0.1, fc='k', ec='k')
dataRot = np.dot(data,U.T)
plt.figure(2)
plt.scatter(dataRot[:,0], dataRot[:,1])
# Checking whitening pca
datawhite = pca.proj_pca_white( data, U, s )
plt.figure(3)
plt.scatter(datawhite[:,0], datawhite[:,1])
# Checking zca
datazca = pca.zca_white( data, U, s )
plt.figure(4)
plt.scatter(datazca[:,0], datazca[:,1])
plt.show()
|
gpl-2.0
|
ricker75/Global-Server
|
data/npc/scripts/Suzy.lua
|
14636
|
local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
local count = {}
local transfer = {}
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
local lastSound = 0
function onThink()
if lastSound < os.time() then
lastSound = (os.time() + 5)
if math.random(100) < 25 then
Npc():say("Yes indeed, it's a wise idea to store your money in your bank account.", TALKTYPE_SAY)
end
end
npcHandler:onThink()
end
local function greetCallback(cid)
count[cid], transfer[cid] = nil, nil
return true
end
local function creatureSayCallback(cid, type, msg)
if not npcHandler:isFocused(cid) then
return false
end
local player = Player(cid)
---------------------------- help ------------------------
if msgcontains(msg, 'bank account') then
npcHandler:say({
'Every Tibian has one. The big advantage is that you can access your money in every branch of the Tibian Bank! ...',
'Would you like to know more about the {basic} functions of your bank account, the {advanced} functions, or are you already bored, perhaps?'
}, cid)
npcHandler.topic[cid] = 0
return true
---------------------------- balance ---------------------
elseif msgcontains(msg, 'balance') then
npcHandler.topic[cid] = 0
if player:getBankBalance() >= 100000000 then
npcHandler:say('I think you must be one of the richest inhabitants in the world! Your account balance is ' .. player:getBankBalance() .. ' gold.', cid)
return true
elseif player:getBankBalance() >= 10000000 then
npcHandler:say('You have made ten millions and it still grows! Your account balance is ' .. player:getBankBalance() .. ' gold.', cid)
return true
elseif player:getBankBalance() >= 1000000 then
npcHandler:say('Wow, you have reached the magic number of a million gp!!! Your account balance is ' .. player:getBankBalance() .. ' gold!', cid)
return true
elseif player:getBankBalance() >= 100000 then
npcHandler:say('You certainly have made a pretty penny. Your account balance is ' .. player:getBankBalance() .. ' gold.', cid)
return true
else
npcHandler:say('Your account balance is ' .. player:getBankBalance() .. ' gold.', cid)
return true
end
---------------------------- deposit ---------------------
elseif msgcontains(msg, 'deposit') then
count[cid] = player:getMoney()
if count[cid] < 1 then
npcHandler:say('You do not have enough gold.', cid)
npcHandler.topic[cid] = 0
return false
end
if msgcontains(msg, 'all') then
count[cid] = player:getMoney()
npcHandler:say('Would you really like to deposit ' .. count[cid] .. ' gold?', cid)
npcHandler.topic[cid] = 2
return true
else
if string.match(msg,'%d+') then
count[cid] = getMoneyCount(msg)
if count[cid] < 1 then
npcHandler:say('You do not have enough gold.', cid)
npcHandler.topic[cid] = 0
return false
end
npcHandler:say('Would you really like to deposit ' .. count[cid] .. ' gold?', cid)
npcHandler.topic[cid] = 2
return true
else
npcHandler:say('Please tell me how much gold it is you would like to deposit.', cid)
npcHandler.topic[cid] = 1
return true
end
end
if not isValidMoney(count[cid]) then
npcHandler:say('Sorry, but you can\'t deposit that much.', cid)
npcHandler.topic[cid] = 0
return false
end
elseif npcHandler.topic[cid] == 1 then
count[cid] = getMoneyCount(msg)
if isValidMoney(count[cid]) then
npcHandler:say('Would you really like to deposit ' .. count[cid] .. ' gold?', cid)
npcHandler.topic[cid] = 2
return true
else
npcHandler:say('You do not have enough gold.', cid)
npcHandler.topic[cid] = 0
return true
end
elseif npcHandler.topic[cid] == 2 then
if msgcontains(msg, 'yes') then
if player:getMoney() >= tonumber(count[cid]) then
player:depositMoney(count[cid])
npcHandler:say('Alright, we have added the amount of ' .. count[cid] .. ' gold to your {balance}. You can {withdraw} your money anytime you want to.', cid)
else
npcHandler:say('You do not have enough gold.', cid)
end
elseif msgcontains(msg, 'no') then
npcHandler:say('As you wish. Is there something else I can do for you?', cid)
end
npcHandler.topic[cid] = 0
return true
---------------------------- withdraw --------------------
elseif msgcontains(msg, 'withdraw') then
if string.match(msg,'%d+') then
count[cid] = getMoneyCount(msg)
if isValidMoney(count[cid]) then
npcHandler:say('Are you sure you wish to withdraw ' .. count[cid] .. ' gold from your bank account?', cid)
npcHandler.topic[cid] = 7
else
npcHandler:say('There is not enough gold on your account.', cid)
npcHandler.topic[cid] = 0
end
return true
else
npcHandler:say('Please tell me how much gold you would like to withdraw.', cid)
npcHandler.topic[cid] = 6
return true
end
elseif npcHandler.topic[cid] == 6 then
count[cid] = getMoneyCount(msg)
if isValidMoney(count[cid]) then
npcHandler:say('Are you sure you wish to withdraw ' .. count[cid] .. ' gold from your bank account?', cid)
npcHandler.topic[cid] = 7
else
npcHandler:say('There is not enough gold on your account.', cid)
npcHandler.topic[cid] = 0
end
return true
elseif npcHandler.topic[cid] == 7 then
if msgcontains(msg, 'yes') then
if player:getFreeCapacity() >= getMoneyWeight(count[cid]) then
if not player:withdrawMoney(count[cid]) then
npcHandler:say('There is not enough gold on your account.', cid)
else
npcHandler:say('Here you are, ' .. count[cid] .. ' gold. Please let me know if there is something else I can do for you.', cid)
end
else
npcHandler:say('Whoah, hold on, you have no room in your inventory to carry all those coins. I don\'t want you to drop it on the floor, maybe come back with a cart!', cid)
end
npcHandler.topic[cid] = 0
elseif msgcontains(msg, 'no') then
npcHandler:say('The customer is king! Come back anytime you want to if you wish to {withdraw} your money.', cid)
npcHandler.topic[cid] = 0
end
return true
---------------------------- transfer --------------------
elseif msgcontains(msg, 'transfer') then
npcHandler:say('Please tell me the amount of gold you would like to transfer.', cid)
npcHandler.topic[cid] = 11
elseif npcHandler.topic[cid] == 11 then
count[cid] = getMoneyCount(msg)
if player:getBankBalance() < count[cid] then
npcHandler:say('There is not enough gold on your account.', cid)
npcHandler.topic[cid] = 0
return true
end
if isValidMoney(count[cid]) then
npcHandler:say('Who would you like transfer ' .. count[cid] .. ' gold to?', cid)
npcHandler.topic[cid] = 12
else
npcHandler:say('There is not enough gold on your account.', cid)
npcHandler.topic[cid] = 0
end
elseif npcHandler.topic[cid] == 12 then
transfer[cid] = msg
if player:getName() == transfer[cid] then
npcHandler:say('Fill in this field with person who receives your gold!', cid)
npcHandler.topic[cid] = 0
return true
end
if playerExists(transfer[cid]) then
npcHandler:say('So you would like to transfer ' .. count[cid] .. ' gold to ' .. transfer[cid] .. '?', cid)
npcHandler.topic[cid] = 13
else
npcHandler:say('This player does not exist.', cid)
npcHandler.topic[cid] = 0
end
elseif npcHandler.topic[cid] == 13 then
if msgcontains(msg, 'yes') then
if not player:transferMoneyTo(transfer[cid], count[cid]) then
npcHandler:say('You cannot transfer money to this account.', cid)
else
npcHandler:say('Very well. You have transferred ' .. count[cid] .. ' gold to ' .. transfer[cid] ..'.', cid)
transfer[cid] = nil
end
elseif msgcontains(msg, 'no') then
npcHandler:say('Alright, is there something else I can do for you?', cid)
end
npcHandler.topic[cid] = 0
---------------------------- money exchange --------------
elseif msgcontains(msg, 'change gold') then
npcHandler:say('How many platinum coins would you like to get?', cid)
npcHandler.topic[cid] = 14
elseif npcHandler.topic[cid] == 14 then
if getMoneyCount(msg) < 1 then
npcHandler:say('Sorry, you do not have enough gold coins.', cid)
npcHandler.topic[cid] = 0
else
count[cid] = getMoneyCount(msg)
npcHandler:say('So you would like me to change ' .. count[cid] * 100 .. ' of your gold coins into ' .. count[cid] .. ' platinum coins?', cid)
npcHandler.topic[cid] = 15
end
elseif npcHandler.topic[cid] == 15 then
if msgcontains(msg, 'yes') then
if player:removeItem(2148, count[cid] * 100) then
player:addItem(2152, count[cid])
npcHandler:say('Here you are.', cid)
else
npcHandler:say('Sorry, you do not have enough gold coins.', cid)
end
else
npcHandler:say('Well, can I help you with something else?', cid)
end
npcHandler.topic[cid] = 0
elseif msgcontains(msg, 'change platinum') then
npcHandler:say('Would you like to change your platinum coins into gold or crystal?', cid)
npcHandler.topic[cid] = 16
elseif npcHandler.topic[cid] == 16 then
if msgcontains(msg, 'gold') then
npcHandler:say('How many platinum coins would you like to change into gold?', cid)
npcHandler.topic[cid] = 17
elseif msgcontains(msg, 'crystal') then
npcHandler:say('How many crystal coins would you like to get?', cid)
npcHandler.topic[cid] = 19
else
npcHandler:say('Well, can I help you with something else?', cid)
npcHandler.topic[cid] = 0
end
elseif npcHandler.topic[cid] == 17 then
if getMoneyCount(msg) < 1 then
npcHandler:say('Sorry, you do not have enough platinum coins.', cid)
npcHandler.topic[cid] = 0
else
count[cid] = getMoneyCount(msg)
npcHandler:say('So you would like me to change ' .. count[cid] .. ' of your platinum coins into ' .. count[cid] * 100 .. ' gold coins for you?', cid)
npcHandler.topic[cid] = 18
end
elseif npcHandler.topic[cid] == 18 then
if msgcontains(msg, 'yes') then
if player:removeItem(2152, count[cid]) then
player:addItem(2148, count[cid] * 100)
npcHandler:say('Here you are.', cid)
else
npcHandler:say('Sorry, you do not have enough platinum coins.', cid)
end
else
npcHandler:say('Well, can I help you with something else?', cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 19 then
if getMoneyCount(msg) < 1 then
npcHandler:say('Sorry, you do not have enough platinum coins.', cid)
npcHandler.topic[cid] = 0
else
count[cid] = getMoneyCount(msg)
npcHandler:say('So you would like me to change ' .. count[cid] * 100 .. ' of your platinum coins into ' .. count[cid] .. ' crystal coins for you?', cid)
npcHandler.topic[cid] = 20
end
elseif npcHandler.topic[cid] == 20 then
if msgcontains(msg, 'yes') then
if player:removeItem(2152, count[cid] * 100) then
player:addItem(2160, count[cid])
npcHandler:say('Here you are.', cid)
else
npcHandler:say('Sorry, you do not have enough platinum coins.', cid)
end
else
npcHandler:say('Well, can I help you with something else?', cid)
end
npcHandler.topic[cid] = 0
elseif msgcontains(msg, 'change crystal') then
npcHandler:say('How many crystal coins would you like to change into platinum?', cid)
npcHandler.topic[cid] = 21
elseif npcHandler.topic[cid] == 21 then
if getMoneyCount(msg) < 1 then
npcHandler:say('Sorry, you do not have enough crystal coins.', cid)
npcHandler.topic[cid] = 0
else
count[cid] = getMoneyCount(msg)
npcHandler:say('So you would like me to change ' .. count[cid] .. ' of your crystal coins into ' .. count[cid] * 100 .. ' platinum coins for you?', cid)
npcHandler.topic[cid] = 22
end
elseif npcHandler.topic[cid] == 22 then
if msgcontains(msg, 'yes') then
if player:removeItem(2160, count[cid]) then
player:addItem(2152, count[cid] * 100)
npcHandler:say('Here you are.', cid)
else
npcHandler:say('Sorry, you do not have enough crystal coins.', cid)
end
else
npcHandler:say('Well, can I help you with something else?', cid)
end
npcHandler.topic[cid] = 0
end
return true
end
keywordHandler:addKeyword({'money'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'We can {change} money for you. You can also access your {bank account}.'})
keywordHandler:addKeyword({'change'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'There are three different coin types in Tibia: 100 gold coins equal 1 platinum coin, 100 platinum coins equal 1 crystal coin. So if you\'d like to change 100 gold into 1 platinum, simply say \'{change gold}\' and then \'1 platinum\'.'})
keywordHandler:addKeyword({'bank'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'We can {change} money for you. You can also access your {bank account}.'})
keywordHandler:addKeyword({'advanced'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'Your bank account will be used automatically when you want to {rent} a house or place an offer on an item on the {market}. Let me know if you want to know about how either one works.'})
keywordHandler:addKeyword({'help'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'You can check the {balance} of your bank account, {deposit} money or {withdraw} it. You can also {transfer} money to other characters, provided that they have a vocation.'})
keywordHandler:addKeyword({'functions'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'You can check the {balance} of your bank account, {deposit} money or {withdraw} it. You can also {transfer} money to other characters, provided that they have a vocation.'})
keywordHandler:addKeyword({'basic'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'You can check the {balance} of your bank account, {deposit} money or {withdraw} it. You can also {transfer} money to other characters, provided that they have a vocation.'})
keywordHandler:addKeyword({'job'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'I work in this bank. I can change money for you and help you with your bank account.'})
npcHandler:setMessage(MESSAGE_GREET, 'Welcome to the Tibian {bank}, |PLAYERNAME|! What can I do for you?')
npcHandler:setMessage(MESSAGE_FAREWELL, "Good Bye.")
npcHandler:setMessage(MESSAGE_WALKAWAY, "Good Bye.")
npcHandler:setCallback(CALLBACK_GREET, greetCallback)
npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback)
npcHandler:addModule(FocusModule:new())
|
gpl-2.0
|
wargoth/tophat
|
src/Form/DataField/RoughTime.cpp
|
2269
|
/*
Copyright_License {
Top Hat Soaring Glide Computer - http://www.tophatsoaring.org/
Copyright (C) 2000-2016 The Top Hat Soaring Project
A detailed list of copyright holders can be found in the file "AUTHORS".
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program 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 Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
*/
#include "RoughTime.hpp"
#include "Util/NumberParser.hpp"
#include "Time/BrokenDateTime.hpp"
#include <stdio.h>
static TCHAR buffer[6];
void
RoughTimeDataField::ModifyValue(RoughTime _value)
{
if (_value == value)
return;
value = _value;
Modified();
}
int
RoughTimeDataField::GetAsInteger() const
{
return value.IsValid()
? value.GetMinuteOfDay()
: -1;
}
const TCHAR *
RoughTimeDataField::GetAsString() const
{
if (!value.IsValid())
return _T("");
_stprintf(buffer, _T("%02u:%02u"), value.GetHour(), value.GetMinute());
return buffer;
}
const TCHAR *
RoughTimeDataField::GetAsDisplayString() const
{
if (!value.IsValid())
return _T("");
RoughTime local_value = value + time_zone;
_stprintf(buffer, _T("%02u:%02u"),
local_value.GetHour(), local_value.GetMinute());
return buffer;
}
void
RoughTimeDataField::Inc()
{
RoughTime new_value = value;
if (new_value.IsValid())
++new_value;
else {
const BrokenTime bt = BrokenDateTime::NowUTC();
new_value = RoughTime(bt.hour, bt.minute);
}
ModifyValue(new_value);
}
void
RoughTimeDataField::Dec()
{
RoughTime new_value = value;
if (new_value.IsValid())
--new_value;
else {
const BrokenTime bt = BrokenDateTime::NowUTC();
new_value = RoughTime(bt.hour, bt.minute);
}
ModifyValue(new_value);
}
|
gpl-2.0
|
rowanthorpe/IXP-Manager
|
database/Proxies/__CG__EntitiesIRRDBConfig.php
|
7446
|
<?php
namespace Proxies\__CG__\Entities;
/**
* DO NOT EDIT THIS FILE - IT WAS CREATED BY DOCTRINE'S PROXY GENERATOR
*/
class IRRDBConfig extends \Entities\IRRDBConfig implements \Doctrine\ORM\Proxy\Proxy
{
/**
* @var \Closure the callback responsible for loading properties in the proxy object. This callback is called with
* three parameters, being respectively the proxy object to be initialized, the method that triggered the
* initialization process and an array of ordered parameters that were passed to that method.
*
* @see \Doctrine\Common\Persistence\Proxy::__setInitializer
*/
public $__initializer__;
/**
* @var \Closure the callback responsible of loading properties that need to be copied in the cloned object
*
* @see \Doctrine\Common\Persistence\Proxy::__setCloner
*/
public $__cloner__;
/**
* @var boolean flag indicating if this object was already initialized
*
* @see \Doctrine\Common\Persistence\Proxy::__isInitialized
*/
public $__isInitialized__ = false;
/**
* @var array properties to be lazy loaded, with keys being the property
* names and values being their default values
*
* @see \Doctrine\Common\Persistence\Proxy::__getLazyProperties
*/
public static $lazyPropertiesDefaults = [];
/**
* @param \Closure $initializer
* @param \Closure $cloner
*/
public function __construct($initializer = null, $cloner = null)
{
$this->__initializer__ = $initializer;
$this->__cloner__ = $cloner;
}
/**
*
* @return array
*/
public function __sleep()
{
if ($this->__isInitialized__) {
return ['__isInitialized__', 'host', 'protocol', 'source', 'notes', 'id', 'Customers'];
}
return ['__isInitialized__', 'host', 'protocol', 'source', 'notes', 'id', 'Customers'];
}
/**
*
*/
public function __wakeup()
{
if ( ! $this->__isInitialized__) {
$this->__initializer__ = function (IRRDBConfig $proxy) {
$proxy->__setInitializer(null);
$proxy->__setCloner(null);
$existingProperties = get_object_vars($proxy);
foreach ($proxy->__getLazyProperties() as $property => $defaultValue) {
if ( ! array_key_exists($property, $existingProperties)) {
$proxy->$property = $defaultValue;
}
}
};
}
}
/**
*
*/
public function __clone()
{
$this->__cloner__ && $this->__cloner__->__invoke($this, '__clone', []);
}
/**
* Forces initialization of the proxy
*/
public function __load()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, '__load', []);
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __isInitialized()
{
return $this->__isInitialized__;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __setInitialized($initialized)
{
$this->__isInitialized__ = $initialized;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __setInitializer(\Closure $initializer = null)
{
$this->__initializer__ = $initializer;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __getInitializer()
{
return $this->__initializer__;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __setCloner(\Closure $cloner = null)
{
$this->__cloner__ = $cloner;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific cloning logic
*/
public function __getCloner()
{
return $this->__cloner__;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
* @static
*/
public function __getLazyProperties()
{
return self::$lazyPropertiesDefaults;
}
/**
* {@inheritDoc}
*/
public function setHost($host)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setHost', [$host]);
return parent::setHost($host);
}
/**
* {@inheritDoc}
*/
public function getHost()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getHost', []);
return parent::getHost();
}
/**
* {@inheritDoc}
*/
public function setProtocol($protocol)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setProtocol', [$protocol]);
return parent::setProtocol($protocol);
}
/**
* {@inheritDoc}
*/
public function getProtocol()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getProtocol', []);
return parent::getProtocol();
}
/**
* {@inheritDoc}
*/
public function setSource($source)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setSource', [$source]);
return parent::setSource($source);
}
/**
* {@inheritDoc}
*/
public function getSource()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getSource', []);
return parent::getSource();
}
/**
* {@inheritDoc}
*/
public function setNotes($notes)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setNotes', [$notes]);
return parent::setNotes($notes);
}
/**
* {@inheritDoc}
*/
public function getNotes()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getNotes', []);
return parent::getNotes();
}
/**
* {@inheritDoc}
*/
public function getId()
{
if ($this->__isInitialized__ === false) {
return (int) parent::getId();
}
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getId', []);
return parent::getId();
}
/**
* {@inheritDoc}
*/
public function addCustomer(\Entities\Customer $customers)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'addCustomer', [$customers]);
return parent::addCustomer($customers);
}
/**
* {@inheritDoc}
*/
public function removeCustomer(\Entities\Customer $customers)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'removeCustomer', [$customers]);
return parent::removeCustomer($customers);
}
/**
* {@inheritDoc}
*/
public function getCustomers()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getCustomers', []);
return parent::getCustomers();
}
}
|
gpl-2.0
|
oracle2025/openmovieeditor
|
src/PortAudio19PlaybackCore.H
|
1671
|
/* PortAudio19PlaybackCore.H
*
* Copyright (C) 2005, 2006, 2008 Richard Spindler <richard.spindler AT gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef _PORT_AUDIO_19_PLAYBACK_CORE_H_
#define _PORT_AUDIO_19_PLAYBACK_CORE_H_
#include <stdint.h>
#include "IPlaybackCore.H"
namespace nle
{
class IAudioReader;
class IVideoReader;
class IVideoWriter;
class PortAudio19PlaybackCore : public IPlaybackCore
{
public:
PortAudio19PlaybackCore( IAudioReader* audioReader, IVideoReader* videoReader, IVideoWriter* videoWriter );
~PortAudio19PlaybackCore();
void play();
void stop();
bool ok() { return true; }
int readAudio( float* output, unsigned long frames );
void flipFrame();
void checkPlayButton();
private:
IAudioReader* m_audioReader;
IVideoReader* m_videoReader;
IVideoWriter* m_videoWriter;
int64_t m_audioPosition;
int64_t m_currentFrame;
int64_t m_lastFrame;
};
} /* namespace nle */
#endif /* _PORT_AUDIO_PLAYBACK_CORE_H_ */
|
gpl-2.0
|
jurgel/Maratis-4
|
Sources/MSDK/MCore/Sources/MMatrix4x4.cpp
|
25142
|
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// MCore
// MMatrix4x4.cpp
/////////////////////////////////////////////////////////////////////////////////////////////////////////
//========================================================================
// Copyright (c) 2003-2011 Anael Seghezzi <www.maratis3d.com>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#include <memory.h>
#include "../Includes/MCore.h"
MMatrix4x4::MMatrix4x4(
float e0, float e1, float e2, float e3,
float e4, float e5, float e6, float e7,
float e8, float e9, float e10, float e11,
float e12, float e13, float e14, float e15)
{
entries[0] = e0;
entries[1] = e1;
entries[2] = e2;
entries[3] = e3;
entries[4] = e4;
entries[5] = e5;
entries[6] = e6;
entries[7] = e7;
entries[8] = e8;
entries[9] = e9;
entries[10] = e10;
entries[11] = e11;
entries[12] = e12;
entries[13] = e13;
entries[14] = e14;
entries[15] = e15;
}
MMatrix4x4::MMatrix4x4(const MMatrix4x4 & mat)
{
memcpy(entries, mat.entries, 16 * sizeof(float));
}
MMatrix4x4::MMatrix4x4(const float * value)
{
memcpy(entries, value, 16*sizeof(float));
}
void MMatrix4x4::setEntry(int position, float value)
{
if(position >= 0 && position <= 15)
entries[position] = value;
}
float MMatrix4x4::getEntry(int position) const
{
if(position >= 0 && position <= 15)
return entries[position];
return 0.0f;
}
MVector4 MMatrix4x4::getRow(int position) const
{
if(position == 0)
return MVector4(entries[0], entries[4], entries[8], entries[12]);
if(position == 1)
return MVector4(entries[1], entries[5], entries[9], entries[13]);
if(position == 2)
return MVector4(entries[2], entries[6], entries[10], entries[14]);
if(position == 3)
return MVector4(entries[3], entries[7], entries[11], entries[15]);
return MVector4(0.0f, 0.0f, 0.0f, 0.0f);
}
MVector4 MMatrix4x4::getColumn(int position) const
{
if(position == 0)
return MVector4(entries[0], entries[1], entries[2], entries[3]);
if(position == 1)
return MVector4(entries[4], entries[5], entries[6], entries[7]);
if(position == 2)
return MVector4(entries[8], entries[9], entries[10], entries[11]);
if(position == 3)
return MVector4(entries[12], entries[13], entries[14], entries[15]);
return MVector4(0.0f, 0.0f, 0.0f, 0.0f);
}
MVector3 MMatrix4x4::getEulerAngles(void) const
{
// get euler angles from matrix
float cy = sqrtf(entries[0] * entries[0] + entries[1] * entries[1]);
if(cy > (16.0 * 1.192092896e-07F))
{
MVector3 euler;
MVector3 euler1;
MVector3 euler2;
euler1.x = atan2f(entries[6], entries[10]);
euler1.y = atan2f(- entries[2], cy);
euler1.z = atan2f(entries[1], entries[0]);
euler2.x = atan2f(- entries[6], - entries[10]);
euler2.y = atan2f(- entries[2], - cy);
euler2.z = atan2f(- entries[1], - entries[0]);
if( (fabs(euler1.x) + fabs(euler1.y) + fabs(euler1.z)) >
(fabs(euler2.x) + fabs(euler2.y) + fabs(euler2.z)))
{
euler = euler2;
}
else
{
euler = euler1;
}
return euler * (float)RAD_TO_DEG;
}
else
{
MVector3 euler;
euler.x = atan2f(- entries[9], entries[5]);
euler.y = atan2f(- entries[2], cy);
euler.z = 0.0f;
return euler * (float)RAD_TO_DEG;
}
return MVector3(0, 0, 0);
}
MVector3 MMatrix4x4::getScale(void) const
{
float xSize = getRotatedVector3(MVector3(1, 0, 0)).getLength();
float ySize = getRotatedVector3(MVector3(0, 1, 0)).getLength();
float zSize = getRotatedVector3(MVector3(0, 0, 1)).getLength();
return MVector3(xSize, ySize, zSize);
}
void MMatrix4x4::loadIdentity(void)
{
memset(entries, 0, 16*sizeof(float));
entries[0] = 1.0f;
entries[5] = 1.0f;
entries[10] = 1.0f;
entries[15] = 1.0f;
}
void MMatrix4x4::loadZero(void)
{
memset(entries, 0, 16*sizeof(float));
}
MMatrix4x4 MMatrix4x4::operator + (const MMatrix4x4 & mat) const
{
return MMatrix4x4(
entries[0] + mat.entries[0],
entries[1] + mat.entries[1],
entries[2] + mat.entries[2],
entries[3] + mat.entries[3],
entries[4] + mat.entries[4],
entries[5] + mat.entries[5],
entries[6] + mat.entries[6],
entries[7] + mat.entries[7],
entries[8] + mat.entries[8],
entries[9] + mat.entries[9],
entries[10] + mat.entries[10],
entries[11] + mat.entries[11],
entries[12] + mat.entries[12],
entries[13] + mat.entries[13],
entries[14] + mat.entries[14],
entries[15] + mat.entries[15]
);
}
MMatrix4x4 MMatrix4x4::operator - (const MMatrix4x4 & mat) const
{
return MMatrix4x4(
entries[0] - mat.entries[0],
entries[1] - mat.entries[1],
entries[2] - mat.entries[2],
entries[3] - mat.entries[3],
entries[4] - mat.entries[4],
entries[5] - mat.entries[5],
entries[6] - mat.entries[6],
entries[7] - mat.entries[7],
entries[8] - mat.entries[8],
entries[9] - mat.entries[9],
entries[10] - mat.entries[10],
entries[11] - mat.entries[11],
entries[12] - mat.entries[12],
entries[13] - mat.entries[13],
entries[14] - mat.entries[14],
entries[15] - mat.entries[15]
);
}
MMatrix4x4 MMatrix4x4::operator * (const MMatrix4x4 & mat) const
{
// if bottom row is (0, 0, 0, 1) in both matrices
if( entries[3]==0.0f && entries[7]==0.0f &&
entries[11]==0.0f && entries[15]==1.0f &&
mat.entries[3]==0.0f && mat.entries[7]==0.0f &&
mat.entries[11]==0.0f && mat.entries[15]==1.0f)
{
return MMatrix4x4(
entries[0]*mat.entries[0]+entries[4]*mat.entries[1]+entries[8]*mat.entries[2],
entries[1]*mat.entries[0]+entries[5]*mat.entries[1]+entries[9]*mat.entries[2],
entries[2]*mat.entries[0]+entries[6]*mat.entries[1]+entries[10]*mat.entries[2],
0.0f,
entries[0]*mat.entries[4]+entries[4]*mat.entries[5]+entries[8]*mat.entries[6],
entries[1]*mat.entries[4]+entries[5]*mat.entries[5]+entries[9]*mat.entries[6],
entries[2]*mat.entries[4]+entries[6]*mat.entries[5]+entries[10]*mat.entries[6],
0.0f,
entries[0]*mat.entries[8]+entries[4]*mat.entries[9]+entries[8]*mat.entries[10],
entries[1]*mat.entries[8]+entries[5]*mat.entries[9]+entries[9]*mat.entries[10],
entries[2]*mat.entries[8]+entries[6]*mat.entries[9]+entries[10]*mat.entries[10],
0.0f,
entries[0]*mat.entries[12]+entries[4]*mat.entries[13]+entries[8]*mat.entries[14]+entries[12],
entries[1]*mat.entries[12]+entries[5]*mat.entries[13]+entries[9]*mat.entries[14]+entries[13],
entries[2]*mat.entries[12]+entries[6]*mat.entries[13]+entries[10]*mat.entries[14]+entries[14],
1.0f
);
}
// if bottom row of 1st matrix is (0, 0, 0, 1)
if( entries[3]==0.0f && entries[7]==0.0f &&
entries[11]==0.0f && entries[15]==1.0f)
{
return MMatrix4x4(
entries[0]*mat.entries[0]+entries[4]*mat.entries[1]+entries[8]*mat.entries[2]+entries[12]*mat.entries[3],
entries[1]*mat.entries[0]+entries[5]*mat.entries[1]+entries[9]*mat.entries[2]+entries[13]*mat.entries[3],
entries[2]*mat.entries[0]+entries[6]*mat.entries[1]+entries[10]*mat.entries[2]+entries[14]*mat.entries[3],
mat.entries[3],
entries[0]*mat.entries[4]+entries[4]*mat.entries[5]+entries[8]*mat.entries[6]+entries[12]*mat.entries[7],
entries[1]*mat.entries[4]+entries[5]*mat.entries[5]+entries[9]*mat.entries[6]+entries[13]*mat.entries[7],
entries[2]*mat.entries[4]+entries[6]*mat.entries[5]+entries[10]*mat.entries[6]+entries[14]*mat.entries[7],
mat.entries[7],
entries[0]*mat.entries[8]+entries[4]*mat.entries[9]+entries[8]*mat.entries[10]+entries[12]*mat.entries[11],
entries[1]*mat.entries[8]+entries[5]*mat.entries[9]+entries[9]*mat.entries[10]+entries[13]*mat.entries[11],
entries[2]*mat.entries[8]+entries[6]*mat.entries[9]+entries[10]*mat.entries[10]+entries[14]*mat.entries[11],
mat.entries[11],
entries[0]*mat.entries[12]+entries[4]*mat.entries[13]+entries[8]*mat.entries[14]+entries[12]*mat.entries[15],
entries[1]*mat.entries[12]+entries[5]*mat.entries[13]+entries[9]*mat.entries[14]+entries[13]*mat.entries[15],
entries[2]*mat.entries[12]+entries[6]*mat.entries[13]+entries[10]*mat.entries[14]+entries[14]*mat.entries[15],
mat.entries[15]
);
}
// if bottom row of 2nd matrix is (0, 0, 0, 1)
if( mat.entries[3]==0.0f && mat.entries[7]==0.0f &&
mat.entries[11]==0.0f && mat.entries[15]==1.0f)
{
return MMatrix4x4(
entries[0]*mat.entries[0]+entries[4]*mat.entries[1]+entries[8]*mat.entries[2],
entries[1]*mat.entries[0]+entries[5]*mat.entries[1]+entries[9]*mat.entries[2],
entries[2]*mat.entries[0]+entries[6]*mat.entries[1]+entries[10]*mat.entries[2],
entries[3]*mat.entries[0]+entries[7]*mat.entries[1]+entries[11]*mat.entries[2],
entries[0]*mat.entries[4]+entries[4]*mat.entries[5]+entries[8]*mat.entries[6],
entries[1]*mat.entries[4]+entries[5]*mat.entries[5]+entries[9]*mat.entries[6],
entries[2]*mat.entries[4]+entries[6]*mat.entries[5]+entries[10]*mat.entries[6],
entries[3]*mat.entries[4]+entries[7]*mat.entries[5]+entries[11]*mat.entries[6],
entries[0]*mat.entries[8]+entries[4]*mat.entries[9]+entries[8]*mat.entries[10],
entries[1]*mat.entries[8]+entries[5]*mat.entries[9]+entries[9]*mat.entries[10],
entries[2]*mat.entries[8]+entries[6]*mat.entries[9]+entries[10]*mat.entries[10],
entries[3]*mat.entries[8]+entries[7]*mat.entries[9]+entries[11]*mat.entries[10],
entries[0]*mat.entries[12]+entries[4]*mat.entries[13]+entries[8]*mat.entries[14]+entries[12],
entries[1]*mat.entries[12]+entries[5]*mat.entries[13]+entries[9]*mat.entries[14]+entries[13],
entries[2]*mat.entries[12]+entries[6]*mat.entries[13]+entries[10]*mat.entries[14]+entries[14],
entries[3]*mat.entries[12]+entries[7]*mat.entries[13]+entries[11]*mat.entries[14]+entries[15]
);
}
return MMatrix4x4(
entries[0]*mat.entries[0]+entries[4]*mat.entries[1]+entries[8]*mat.entries[2]+entries[12]*mat.entries[3],
entries[1]*mat.entries[0]+entries[5]*mat.entries[1]+entries[9]*mat.entries[2]+entries[13]*mat.entries[3],
entries[2]*mat.entries[0]+entries[6]*mat.entries[1]+entries[10]*mat.entries[2]+entries[14]*mat.entries[3],
entries[3]*mat.entries[0]+entries[7]*mat.entries[1]+entries[11]*mat.entries[2]+entries[15]*mat.entries[3],
entries[0]*mat.entries[4]+entries[4]*mat.entries[5]+entries[8]*mat.entries[6]+entries[12]*mat.entries[7],
entries[1]*mat.entries[4]+entries[5]*mat.entries[5]+entries[9]*mat.entries[6]+entries[13]*mat.entries[7],
entries[2]*mat.entries[4]+entries[6]*mat.entries[5]+entries[10]*mat.entries[6]+entries[14]*mat.entries[7],
entries[3]*mat.entries[4]+entries[7]*mat.entries[5]+entries[11]*mat.entries[6]+entries[15]*mat.entries[7],
entries[0]*mat.entries[8]+entries[4]*mat.entries[9]+entries[8]*mat.entries[10]+entries[12]*mat.entries[11],
entries[1]*mat.entries[8]+entries[5]*mat.entries[9]+entries[9]*mat.entries[10]+entries[13]*mat.entries[11],
entries[2]*mat.entries[8]+entries[6]*mat.entries[9]+entries[10]*mat.entries[10]+entries[14]*mat.entries[11],
entries[3]*mat.entries[8]+entries[7]*mat.entries[9]+entries[11]*mat.entries[10]+entries[15]*mat.entries[11],
entries[0]*mat.entries[12]+entries[4]*mat.entries[13]+entries[8]*mat.entries[14]+entries[12]*mat.entries[15],
entries[1]*mat.entries[12]+entries[5]*mat.entries[13]+entries[9]*mat.entries[14]+entries[13]*mat.entries[15],
entries[2]*mat.entries[12]+entries[6]*mat.entries[13]+entries[10]*mat.entries[14]+entries[14]*mat.entries[15],
entries[3]*mat.entries[12]+entries[7]*mat.entries[13]+entries[11]*mat.entries[14]+entries[15]*mat.entries[15]
);
}
MMatrix4x4 MMatrix4x4::operator * (const float value) const
{
return MMatrix4x4(
entries[0] * value,
entries[1] * value,
entries[2] * value,
entries[3] * value,
entries[4] * value,
entries[5] * value,
entries[6] * value,
entries[7] * value,
entries[8] * value,
entries[9] * value,
entries[10] * value,
entries[11] * value,
entries[12] * value,
entries[13] * value,
entries[14] * value,
entries[15] * value
);
}
MMatrix4x4 MMatrix4x4::operator / (const float value) const
{
if(value == 0.0f || value == 1.0f)
return (*this);
float temp = 1/value;
return (*this) * temp;
}
MMatrix4x4 operator * (float factor, const MMatrix4x4 & mat)
{
return mat * factor;
}
bool MMatrix4x4::operator == (const MMatrix4x4 & mat) const
{
for(int i=0; i<16; i++)
{
if(entries[i] != mat.entries[i])
return false;
}
return true;
}
bool MMatrix4x4::operator != (const MMatrix4x4 & mat) const
{
return !((*this) == mat);
}
void MMatrix4x4::operator += (const MMatrix4x4 & mat)
{
(*this) = (*this) + mat;
}
void MMatrix4x4::operator -= (const MMatrix4x4 & mat)
{
(*this) = (*this) - mat;
}
void MMatrix4x4::operator *= (const MMatrix4x4 & mat)
{
(*this) = (*this) * mat;
}
void MMatrix4x4::operator *= (const float value)
{
(*this) = (*this) * value;
}
void MMatrix4x4::operator /= (const float value)
{
(*this) = (*this) / value;
}
MMatrix4x4 MMatrix4x4::operator - (void) const
{
MMatrix4x4 result(*this);
for(int i=0; i<16; i++)
result.entries[i] = -result.entries[i];
return result;
}
MVector4 MMatrix4x4::operator * (const MVector4 mat) const
{
// if bottom row is (0, 0, 0, 1)
if(entries[3] == 0.0f && entries[7] == 0.0f && entries[11] == 0.0f && entries[15] == 1.0f)
{
return MVector4(
entries[0]*mat.x
+ entries[4]*mat.y
+ entries[8]*mat.z
+ entries[12]*mat.w,
entries[1]*mat.x
+ entries[5]*mat.y
+ entries[9]*mat.z
+ entries[13]*mat.w,
entries[2]*mat.x
+ entries[6]*mat.y
+ entries[10]*mat.z
+ entries[14]*mat.w,
mat.w
);
}
return MVector4(
entries[0]*mat.x
+ entries[4]*mat.y
+ entries[8]*mat.z
+ entries[12]*mat.w,
entries[1]*mat.x
+ entries[5]*mat.y
+ entries[9]*mat.z
+ entries[13]*mat.w,
entries[2]*mat.x
+ entries[6]*mat.y
+ entries[10]*mat.z
+ entries[14]*mat.w,
entries[3]*mat.x
+ entries[7]*mat.y
+ entries[11]*mat.z
+ entries[15]*mat.w
);
}
MVector3 MMatrix4x4::getInverseRotatedVector3(const MVector3 & vec) const
{
return MVector3(
entries[0]*vec.x + entries[1]*vec.y + entries[2]*vec.z,
entries[4]*vec.x + entries[5]*vec.y + entries[6]*vec.z,
entries[8]*vec.x + entries[9]*vec.y + entries[10]*vec.z
);
}
MVector3 MMatrix4x4::getTranslatedVector3(const MVector3 & vec) const
{
return MVector3(vec.x + entries[12], vec.y + entries[13], vec.z + entries[14]);
}
MVector3 MMatrix4x4::getInversetranslatedVector3(const MVector3 & vec) const
{
return MVector3(vec.x - entries[12], vec.y - entries[13], vec.z - entries[14]);
}
void MMatrix4x4::invert(void)
{
*this = getInverse();
}
MMatrix4x4 MMatrix4x4::getInverse(void) const
{
MMatrix4x4 result = getInversetranspose();
result.transpose();
return result;
}
void MMatrix4x4::transpose(void)
{
*this = getTranspose();
}
MMatrix4x4 MMatrix4x4::getTranspose(void) const
{
return MMatrix4x4(
entries[ 0], entries[ 4], entries[ 8], entries[12],
entries[ 1], entries[ 5], entries[ 9], entries[13],
entries[ 2], entries[ 6], entries[10], entries[14],
entries[ 3], entries[ 7], entries[11], entries[15]
);
}
void MMatrix4x4::invertTranspose(void)
{
*this = getInversetranspose();
}
MMatrix4x4 MMatrix4x4::getInversetranspose(void) const
{
MMatrix4x4 result;
float tmp[12]; // pair storage
float det; // determinant
// calculate pairs for first 8 elements (cofactors)
tmp[0] = entries[10] * entries[15];
tmp[1] = entries[11] * entries[14];
tmp[2] = entries[9] * entries[15];
tmp[3] = entries[11] * entries[13];
tmp[4] = entries[9] * entries[14];
tmp[5] = entries[10] * entries[13];
tmp[6] = entries[8] * entries[15];
tmp[7] = entries[11] * entries[12];
tmp[8] = entries[8] * entries[14];
tmp[9] = entries[10] * entries[12];
tmp[10] = entries[8] * entries[13];
tmp[11] = entries[9] * entries[12];
// calculate first 8 elements (cofactors)
result.setEntry(0, tmp[0]*entries[5] + tmp[3]*entries[6] + tmp[4]*entries[7]
- tmp[1]*entries[5] - tmp[2]*entries[6] - tmp[5]*entries[7]);
result.setEntry(1, tmp[1]*entries[4] + tmp[6]*entries[6] + tmp[9]*entries[7]
- tmp[0]*entries[4] - tmp[7]*entries[6] - tmp[8]*entries[7]);
result.setEntry(2, tmp[2]*entries[4] + tmp[7]*entries[5] + tmp[10]*entries[7]
- tmp[3]*entries[4] - tmp[6]*entries[5] - tmp[11]*entries[7]);
result.setEntry(3, tmp[5]*entries[4] + tmp[8]*entries[5] + tmp[11]*entries[6]
- tmp[4]*entries[4] - tmp[9]*entries[5] - tmp[10]*entries[6]);
result.setEntry(4, tmp[1]*entries[1] + tmp[2]*entries[2] + tmp[5]*entries[3]
- tmp[0]*entries[1] - tmp[3]*entries[2] - tmp[4]*entries[3]);
result.setEntry(5, tmp[0]*entries[0] + tmp[7]*entries[2] + tmp[8]*entries[3]
- tmp[1]*entries[0] - tmp[6]*entries[2] - tmp[9]*entries[3]);
result.setEntry(6, tmp[3]*entries[0] + tmp[6]*entries[1] + tmp[11]*entries[3]
- tmp[2]*entries[0] - tmp[7]*entries[1] - tmp[10]*entries[3]);
result.setEntry(7, tmp[4]*entries[0] + tmp[9]*entries[1] + tmp[10]*entries[2]
- tmp[5]*entries[0] - tmp[8]*entries[1] - tmp[11]*entries[2]);
// calculate pairs for second 8 elements (cofactors)
tmp[0] = entries[2]*entries[7];
tmp[1] = entries[3]*entries[6];
tmp[2] = entries[1]*entries[7];
tmp[3] = entries[3]*entries[5];
tmp[4] = entries[1]*entries[6];
tmp[5] = entries[2]*entries[5];
tmp[6] = entries[0]*entries[7];
tmp[7] = entries[3]*entries[4];
tmp[8] = entries[0]*entries[6];
tmp[9] = entries[2]*entries[4];
tmp[10] = entries[0]*entries[5];
tmp[11] = entries[1]*entries[4];
// calculate second 8 elements (cofactors)
result.setEntry(8, tmp[0]*entries[13] + tmp[3]*entries[14] + tmp[4]*entries[15]
- tmp[1]*entries[13] - tmp[2]*entries[14] - tmp[5]*entries[15]);
result.setEntry(9, tmp[1]*entries[12] + tmp[6]*entries[14] + tmp[9]*entries[15]
- tmp[0]*entries[12] - tmp[7]*entries[14] - tmp[8]*entries[15]);
result.setEntry(10, tmp[2]*entries[12] + tmp[7]*entries[13] + tmp[10]*entries[15]
- tmp[3]*entries[12] - tmp[6]*entries[13] - tmp[11]*entries[15]);
result.setEntry(11, tmp[5]*entries[12] + tmp[8]*entries[13] + tmp[11]*entries[14]
- tmp[4]*entries[12] - tmp[9]*entries[13] - tmp[10]*entries[14]);
result.setEntry(12, tmp[2]*entries[10] + tmp[5]*entries[11] + tmp[1]*entries[9]
- tmp[4]*entries[11] - tmp[0]*entries[9] - tmp[3]*entries[10]);
result.setEntry(13, tmp[8]*entries[11] + tmp[0]*entries[8] + tmp[7]*entries[10]
- tmp[6]*entries[10] - tmp[9]*entries[11] - tmp[1]*entries[8]);
result.setEntry(14, tmp[6]*entries[9] + tmp[11]*entries[11] + tmp[3]*entries[8]
- tmp[10]*entries[11] - tmp[2]*entries[8] - tmp[7]*entries[9]);
result.setEntry(15, tmp[10]*entries[10] + tmp[4]*entries[8] + tmp[9]*entries[9]
- tmp[8]*entries[9] - tmp[11]*entries[10] - tmp[5]*entries[8]);
// calculate determinant
det = entries[0]*result.getEntry(0)
+ entries[1]*result.getEntry(1)
+ entries[2]*result.getEntry(2)
+ entries[3]*result.getEntry(3);
if(det == 0.0f)
{
MMatrix4x4 id;
return id;
}
result = result/det;
return result;
}
void MMatrix4x4::affineInvert(void)
{
(*this) = getAffineInverse();
}
MMatrix4x4 MMatrix4x4::getAffineInverse(void) const
{
return MMatrix4x4(
entries[0],
entries[4],
entries[8],
0.0f,
entries[1],
entries[5],
entries[9],
0.0f,
entries[2],
entries[6],
entries[10],
0.0f,
-(entries[0]*entries[12] + entries[1]*entries[13] + entries[2]*entries[14]),
-(entries[4]*entries[12] + entries[5]*entries[13] + entries[6]*entries[14]),
-(entries[8]*entries[12] + entries[9]*entries[13] + entries[10]*entries[14]),
1.0f
);
}
void MMatrix4x4::affineInvertTranspose(void)
{
(*this) = getAffineInverseTranspose();
}
MMatrix4x4 MMatrix4x4::getAffineInverseTranspose(void) const
{
return MMatrix4x4(
entries[0],
entries[1],
entries[2],
-(entries[0]*entries[12] + entries[1]*entries[13] + entries[2]*entries[14]),
entries[4],
entries[5],
entries[6],
-(entries[4]*entries[12] +entries[5]*entries[13] + entries[6]*entries[14]),
entries[8],
entries[9],
entries[10],
-(entries[8]*entries[12] +entries[9]*entries[13] + entries[10]*entries[14]),
0.0f, 0.0f, 0.0f, 1.0f
);
}
void MMatrix4x4::setTranslation(const MVector3 & translation)
{
loadIdentity();
setTranslationPart(translation);
}
void MMatrix4x4::setScale(const MVector3 & scaleFactor)
{
loadIdentity();
entries[0] = scaleFactor.x;
entries[5] = scaleFactor.y;
entries[10] = scaleFactor.z;
}
void MMatrix4x4::setUniformScale(const float size)
{
loadIdentity();
entries[0] = entries[5] = entries[10] = size;
}
void MMatrix4x4::scale(const MVector3 & scaleFactor)
{
entries[0] *= scaleFactor.x;
entries[1] *= scaleFactor.x;
entries[2] *= scaleFactor.x;
entries[3] *= scaleFactor.x;
entries[4] *= scaleFactor.y;
entries[5] *= scaleFactor.y;
entries[6] *= scaleFactor.y;
entries[7] *= scaleFactor.y;
entries[8] *= scaleFactor.z;
entries[9] *= scaleFactor.z;
entries[10] *= scaleFactor.z;
entries[11] *= scaleFactor.z;
}
void MMatrix4x4::rotate(const MVector3 & axis, const float angle)
{
MMatrix4x4 matrix;
matrix.setRotationAxis(angle, axis);
(*this) = (*this) * matrix;
}
void MMatrix4x4::translate(const MVector3 translate)
{
MMatrix4x4 matrix;
matrix.setTranslationPart(translate);
(*this) = (*this) * matrix;
}
void MMatrix4x4::setRotationAxis(const float angle, const MVector3 & axis)
{
MVector3 u = axis.getNormalized();
float sinAngle = (float)sin(angle * DEG_TO_RAD);
float cosAngle = (float)cos(angle * DEG_TO_RAD);
float oneMinusCosAngle = 1.0f - cosAngle;
loadIdentity();
entries[0] = (u.x)*(u.x) + cosAngle * (1-(u.x)*(u.x));
entries[4] = (u.x)*(u.y)*(oneMinusCosAngle) - sinAngle*u.z;
entries[8] = (u.x)*(u.z)*(oneMinusCosAngle) + sinAngle*u.y;
entries[1] = (u.x)*(u.y)*(oneMinusCosAngle) + sinAngle*u.z;
entries[5] = (u.y)*(u.y) + cosAngle * (1-(u.y)*(u.y));
entries[9] = (u.y)*(u.z)*(oneMinusCosAngle) - sinAngle*u.x;
entries[2] = (u.x)*(u.z)*(oneMinusCosAngle) - sinAngle*u.y;
entries[6] = (u.y)*(u.z)*(oneMinusCosAngle) + sinAngle*u.x;
entries[10] = (u.z)*(u.z) + cosAngle * (1-(u.z)*(u.z));
}
void MMatrix4x4::setRotationX(const float angle)
{
loadIdentity();
entries[5] = (float)cos(angle * DEG_TO_RAD);
entries[6] = (float)sin(angle * DEG_TO_RAD);
entries[9] = -entries[6];
entries[10] = entries[5];
}
void MMatrix4x4::setRotationY(const float angle)
{
loadIdentity();
entries[0] = (float)cos(angle * DEG_TO_RAD);
entries[2] = -(float)sin(angle * DEG_TO_RAD);
entries[2] = -entries[8];
entries[10] = entries[0];
}
void MMatrix4x4::setRotationZ(const float angle)
{
loadIdentity();
entries[0] = (float)cos(angle * DEG_TO_RAD);
entries[1] = (float)sin(angle * DEG_TO_RAD);
entries[4] = -entries[1];
entries[5] = entries[0];
}
void MMatrix4x4::setRotationEuler(const float angleX, const float angleY, const float angleZ)
{
loadIdentity();
setRotationPartEuler(angleX, angleY, angleZ);
}
void MMatrix4x4::setTranslationPart(const MVector3 & translation)
{
entries[12] = translation.x;
entries[13] = translation.y;
entries[14] = translation.z;
}
void MMatrix4x4::setRotationPartEuler(const float angleX, const float angleY, const float angleZ)
{
double cr = cos( angleX * DEG_TO_RAD );
double sr = sin( angleX * DEG_TO_RAD );
double cp = cos( angleY * DEG_TO_RAD );
double sp = sin( angleY * DEG_TO_RAD );
double cy = cos( angleZ * DEG_TO_RAD );
double sy = sin( angleZ * DEG_TO_RAD );
entries[0] = ( float )( cp*cy );
entries[1] = ( float )( cp*sy );
entries[2] = ( float )( -sp );
double srsp = sr*sp;
double crsp = cr*sp;
entries[4] = ( float )( srsp*cy-cr*sy );
entries[5] = ( float )( srsp*sy+cr*cy );
entries[6] = ( float )( sr*cp );
entries[8] = ( float )( crsp*cy+sr*sy );
entries[9] = ( float )( crsp*sy-sr*cy );
entries[10] = ( float )( cr*cp );
}
void MMatrix4x4::lookAt(const MVector3 & pos, const MVector3 & dir, const MVector3 & up)
{
MVector3 lftN = dir.crossProduct(up).getNormalized();
MVector3 upN = lftN.crossProduct(dir).getNormalized();
MVector3 dirN = dir.getNormalized();
entries[0] = lftN.x;
entries[1] = upN.x;
entries[2] = -dirN.x;
entries[3] = 0.0f;
entries[4] = lftN.y;
entries[5] = upN.y;
entries[6] = -dirN.y;
entries[7] = 0.0f;
entries[8] = lftN.z;
entries[9] = upN.z;
entries[10] = -dirN.z;
entries[11] = 0.0f;
entries[12] = -lftN.dotProduct(pos);
entries[13] = -upN.dotProduct(pos);
entries[14] = dirN.dotProduct(pos);
entries[15] = 1.0f;
}
|
gpl-2.0
|
smalyshev/blazegraph
|
bigdata-jini/src/java/com/bigdata/jini/start/config/TransactionServerConfiguration.java
|
2705
|
/*
Copyright (C) SYSTAP, LLC 2006-2015. All rights reserved.
Contact:
SYSTAP, LLC
2501 Calvert ST NW #106
Washington, DC 20008
licenses@systap.com
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program 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 Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* Created on Jan 5, 2009
*/
package com.bigdata.jini.start.config;
import net.jini.config.Configuration;
import net.jini.config.ConfigurationException;
import net.jini.core.entry.Entry;
import com.bigdata.jini.start.IServiceListener;
import com.bigdata.jini.start.process.JiniServiceProcessHelper;
import com.bigdata.service.jini.JiniFederation;
import com.bigdata.service.jini.TransactionServer;
import com.bigdata.util.NV;
/**
* Configuration for the {@link TransactionServer}.
*
* @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan Thompson</a>
* @version $Id$
*/
public class TransactionServerConfiguration extends
BigdataServiceConfiguration {
/**
*
*/
private static final long serialVersionUID = 2616176455506215566L;
/**
* @param config
*/
public TransactionServerConfiguration(Configuration config)
throws ConfigurationException {
super(TransactionServer.class, config);
}
public TransactionServiceStarter newServiceStarter(JiniFederation fed,
IServiceListener listener, String zpath, Entry[] attributes)
throws Exception {
return new TransactionServiceStarter(fed, listener, zpath, attributes);
}
public class TransactionServiceStarter<V extends JiniServiceProcessHelper>
extends BigdataServiceStarter<V> {
/**
* @param fed
* @param listener
* @param zpath
*/
protected TransactionServiceStarter(JiniFederation fed,
IServiceListener listener, String zpath, Entry[] attributes) {
super(fed, listener, zpath, attributes);
}
@Override
protected NV getDataDir() {
return new NV(TransactionServer.Options.DATA_DIR, serviceDir
.toString());
}
}
}
|
gpl-2.0
|
md-5/jdk10
|
src/hotspot/share/gc/shenandoah/shenandoahUnload.cpp
|
6103
|
/*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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 Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "classfile/classLoaderDataGraph.hpp"
#include "classfile/systemDictionary.hpp"
#include "code/codeBehaviours.hpp"
#include "code/codeCache.hpp"
#include "code/dependencyContext.hpp"
#include "gc/shared/gcBehaviours.hpp"
#include "gc/shared/suspendibleThreadSet.hpp"
#include "gc/shenandoah/shenandoahClosures.inline.hpp"
#include "gc/shenandoah/shenandoahCodeRoots.hpp"
#include "gc/shenandoah/shenandoahConcurrentRoots.hpp"
#include "gc/shenandoah/shenandoahNMethod.inline.hpp"
#include "gc/shenandoah/shenandoahLock.hpp"
#include "gc/shenandoah/shenandoahRootProcessor.hpp"
#include "gc/shenandoah/shenandoahUnload.hpp"
#include "gc/shenandoah/shenandoahVerifier.hpp"
#include "memory/iterator.hpp"
#include "memory/resourceArea.hpp"
#include "oops/access.inline.hpp"
class ShenandoahIsUnloadingOopClosure : public OopClosure {
private:
ShenandoahMarkingContext* _marking_context;
bool _is_unloading;
public:
ShenandoahIsUnloadingOopClosure() :
_marking_context(ShenandoahHeap::heap()->marking_context()),
_is_unloading(false) {
}
virtual void do_oop(oop* p) {
if (_is_unloading) {
return;
}
const oop o = RawAccess<>::oop_load(p);
if (!CompressedOops::is_null(o) &&
_marking_context->is_complete() &&
!_marking_context->is_marked(o)) {
_is_unloading = true;
}
}
virtual void do_oop(narrowOop* p) {
ShouldNotReachHere();
}
bool is_unloading() const {
return _is_unloading;
}
};
class ShenandoahIsUnloadingBehaviour : public IsUnloadingBehaviour {
public:
virtual bool is_unloading(CompiledMethod* method) const {
nmethod* const nm = method->as_nmethod();
guarantee(ShenandoahHeap::heap()->is_concurrent_root_in_progress(), "Only this phase");
ShenandoahNMethod* data = ShenandoahNMethod::gc_data(nm);
ShenandoahReentrantLocker locker(data->lock());
ShenandoahIsUnloadingOopClosure cl;
data->oops_do(&cl);
return cl.is_unloading();
}
};
class ShenandoahCompiledICProtectionBehaviour : public CompiledICProtectionBehaviour {
public:
virtual bool lock(CompiledMethod* method) {
nmethod* const nm = method->as_nmethod();
ShenandoahReentrantLock* const lock = ShenandoahNMethod::lock_for_nmethod(nm);
assert(lock != NULL, "Not yet registered?");
lock->lock();
return true;
}
virtual void unlock(CompiledMethod* method) {
nmethod* const nm = method->as_nmethod();
ShenandoahReentrantLock* const lock = ShenandoahNMethod::lock_for_nmethod(nm);
assert(lock != NULL, "Not yet registered?");
lock->unlock();
}
virtual bool is_safe(CompiledMethod* method) {
if (SafepointSynchronize::is_at_safepoint()) {
return true;
}
nmethod* const nm = method->as_nmethod();
ShenandoahReentrantLock* const lock = ShenandoahNMethod::lock_for_nmethod(nm);
assert(lock != NULL, "Not yet registered?");
return lock->owned_by_self();
}
};
ShenandoahUnload::ShenandoahUnload() {
if (ShenandoahConcurrentRoots::can_do_concurrent_class_unloading()) {
static ShenandoahIsUnloadingBehaviour is_unloading_behaviour;
IsUnloadingBehaviour::set_current(&is_unloading_behaviour);
static ShenandoahCompiledICProtectionBehaviour ic_protection_behaviour;
CompiledICProtectionBehaviour::set_current(&ic_protection_behaviour);
}
}
void ShenandoahUnload::prepare() {
assert(SafepointSynchronize::is_at_safepoint(), "Should be at safepoint");
assert(ShenandoahConcurrentRoots::can_do_concurrent_class_unloading(), "Sanity");
CodeCache::increment_unloading_cycle();
DependencyContext::cleaning_start();
}
void ShenandoahUnload::unlink() {
SuspendibleThreadSetJoiner sts;
bool unloading_occurred;
ShenandoahHeap* const heap = ShenandoahHeap::heap();
{
MutexLocker cldg_ml(ClassLoaderDataGraph_lock);
unloading_occurred = SystemDictionary::do_unloading(heap->gc_timer());
}
Klass::clean_weak_klass_links(unloading_occurred);
ShenandoahCodeRoots::unlink(ShenandoahHeap::heap()->workers(), unloading_occurred);
DependencyContext::cleaning_end();
}
void ShenandoahUnload::purge() {
{
SuspendibleThreadSetJoiner sts;
ShenandoahCodeRoots::purge(ShenandoahHeap::heap()->workers());
}
ClassLoaderDataGraph::purge();
CodeCache::purge_exception_caches();
}
class ShenandoahUnloadRendezvousClosure : public HandshakeClosure {
public:
ShenandoahUnloadRendezvousClosure() : HandshakeClosure("ShenandoahUnloadRendezvous") {}
void do_thread(Thread* thread) {}
};
void ShenandoahUnload::unload() {
assert(ShenandoahConcurrentRoots::can_do_concurrent_class_unloading(), "Why we here?");
if (!ShenandoahHeap::heap()->is_concurrent_root_in_progress()) {
return;
}
// Unlink stale metadata and nmethods
unlink();
// Make sure stale metadata and nmethods are no longer observable
ShenandoahUnloadRendezvousClosure cl;
Handshake::execute(&cl);
// Purge stale metadata and nmethods that were unlinked
purge();
}
void ShenandoahUnload::finish() {
MetaspaceGC::compute_new_size();
MetaspaceUtils::verify_metrics();
}
|
gpl-2.0
|
muoiplus/hoangxuan
|
wp-content/plugins/wp-post-template/inic-post-template.php
|
4934
|
<?php
/*
Plugin Name: Post Template
Plugin URI: http://wordpress.org/extend/plugins/wp-post-template/
Description: WordPress allows users to customize templates for webpages but, it is not so for blog posts. Post Template plug-in from <a href="http://www.indianic.com/">IndiaNIC</a> enables you to use the customized page templates for your blog posts also.
Author: IndiaNIC
Version: 1.0
Author URI: http://profiles.wordpress.org/indianic
*/
class inic_post_template {
var $pluginPath;
private $tpl_meta_key;
private $post_ID;
public function __construct() {
$this->tpl_meta_key = 'inic_post_template';
$this->pluginPath = plugin_dir_path(__FILE__);
$this->add_action('admin_init');
$this->add_action('save_post');
$this->add_filter('single_template', 'filter_single_template');
}
function add_action($action, $function = '', $priority = 10, $accepted_args = 1) {
add_action($action, array(&$this, $function == '' ? $action : $function), $priority, $accepted_args);
}
function add_filter($filter, $function = '', $priority = 10, $accepted_args = 1) {
add_filter($filter, array(&$this, $function == '' ? $filter : $function), $priority, $accepted_args);
}
public function admin_init() {
$post_types = apply_filters('cpt_post_types', array('post'));
foreach ($post_types as $post_type) {
$this->add_meta_box('inic_post_template', __('Post Template', 'custom-post-templates'), 'inic_post_template', $post_type, 'side', 'high');
}
}
function add_meta_box($id, $title, $function = '', $page, $context = 'advanced', $priority = 'default') {
add_meta_box($id, $title, array(&$this, $function == '' ? $id : $function), $page, $context, $priority);
}
public function inic_post_template($post) {
$this->post_ID = $post->ID;
$template_vars = array();
$template_vars['templates'] = $this->get_post_templates();
$template_vars['custom_template'] = $this->get_custom_post_template();
foreach ($template_vars AS $key => $val) {
$$key = $val;
}
if ($templates) {
echo '<input type="hidden" name="inic_post_templates_present" value="1" /><select name="inic_post_templates" id="inic_post_templates">';
$_default_selected = $custom_template ? "" : " selected='selected'";
echo "<option value=\"default\"{$_default_selected}>Default Template</option>";
foreach ($templates AS $filename => $name) {
$_is_selected = $custom_template == $filename ? " selected='selected'" : "";
echo "<option value=\"{$filename}\"{$_is_selected}>{$name}</option>";
}
echo "</select>";
echo "<p>This themes have custom templates you can use for certain posts that might have additional features or custom layouts.</p>";
} else {
echo "<p>This theme has no available custom templates</p>";
}
}
protected function get_post_templates() {
$theme = wp_get_theme();
$post_templates = array();
$files = (array) $theme->get_files('php', 1);
foreach ($files as $file => $full_path) {
$headers = get_file_data($full_path, array('Template Name' => 'Template Name'));
if (empty($headers['Template Name']))
continue;
$post_templates[$file] = $headers['Template Name'];
}
return $post_templates;
}
protected function get_custom_post_template() {
$custom_template = get_post_meta($this->post_ID, $this->tpl_meta_key, true);
return $custom_template;
}
public function save_post($post_ID) {
if (!isset($_POST['inic_post_templates_present']) && !$_POST['inic_post_templates_present'])
return;
$this->post_ID = $post_ID;
delete_post_meta($this->post_ID, $this->tpl_meta_key);
if (isset($_POST['inic_post_templates']) && $_POST['inic_post_templates'] != 'default') {
add_post_meta($this->post_ID, $this->tpl_meta_key, $_POST['inic_post_templates']);
}
}
public function filter_single_template($template) {
global $wp_query;
$this->post_ID = $wp_query->post->ID;
$template_file = $this->get_custom_post_template();
if (!$template_file)
return $template;
if (file_exists(STYLESHEETPATH . DIRECTORY_SEPARATOR . $template_file)) {
return STYLESHEETPATH . DIRECTORY_SEPARATOR . $template_file;
} else if (TEMPLATEPATH . DIRECTORY_SEPARATOR . $template_file) {
return TEMPLATEPATH . DIRECTORY_SEPARATOR . $template_file;
}
return $template;
}
function is_post_template($template = '') {
if (!is_single()) {
return false;
}
global $wp_query;
$post = $wp_query->get_queried_object();
$post_template = get_post_meta($post->ID, $this->tpl_meta_key, true);
if (empty($template)) {
if (!empty($post_template)) {
return true;
}
} elseif ($template == $post_template) {
return true;
}
return false;
}
}
$inic_post_template = new inic_post_template();
?>
|
gpl-2.0
|
ccp137/GemPuzzle
|
xiaotian/GemPuzzle_XTZ/tests.cpp
|
8928
|
//
// tests.cpp -- functions for testing
//
// Written by Xiaotian Zhu
//
#include <iostream>
#include "Game.h"
void testPuzzle(){
std::cout << "Tests for Puzzle:" << std::endl;
// testing IsDefault()
std::cout << "0. testing IsDefault():" << std::endl;
Puzzle myPuzzleNeg1(3,3);
myPuzzleNeg1.Display();
std::cout << std::endl << myPuzzleNeg1.IsDefault() << std::endl;
myPuzzleNeg1.RandomSet();
myPuzzleNeg1.Display();
std::cout << std::endl << myPuzzleNeg1.IsDefault() << std::endl;
int resetArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 0};
myPuzzleNeg1.SetEntries(resetArray);
myPuzzleNeg1.Display();
std::cout << std::endl << myPuzzleNeg1.IsDefault() << std::endl;
std::cin.ignore();
// testing default constructor
std::cout << "1. testing default constructor:" << std::endl;
Puzzle myPuzzle0;
myPuzzle0.Display();
std::cin.ignore();
// testing init constructor
std::cout << "2. testing init constructor:" << std::endl;
Puzzle myPuzzle1(3,5);
myPuzzle1.Display();
std::cin.ignore();
// testing init constructor version 2
std::cout << "3. testing init constructor versioin 2:" << std::endl;
int thisArray[] = {2, 1, 7, 13, 12, 11, 16, 15, 3, 4, 5, 6, 8, 9, 10, 14, 17, 18, 19, 0, 20, 21, 22, 23};
Puzzle myPuzzle2(4,6,thisArray);
myPuzzle2.Display();
std::cin.ignore();
// testing copy constructor
std::cout << "4. testing copy constructor:" << std::endl;
Puzzle myPuzzle3 = myPuzzle2;
myPuzzle3.Display();
std::cin.ignore();
// testing deep copy assignment operator and RandomSet()
std::cout << "5. testing deep copy assignment operator:" << std::endl;
myPuzzle3 = myPuzzle1;
myPuzzle3.Display();
myPuzzle3.RandomSet();
myPuzzle3.Display();
myPuzzle1.Display();
std::cin.ignore();
// testing GetNrow(), GetNcol(), GetVblank(), GetHblank()
std::cout << "6. testing GetNrow(), GetNcol(), GetVblank(), GetHblank():" << std::endl;
std::cout << "myPuzzle3.GetNrow() -- " << myPuzzle3.GetNrow() << std::endl;
std::cout << "myPuzzle3.GetNcol() -- " << myPuzzle3.GetNcol() << std::endl;
std::cout << "myPuzzle3.GetVblank() -- " << myPuzzle3.GetVblank() << std::endl;
std::cout << "myPuzzle3.GetHblank() -- " << myPuzzle3.GetHblank() << std::endl;
std::cin.ignore();
// testing SetEntries()
std::cout << "7. testing SetEntries():" << std::endl;
Puzzle myPuzzle4(3,2);
myPuzzle4.Display();
int thatArray[] = {5, 0, 1, 4, 3, 2};
myPuzzle4.SetEntries(thatArray);
myPuzzle4.Display();
std::cin.ignore();
// testing Swap()
std::cout << "8. testing Swap():" << std::endl;
Puzzle myPuzzle6(6,6);
myPuzzle6.RandomSet();
myPuzzle6.Display();
std::cin.ignore();
myPuzzle6.Swap(BLANK_DOWN);
myPuzzle6.Display();
std::cin.ignore();
myPuzzle6.Swap(BLANK_LEFT);
myPuzzle6.Display();
std::cin.ignore();
myPuzzle6.Swap(BLANK_UP);
myPuzzle6.Display();
std::cin.ignore();
myPuzzle6.Swap(BLANK_RIGHT);
myPuzzle6.Display();
std::cin.ignore();
for(int i = 0; i < 6; i++){
myPuzzle6.Swap(BLANK_RIGHT);
myPuzzle6.Display();
std::cin.ignore();
}
for(int i = 0; i < 6; i++){
myPuzzle6.Swap(BLANK_DOWN);
myPuzzle6.Display();
std::cin.ignore();
}
for(int i = 0; i < 6; i++){
myPuzzle6.Swap(BLANK_LEFT);
myPuzzle6.Display();
std::cin.ignore();
}
for(int i = 0; i < 6; i++){
myPuzzle6.Swap(BLANK_UP);
myPuzzle6.Display();
std::cin.ignore();
}
// testing ByUser();
std::cout << "9. testing ByUser():" << std::endl;
Puzzle myPuzzle5;
myPuzzle5.ByUser();
myPuzzle5.Display();
std::cout << std::endl;
std::cin.ignore();
Puzzle myPuzzle5b(3,3);
myPuzzle5b.ByUser();
myPuzzle5b.Display();
std::cout << std::endl;
std::cin.ignore();
std::cin.get();
// testing Puzzle::operator ==
std::cout << "10. testing Puzzle::operator ==" << std::endl;
Puzzle myPuzzle7(2,2);
int tempArray1[] = {3,0,1,2};
myPuzzle7.SetEntries(tempArray1);
myPuzzle7.Display();
Puzzle myPuzzle8(2,2);
int tempArray2[] = {0,3,1,2};
myPuzzle8.SetEntries(tempArray2);
myPuzzle8.Display();
std::cout << std::endl << (myPuzzle7 == myPuzzle8) << std::endl;
myPuzzle7.Swap(BLANK_LEFT);
std::cout << std::endl << (myPuzzle7 == myPuzzle8) << std::endl;
// testing functions used in determining solvability
std::cout << "11. testing functions used in determining solvability" << std::endl;
// testing CountInversions
Puzzle myPuzzle9(4,4);
//int thatArray3[] = {8,13,1,4,2,14,0,5,3,12,10,7,11,6,9,15};
//int thatArray3[] = {6,1,10,2,7,11,4,14,5,0,9,15,8,12,13,3};
int thatArray3[] = {12,1,10,2,7,11,4,14,5,0,9,15,8,13,6,3};
int temp;
myPuzzle9.SetEntries(thatArray3);
myPuzzle9.Display();
temp = myPuzzle9.CountInversions(0, 0);
std::cout << std::endl << temp << std::endl;
// testing SumInversions
temp = myPuzzle9.SumInversions();
std::cout << std::endl << temp << std::endl;
Puzzle myPuzzle10(4,4);
//int thatArray4[] = {8,13,1,4,2,14,10,5,3,12,0,7,11,6,9,15};
//int thatArray4[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,15,14,0};
int thatArray4[] = {12,1,10,2,7,0,4,14,5,11,9,15,8,13,6,3};
myPuzzle10.SetEntries(thatArray4);
myPuzzle10.Display();
temp = myPuzzle10.SumInversions();
std::cout << std::endl << temp << std::endl;
// testing IsSolvable
bool temp2,temp3;
temp2 = myPuzzle9.IsSolvable();
std::cout << std::endl << temp2 << std::endl;
temp3 = myPuzzle10.IsSolvable();
std::cout << std::endl << temp3 << std::endl;
Puzzle myPuzzle11;
int thatArray5[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0};
myPuzzle11.SetEntries(thatArray5);
myPuzzle11.Display();
std::cout << std::endl << myPuzzle11.IsSolvable() << std::endl;
int thatArray6[] = {1,2,4,3,5,0,6,7,8,10,9,11,12,13,15,14};
myPuzzle11.SetEntries(thatArray6);
myPuzzle11.Display();
std::cout << std::endl << myPuzzle11.IsSolvable() << std::endl;
int thatArray7[] = {2,10,4,8,9,6,14,12,1,5,0,15,13,7,3,11};
myPuzzle11.SetEntries(thatArray7);
myPuzzle11.Display();
std::cout << std::endl << myPuzzle11.IsSolvable() << std::endl;
int thatArray8[] = {15,12,9,14,8,2,0,4,13,1,6,11,5,10,7,3};
myPuzzle11.SetEntries(thatArray8);
myPuzzle11.Display();
std::cout << std::endl << myPuzzle11.IsSolvable() << std::endl;
// testing Huristic()
std::cout << std::endl << "testing Huristic()" << std::endl;
Puzzle myPuzzle12;
int thatArray12[] = {2,10,4,8,9,6,14,12,1,0,5,15,13,7,3,11};
myPuzzle12.SetEntries(thatArray12);
myPuzzle12.Display();
std::cout << std::endl << myPuzzle12.Heuristic() << std::endl;
/*Puzzle myPuzzle13;
int thatArray[]={14,9,4,3,10,7,15,2,1,0,13,12,5,11,8,6};
myPuzzle13.SetEntries(thatArray);
myPuzzle13.Display();
PuzzleSearchNode myPuzzleSearchNode1(myPuzzle13,0);
myPuzzleSearchNode1.PuzzleToSolve.Display();
std::cout << std::endl << myPuzzleSearchNode1.G << " " << myPuzzleSearchNode1.H << " " << myPuzzleSearchNode1.F << std::endl;
Game myGame1;
myGame1.GetCurrentPuzzle() -> SetEntries(thatArray);
myGame1.Display();
PuzzleSearchNode Root(*(myGame1.GetCurrentPuzzle()), 0);
std::cout << std::endl << Root.G << " " << Root.H << " " << Root.F << std::endl;
Root.PuzzleToSolve.RandomSet();
myGame1.Display();
Root.PuzzleToSolve.Display();
std::cout << std::endl << Root.G << " " << Root.H << " " << Root.F << std::endl;
Root.CalcHF();
std::cout << std::endl << Root.G << " " << Root.H << " " << Root.F << std::endl;*/
}
void testGame(){
std::cout << "Tests for Game:" << std::endl;
// testing constructors etc.
std::cout << "0. testing constructors etc.:" << std::endl;
Game firstGame(3,3);
Game secondGame = firstGame;
Game thirdGame(3,3);
firstGame.Display();
secondGame.Display();
thirdGame.Display();
Game fourthGame(3,3);
secondGame = fourthGame;
thirdGame = fourthGame;
firstGame.Display();
secondGame.Display();
thirdGame.Display();
thirdGame.Display();
Game fifthGame;
std::cout << std::endl << fifthGame.IsWin() << std::endl;
/*Puzzle myPuzzle14(3,3);
int thatArray14[] = {4,0,5,8,3,2,1,6,7};
myPuzzle14.SetEntries(thatArray14);
myPuzzle14.Display();
std::cout << std::endl << myPuzzle14.IsSolvable() << std::endl;
Game myGame14(3,3);
myGame14.GetInitialPuzzle() -> SetEntries(thatArray14);
myGame14.GetCurrentPuzzle() -> SetEntries(thatArray14);
myGame14.Display();
myGame14.SolveIt();
myGame14.Display();*/
}
|
gpl-2.0
|
PowerCMS/DynamicMTML2.0
|
addons/DynamicMTML.pack/php/class.mt_log.php
|
1535
|
<?php
require_once( 'class.baseobject.php' );
class Log extends BaseObject {
public $_table = 'mt_log';
protected $_prefix = "log_";
public function Save() {
$mt = MT::get_instance();
if ( $created_on = $this->created_on ) {
if( preg_match( '/^[0-9]{14}$/', $created_on ) ) {
$this->created_on = $mt->db()->ts2db( $created_on );
}
}
if ( $modified_on = $this->modified_on ) {
if( preg_match( '/^[0-9]{14}$/', $modified_on ) ) {
$this->modified_on = $mt->db()->ts2db( $modified_on );
}
}
$driver = $mt->config( 'ObjectDriver' );
if ( strpos( $driver, 'SQLServer' ) !== FALSE ) {
// UMSSQLServer
$sql = 'select max(log_id) from mt_log';
$res = $mt->db()->Execute( $sql );
$max = $res->_array[ 0 ][ '' ];
$sql = 'SET IDENTITY_INSERT mt_log ON';
$mt->db()->Execute( $sql );
$max++;
$this->id = $max;
try {
$this->Insert();
} catch ( Exception $e ) {
// $e->getMessage();
$max += 10;
$this->id = $max;
try {
$res = $this->Insert();
} catch ( Exception $e ) {
}
}
$sql = 'SET IDENTITY_INSERT mt_log OFF';
$mt->db()->Execute( $sql );
} else {
$res = parent::Save();
}
}
}
?>
|
gpl-2.0
|
kalle404/cautious-broccoli
|
lib/plugins/dw2pdf/lang/zh/lang.php
|
263
|
<?php
/**
* @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
*
* @author oott123 <ip.192.168.1.1@qq.com>
*/
$lang['export_pdf_button'] = 'ๅฏผๅบ PDF';
$lang['empty'] = "ๆจ่ฟๆฒกๆ้ๆฉ็้กต้ขใ";
$lang['needtitle'] = "้่ฆๆๅฎๆ ้ข";
|
gpl-2.0
|
dax1216/nolimits
|
wp-content/plugins/thoughtful-comments/fv-thoughtful-comments.php
|
45204
|
<?php
/*
Plugin Name: FV Thoughtful Comments
Plugin URI: http://foliovision.com/
Description: Manage incomming comments more effectively by using frontend comment moderation system provided by this plugin.
Version: 0.2.5
Author: Foliovision
Author URI: http://foliovision.com/seo-tools/wordpress/plugins/thoughtful-comments/
The users cappable of moderate_comments are getting all of these features and are not blocked
*/
/* Copyright 2009 - 2013 Foliovision (email : programming@foliovision.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program 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 Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @package foliovision-tc
* @author Foliovision <programming@foliovision.com>
* version 0.2.5
*/
include( 'fp-api.php' );
if( class_exists('fv_tc_Plugin') ) :
class fv_tc extends fv_tc_Plugin {
/**
* Plugin directory URI
* @var string
*/
var $url;
/**
* Plugin version
* @var string
*/
var $strVersion = '0.2.5';
/**
* Class contructor. Sets all basic variables.
*/
function __construct(){
$this->url = trailingslashit( site_url() ).PLUGINDIR.'/'. dirname( plugin_basename(__FILE__) );
$this->readme_URL = 'http://plugins.trac.wordpress.org/browser/thoughtful-comments/trunk/readme.txt?format=txt';
add_action( 'in_plugin_update_message-thoughtful-comments/fv-thoughtful-comments.php', array( &$this, 'plugin_update_message' ) );
add_action( 'activate_' .plugin_basename(__FILE__), array( $this, 'activate' ) );
}
function activate() {
if( !get_option('thoughtful_comments') ) update_option( 'thoughtful_comments', array( 'shorten_urls' => true, 'reply_link' => false ) );
}
function ap_action_init()
{
// Localization
load_plugin_textdomain('fv_tc', false, dirname(plugin_basename(__FILE__)) . "/languages");
}
function admin_init() {
/*
Simple text field which is sanitized to fit into YYYY-MM-DD and only >= editors are able to edit it for themselves
*/
x_add_metadata_field( 'fv_tc_moderated', 'user', array(
'field_type' => 'text',
'label' => 'Moderation queue',
'display_column' => true,
'display_column_callback' => 'fv_tc_x_add_metadata_field'
)
);
}
function admin_menu(){
add_options_page( 'FV Thoughtful Comments', 'FV Thoughtful Comments', 'manage_options', 'manage_fv_thoughtful_comments', array($this, 'options_panel') );
}
/**
* Adds the plugin functions into Comment Moderation in backend. Hooked on comment_row_actions.
*
* @param array $actions Array containing all the actions associated with each of the comments
*
* @global object Current comment object
* @global object Post object associated with the current comment
*
* @todo Delete thread options should be displayed only fif the comment has some children, but that may be too much for the SQL server
*
* @return array Comment actions array with our new items in it.
*/
function admin($actions) {
global $comment, $post;/*, $_comment_pending_count;*/
if ( current_user_can('edit_post', $post->ID) ) {
/* If the IP isn't on the blacklist yet, display delete and ban ip link */
$banned = stripos(trim(get_option('blacklist_keys')),$comment->comment_author_IP);
$child = $this->comment_has_child($comment->comment_ID, $comment->comment_post_ID);
if($banned===FALSE)
$actions['delete_ban'] = $this->get_t_delete_ban($comment);
else
$actions['delete_ban'] = '<a href="#">' . __('Already banned!', 'fv_tc') . '</a>';
if($child>0) {
$actions['delete_thread'] = $this->get_t_delete_thread($comment);
if($banned===FALSE)
$actions['delete_thread_ban'] = $this->get_t_delete_thread_ban($comment);
/*else
$actions['delete_banned'] = '<a href="#">Already banned!</a>';*/
}
// blacklist email address
/*if(stripos(trim(get_option('blacklist_keys')),$comment->comment_author_email)!==FALSE)
$actions['blacklist_email'] = "Email Already Blacklisted";
else
$actions['blacklist_email'] = "<a href='$blacklist_email' target='_blank' class='dim:the-comment-list:comment-$comment->comment_ID:unapproved:e7e7d3:e7e7d3:new=approved vim-a' title='" . __( 'Blacklist Email' ) . "'>" . __( 'Blacklist Email' ) . '</a>';*/
}
return $actions;
}
/**
* Filter for manage_users_columns to add new column into user management table
*
* @param array $columns Array of all the columns
*
* @return array Array with added columns
*/
function column($columns) {
$columns['fv_tc_moderated'] = "Moderation queue";
return $columns;
}
/**
* Filter for manage_users_custom_column inserting the info about comment moderation into the right column
*
* @return string Column content
*/
function column_content($content) {
/* $args[0] = column content (empty), $args[1] = column name, $args[2] = user ID */
$args = func_get_args();
/* Check the custom column name */
if($args[1] == 'fv_tc_moderated') {
/* output Allow user to comment without moderation/Moderate future comments by this user by using user ID in $args[2] */
return $this->get_t_moderated($args[2],false);
}
return $content;
}
/**
* Remove the esc_html filter for admins so that the comment highlight is visible
*
* @param string $contnet Comment author name
*
* @return string Comment author name
*/
function comment_author_no_esc_html( $content ) {
if( current_user_can('manage_options') ) {
remove_filter( 'comment_author', 'esc_html' );
}
return $content;
}
/**
* Check if comment has any child
*
* @param int $id Comment ID
*
* @global object Wordpress db object
*
* @return number of child comments
*/
function comment_has_child($id, $postid) {
global $wp_query;
/// addition 2010/06/02 - check if you have comments filled in
if ($wp_query->comments != NULL ) {
foreach( $wp_query->comments AS $comment ) {
if( $comment->comment_parent == $id ) {
return true;
}
}
}
return false;
// forget about the database!
/*global $wpdb;
return $wpdb->get_var("SELECT comment_ID FROM {$wpdb->comments} WHERE comment_post_id = '{$postid}' AND comment_parent = '{$id}' LIMIT 1");
*/
}
/**
* Replace url of reply link only with #
* functionality is done only by JavaScript
*/
function comment_reply_links ($strLink = null) {
$options = get_option('thoughtful_comments');
$strReplyKeyWord = 'comment-';
if( isset( $options['tc_replyKW'] ) && !empty( $options[ 'tc_replyKW' ] ) ) {
$strReplyKeyWord = $options['tc_replyKW'];
}
$strLink = preg_replace(
'~href="([^"]*)"~' ,
'href="$1' . urlencode( '#' . $strReplyKeyWord . get_comment_ID() ) . '"',
$strLink
);
if ($options['reply_link']) {
$noscript = '<noscript>' . __('Reply link does not work in your browser because JavaScript is disabled.', 'fv_tc') . '<br /></noscript>';
$link_script = preg_replace( '~href.*onclick~' , 'href="#" onclick' , $strLink );
return $noscript . $link_script;
}
return $strLink;
}
/**
* Clear the URI for use in onclick events.
*
* @param string The original URI
*
* @return string Cleaned up URI
*/
function esc_url($url) {
if(function_exists('esc_url'))
return esc_url($url);
/* Legacy WP support */
else
return clean_url($url);
}
/**
* Filter for comment_text. Displays frontend moderation options if user can edit posts.
*
* @param string $content Comment text.
*
* @global int Current user ID
* @global object Current comment object
*
* @return string Comment text with added features.
*/
function frontend ($content) {
if( is_admin() ) {
return $content;
}
global $user_ID, $comment, $post;
$user_info = get_userdata($comment->user_id);
//if($user_ID && current_user_can('edit_post', $post->ID) && !is_admin()) {
if( current_user_can('manage_options') ) {
$child = $this->comment_has_child($comment->comment_ID, $comment->comment_post_ID);
/* Container */
$out = '<p class="tc-frontend">';
/* Approve comment */
if($comment->comment_approved == '0') {
$out .= '<span id="comment-'.$comment->comment_ID.'-approve">'.$this->get_t_approve($comment).' | </span>';
}
/* Delete comment */
$out .= $this->get_t_delete($comment).' | ';
/* Delete thread */
if($child>0) {
$out .= $this->get_t_delete_thread($comment).' | ';
}
/* If IP isn't banned */
if(stripos(trim(get_option('blacklist_keys')),$comment->comment_author_IP)===FALSE) {
/* Delete and ban */
$out .= $this->get_t_delete_ban($comment);//.' | ';
/* Delete thread and ban */
if($child>0)
$out .= ' | '.$this->get_t_delete_thread_ban($comment);
} else {
$out .= 'IP '.$comment->comment_author_IP.' ';
$out .= __('already banned!', 'fv_tc' );
}
/* Moderation status */
if( $user_info && $user_info->user_level < 3) {
$out .= '<br />'.$this->get_t_moderated($comment->user_id);
} else if( $user_info && $user_info->user_level >= 3 ) {
$out .= '<br /><abbr title="' . __('Comments from this user level are automatically approved', 'fv_tc') . '">' . __('Power user', 'fv_tc') . '</a>';
}
$out .= '</p>';
$out .= '<span id="fv-tc-comment-'.$comment->comment_ID.'"></span>';
return $content . $out;
}
return $content;
}
function get_js_translations() {
$aStrings = Array(
'comment_delete' => __('Do you really want to delete this comment?', 'fv_tc'),
'delete_error' => __('Error deleting comment', 'fv_tc'),
'comment_delete_ban_ip' => __('Do you really want to delete this comment and ban the IP?', 'fv_tc'),
'comment_delete_replies' => __('Do you really want to delete this comment and all the replies?', 'fv_tc'),
'comment_delete_replies_ban_ip' => __('Do you really want to delete this comment with all the replies and ban the IP?', 'fv_tc'),
'moderate_future' => __('Moderate future comments by this user','fv_tc'),
'unmoderate' => __('Unmoderated','fv_tc'),
'without_moderation' => __('Allow user to comment without moderation','fv_tc'),
'moderate' => __('Moderated','fv_tc'),
'mod_error' => __('Error','fv_tc'),
'wait' => __('Wait...', 'fv_tc'),
);
return $aStrings;
}
/**
* Generate the anchor for approve function
*
* @param object $comment Comment object
*
* @return string HTML of the anchor
*/
function get_t_approve($comment) {
return '<a href="#" onclick="fv_tc_approve('.$comment->comment_ID.'); return false">' . __('Approve', 'fv_tc') . '</a>';
//return '<a href="#" onclick="fv_tc_approve('.$comment->comment_ID.',\''.$this->esc_url( wp_nonce_url($this->url.'/ajax.php','fv-tc-approve_' . $comment->comment_ID)).'\', \''. __('Wait...', 'fv_tc').'\'); return false">' . __('Approve', 'fv_tc') . '</a>';
}
/**
* Generate the anchor for delete function
*
* @param object $comment Comment object
*
* @return string HTML of the anchor
*/
function get_t_delete($comment) {
return '<a href="#" onclick="fv_tc_delete('.$comment->comment_ID.'); return false">' . __('Delete', 'fv_tc') . '</a>';
}
/**
* Generate the anchor for delete and ban IP function
*
* @param object $comment Comment object
*
* @return string HTML of the anchor
*/
function get_t_delete_ban($comment) {
return '<a href="#" onclick="fv_tc_delete_ban('.$comment->comment_ID.',\''.$comment->comment_author_IP.'\'); return false">' . __('Delete & Ban IP', 'fv_tc') . '</a>';
}
/**
* Generate the anchor for delete thread function
*
* @param object $comment Comment object
*
* @return string HTML of the anchor
*/
function get_t_delete_thread($comment) {
return '<a href="#" onclick="fv_tc_delete_thread('.$comment->comment_ID.'); return false">' . __('Delete Thread', 'fv_tc') . '</a>';
}
/**
* Generate the anchor for delete thread and ban IP function
*
* @param object $comment Comment object
*
* @return string HTML of the anchor
*/
function get_t_delete_thread_ban($comment) {
return '<a href="#" onclick="fv_tc_delete_thread_ban('.$comment->comment_ID.',\''.$comment->comment_author_IP.'\'); return false">' . __('Delete Thread & Ban IP','fv_tc') . '</a>';
}
/**
* Generate the anchor for auto approving function
*
* @param object $comment Comment object
* @param bool $frontend Alters the anchor text if the function is used in backend.
*
* @return string HTML of the anchor
*/
function get_t_moderated($user_ID, $frontend = true) {
if($frontend)
$frontend2 = 'true';
else
$frontend2 = 'false';
$out = '<a href="#" class="commenter-'.$user_ID.'-moderated" onclick="fv_tc_moderated('.$user_ID.', '. $frontend2 .'); return false">';
if(!get_user_meta($user_ID,'fv_tc_moderated'))
if($frontend)
$out .= __('Allow user to comment without moderation','fv_tc') . '</a>';
else
$out .= __('Moderated', 'fv_tc') . '</a>';
else
if($frontend)
$out .= __('Moderate future comments by this user', 'fv_tc') . '</a>';
else
$out .= __('Unmoderated', 'fv_tc') . '</a>';
return $out;
}
/**
* Filter for pre_comment_approved. Skip moderation queue if the user is allowed to comment without moderation
*
* @params string $approved Current moderation queue status
*
* @global int Comment author user ID
*
* @return string New comment status
*/
function moderate($approved) {
global $user_ID;
///////////////////////////
/*global $wp_filter;
var_dump($wp_filter['pre_comment_approved']);
echo '<h3>before: </h3>';
var_dump($approved);
echo '<h3>fv_tc actions: </h3>';
if(get_user_meta($user_ID,'fv_tc_moderated')) {
echo '<p>putting into approved</p>';
}
else {
echo '<p>putting into unapproved</p>';
}
die('end');*/
/////////////////////////
if(get_user_meta($user_ID,'fv_tc_moderated'))
return true;
return $approved;
}
function options_panel() {
if (!empty($_POST)) :
check_admin_referer('thoughtful_comments');
$options = array(
'shorten_urls' => ( $_POST['shorten_urls'] ) ? true : false,
'reply_link' => ( $_POST['reply_link'] ) ? true : false,
'tc_replyKW' => isset( $_POST['tc_replyKW'] ) ? $_POST['tc_replyKW'] : 'comment-'
);
if( update_option( 'thoughtful_comments', $options ) ) :
?>
<div id="message" class="updated fade">
<p>
<strong>
<?php _e('Settings saved', 'fv_tc'); ?>
</strong>
</p>
</div>
<?php
endif; // update_option
endif; // $_POST
$options = get_option('thoughtful_comments');
?>
<div class="wrap">
<div style="position: absolute; right: 20px; margin-top: 5px">
<a href="http://foliovision.com/seo-tools/wordpress/plugins/thoughtful-comments" target="_blank" title="Documentation"><img alt="visit foliovision" src="http://foliovision.com/shared/fv-logo.png" /></a>
</div>
<div>
<div id="icon-options-general" class="icon32"><br /></div>
<h2>FV Thoughtful Comments</h2>
</div>
<form method="post" action="">
<?php wp_nonce_field('thoughtful_comments') ?>
<div id="poststuff" class="ui-sortable">
<div class="postbox">
<h3>
<?php _e('Comment Tweaks', 'fv_tc') ?>
</h3>
<div class="inside">
<table class="optiontable form-table">
<tr valign="top">
<th scope="row"><?php _e('Link shortening', 'fv_tc'); ?> </th>
<td><fieldset><legend class="screen-reader-text"><span><?php _e('Link shortening', 'fv_tc'); ?></span></legend>
<input id="shorten_urls" type="checkbox" name="shorten_urls" value="1"
<?php if( $options['shorten_urls'] ) echo 'checked="checked"'; ?> />
<label for="shorten_urls"><span><?php _e('Shortens the plain URL link text in comments to "link to: domain.com". Prevents display issues if the links have too long URL.', 'fv_tc'); ?></span></label><br />
</td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('Reply link', 'fv_tc'); ?> </th>
<td><fieldset><legend class="screen-reader-text"><span><?php _e('Reply link', 'fv_tc'); ?></span></legend>
<input id="reply_link" type="checkbox" name="reply_link" value="1"
<?php if( $options['reply_link'] ) echo 'checked="checked"'; ?> />
<label for="reply_link"><span><?php _e('Check to make comment reply links use JavaScript only. Useful if your site has a lot of comments and web crawlers are browsing through all of their reply links.', 'fv_tc'); ?></span></label><br />
</td>
</tr>
<?php
$bCommentReg = get_option( 'comment_registration' );
if( isset( $bCommentReg ) && 1 == $bCommentReg ) { ?>
<tr valign="top">
<th scope="row"><?php _e('Reply link Keyword', 'fv_tc'); ?> </th>
<td><fieldset><legend class="screen-reader-text"><span><?php _e('Reply link', 'fv_tc'); ?></span></legend>
<input id="tc_replyKW" type="text" name="tc_replyKW" size="10"
value="<?php if( isset( $options['tc_replyKW'] ) ) echo $options['tc_replyKW']; else echo 'comment-'; ?>" />
<label for="tc_replyKW"><span><?php _e('<strong>Advanced!</strong> Only change this if your "Log in to Reply" link doesn\'t bring the commenter back to the comment they wanted to comment on after logging in.', 'fv_tc'); ?></span></label><br />
</td>
</tr>
<?php } ?>
</table>
<p>
<input type="submit" name="fv_feedburner_replacement_submit" class="button-primary" value="<?php _e('Save Changes', 'fv_tc') ?>" />
</p>
</div>
</div>
</div>
</form>
</div>
<?php
}
/**
* Action for wp_print_scripts - enqueues plugin js which is dependend on jquery. Improved in 0.2.3 ////
*
* @global int Current user ID
*/
function scripts() {
if( current_user_can('moderate_comments') ) {
wp_enqueue_script('fv_tc',$this->url. '/js/fv_tc.js',array('jquery'), $this->strVersion);
wp_localize_script('fv_tc', 'fv_tc_translations', $this->get_js_translations());
wp_localize_script('fv_tc', 'fv_tc_ajaxurl', admin_url('admin-ajax.php'));
}
}
/**
* Filter for comments_number. Shows number of unapproved comments for every article in the frontend if the user can edit the post. In WP, all the unapproved comments are shown both to contributors and authors in wp-admin, but we don't do that in frontend.
*
* @global int Current user ID
* @global object Current post object
*
* @param string $content Text containing the number of comments.
*
* @return string Number of comments with inserted number of unapproved comments.
*/
function show_unapproved_count($content) {
global $user_ID;
global $post;
if($user_ID && current_user_can('edit_post', $post->ID)) {
if(function_exists('get_comments'))
$comments = get_comments( array('post_id' => $post->ID, 'order' => 'ASC', 'status' => 'hold') );
/* Legacy WP support */
else {
global $wpdb;
$comments = $wpdb->get_results("SELECT * FROM {$wpdb->comments} WHERE comment_post_ID = {$post->ID} AND comment_approved = '0' ORDER BY comment_date ASC");
}
$count = count($comments);
if($count!= 0) {
//return '<span class="tc_highlight"><abbr title="This post has '.$count.' unapproved comments">'.str_ireplace(' comm','/'.$count.'</abbr></span> comm',$content).'';
$content = preg_replace( '~(\d+)~', '<span class="tc_highlight"><abbr title="' . sprintf( _n( 'This post has one unapproved comment.', 'This post has %d unapproved comments.', $count, 'fv_tc' ), $count ) . '">$1</abbr></span>', $content );
return $content;
}
}
return $content;
}
/**
* Styling for the plugin
*/
function styles() {
global $post;
// this is executed in the header, so we can't do the check for every post on index/archive pages, so we better load styles if there are any unapproved comments to show. it's loaded even for contributors which don't need it.
if(!is_admin() && current_user_can('edit_posts')) {
echo '<link rel="stylesheet" href="'.$this->url.'/css/frontend.css" type="text/css" media="screen" />';
}
}
/**
* Thesis is not using comment_text filter. It uses thesis_hook_after_comment action, so this outputs our links
*
* @param string $new_status Empty string.
*/
function thesis_frontend_show($content) {
echo $this->frontend($content);
}
/**
* Call hooks for when a comment status transition occurs.
*
* @param string $new_status New comment status.
* @param string $old_status Previous comment status.
* @param object $comment Comment data.
*/
function transition_comment_status( $new_status, $old_status, $comment ) {
global $wpdb;
if( $old_status == 'trash' && $new_status != 'spam' ) { // restoring comment
$children = get_comment_meta( $comment->comment_ID, 'children', true );
if( $children && is_array( $children ) ) {
$children = implode( ',', $children );
$wpdb->query( "UPDATE $wpdb->comments SET comment_parent = '{$comment->comment_ID}' WHERE comment_ID IN ({$children}) " );
}
delete_comment_meta( $comment->comment_ID, 'children' );
}
if( $new_status == 'trash' ) { // trashing comment
if( function_exists( 'update_comment_meta' ) ) { // store children in meta
$children = $wpdb->get_col( "SELECT comment_ID FROM $wpdb->comments WHERE comment_parent = '{$comment->comment_ID}' " );
if( $children ) {
update_comment_meta( $comment->comment_ID, 'children', $children );
}
} // assign new parents
$wpdb->query( "UPDATE $wpdb->comments SET comment_parent = '{$comment->comment_parent}' WHERE comment_parent = '{$comment->comment_ID}' " );
/*var_dump( $old_status );
echo ' -> ';
var_dump( $new_status ); // approved
die();*/
}
}
/**
* Shows unapproved comments bellow posts if user can moderate_comments. Hooked to comments_array. In WP, all the unapproved comments are shown both to contributors and authors in wp-admin, but we don't do that in frontend.
*
* @param array $comments Original array of the post comments, that means only the approved comments.
* @global int Current user ID.
* @global object Current post object.
*
* @return array Array of both approved and unapproved comments.
*/
function unapproved($comments) {
global $user_ID;
global $post;
/*if( count($comments) > 200 ) {
remove_filter( 'comment_text', 'wptexturize' );
remove_filter( 'comment_text', 'convert_smilies', 20 );
remove_filter( 'comment_text', 'wpautop', 30 );
add_filter( 'comment_text', array( $this, 'wpautop_lite' ), 30 );
}*/
/* Check user permissions */
if($user_ID && current_user_can('edit_post', $post->ID)) {
/* Use the standard WP function to get the comments */
if(function_exists('get_comments'))
$comments = get_comments( array('post_id' => $post->ID, 'order' => 'ASC') );
/* Use DB query for older WP versions */
else {
global $wpdb;
$comments = $wpdb->get_results("SELECT * FROM {$wpdb->comments} WHERE comment_post_ID = {$post->ID} AND comment_approved != 'spam' ORDER BY comment_date ASC");
}
/* Target array where both approved and unapproved comments are added */
$new_comments = array();
foreach($comments AS $comment) {
/* Don't display the spam comments */
if($comment->comment_approved == 'spam')
continue;
/* Highlight the comment author in case the comment isn't approved yet */
if($comment->comment_approved == '0') {
/* Alternative - highlight the comment content */
//$comment->comment_content = '<div id="comment-'.$comment->comment_ID.'-unapproved" style="background: #ffff99;">'.$comment->comment_content.'</div>';
$comment->comment_author = '<span id="comment-'.$comment->comment_ID.'-unapproved" class="tc_highlight">'.$comment->comment_author.'</span>';
}
$new_comments[] = $comment;
}
return $new_comments;
}
return $comments;
}
/* Experimental stuff */
/* mess with the WP blacklist mechanism */
function blacklist($author) {
$args = func_get_args();
echo '<p>'.$args[0].', '.$args[1].', '.$args[2].', '.$args[3].', '.$args[4].', '.$args[5].'</p>';
//die('blacklist dies');
}
function comment_moderation_headers( $message_headers ) {
$options = get_option('thoughtful_comments');
if( $options['enhance_notify'] == false && isset( $options['enhance_notify'] ) ) return $message_headers;
$message_headers .= "\r\n"."Content-Type: text/html"; // this should add up
return $message_headers;
}
function comment_moderation_text( $notify_message ) {
$options = get_option('thoughtful_comments');
if( $options['enhance_notify'] == false && isset( $options['enhance_notify'] ) ) return $notify_message;
global $wpdb;
preg_match( '~&c=(\d+)~', $notify_message, $comment_id ); // we must get the comment ID somehow
$comment_id = $comment_id[1];
if( intval( $comment_id ) > 0 ) {
/// all links until now are non-html, so we add it now
$notify_message = preg_replace( '~([^"\'])(http://\S*)([^"\'])~', '$1<a href="$2">$2</a>$3', $notify_message );
$comment = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_ID=%d LIMIT 1", $comment_id));
$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID=%d LIMIT 1", $comment->comment_post_ID));
$rows = explode( "\n", $comment->comment_content );
foreach( $rows AS $key => $value ) {
$rows[$key] = '> '.$value;
}
$content = "\r\n\r\n".implode( "\n", $rows );
$sApproveTranslated = substr(__('Approve it: %s'), 0, strlen(__('Approve it: %s')) - 3);
$replyto = __('Reply to comment via email', 'fv_tc') . ': <a href="mailto:'.rawurlencode('"'.$comment->comment_author.'" ').'<'.$comment->comment_author_email.'>'.'?subject='.rawurlencode( __('Your comment on', 'fv_tc') . ' "'.$post->post_title.'"' ).'&body='.rawurlencode( $content ).'&bcc='.$options['reply_bcc'].'">' . __('Email reply', 'fv_tc') . '</a>'."\r\n";
$linkto .= __('Link to comment', 'fv_tc') . ': <a href="'.get_permalink($comment->comment_post_ID) . '#comment-'.$comment_id.'">' . __('Comment link', 'fv_tc') . '</a>'."\r\n";
$notify_message = str_replace( $sApproveTranslated, $replyto.$sApproveTranslated, $notify_message );
$notify_message = str_replace( $sApproveTranslated, $linkto.$sApproveTranslated, $notify_message );
$notify_message = wpautop( $notify_message );
}
//echo $notify_message; die();
return $notify_message;
}
/**
* Callback for plain link replacement in links
*
* @param string Link
*
* @return string New link
*/
function comment_links_replace( $link ) {
//echo '<!--link'.var_export( $link, true ).'-->';
/*if( !stripos( $link[1], '://' ) ) {
return $link[0];
}*/
$match_domain = $link[2];
$match_domain = str_replace( '://www.', '://', $match_domain );
preg_match( '!//(.+?)/!', $match_domain, $domain );
//var_dump( $domain );
$link = $link[1].'<a href="'.esc_url($link[2]).'">' . __('link to', 'fv_tc') . ' '.$domain[1].'</a><br />'.$link[3];
return $link;
}
/**
* Callback for <a href="LINK">LINK</a> replacement in comments
*
* @param string Link
*
* @return string New link
*/
function comment_links_replace_2( $link ) {
preg_match( '~href=["\'](.*?)["\']~', $link[0], $href );
preg_match( '~>(.*?)</a>~', $link[0], $text );
if( $href[1] == $text[1] ) {
preg_match( '!//(.+?)/!', $text[1], $domain );
if( $domain[1] ) {
$domain[1] = preg_replace( '~^www\.~', '', $domain[1] );
$link[0] = str_replace( $text[1].'</a>', __('link to', 'fv_tc') . ' '.$domain[1].'</a>', $link[0] );
}
}
return $link[0];
}
/**
* Replace long links with shorter versions
*
* @param string Comment text
*
* @return string New comments text
*/
function comment_links( $content ) {
$options = get_option('thoughtful_comments');
if( $options['shorten_urls'] == false && isset( $options['shorten_urls'] ) ) return $content;
$content = ' ' . $content;
$content = preg_replace_callback( '!<a[\s\S]*?</a>!', array(get_class($this), 'comment_links_replace_2' ), $content );
return $content;
}
function stc_comment_deleted() {
global $wp_subscribe_reloaded;
if( !is_admin() && $wp_subscribe_reloaded ) {
add_action('deleted_comment', array( $wp_subscribe_reloaded, 'comment_deleted'));
}
}
function stc_comment_status_changed() {
global $wp_subscribe_reloaded;
if( !is_admin() && $wp_subscribe_reloaded ) {
add_action('wp_set_comment_status', array( $wp_subscribe_reloaded, 'comment_status_changed'));
}
}
function users_cache( $comments ) {
global $wpdb;
if( $comments !== NULL && count( $comments ) > 0 ) {
$all_IDs = array();
foreach( $comments AS $comment ) {
$all_IDs[] = $comment->user_id;
}
$all_IDs = array_unique( $all_IDs );
$all_IDs_string = implode (',', $all_IDs );
$all_IDs_users = $wpdb->get_results( "SELECT * FROM `{$wpdb->users}` WHERE ID IN ({$all_IDs_string}) " );
$all_IDs_meta = $wpdb->get_results( "SELECT * FROM `{$wpdb->usermeta}` WHERE user_id IN ({$all_IDs_string}) ORDER BY user_id " );
//echo '<!--meta'.var_export( $all_IDs_meta, true ).'-->';
$meta_cache = array();
foreach( $all_IDs_meta AS $all_IDs_meta_item ) {
$meta_cache[$all_IDs_meta_item->user_id][] = $all_IDs_meta_item;
}
foreach( $all_IDs_users AS $all_IDs_users_item ) {
foreach( $meta_cache[$all_IDs_users_item->ID] AS $meta ) {
$value = maybe_unserialize($meta->meta_value);
// Keys used as object vars cannot have dashes.
$key = str_replace('-', '', $meta->meta_key);
$all_IDs_users_item->{$key} = $value;
}
wp_cache_set( $all_IDs_users_item->ID, $all_IDs_users_item, 'users' );
wp_cache_add( $all_IDs_users_item->user_login, $all_IDs_users_item->ID, 'userlogins');
wp_cache_add( $all_IDs_users_item->user_email, $all_IDs_users_item->ID, 'useremail');
wp_cache_add( $all_IDs_users_item->user_nicename, $all_IDs_users_item->ID, 'userslugs');
}
$column = esc_sql( 'user_id');
$cache_key = 'user_meta';
if ( !empty($all_IDs_meta) ) {
foreach ( $all_IDs_meta as $metarow) {
$mpid = intval($metarow->{$column});
$mkey = $metarow->meta_key;
$mval = $metarow->meta_value;
// Force subkeys to be array type:
if ( !isset($cache[$mpid]) || !is_array($cache[$mpid]) )
$cache[$mpid] = array();
if ( !isset($cache[$mpid][$mkey]) || !is_array($cache[$mpid][$mkey]) )
$cache[$mpid][$mkey] = array();
// Add a value to the current pid/key:
$cache[$mpid][$mkey][] = $mval;
}
}
foreach ( $all_IDs as $id ) {
if ( ! isset($cache[$id]) )
$cache[$id] = array();
wp_cache_add( $id, $cache[$id], $cache_key );
}
}
return $comments;
}
function mysql2date_lite($dateformatstring, $mysqlstring, $use_b2configmonthsdays = 1) {
global $month, $weekday;
$m = $mysqlstring;
if (empty($m)) {
return false;
}
$i = mktime(substr($m,11,2),substr($m,14,2),substr($m,17,2),substr($m,5,2),substr($m,8,2),substr($m,0,4));
if (!empty($month) && !empty($weekday) && $use_b2configmonthsdays) {
$datemonth = $month[date('m', $i)];
$dateweekday = $weekday[date('w', $i)];
$dateformatstring = ' '.$dateformatstring;
$dateformatstring = preg_replace("/([^\\\])D/", "\\1".backslashit(substr($dateweekday, 0, 3)), $dateformatstring);
$dateformatstring = preg_replace("/([^\\\])F/", "\\1".backslashit($datemonth), $dateformatstring);
$dateformatstring = preg_replace("/([^\\\])l/", "\\1".backslashit($dateweekday), $dateformatstring);
$dateformatstring = preg_replace("/([^\\\])M/", "\\1".backslashit(substr($datemonth, 0, 3)), $dateformatstring);
$dateformatstring = substr($dateformatstring, 1, strlen($dateformatstring)-1);
}
$j = @date($dateformatstring, $i);
if (!$j) {
// for debug purposes
// echo $i." ".$mysqlstring;
}
return $j;
}
function wpautop_lite( $comment_text ) {
if( stripos($comment_text,'<p') === false ) {
//$aParagraphs = explode( "\n", $comment_text );
$pee = $comment_text;
$br = 1;
/*
Taken from WP 1.0.1-miles
*/
$pee = $pee . "\n"; // just to make things a little easier, pad the end
$pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
$pee = preg_replace('!(<(?:table|tr|td|th|div|ul|ol|li|pre|select|form|blockquote|p|h[1-6])[^>]*>)!', "\n$1", $pee); // Space things out a little
$pee = preg_replace('!(</(?:table|tr|td|th|div|ul|ol|li|pre|select|form|blockquote|p|h[1-6])>)!', "$1\n", $pee); // Space things out a little
$pee = preg_replace("/(\r\n|\r)/", "\n", $pee); // cross-platform newlines
$pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
$pee = preg_replace('/\n?(.+?)(?:\n\s*\n|\z)/s', "\t<p>$1</p>\n", $pee); // make paragraphs, including one at the end
$pee = preg_replace('|<p>\s*?</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
$pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
$pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
$pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
$pee = preg_replace('!<p>\s*(</?(?:table|tr|td|th|div|ul|ol|li|pre|select|form|blockquote|p|h[1-6])[^>]*>)!', "$1", $pee);
$pee = preg_replace('!(</?(?:table|tr|td|th|div|ul|ol|li|pre|select|form|blockquote|p|h[1-6])[^>]*>)\s*</p>!', "$1", $pee);
if ($br) $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
$pee = preg_replace('!(</?(?:table|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|blockquote|p|h[1-6])[^>]*>)\s*<br />!', "$1", $pee);
$pee = preg_replace('!<br />(\s*</?(?:p|li|div|th|pre|td|ul|ol)>)!', '$1', $pee);
$pee = preg_replace('/&([^#])(?![a-z]{1,8};)/', '&$1', $pee);
$comment_text = $pee;
}
return $comment_text;
}
function fv_tc_approve() {
if(!wp_set_comment_status( $_REQUEST['id'], 'approve' ))
die('db error');
}
function fv_tc_delete() {
//check_admin_referer('fv-tc-delete_' . $_GET['id']);
if (isset($_REQUEST['thread'])) {
if($_REQUEST['thread'] == 'yes') {
$this->fv_tc_delete_recursive($_REQUEST['id']);
}
} else {
if(!wp_delete_comment($_REQUEST['id']))
die('db error');
}
if(isset($_REQUEST['ip']) && stripos(trim(get_option('blacklist_keys')),$_REQUEST['ip'])===FALSE) {
$blacklist_keys = trim(stripslashes(get_option('blacklist_keys')));
$blacklist_keys_update = $blacklist_keys."\n".$_REQUEST['ip'];
update_option('blacklist_keys', $blacklist_keys_update);
}
}
function fv_tc_moderated() {
if(get_user_meta($_REQUEST['id'],'fv_tc_moderated')) {
if(!delete_user_meta($_REQUEST['id'],'fv_tc_moderated'))
die('meta error');
echo 'user moderated';
}
else {
if(!update_user_meta($_REQUEST['id'],'fv_tc_moderated','no'))
die('meta error');
echo 'user non-moderated';
}
}
function fv_tc_delete_recursive($id) {
global $wpdb;
echo ' '.$id.' ';
$comments = $wpdb->get_results("SELECT * FROM {$wpdb->comments} WHERE `comment_parent` ='{$id}'",ARRAY_A);
if(strlen($wpdb->last_error)>0)
die('db error');
if(!wp_delete_comment($id))
die('db error');
/* If there are no more children */
if(count($comments)==0)
return;
foreach($comments AS $comment) {
$this->fv_tc_delete_recursive($comment['comment_ID']);
}
}
}
$fv_tc = new fv_tc;
add_action( 'wp_ajax_fv_tc_approve', array( $fv_tc,'fv_tc_approve'));
add_action( 'wp_ajax_fv_tc_delete', array( $fv_tc,'fv_tc_delete'));
add_action( 'wp_ajax_fv_tc_moderated', array( $fv_tc,'fv_tc_moderated'));
/*
Special for 'Custom Metadata Manager' plugin
*/
function fv_tc_x_add_metadata_field( $field_slug, $field, $object_type, $object_id, $value ) { echo '<!--fvtc-column-->';
global $fv_tc;
return $fv_tc->column_content( $field, $field_slug, $object_id );
}
/* Add extra backend moderation options */
add_filter( 'comment_row_actions', array( $fv_tc, 'admin' ) );
if( function_exists( 'x_add_metadata_field' ) ) {
/*
Special for 'Custom Metadata Manager' plugin
*/
add_filter( 'admin_init', array( $fv_tc, 'admin_init' ) );
} else {
/* Add new column into Users management */
add_filter( 'manage_users_columns', array( $fv_tc, 'column' ) );
/* Put the content into the new column in Users management; there are 3 arguments passed to the filter */
add_filter( 'manage_users_custom_column', array( $fv_tc, 'column_content' ), 10, 3 );
}
/* Add frontend moderation options */
add_filter( 'comment_text', array( $fv_tc, 'frontend' ) );
/* Shorten plain links */
add_filter( 'comment_text', array( $fv_tc, 'comment_links' ), 100 );
/* Thesis theme fix */
add_action( 'thesis_hook_after_comment', array( $fv_tc, 'thesis_frontend_show' ), 1 );
/* Thesis theme fix */
add_filter( 'thesis_comment_text', array( $fv_tc, 'comment_links' ), 100 );
/* Approve comment if user is set out of moderation queue */
add_filter( 'pre_comment_approved', array( $fv_tc, 'moderate' ) );
/* Load js */
add_action( 'wp_print_scripts', array( $fv_tc, 'scripts' ) );
/* Show number of unapproved comments in frontend */
add_filter( 'comments_number', array( $fv_tc, 'show_unapproved_count' ) );
//add_filter( 'get_comments_number', array( $fp_ecm, 'show_unapproved_count' ) );
/* Styles */
add_action('wp_print_styles', array( $fv_tc, 'styles' ) );
/* Show unapproved comments bellow posts */
add_filter( 'comments_array', array( $fv_tc, 'unapproved' ) );
/* Cache users */
add_filter( 'comments_array', array( $fv_tc, 'users_cache' ) );
/* Bring back children of deleted comments */
add_action( 'transition_comment_status', array( $fv_tc, 'transition_comment_status' ), 1000, 3 );
/* Admin's won't get the esc_html filter */
add_filter( 'comment_author', array( $fv_tc, 'comment_author_no_esc_html' ), 0 );
/* Experimental stuff */
/* Override Wordpress Blacklisting */
//add_action( 'wp_blacklist_check', array( $fv_tc, 'blacklist' ), 10, 7 );
endif;
add_filter( 'comment_moderation_headers', array( $fv_tc, 'comment_moderation_headers' ) );
add_filter( 'comment_moderation_text', array( $fv_tc, 'comment_moderation_text' ) );
/* Fix for Subscribe to Comments Reloaded */
add_action('deleted_comment', array( $fv_tc, 'stc_comment_deleted'), 0, 1);
add_action('wp_set_comment_status', array( $fv_tc, 'stc_comment_status_changed'), 0, 1);
add_action( 'admin_menu', array($fv_tc, 'admin_menu') );
add_filter('comment_reply_link', array($fv_tc, 'comment_reply_links'));
add_action('init', array($fv_tc, 'ap_action_init'));
|
gpl-2.0
|
SpoonLabs/astor
|
examples/chart_11/source/org/jfree/chart/editor/ChartEditorFactory.java
|
1946
|
/* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2007, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* -----------------------
* ChartEditorFactory.java
* -----------------------
* (C) Copyright 2005-2007, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): ;
*
* Changes
* -------
* 28-Nov-2005 : Version 1 (DG);
*
*/
package org.jfree.chart.editor;
import org.jfree.chart.JFreeChart;
/**
* A factory for creating new {@link ChartEditor} instances.
*/
public interface ChartEditorFactory {
/**
* Creates an editor for the given chart.
*
* @param chart the chart.
*
* @return A chart editor.
*/
public ChartEditor createEditor(JFreeChart chart);
}
|
gpl-2.0
|
AndyPeterman/mrmc
|
xbmc/settings/windows/GUIWindowSettingsScreenCalibration.cpp
|
15027
|
/*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program 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 Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "system.h"
#include "GUIWindowSettingsScreenCalibration.h"
#include "guilib/GUIMoverControl.h"
#include "guilib/GUIResizeControl.h"
#ifdef HAS_VIDEO_PLAYBACK
#include "cores/VideoRenderers/RenderManager.h"
#endif
#include "Application.h"
#include "settings/DisplaySettings.h"
#include "settings/Settings.h"
#include "guilib/GUIWindowManager.h"
#include "dialogs/GUIDialogYesNo.h"
#include "input/Key.h"
#include "guilib/LocalizeStrings.h"
#include "utils/log.h"
#include "utils/StringUtils.h"
#include "utils/Variant.h"
#include "windowing/WindowingFactory.h"
#include <string>
#include <utility>
#define CONTROL_LABEL_ROW1 2
#define CONTROL_LABEL_ROW2 3
#define CONTROL_TOP_LEFT 8
#define CONTROL_BOTTOM_RIGHT 9
#define CONTROL_SUBTITLES 10
#define CONTROL_PIXEL_RATIO 11
#define CONTROL_VIDEO 20
#define CONTROL_NONE 0
CGUIWindowSettingsScreenCalibration::CGUIWindowSettingsScreenCalibration(void)
: CGUIWindow(WINDOW_SCREEN_CALIBRATION, "SettingsScreenCalibration.xml")
{
m_iCurRes = 0;
m_iControl = 0;
m_fPixelRatioBoxHeight = 0.0f;
m_needsScaling = false; // we handle all the scaling
}
CGUIWindowSettingsScreenCalibration::~CGUIWindowSettingsScreenCalibration(void)
{}
bool CGUIWindowSettingsScreenCalibration::OnAction(const CAction &action)
{
switch (action.GetID())
{
case ACTION_CALIBRATE_SWAP_ARROWS:
{
NextControl();
return true;
}
break;
case ACTION_CALIBRATE_RESET:
{
CGUIDialogYesNo* pDialog = (CGUIDialogYesNo*)g_windowManager.GetWindow(WINDOW_DIALOG_YES_NO);
pDialog->SetHeading(CVariant{20325});
std::string strText = StringUtils::Format(g_localizeStrings.Get(20326).c_str(), g_graphicsContext.GetResInfo(m_Res[m_iCurRes]).strMode.c_str());
pDialog->SetLine(0, CVariant{std::move(strText)});
pDialog->SetLine(1, CVariant{20327});
pDialog->SetChoice(0, CVariant{222});
pDialog->SetChoice(1, CVariant{186});
pDialog->Open();
if (pDialog->IsConfirmed())
{
g_graphicsContext.ResetScreenParameters(m_Res[m_iCurRes]);
ResetControls();
}
return true;
}
break;
case ACTION_CHANGE_RESOLUTION:
// choose the next resolution in our list
{
m_iCurRes = (m_iCurRes+1) % m_Res.size();
g_graphicsContext.SetVideoResolution(m_Res[m_iCurRes]);
ResetControls();
return true;
}
break;
// ignore all gesture meta actions
case ACTION_GESTURE_BEGIN:
case ACTION_GESTURE_END:
case ACTION_GESTURE_ABORT:
case ACTION_GESTURE_NOTIFY:
case ACTION_GESTURE_PAN:
case ACTION_GESTURE_ROTATE:
case ACTION_GESTURE_ZOOM:
return true;
}
// if we see a mouse move event without dx and dy (amount2 and amount3) these
// are the focus actions which are generated on touch events and those should
// be eaten/ignored here. Else we will switch to the screencalibration controls
// which are at that x/y value on each touch/tap/swipe which makes the whole window
// unusable for touch screens
if (action.GetID() == ACTION_MOUSE_MOVE && action.GetAmount(2) == 0 && action.GetAmount(3) == 0)
return true;
return CGUIWindow::OnAction(action); // base class to handle basic movement etc.
}
void CGUIWindowSettingsScreenCalibration::AllocResources(bool forceLoad)
{
CGUIWindow::AllocResources(forceLoad);
}
void CGUIWindowSettingsScreenCalibration::FreeResources(bool forceUnload)
{
CGUIWindow::FreeResources(forceUnload);
}
bool CGUIWindowSettingsScreenCalibration::OnMessage(CGUIMessage& message)
{
switch ( message.GetMessage() )
{
case GUI_MSG_WINDOW_DEINIT:
{
CDisplaySettings::GetInstance().UpdateCalibrations();
CSettings::GetInstance().Save();
g_graphicsContext.SetCalibrating(false);
// reset our screen resolution to what it was initially
g_graphicsContext.SetVideoResolution(CDisplaySettings::GetInstance().GetCurrentResolution());
// Inform the player so we can update the resolution
#ifdef HAS_VIDEO_PLAYBACK
g_renderManager.Update();
#endif
g_windowManager.SendMessage(GUI_MSG_NOTIFY_ALL, 0, 0, GUI_MSG_WINDOW_RESIZE);
}
break;
case GUI_MSG_WINDOW_INIT:
{
CGUIWindow::OnMessage(message);
g_graphicsContext.SetCalibrating(true);
// Get the allowable resolutions that we can calibrate...
m_Res.clear();
if (g_application.m_pPlayer->IsPlayingVideo())
{ // don't allow resolution switching if we are playing a video
#ifdef HAS_VIDEO_PLAYBACK
RESOLUTION res = g_renderManager.GetResolution();
g_graphicsContext.SetVideoResolution(res);
// Inform the renderer so we can update the resolution
g_renderManager.Update();
#endif
m_iCurRes = 0;
m_Res.push_back(g_graphicsContext.GetVideoResolution());
SET_CONTROL_VISIBLE(CONTROL_VIDEO);
}
else
{
SET_CONTROL_HIDDEN(CONTROL_VIDEO);
m_iCurRes = (unsigned int)-1;
g_graphicsContext.GetAllowedResolutions(m_Res);
// find our starting resolution
m_iCurRes = FindCurrentResolution();
}
if (m_iCurRes==(unsigned int)-1)
{
CLog::Log(LOGERROR, "CALIBRATION: Reported current resolution: %d", (int)g_graphicsContext.GetVideoResolution());
CLog::Log(LOGERROR, "CALIBRATION: Could not determine current resolution, falling back to default");
m_iCurRes = 0;
}
// Setup the first control
m_iControl = CONTROL_TOP_LEFT;
ResetControls();
return true;
}
break;
case GUI_MSG_CLICKED:
{
// clicked - change the control...
NextControl();
}
break;
case GUI_MSG_NOTIFY_ALL:
{
if (message.GetParam1() == GUI_MSG_WINDOW_RESIZE)
{
m_iCurRes = FindCurrentResolution();
}
}
break;
// send before touch for requesting gesture features - we don't want this
// it would result in unfocus in the onmessage below ...
case GUI_MSG_GESTURE_NOTIFY:
// send after touch for unfocussing - we don't want this in this window!
case GUI_MSG_UNFOCUS_ALL:
return true;
break;
}
return CGUIWindow::OnMessage(message);
}
unsigned int CGUIWindowSettingsScreenCalibration::FindCurrentResolution()
{
RESOLUTION curRes = g_graphicsContext.GetVideoResolution();
for (unsigned int i = 0; i < m_Res.size(); i++)
{
// If it's a CUSTOM (monitor) resolution, then g_graphicsContext.GetAllowedResolutions()
// returns just one entry with CUSTOM in it. Update that entry to point to the current
// CUSTOM resolution.
if (curRes>=RES_CUSTOM)
{
if (m_Res[i]==RES_CUSTOM)
{
m_Res[i] = curRes;
return i;
}
}
else if (m_Res[i] == g_graphicsContext.GetVideoResolution())
return i;
}
return 0;
}
void CGUIWindowSettingsScreenCalibration::NextControl()
{ // set the old control invisible and not focused, and choose the next control
CGUIControl *pControl = GetControl(m_iControl);
if (pControl)
{
pControl->SetVisible(false);
pControl->SetFocus(false);
}
// switch to the next control
m_iControl++;
if (m_iControl > CONTROL_PIXEL_RATIO)
m_iControl = CONTROL_TOP_LEFT;
// enable the new control
EnableControl(m_iControl);
}
void CGUIWindowSettingsScreenCalibration::EnableControl(int iControl)
{
SET_CONTROL_VISIBLE(CONTROL_TOP_LEFT);
SET_CONTROL_VISIBLE(CONTROL_BOTTOM_RIGHT);
SET_CONTROL_VISIBLE(CONTROL_SUBTITLES);
SET_CONTROL_VISIBLE(CONTROL_PIXEL_RATIO);
SET_CONTROL_FOCUS(iControl, 0);
}
void CGUIWindowSettingsScreenCalibration::ResetControls()
{
// disable the video control, so that our other controls take mouse clicks etc.
CONTROL_DISABLE(CONTROL_VIDEO);
// disable the UI calibration for our controls
// and set their limits
// also, set them to invisible if they don't have focus
CGUIMoverControl *pControl = dynamic_cast<CGUIMoverControl*>(GetControl(CONTROL_TOP_LEFT));
RESOLUTION_INFO info = g_graphicsContext.GetResInfo(m_Res[m_iCurRes]);
if (pControl)
{
pControl->SetLimits( -info.iWidth / 4,
-info.iHeight / 4,
info.iWidth / 4,
info.iHeight / 4);
pControl->SetPosition((float)info.Overscan.left,
(float)info.Overscan.top);
pControl->SetLocation(info.Overscan.left,
info.Overscan.top, false);
}
pControl = dynamic_cast<CGUIMoverControl*>(GetControl(CONTROL_BOTTOM_RIGHT));
if (pControl)
{
pControl->SetLimits(info.iWidth*3 / 4,
info.iHeight*3 / 4,
info.iWidth*5 / 4,
info.iHeight*5 / 4);
pControl->SetPosition((float)info.Overscan.right - (int)pControl->GetWidth(),
(float)info.Overscan.bottom - (int)pControl->GetHeight());
pControl->SetLocation(info.Overscan.right,
info.Overscan.bottom, false);
}
// Subtitles and OSD controls can only move up and down
pControl = dynamic_cast<CGUIMoverControl*>(GetControl(CONTROL_SUBTITLES));
if (pControl)
{
pControl->SetLimits(0, info.iHeight*3 / 4,
0, info.iHeight*5 / 4);
pControl->SetPosition((info.iWidth - pControl->GetWidth()) * 0.5f,
info.iSubtitles - pControl->GetHeight());
pControl->SetLocation(0, info.iSubtitles, false);
}
// lastly the pixel ratio control...
CGUIResizeControl *pResize = dynamic_cast<CGUIResizeControl*>(GetControl(CONTROL_PIXEL_RATIO));
if (pResize)
{
pResize->SetLimits(info.iWidth*0.25f, info.iHeight*0.5f,
info.iWidth*0.75f, info.iHeight*0.5f);
pResize->SetHeight(info.iHeight * 0.5f);
pResize->SetWidth(pResize->GetHeight() / info.fPixelRatio);
pResize->SetPosition((info.iWidth - pResize->GetWidth()) / 2,
(info.iHeight - pResize->GetHeight()) / 2);
}
// Enable the default control
EnableControl(m_iControl);
}
void CGUIWindowSettingsScreenCalibration::UpdateFromControl(int iControl)
{
std::string strStatus;
RESOLUTION_INFO info = g_graphicsContext.GetResInfo(m_Res[m_iCurRes]);
if (iControl == CONTROL_PIXEL_RATIO)
{
CGUIControl *pControl = GetControl(CONTROL_PIXEL_RATIO);
if (pControl)
{
float fWidth = (float)pControl->GetWidth();
float fHeight = (float)pControl->GetHeight();
info.fPixelRatio = fHeight / fWidth;
// recenter our control...
pControl->SetPosition((info.iWidth - pControl->GetWidth()) / 2,
(info.iHeight - pControl->GetHeight()) / 2);
strStatus = StringUtils::Format("%s (%5.3f)", g_localizeStrings.Get(275).c_str(), info.fPixelRatio);
SET_CONTROL_LABEL(CONTROL_LABEL_ROW2, 278);
}
}
else
{
const CGUIMoverControl *pControl = dynamic_cast<const CGUIMoverControl*>(GetControl(iControl));
if (pControl)
{
switch (iControl)
{
case CONTROL_TOP_LEFT:
{
info.Overscan.left = pControl->GetXLocation();
info.Overscan.top = pControl->GetYLocation();
strStatus = StringUtils::Format("%s (%i,%i)", g_localizeStrings.Get(272).c_str(), pControl->GetXLocation(), pControl->GetYLocation());
SET_CONTROL_LABEL(CONTROL_LABEL_ROW2, 276);
}
break;
case CONTROL_BOTTOM_RIGHT:
{
info.Overscan.right = pControl->GetXLocation();
info.Overscan.bottom = pControl->GetYLocation();
int iXOff1 = info.iWidth - pControl->GetXLocation();
int iYOff1 = info.iHeight - pControl->GetYLocation();
strStatus = StringUtils::Format("%s (%i,%i)", g_localizeStrings.Get(273).c_str(), iXOff1, iYOff1);
SET_CONTROL_LABEL(CONTROL_LABEL_ROW2, 276);
}
break;
case CONTROL_SUBTITLES:
{
info.iSubtitles = pControl->GetYLocation();
strStatus = StringUtils::Format("%s (%i)", g_localizeStrings.Get(274).c_str(), pControl->GetYLocation());
SET_CONTROL_LABEL(CONTROL_LABEL_ROW2, 277);
}
break;
}
}
}
g_graphicsContext.SetResInfo(m_Res[m_iCurRes], info);
// set the label control correctly
std::string strText;
if (g_Windowing.IsFullScreen())
strText = StringUtils::Format("%ix%i@%.2f - %s | %s",
info.iScreenWidth,
info.iScreenHeight,
info.fRefreshRate,
g_localizeStrings.Get(244).c_str(),
strStatus.c_str());
else
strText = StringUtils::Format("%ix%i - %s | %s",
info.iScreenWidth,
info.iScreenHeight,
g_localizeStrings.Get(242).c_str(),
strStatus.c_str());
SET_CONTROL_LABEL(CONTROL_LABEL_ROW1, strText);
}
void CGUIWindowSettingsScreenCalibration::FrameMove()
{
// g_Windowing.Get3DDevice()->Clear(0, NULL, D3DCLEAR_TARGET, 0, 0, 0);
m_iControl = GetFocusedControlID();
if (m_iControl >= 0)
{
UpdateFromControl(m_iControl);
}
else
{
SET_CONTROL_LABEL(CONTROL_LABEL_ROW1, "");
SET_CONTROL_LABEL(CONTROL_LABEL_ROW2, "");
}
CGUIWindow::FrameMove();
}
void CGUIWindowSettingsScreenCalibration::DoProcess(unsigned int currentTime, CDirtyRegionList &dirtyregions)
{
MarkDirtyRegion();
for (int i = CONTROL_TOP_LEFT; i <= CONTROL_PIXEL_RATIO; i++)
SET_CONTROL_HIDDEN(i);
m_needsScaling = true;
CGUIWindow::DoProcess(currentTime, dirtyregions);
m_needsScaling = false;
g_graphicsContext.SetRenderingResolution(m_Res[m_iCurRes], false);
g_graphicsContext.AddGUITransform();
// process the movers etc.
for (int i = CONTROL_TOP_LEFT; i <= CONTROL_PIXEL_RATIO; i++)
{
SET_CONTROL_VISIBLE(i);
CGUIControl *control = GetControl(i);
if (control)
control->DoProcess(currentTime, dirtyregions);
}
g_graphicsContext.RemoveTransform();
}
void CGUIWindowSettingsScreenCalibration::DoRender()
{
// we set that we need scaling here to render so that anything else on screen scales correctly
m_needsScaling = true;
CGUIWindow::DoRender();
m_needsScaling = false;
}
|
gpl-2.0
|
metrocovarrubias/practica-6
|
Profesor.cs
|
4566
|
๏ปฟusing System;
using MySql.Data.MySqlClient;
namespace Practica6
{
/// <summary>
/// Description of Profesor.
/// </summary>
public class Profesor : Conexion
{
public string id,codigo, nombre;
public Profesor()
{
}
public void Menu(){
int opcion;
string respuesta;
Console.WriteLine("Elegir una opcion");
Console.WriteLine("1.- Mostrar");
Console.WriteLine("2.- Agregar");
Console.WriteLine("3.- Editar");
Console.WriteLine("4.- Eliminar");
Console.WriteLine("5.- Salir");
opcion = int .Parse(Console.ReadLine());
switch (opcion){
case 1:
Console.Clear();
mostrarTodos();
Console.WriteLine("1 ยฟRegresar al menu?");
Console.WriteLine("2 Salir");
respuesta = Console.ReadLine();
if(respuesta == "1"){
Console.Clear();
Menu();
}
else{
Environment.Exit(0);
}
break;
case 2:
Console.Clear();
Console.WriteLine("Ingrese el cรณdigo");
codigo = Console.ReadLine();
Console.WriteLine("Ingrese el nombre");
nombre = Console.ReadLine();
Agregar(id,codigo,nombre);
Console.WriteLine("Exito al guardar" + "\n");
Console.WriteLine("1.- ยฟRegresar al menu?");
Console.WriteLine("2.- Salir");
respuesta = Console.ReadLine();
if(respuesta == "1"){
Console.Clear();
Menu();
}
else{
Environment.Exit(0);
}
break;
case 3:
Console.Clear();
Console.WriteLine("Editar Registro"+"\n");
Console.WriteLine ("Ingrese el id: ");
id = Console.ReadLine();
Console.WriteLine("Ingrese el codigo");
codigo = Console.ReadLine();
Console.WriteLine ("Ingrese el nuevo codigo : ");
codigo = Console.ReadLine();
editarCodigoRegistro(codigo,id);
Console.WriteLine("Exito al guardar" + "\n");
Console.WriteLine("1 ยฟRegresar al menu?");
Console.WriteLine("2 Salir");
respuesta = Console.ReadLine();
if(respuesta == "1"){
Console.Clear();
Menu();
}
else{
Environment.Exit(0);
}
break;
case 4:
Console.Clear();
Console.WriteLine("Eliminar Registro" + "\n");
Console.WriteLine ("Ingrese el ID a borrar");
id=Console.ReadLine();
this.eliminarRegistroPorid(id);
Console.WriteLine("ยฟQuรฉ desea hacer?");
Console.WriteLine("1.- Regresar al menu");
Console.WriteLine("2.- Salir");
respuesta = Console.ReadLine();
if(respuesta == "1"){
Console.Clear();
Menu();
}
else{
Environment.Exit(0);
}
break;
case 5:
Environment.Exit(0);
break;
}
}
public void mostrarTodos(){
this.abrirConexion();
MySqlCommand myCommand = new MySqlCommand(this.querySelect(),
myConnection);
MySqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read()){
string id = myReader["id"].ToString();
string codigo = myReader["codigo"].ToString();
string nombre = myReader["nombre"].ToString();
Console.WriteLine("ID: " + id +"\n"+" Cรณdigo: " + codigo +"\n"+" Nombre: " + nombre+"\n");
}
myReader.Close();
myReader = null;
myCommand.Dispose();
myCommand = null;
this.cerrarConexion();
}
//para poner los datos en la base de datos
public void Agregar(string id,string codigo, string nombre){
this.abrirConexion();
string sql = "INSERT INTO alumno1 (codigo, nombre) VALUES ('" + codigo + "', '" + nombre + "')";
this.ejecutarComando(sql);
this.cerrarConexion();
}
//para poner editar codigo
public void editarCodigoRegistro(string codigo,string id){
this.abrirConexion();
string sql = "UPDATE `alumno1` SET `codigo`='" + codigo + "' WHERE (`id`='" + id + "')";
this.ejecutarComando(sql);
this.cerrarConexion();
}
public void eliminarRegistroPorid ( string id ) {
this.abrirConexion ();
string sql = "DELETE FROM `alumno1` WHERE (`ID`= '" + id + "')" ;
this.ejecutarComando(sql);
this.cerrarConexion();
}
private int ejecutarComando(string sql){
MySqlCommand myCommand = new MySqlCommand(sql,this.myConnection);
int afectadas = myCommand.ExecuteNonQuery();
myCommand.Dispose();
myCommand = null;
return afectadas;
}
private string querySelect(){
return "SELECT * " +
"FROM alumno1";
}
}
}
|
gpl-2.0
|
aleph1888/lorea
|
pages/account/register.php
|
1380
|
<?php
/**
* Assembles and outputs the registration page.
*
* Since 1.8, registration can be disabled via administration. If this is
* the case, calls to this page will forward to the network front page.
*
* If the user is logged in, this page will forward to the network
* front page.
*
* @package Elgg.Core
* @subpackage Registration
*/
// check new registration allowed
if (elgg_get_config('allow_registration') == false) {
register_error(elgg_echo('registerdisabled'));
forward();
}
$friend_guid = (int) get_input('friend_guid', 0);
$invitecode = get_input('invitecode');
// only logged out people need to register
if (elgg_is_logged_in()) {
forward();
}
$title = elgg_echo("register");
$content = elgg_view_title($title);
// create the registration url - including switching to https if configured
$register_url = elgg_get_site_url() . 'action/register';
if (elgg_get_config('https_login')) {
$register_url = str_replace("http:", "https:", $register_url);
}
$form_params = array(
'action' => $register_url,
'class' => 'elgg-form-account float',
);
$body_params = array(
'friend_guid' => $friend_guid,
'invitecode' => $invitecode
);
$content .= elgg_view_form('register', $form_params, $body_params);
$content .= elgg_view('help/register');
$body = elgg_view_layout("one_column", array('content' => $content));
echo elgg_view_page($title, $body);
|
gpl-2.0
|
MiMartinezcomSAS/lilipinkqua
|
wp-content/themes/cb-modello/woocommerce/global/wrapper-end.php
|
241
|
<?php
/**
* Content wrappers
*
* @author WooThemes
* @package WooCommerce/Templates
* @version 1.6.4
*/
?>
</div><div>
<!--/ page end-->
<?php
global $post;
$cbtheme_shop=new cbtheme();
$cbtheme_shop->page_footer();
?>
|
gpl-2.0
|
unofficial-opensource-apple/gcc_40
|
libstdc++-v3/testsuite/27_io/basic_fstream/2.cc
|
1873
|
// 2002-07-25 Benjamin Kosnik <bkoz@redhat.com>
// Copyright (C) 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
// As a special exception, you may use this file as part of a free software
// library without restriction. Specifically, if other files instantiate
// templates or use macros or inline functions from this file, or you compile
// this file and link it with other files to produce an executable, this
// file does not by itself cause the resulting executable to be covered by
// the GNU General Public License. This exception does not however
// invalidate any other reasons why the executable file might be covered by
// the GNU General Public License.
// 27.8.1.11 - Template class basic_fstream
// NB: This file is for testing basic_fstream with NO OTHER INCLUDES.
#include <fstream>
#include <testsuite_hooks.h>
#include <testsuite_character.h>
// { dg-do compile }
namespace std
{
using __gnu_test::pod_char;
typedef short type_t;
template class basic_fstream<type_t, char_traits<type_t> >;
template class basic_fstream<pod_char, char_traits<pod_char> >;
} // test
|
gpl-2.0
|
wljcom/vlc
|
modules/demux/mkv/mkv.hpp
|
6823
|
/*****************************************************************************
* mkv.hpp : matroska demuxer
*****************************************************************************
* Copyright (C) 2003-2005, 2008 VLC authors and VideoLAN
* $Id$
*
* Authors: Laurent Aimar <fenrir@via.ecp.fr>
* Steve Lhomme <steve.lhomme@free.fr>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifndef _MKV_H_
#define _MKV_H_
/*****************************************************************************
* Preamble
*****************************************************************************/
/* config.h may include inttypes.h, so make sure we define that option
* early enough. */
#define __STDC_FORMAT_MACROS 1
#define __STDC_CONSTANT_MACROS 1
#define __STDC_LIMIT_MACROS 1
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <inttypes.h>
#include <vlc_common.h>
#include <vlc_plugin.h>
#include <time.h>
#include <vlc_meta.h>
#include <vlc_charset.h>
#include <vlc_input.h>
#include <vlc_demux.h>
#include <vlc_aout.h> /* For reordering */
#include <iostream>
#include <cassert>
#include <typeinfo>
#include <string>
#include <vector>
#include <algorithm>
/* libebml and matroska */
#include "ebml/EbmlHead.h"
#include "ebml/EbmlSubHead.h"
#include "ebml/EbmlStream.h"
#include "ebml/EbmlContexts.h"
#include "ebml/EbmlVoid.h"
#include "ebml/EbmlVersion.h"
#include "ebml/StdIOCallback.h"
#include "matroska/KaxAttachments.h"
#include "matroska/KaxAttached.h"
#include "matroska/KaxBlock.h"
#include "matroska/KaxBlockData.h"
#include "matroska/KaxChapters.h"
#include "matroska/KaxCluster.h"
#include "matroska/KaxClusterData.h"
#include "matroska/KaxContexts.h"
#include "matroska/KaxCues.h"
#include "matroska/KaxCuesData.h"
#include "matroska/KaxInfo.h"
#include "matroska/KaxInfoData.h"
#include "matroska/KaxSeekHead.h"
#include "matroska/KaxSegment.h"
#include "matroska/KaxTag.h"
#include "matroska/KaxTags.h"
//#include "matroska/KaxTagMulti.h"
#include "matroska/KaxTracks.h"
#include "matroska/KaxTrackAudio.h"
#include "matroska/KaxTrackVideo.h"
#include "matroska/KaxTrackEntryData.h"
#include "matroska/KaxContentEncoding.h"
#include "matroska/KaxVersion.h"
#include "ebml/StdIOCallback.h"
#ifdef HAVE_ZLIB_H
# include <zlib.h>
#endif
#define MKV_DEBUG 0
#define MATROSKA_COMPRESSION_NONE -1
#define MATROSKA_COMPRESSION_ZLIB 0
#define MATROSKA_COMPRESSION_BLIB 1
#define MATROSKA_COMPRESSION_LZOX 2
#define MATROSKA_COMPRESSION_HEADER 3
enum
{
MATROSKA_ENCODING_SCOPE_ALL_FRAMES = 1,
MATROSKA_ENCODING_SCOPE_PRIVATE = 2,
MATROSKA_ENCODING_SCOPE_NEXT = 4 /* unsupported */
};
#define MKVD_TIMECODESCALE 1000000
#define MKV_IS_ID( el, C ) ( el != NULL && typeid( *el ) == typeid( C ) )
using namespace LIBMATROSKA_NAMESPACE;
using namespace std;
void BlockDecode( demux_t *p_demux, KaxBlock *block, KaxSimpleBlock *simpleblock,
mtime_t i_pts, mtime_t i_duration, bool f_mandatory );
class attachment_c
{
public:
attachment_c( const std::string& _psz_file_name, const std::string& _psz_mime_type, int _i_size )
:i_size(_i_size)
,psz_file_name( _psz_file_name)
,psz_mime_type( _psz_mime_type)
{
p_data = NULL;
}
~attachment_c() { free( p_data ); }
/* Allocs the data space. Returns true if allocation went ok */
bool init()
{
p_data = malloc( i_size );
return (p_data != NULL);
}
const char* fileName() const { return psz_file_name.c_str(); }
const char* mimeType() const { return psz_mime_type.c_str(); }
int size() const { return i_size; }
void *p_data;
private:
int i_size;
std::string psz_file_name;
std::string psz_mime_type;
};
class matroska_segment_c;
struct matroska_stream_c
{
matroska_stream_c() :p_io_callback(NULL) ,p_estream(NULL) {}
~matroska_stream_c()
{
delete p_io_callback;
delete p_estream;
}
IOCallback *p_io_callback;
EbmlStream *p_estream;
std::vector<matroska_segment_c*> segments;
};
/*****************************************************************************
* definitions of structures and functions used by this plugins
*****************************************************************************/
class PrivateTrackData
{
public:
virtual ~PrivateTrackData() {}
virtual int32_t Init() { return 0; }
};
struct mkv_track_t
{
bool b_default;
bool b_enabled;
bool b_forced;
unsigned int i_number;
unsigned int i_extra_data;
uint8_t *p_extra_data;
char *psz_codec;
bool b_dts_only;
bool b_pts_only;
bool b_no_duration;
uint64_t i_default_duration;
float f_timecodescale;
mtime_t i_last_dts;
/* video */
es_format_t fmt;
float f_fps;
es_out_id_t *p_es;
/* audio */
unsigned int i_original_rate;
uint8_t i_chans_to_reorder; /* do we need channel reordering */
uint8_t pi_chan_table[AOUT_CHAN_MAX];
/* Private track paramters */
PrivateTrackData *p_sys;
bool b_inited;
/* data to be send first */
int i_data_init;
uint8_t *p_data_init;
/* hack : it's for seek */
bool b_search_keyframe;
bool b_silent;
/* informative */
const char *psz_codec_name;
const char *psz_codec_settings;
const char *psz_codec_info_url;
const char *psz_codec_download_url;
/* encryption/compression */
int i_compression_type;
uint32_t i_encoding_scope;
KaxContentCompSettings *p_compression_data;
/* Matroska 4 new elements used by Opus */
mtime_t i_seek_preroll;
mtime_t i_codec_delay;
};
struct mkv_index_t
{
int i_track;
int i_block_number;
int64_t i_position;
int64_t i_time;
bool b_key;
};
#endif /* _MKV_HPP_ */
|
gpl-2.0
|
DigitalMediaServer/DigitalMediaServer
|
src/main/java/net/pms/util/jna/macos/kernreturn/KernReturnTConverter.java
|
1715
|
/*
* Digital Media Server, for streaming digital media to UPnP AV or DLNA
* compatible devices based on PS3 Media Server and Universal Media Server.
* Copyright (C) 2016 Digital Media Server developers.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program 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 Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see http://www.gnu.org/licenses/.
*/
package net.pms.util.jna.macos.kernreturn;
import com.sun.jna.FromNativeContext;
import com.sun.jna.ToNativeContext;
import com.sun.jna.TypeConverter;
/**
* Performs conversion between {@link KernReturnT} and native kernel return
* codes.
*
* @author Nadahar
*/
public class KernReturnTConverter implements TypeConverter {
@Override
public Object fromNative(Object input, FromNativeContext context) {
if (!KernReturnT.class.isAssignableFrom(context.getTargetType())) {
throw new IllegalStateException(
"KernReturnTConverter can only convert objects implementing KernReturnT"
);
}
return DefaultKernReturnT.typeOf((int) input);
}
@Override
public Class<Integer> nativeType() {
return Integer.class;
}
@Override
public Integer toNative(Object input, ToNativeContext context) {
return ((KernReturnT) input).getValue();
}
}
|
gpl-2.0
|
ineiti/cothorities
|
eventlog/service.go
|
10298
|
package eventlog
import (
"errors"
"fmt"
"time"
"go.dedis.ch/cothority/v3/byzcoin"
"go.dedis.ch/onet/v3"
"go.dedis.ch/onet/v3/log"
"go.dedis.ch/protobuf"
)
// ServiceName is the service name for the EventLog service.
var ServiceName = "EventLog"
var sid onet.ServiceID
const contractName = "eventlog"
const logCmd = "log"
// Set a relatively low time for bucketMaxAge: during peak message arrival
// this will pretect the buckets from getting too big. During low message
// arrival (< 1 per 5 sec) it does not create extra buckets, because time
// periods with no events do not need buckets created for them.
const bucketMaxAge = 5 * time.Second
func init() {
var err error
sid, err = onet.RegisterNewService(ServiceName, newService)
if err != nil {
log.Fatal(err)
}
err = byzcoin.RegisterGlobalContract(contractName, contractFromBytes)
if err != nil {
log.ErrFatal(err)
}
}
// Service is the EventLog service.
type Service struct {
*onet.ServiceProcessor
omni *byzcoin.Service
bucketMaxAge time.Duration
}
const defaultBlockInterval = 5 * time.Second
// This should be a const, but we want to be able to hack it from tests.
var searchMax = 10000
// Search will search the event log for matching entries.
func (s *Service) Search(req *SearchRequest) (*SearchResponse, error) {
if req.ID.IsNull() {
return nil, errors.New("skipchain ID required")
}
if req.To == 0 {
req.To = time.Now().UnixNano()
}
v, err := s.omni.GetReadOnlyStateTrie(req.ID)
if err != nil {
return nil, err
}
el := &eventLog{Instance: req.Instance, v: v}
id, b, err := el.getLatestBucket()
if err != nil {
return nil, err
}
if b == nil {
// There are no events yet on this chain, so return no results.
return &SearchResponse{}, nil
}
// bEnd is normally updated from the last bucket's start. For the latest
// bucket, bEnd is now.
bEnd := time.Now().UnixNano()
// Walk backwards in the bucket chain through 2 zones: first where the
// bucket covers time that is not in our search range, and then where the buckets
// do cover the search range. When we see a bucket that ends before our search
// range, we can stop walking buckets.
var buckets []*bucket
var bids [][]byte
for {
if req.From > bEnd {
// This bucket is before the search range, so we are done walking back the bucket chain.
break
}
if req.To < b.Start {
// This bucket is after the search range, so we do not add it to buckets, but
// we keep walking up the chain.
} else {
buckets = append(buckets, b)
bids = append(bids, id)
}
if b.isFirst() {
break
}
bEnd = b.Start
id = b.Prev
b, err = el.getBucketByID(id)
if err != nil {
// This indicates that the event log data structure is wrong, so
// we cannot claim to correctly search it. Give up instead.
log.Errorf("expected event log bucket id %v not found: %v", string(id), err)
return nil, err
}
}
reply := &SearchResponse{}
// Process the time buckets from earliest to latest so that
// if we truncate, it is the latest events that are not returned,
// so that they can set req.From = resp.Events[len(resp.Events)-1].When.
filter:
for i := len(buckets) - 1; i >= 0; i-- {
b := buckets[i]
for _, e := range b.EventRefs {
ev, err := getEventByID(v, e)
if err != nil {
log.Errorf("bucket %x points to event %x, but the event was not found: %v", bids[i], e, err)
return nil, err
}
if req.From <= ev.When && ev.When < req.To {
if req.Topic == "" || req.Topic == ev.Topic {
reply.Events = append(reply.Events, *ev)
if len(reply.Events) >= searchMax {
reply.Truncated = true
break filter
}
}
}
}
}
return reply, nil
}
func decodeAndCheckEvent(coll byzcoin.ReadOnlyStateTrie, eventBuf []byte) (*Event, error) {
// Check the timestamp of the event: it should never be in the future,
// and it should not be more than 30 seconds in the past. (Why 30 sec
// and not something more auto-scaling like blockInterval * 30?
// Because a # of blocks limit is too fragile when using fast blocks for
// tests.)
//
// Also: An event a few seconds into the future is OK because there might be
// time skew between a legitimate event producer and the network. See issue #1331.
event := &Event{}
err := protobuf.Decode(eventBuf, event)
if err != nil {
return nil, err
}
when := time.Unix(0, event.When)
now := time.Now()
if when.Before(now.Add(-30 * time.Second)) {
return nil, fmt.Errorf("event timestamp too long ago - when=%v, now=%v", when, now)
}
if when.After(now.Add(5 * time.Second)) {
return nil, errors.New("event timestamp is too far in the future")
}
return event, nil
}
// invoke will add an event and update the corresponding indices.
func (c *contract) Invoke(rst byzcoin.ReadOnlyStateTrie, inst byzcoin.Instruction, coins []byzcoin.Coin) (sc []byzcoin.StateChange, cout []byzcoin.Coin, err error) {
cout = coins
_, _, cid, darcID, err := rst.GetValues(inst.InstanceID.Slice())
if err != nil {
return nil, nil, err
}
if cid != contractName {
return nil, nil, fmt.Errorf("expected contract ID to be \"%s\" but got \"%s\"", contractName, cid)
}
if inst.Invoke.Command != logCmd {
return nil, nil, fmt.Errorf("invalid command, got \"%s\" but need \"%s\"", inst.Invoke.Command, logCmd)
}
eventBuf := inst.Invoke.Args.Search("event")
if eventBuf == nil {
return nil, nil, errors.New("expected a named argument of \"event\"")
}
event, err := decodeAndCheckEvent(rst, eventBuf)
if err != nil {
return nil, nil, err
}
// Even though this is an invoke, we'll use the Spawn convention,
// since the new event is essentially being spawned on this eventlog.
eventID := inst.DeriveID("")
sc = append(sc, byzcoin.NewStateChange(byzcoin.Create, eventID, cid, eventBuf, darcID))
// Walk from latest bucket back towards beginning looking for the right bucket.
//
// If you don't find a bucket with b.Start <= ev.When,
// create a new bucket, put in the event, set the start, emit the bucket,
// update prev in the bucket before (and also possibly the index key).
//
// If you find an existing latest bucket, and b.Start is more than X seconds
// ago, make a new bucket anyway.
//
// If you find the right bucket, add the event and emit the updated bucket.
// For now: buckets are allowed to grow as big as needed (but the previous
// rule prevents buckets from getting too big by timing them out).
el := &eventLog{Instance: inst.InstanceID, v: rst}
bID, b, err := el.getLatestBucket()
if err != nil {
return nil, nil, err
}
isHead := true
for b != nil && !b.isFirst() {
if b.Start <= event.When {
break
}
bID = b.Prev
b, err = el.getBucketByID(bID)
if err != nil {
return nil, nil, err
}
isHead = false
}
// Make a new head bucket if:
// No latest bucket (b == nil).
// or
// Found a bucket, and it is head, and it is too old.
if b == nil || isHead && time.Duration(event.When-b.Start) > bucketMaxAge {
newBid := inst.DeriveID("bucket")
if b == nil {
// Special case: The first bucket for an eventlog
// needs a catch-all bucket before it, in case later
// events come in.
catchID := inst.DeriveID("bucket-catch-all")
newb := &bucket{
Start: 0,
Prev: nil,
EventRefs: nil,
}
buf, err := protobuf.Encode(newb)
if err != nil {
return nil, nil, err
}
sc = append(sc, byzcoin.NewStateChange(byzcoin.Create, catchID, cid, buf, darcID))
bID = catchID.Slice()
}
newb := &bucket{
// This new bucket will start with this event.
Start: event.When,
// It links to the previous latest bucket, or to the catch-all bucket
// if there was no previous bucket.
Prev: bID,
EventRefs: [][]byte{eventID.Slice()},
}
buf, err := protobuf.Encode(newb)
if err != nil {
return nil, nil, err
}
sc = append(sc, byzcoin.NewStateChange(byzcoin.Create, newBid, cid, buf, darcID))
// Update the pointer to the latest bucket.
sc = append(sc, byzcoin.NewStateChange(byzcoin.Update, inst.InstanceID, cid, newBid.Slice(), darcID))
} else {
// Otherwise just add into whatever bucket we found, no matter how
// many are already there. (Splitting buckets is hard and not important to us.)
b.EventRefs = append(b.EventRefs, eventID.Slice())
bucketBuf, err := protobuf.Encode(b)
if err != nil {
return nil, nil, err
}
sc = append(sc,
byzcoin.StateChange{
StateAction: byzcoin.Update,
InstanceID: bID,
ContractID: contractName,
Value: bucketBuf,
})
}
return
}
func (c *contract) Spawn(rst byzcoin.ReadOnlyStateTrie, inst byzcoin.Instruction, coins []byzcoin.Coin) (sc []byzcoin.StateChange, cout []byzcoin.Coin, err error) {
cout = coins
_, _, _, darcID, err := rst.GetValues(inst.InstanceID.Slice())
if err != nil {
return nil, nil, err
}
// Store c.iid as the pointer to the first bucket. It will in fact be all zeros,
// because during spawning, ByzCoin passes a zero-length slice to the new contract factory.
// In invoke we'll detect that the first bucket does not exist and do the necessary.
return []byzcoin.StateChange{
byzcoin.NewStateChange(byzcoin.Create, inst.DeriveID(""), contractName, c.iid.Slice(), darcID),
}, nil, nil
}
type contract struct {
byzcoin.BasicContract
iid byzcoin.InstanceID
}
func contractFromBytes(in []byte) (byzcoin.Contract, error) {
c := &contract{}
c.iid = byzcoin.NewInstanceID(in)
return c, nil
}
// newService receives the context that holds information about the node it's
// running on. Saving and loading can be done using the context. The data will
// be stored in memory for tests and simulations, and on disk for real
// deployments.
func newService(c *onet.Context) (onet.Service, error) {
s := &Service{
ServiceProcessor: onet.NewServiceProcessor(c),
omni: c.Service(byzcoin.ServiceName).(*byzcoin.Service),
}
if err := s.RegisterHandlers(s.Search); err != nil {
log.ErrFatal(err, "Couldn't register messages")
}
return s, nil
}
func getEventByID(view byzcoin.ReadOnlyStateTrie, eid []byte) (*Event, error) {
v0, _, _, _, err := view.GetValues(eid)
if err != nil {
return nil, err
}
var e Event
if err := protobuf.Decode(v0, &e); err != nil {
return nil, err
}
return &e, nil
}
|
gpl-2.0
|
smarr/Truffle
|
tools/src/com.oracle.truffle.tools.chromeinspector/src/com/oracle/truffle/tools/chromeinspector/types/PropertyDescriptor.java
|
3987
|
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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 Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.truffle.tools.chromeinspector.types;
import com.oracle.truffle.tools.utils.json.JSONObject;
public final class PropertyDescriptor {
private final JSONObject jsonObject;
/**
* Create an object property descriptor.
*
* @param name Property name or symbol description.
* @param value The value associated with the property.
* @param writable True if the value associated with the property may be changed (data
* descriptors only).
* @param get A function which serves as a getter for the property, or <code>undefined</code> if
* there is no getter (accessor descriptors only).
* @param set A function which serves as a setter for the property, or <code>undefined</code> if
* there is no setter (accessor descriptors only).
* @param configurable True if the type of this property descriptor may be changed and if the
* property may be deleted from the corresponding object.
* @param enumerable True if this property shows up during enumeration of the properties on the
* corresponding object.
* @param wasThrown True if the result was thrown during the evaluation.
* @param isOwn True if the property is owned for the object.
* @param symbol Property symbol object, if the property is of the <code>symbol</code> type.
*/
public PropertyDescriptor(String name, RemoteObject value, Boolean writable,
RemoteObject get, RemoteObject set, boolean configurable,
boolean enumerable, Boolean wasThrown, Boolean isOwn, RemoteObject symbol) {
jsonObject = createJSON(name, value, writable, get, set, configurable, enumerable, wasThrown, isOwn, symbol);
}
private static JSONObject createJSON(String name, RemoteObject value, Boolean writable,
RemoteObject get, RemoteObject set, boolean configurable,
boolean enumerable, Boolean wasThrown, Boolean isOwn, RemoteObject symbol) {
JSONObject json = new JSONObject();
json.put("name", name);
if (value != null && get == null) {
json.put("value", value.toJSON());
}
json.putOpt("writable", writable);
if (get != null) {
json.put("get", get.toJSON());
}
if (set != null) {
json.put("set", set.toJSON());
}
json.put("configurable", configurable);
json.put("enumerable", enumerable);
json.putOpt("wasThrown", wasThrown);
json.putOpt("isOwn", isOwn);
if (symbol != null) {
json.put("symbol", symbol.toJSON());
}
return json;
}
public JSONObject toJSON() {
return jsonObject;
}
}
|
gpl-2.0
|
mtedwards/acmc
|
wp-content/themes/Masterchef/includes/contact-buttons.php
|
1544
|
<div class="contact-buttons">
<?php // Facebook
$fb = get_field('fbtext');
if($fb) {?>
<a onClick="ga('send', 'event', 'talent', '<?php echo $name; ?>', 'Facebook');" href="<?php the_field('fblink'); ?>" target="_blank" class="button facebook">
<?php echo $fb; ?>
</a>
<?php } ?>
<?php // Twitter
$tw = get_field('twtext');
if($tw) {?>
<a onClick="ga('send', 'event', 'talent', '<?php echo $name; ?>', 'Twitter');" href="<?php the_field('twlink'); ?>" target="_blank" class="button twitter">
<?php echo $tw; ?>
</a>
<?php } ?>
<?php // Website
$web = get_field('webtext');
if($web) {?>
<a onClick="ga('send', 'event', 'talent', '<?php echo $name; ?>', 'Website');" href="<?php the_field('weblink'); ?>" target="_blank" class="button web">
<?php echo $web; ?>
</a>
<?php } ?>
<?php // Other
$other = get_field('othertext');
if($other) {?>
<a onClick="ga('send', 'event', 'talent', '<?php echo $name; ?>', '<?php the_field('otherlink'); ?>');" href="<?php the_field('otherlink'); ?>" target="_blank" class="button other">
<?php echo $other; ?>
</a>
<?php } ?>
<?php // Dimmi
$dim = get_field('dimtext');
if($dim) {
if(is_page('Talent')){} else {
?>
<a onClick="ga('send', 'event', 'talent', '<?php echo $name; ?>', 'Dimmi');" href="<?php the_field('dimlink'); ?>" target="_blank" class="button dimmi">
<?php echo $dim; ?>
</a>
<?php
} // end if Talent
} // end if Dimmi
?>
</div>
|
gpl-2.0
|
thebruce/d8-test-junk
|
core/modules/datetime/lib/Drupal/datetime/Plugin/field/widget/DatetimeDefaultWidget.php
|
4846
|
<?php
/**
* @file
* Contains \Drupal\datetime\Plugin\field\widget\DateTimeDefaultWidget.
*/
namespace Drupal\datetime\Plugin\field\widget;
use Drupal\Component\Annotation\Plugin;
use Drupal\Core\Annotation\Translation;
use Drupal\field\Plugin\Type\Widget\WidgetBase;
use Drupal\Component\Plugin\Discovery\DiscoveryInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Field\FieldDefinitionInterface;
use Drupal\field\Plugin\PluginSettingsBase;
use Drupal\field\FieldInstanceInterface;
use Drupal\Core\Datetime\DrupalDateTime;
/**
* Plugin implementation of the 'datetime_default' widget.
*
* @Plugin(
* id = "datetime_default",
* module = "datetime",
* label = @Translation("Date and time"),
* field_types = {
* "datetime"
* }
* )
*/
class DateTimeDefaultWidget extends WidgetBase {
/**
* The date format storage.
*
* @var \Drupal\Core\Entity\EntityStorageControllerInterface
*/
protected $dateStorage;
/**
* {@inheritdoc}
*/
public function __construct($plugin_id, array $plugin_definition, FieldDefinitionInterface $field_definition, array $settings) {
// Identify the function used to set the default value.
// @todo Make this work for both configurable and nonconfigurable fields:
// https://drupal.org/node/1989468.
if ($field_definition instanceof FieldInstanceInterface) {
$field_definition->default_value_function = $this->defaultValueFunction();
}
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings);
// @todo Inject this once https://drupal.org/node/2035317 is in.
$this->dateStorage = \Drupal::entityManager()->getStorageController('date_format');
}
/**
* Return the callback used to set a date default value.
*
* @return string
* The name of the callback to use when setting a default date value.
*/
public function defaultValueFunction() {
return 'datetime_default_value';
}
/**
* {@inheritdoc}
*/
public function formElement(array $items, $delta, array $element, $langcode, array &$form, array &$form_state) {
$format_type = datetime_default_format_type();
// We are nesting some sub-elements inside the parent, so we need a wrapper.
// We also need to add another #title attribute at the top level for ease in
// identifying this item in error messages. We do not want to display this
// title because the actual title display is handled at a higher level by
// the Field module.
$element['#theme_wrappers'][] = 'datetime_wrapper';
$element['#attributes']['class'][] = 'container-inline';
$element['#element_validate'][] = 'datetime_datetime_widget_validate';
// Identify the type of date and time elements to use.
switch ($this->getFieldSetting('datetime_type')) {
case 'date':
$date_type = 'date';
$time_type = 'none';
$date_format = $this->dateStorage->load('html_date')->getPattern($format_type);
$time_format = '';
$element_format = $date_format;
$storage_format = DATETIME_DATE_STORAGE_FORMAT;
break;
default:
$date_type = 'date';
$time_type = 'time';
$date_format = $this->dateStorage->load('html_date')->getPattern($format_type);
$time_format = $this->dateStorage->load('html_time')->getPattern($format_type);
$element_format = $date_format . ' ' . $time_format;
$storage_format = DATETIME_DATETIME_STORAGE_FORMAT;
break;
}
$element['value'] = array(
'#type' => 'datetime',
'#default_value' => NULL,
'#date_increment' => 1,
'#date_date_format'=> $date_format,
'#date_date_element' => $date_type,
'#date_date_callbacks' => array(),
'#date_time_format' => $time_format,
'#date_time_element' => $time_type,
'#date_time_callbacks' => array(),
'#date_timezone' => drupal_get_user_timezone(),
'#required' => $element['#required'],
);
// Set the storage and widget options so the validation can use them. The
// validator will not have access to the field definition.
$element['value']['#date_element_format'] = $element_format;
$element['value']['#date_storage_format'] = $storage_format;
if (!empty($items[$delta]['date'])) {
$date = $items[$delta]['date'];
// The date was created and verified during field_load(), so it is safe to
// use without further inspection.
$date->setTimezone(new \DateTimeZone($element['value']['#date_timezone']));
if ($this->getFieldSetting('datetime_type') == 'date') {
// A date without time will pick up the current time, use the default
// time.
datetime_date_default_time($date);
}
$element['value']['#default_value'] = $date;
}
return $element;
}
}
|
gpl-2.0
|
andreituicu/MuseScore
|
mscore/osc.cpp
|
10871
|
//=============================================================================
// MuseScore
// Music Composition & Notation
// $Id: musescore.cpp 4961 2011-11-11 16:24:17Z lasconic $
//
// Copyright (C) 2002-2011 Werner Schweer and others
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2.
//
// This program 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 Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//=============================================================================
#include <fenv.h>
#include "musescore.h"
#include "libmscore/score.h"
#include "libmscore/instrument.h"
#include "libmscore/measure.h"
#include "libmscore/segment.h"
#include "libmscore/chordrest.h"
#include "libmscore/chord.h"
#include "libmscore/note.h"
#include "libmscore/undo.h"
#include "mixer.h"
#include "scoreview.h"
#include "playpanel.h"
#include "preferences.h"
#include "seq.h"
#include "synthesizer/msynthesizer.h"
#ifdef OSC
#include "ofqf/qoscserver.h"
static int oscPort = 5282;
#endif
namespace Ms {
extern MasterSynthesizer* synti;
//---------------------------------------------------------
// initOsc
//---------------------------------------------------------
#ifndef OSC
void MuseScore::initOsc()
{
}
#else // #ifndef OSC
//---------------------------------------------------------
// initOsc
//---------------------------------------------------------
void MuseScore::initOsc()
{
if (!preferences.useOsc)
return;
int port;
if (oscPort)
port = oscPort;
else
port = preferences.oscPort;
QOscServer* osc = new QOscServer(port, qApp);
PathObject* oo = new PathObject( "/addpitch", QVariant::Int, osc);
QObject::connect(oo, SIGNAL(data(int)), SLOT(oscIntMessage(int)));
oo = new PathObject( "/tempo", QVariant::Int, osc);
QObject::connect(oo, SIGNAL(data(int)), SLOT(oscTempo(int)));
oo = new PathObject( "/volume", QVariant::Int, osc);
QObject::connect(oo, SIGNAL(data(int)), SLOT(oscVolume(int)));
oo = new PathObject( "/goto", QVariant::Int, osc);
QObject::connect(oo, SIGNAL(data(int)), SLOT(oscGoto(int)));
oo = new PathObject( "/select-measure", QVariant::Int, osc);
QObject::connect(oo, SIGNAL(data(int)), SLOT(oscSelectMeasure(int)));
for (int i = 1; i <= 12; i++ ) {
oo = new PathObject( QString("/vol%1").arg(i), QVariant::Double, osc);
QObject::connect(oo, SIGNAL(data(double)), SLOT(oscVolChannel(double)));
}
for(int i = 1; i <= 12; i++ ) {
oo = new PathObject( QString("/pan%1").arg(i), QVariant::Double, osc);
QObject::connect(oo, SIGNAL(data(double)), SLOT(oscPanChannel(double)));
}
for(int i = 1; i <= 12; i++ ) {
oo = new PathObject( QString("/mute%1").arg(i), QVariant::Double, osc);
QObject::connect(oo, SIGNAL(data(double)), SLOT(oscMuteChannel(double)));
}
oo = new PathObject( "/open", QVariant::String, osc);
QObject::connect(oo, SIGNAL(data(QString)), SLOT(oscOpen(QString)));
oo = new PathObject( "/close-all", QVariant::Invalid, osc);
QObject::connect(oo, SIGNAL(data()), SLOT(oscCloseAll()));
oo = new PathObject( "/plugin", QVariant::String, osc);
QObject::connect(oo, SIGNAL(data(QString)), SLOT(oscTriggerPlugin(QString)));
oo = new PathObject( "/color-note", QVariant::List, osc);
QObject::connect(oo, SIGNAL(data(QVariantList)), SLOT(oscColorNote(QVariantList)));
for (const Shortcut* s : Shortcut::shortcuts()) {
oo = new PathObject( QString("/actions/%1").arg(s->key()), QVariant::Invalid, osc);
QObject::connect(oo, SIGNAL(data()), SLOT(oscAction()));
}
}
//---------------------------------------------------------
// oscIntMessage
//---------------------------------------------------------
void MuseScore::oscIntMessage(int val)
{
if (val < 128) {
midiNoteReceived(0, val, 60);
midiNoteReceived(0, val, 0);
}
else
midiCtrlReceived(val-128, 22);
}
void MuseScore::oscAction()
{
PathObject* pathObject = qobject_cast<PathObject*>(sender());
QString path = pathObject->path().mid(9);
QAction* a = getAction(path.toLocal8Bit().data());
a->trigger();
}
void MuseScore::oscGoto(int m)
{
qDebug("GOTO %d", m);
if (cv == 0)
return;
cv->searchPage(m);
}
void MuseScore::oscSelectMeasure(int m)
{
qDebug("SelectMeasure %d", m);
if (cv == 0)
return;
cv->selectMeasure(m);
}
void MuseScore::oscOpen(QString path)
{
qDebug("Open %s", qPrintable(path));
openScore(path);
}
void MuseScore::oscCloseAll()
{
qDebug("CloseAll");
while(cs != 0)
closeScore(cs);
}
//---------------------------------------------------------
// oscTempo
//---------------------------------------------------------
void MuseScore::oscTempo(int val)
{
if (val < 0)
val = 0;
if (val > 127)
val = 127;
val = (val * 240) / 128;
if (playPanel)
playPanel->setRelTempo(val);
if (seq)
seq->setRelTempo(double(val));
}
//---------------------------------------------------------
// oscTriggerPlugin
//---------------------------------------------------------
void MuseScore::oscTriggerPlugin(QString /*s*/)
{
#if 0 // TODO
QStringList args = s.split(",");
if(args.length() > 0) {
int idx = pluginIdxFromPath(args.at(0));
if(idx != -1) {
for(int i = 1; i < args.length()-1; i++) {
addGlobalObjectToPluginEngine(qPrintable(args.at(i)), args.at(i+1));
i++;
}
pluginTriggered(idx);
}
}
#endif
}
//---------------------------------------------------------
// oscColorNote
//---------------------------------------------------------
void MuseScore::oscColorNote(QVariantList list)
{
qDebug() << list;
if(!cs)
return;
if (list.length() != 2 && list.length() != 3)
return;
int tick;
int pitch;
QColor noteColor("red"); //default to red
bool ok;
tick = list[0].toInt(&ok);
if (!ok)
return;
pitch = list[1].toInt(&ok);
if (!ok)
return;
if(list.length() == 3 && list[2].canConvert(QVariant::String)) {
QColor color(list[2].toString());
if(color.isValid())
noteColor = color;
}
Measure* measure = cs->tick2measure(tick);
if(!measure)
return;
Segment* s = measure->findSegment(Segment::SegChordRest, tick);
if (!s)
return;
//get all chords in segment...
int n = cs->nstaves() * VOICES;
for (int i = 0; i < n; i++) {
Element* e = s->element(i);
if (e && e->isChordRest()) {
ChordRest* cr = static_cast<ChordRest*>(e);
if(cr->type() == Element::CHORD) {
Chord* chord = static_cast<Chord*>(cr);
for (int idx = 0; idx < chord->notes().length(); idx++) {
Note* note = chord->notes()[idx];
if (note->pitch() == pitch) {
cs->startCmd();
cs->undo(new ChangeProperty(note, P_COLOR, noteColor));
cs->endCmd();
cs->end();
return;
}
}
}
}
}
}
//---------------------------------------------------------
// oscVolume
//---------------------------------------------------------
void MuseScore::oscVolume(int val)
{
double v = val / 128.0;
synti->setGain(v);
}
//---------------------------------------------------------
// oscVolChannel
//---------------------------------------------------------
void MuseScore::oscVolChannel(double val)
{
if(!cs)
return;
PathObject* po = (PathObject*) sender();
int i = po->path().mid(4).toInt() - 1;
QList<MidiMapping>* mms = cs->midiMapping();
if( i >= 0 && i < mms->size()) {
MidiMapping mm = mms->at(i);
Channel* channel = mm.articulation;
int iv = lrint(val*127);
seq->setController(channel->channel, CTRL_VOLUME, iv);
channel->volume = iv;
if (mixer)
mixer->partEdit(i)->volume->setValue(iv);
}
}
//---------------------------------------------------------
// oscPanChannel
//---------------------------------------------------------
void MuseScore::oscPanChannel(double val)
{
if(!cs)
return;
PathObject* po = (PathObject*) sender();
int i = po->path().mid(4).toInt() - 1;
QList<MidiMapping>* mms = cs->midiMapping();
if( i >= 0 && i < mms->size()) {
MidiMapping mm = mms->at(i);
Channel* channel = mm.articulation;
int iv = lrint((val + 1) * 64);
seq->setController(channel->channel, CTRL_PANPOT, iv);
channel->volume = iv;
if (mixer)
mixer->partEdit(i)->pan->setValue(iv);
}
}
//---------------------------------------------------------
// oscMuteChannel
//---------------------------------------------------------
void MuseScore::oscMuteChannel(double val)
{
if(!cs)
return;
PathObject* po = (PathObject*) sender();
int i = po->path().mid(5).toInt() - 1;
QList<MidiMapping>* mms = cs->midiMapping();
if( i >= 0 && i < mms->size()) {
MidiMapping mm = mms->at(i);
Channel* channel = mm.articulation;
channel->mute = (val==0.0f ? false : true);
if (mixer)
mixer->partEdit(i)->mute->setCheckState(val==0.0f ? Qt::Unchecked:Qt::Checked);
}
}
#endif // #ifndef OSC
}
|
gpl-2.0
|
ljx0305/ice
|
csharp/test/Glacier2/application/Server.cs
|
1294
|
// **********************************************************************
//
// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
using System;
using System.Reflection;
[assembly: CLSCompliant(true)]
[assembly: AssemblyTitle("IceTest")]
[assembly: AssemblyDescription("Ice test")]
[assembly: AssemblyCompany("ZeroC, Inc.")]
public class Server : TestCommon.Application
{
public override int run(string[] args)
{
communicator().getProperties().setProperty("DeactivatedAdapter.Endpoints", getTestEndpoint(1));
communicator().createObjectAdapter("DeactivatedAdapter");
communicator().getProperties().setProperty("CallbackAdapter.Endpoints", getTestEndpoint(0));
Ice.ObjectAdapter adapter = communicator().createObjectAdapter("CallbackAdapter");
adapter.add(new CallbackI(), Ice.Util.stringToIdentity("callback"));
adapter.activate();
communicator().waitForShutdown();
return 0;
}
public static int Main(string[] args)
{
Server app = new Server();
return app.runmain(args);
}
}
|
gpl-2.0
|
WBCE/WBCE_CMS
|
wbce/modules/ckeditor/ckeditor/plugins/colordialog/lang/sl.js
|
343
|
/*
Copyright (c) 2003-2021, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'colordialog', 'sl', {
clear: 'Poฤisti',
highlight: 'Poudarjeno',
options: 'Moลพnosti barve',
selected: 'Izbrana barva',
title: 'Izberi barvo'
} );
|
gpl-2.0
|
adrianjonmiller/precisionweldingoffroad
|
wp-content/plugins/wp-all-import/views/admin/import/options.php
|
9250
|
<?php
$custom_types = get_post_types(array('_builtin' => false), 'objects');
$isWizard = $this->isWizard;
$baseUrl = $this->baseUrl;
?>
<input type="hidden" id="selected_post_type" value="<?php echo (!empty($post['custom_type'])) ? $post['custom_type'] : '';?>">
<input type="hidden" id="selected_type" value="<?php echo (!empty($post['type'])) ? $post['type'] : '';?>">
<h2>
<?php if ($isWizard): ?>
<?php _e('Import XML/CSV - Step 4: Options', 'pmxi_plugin') ?>
<?php else: ?>
<?php _e('Edit Import Options', 'pmxi_plugin') ?>
<?php endif ?>
</h2>
<h3><?php _e('Click the appropriate tab to choose the type of posts to create.', 'pmxi_plugin');?></h3>
<?php do_action('pmxi_options_header', $isWizard, $post); ?>
<div class="ajax-console">
<?php if ($this->errors->get_error_codes()): ?>
<?php $this->error() ?>
<?php endif ?>
</div>
<table class="layout">
<tr>
<td class="left" style="width:100%;">
<?php $templates = new PMXI_Template_List() ?>
<form class="load_options options <?php echo ! $isWizard ? 'edit' : '' ?>" method="post">
<div class="load-template">
<span><?php _e('Load existing template:','pmxi_plugin');?> </span>
<select name="load_template">
<option value=""><?php _e('Load Template...', 'pmxi_plugin') ?></option>
<?php foreach ($templates->getBy()->convertRecords() as $t): ?>
<option value="<?php echo $t->id ?>"><?php echo $t->name ?></option>
<?php endforeach ?>
<option value="-1"><?php _e('Reset...', 'pmxi_plugin') ?></option>
</select>
</div>
</form>
<h2 class="nav-tab-wrapper woo-nav-tab-wrapper">
<a class="nav-tab nav-tab-active" rel="posts" href="javascript:void(0);"><?php _e('Posts','pmxi_plugin');?></a>
<a class="nav-tab" rel="pages" href="javascript:void(0);"><?php _e('Pages','pmxi_plugin');?></a>
<?php $custom_types = apply_filters( 'pmxi_custom_types', $custom_types );?>
<?php if (count($custom_types)): ?>
<?php foreach ($custom_types as $key => $ct):?>
<a class="nav-tab" rel="<?php echo $key; ?>" href="javascript:void(0);"><?php echo $ct->labels->name ?></a>
<?php endforeach ?>
<?php endif ?>
<?php do_action('pmxi_custom_menu_item'); ?>
</h2>
<div id="pmxi_tabs">
<div class="left">
<!-- Post Options -->
<div id="posts" class="pmxi_tab"> <!-- Basic -->
<form class="options <?php echo ! $isWizard ? 'edit' : '' ?>" method="post">
<input type="hidden" name="type" value="post"/>
<input type="hidden" name="custom_type" value=""/>
<div class="post-type-options">
<table class="form-table" style="max-width:none;">
<?php
$post_type = 'post';
$entry = 'post';
include( 'options/_main_options_template.php' );
do_action('pmxi_extend_options_main', $entry);
include( 'options/_taxonomies_template.php' );
do_action('pmxi_extend_options_taxonomies', $entry);
include( 'options/_categories_template.php' );
do_action('pmxi_extend_options_categories', $entry);
include( 'options/_custom_fields_template.php' );
do_action('pmxi_extend_options_custom_fields', $entry);
include( 'options/_featured_template.php' );
do_action('pmxi_extend_options_featured', $entry);
include( 'options/_author_template.php' );
do_action('pmxi_extend_options_author', $entry);
include( 'options/_reimport_template.php' );
include( 'options/_settings_template.php' );
?>
</table>
</div>
<?php include( 'options/_buttons_template.php' ); ?>
</form>
</div>
<!-- Page Options -->
<div id="pages" class="pmxi_tab">
<form class="options <?php echo ! $isWizard ? 'edit' : '' ?>" method="post">
<input type="hidden" name="type" value="page"/>
<input type="hidden" name="custom_type" value=""/>
<div class="post-type-options">
<table class="form-table" style="max-width:none;">
<?php
$post_type = 'post';
$entry = 'page';
include( 'options/_main_options_template.php' );
?>
<tr>
<td align="center" width="33%">
<label><?php _e('Page Template', 'pmxi_plugin') ?></label> <br>
<select name="page_template" id="page_template">
<option value='default'><?php _e('Default', 'pmxi_plugin') ?></option>
<?php page_template_dropdown($post['page_template']); ?>
</select>
</td>
<td align="center" width="33%">
<label><?php _e('Parent Page', 'pmxi_plugin') ?></label> <br>
<?php wp_dropdown_pages(array('post_type' => 'page', 'selected' => $post['parent'], 'name' => 'parent', 'show_option_none' => __('(no parent)', 'pmxi_plugin'), 'sort_column'=> 'menu_order, post_title',)) ?>
</td>
<td align="center" width="33%">
<label><?php _e('Order', 'pmxi_plugin') ?></label> <br>
<input type="text" class="" name="order" value="<?php echo esc_attr($post['order']) ?>" />
</td>
</tr>
<?php
do_action('pmxi_extend_options_main', $entry);
include( 'options/_custom_fields_template.php' );
do_action('pmxi_extend_options_custom_fields', $entry);
include( 'options/_taxonomies_template.php' );
do_action('pmxi_extend_options_taxonomies', $entry);
include( 'options/_featured_template.php' );
do_action('pmxi_extend_options_featured', $entry);
include( 'options/_author_template.php' );
do_action('pmxi_extend_options_author', $entry);
include( 'options/_reimport_template.php' );
include( 'options/_settings_template.php' );
?>
</table>
</div>
<?php include( 'options/_buttons_template.php' ); ?>
</form>
</div>
<!-- Custom Post Types -->
<?php
if (count($custom_types)): ?>
<?php foreach ($custom_types as $key => $ct):?>
<div id="<?php echo $key;?>" class="pmxi_tab">
<form class="options <?php echo ! $isWizard ? 'edit' : '' ?>" method="post">
<input type="hidden" name="custom_type" value="<?php echo $key; ?>"/>
<input type="hidden" name="type" value="post"/>
<div class="post-type-options">
<table class="form-table" style="max-width:none;">
<?php
$post_type = $entry = $key;
include( 'options/_main_options_template.php' );
do_action('pmxi_extend_options_main', $entry);
include( 'options/_taxonomies_template.php' );
do_action('pmxi_extend_options_taxonomies', $entry);
include( 'options/_categories_template.php' );
do_action('pmxi_extend_options_categories', $entry);
include( 'options/_custom_fields_template.php' );
do_action('pmxi_extend_options_custom_fields', $entry);
include( 'options/_featured_template.php' );
do_action('pmxi_extend_options_featured', $entry);
include( 'options/_author_template.php' );
do_action('pmxi_extend_options_author', $entry);
include( 'options/_reimport_template.php' );
include( 'options/_settings_template.php' );
?>
</table>
</div>
<?php include( 'options/_buttons_template.php' ); ?>
</form>
</div>
<?php endforeach ?>
<?php endif ?>
<?php do_action('pmxi_custom_options_tab', $isWizard, $post);?>
</div>
<?php if ($isWizard or $this->isTemplateEdit): ?>
<div class="right options">
<?php $this->tag() ?>
</div>
<?php endif ?>
</div>
</td>
</tr>
</table>
<div id="record_matching_pointer" style="display:none;">
<h3><?php _e("Record Matching", "pmxi_plugin");?></h3>
<p>
<b><?php _e("Record Matching is how WP All Import matches records in your file with posts that already exist WordPress.","pmxi_plugin");?></b>
</p>
<p>
<?php _e("Record Matching is most commonly used to tell WP All Import how to match up records in your file with posts WP All Import has already created on your site, so that if your file is updated with new data, WP All Import can update your posts accordingly.","pmxi_plugin");?>
</p>
<hr />
<p><?php _e("AUTOMATIC RECORD MATCHING","pmxi_plugin");?></p>
<p>
<?php _e("Automatic Record Matching allows WP All Import to update records that were imported or updated during the last run of this same import.","pmxi_plugin");?>
</p>
<p>
<?php _e("Your unique key must be UNIQUE for each record in your feed. Make sure you get it right - you can't change it later. You'll have to re-create your import.","pmxi_plugin");?>
</p>
<hr />
<p><?php _e("MANUAL RECORD MATCHING", "pmxi_plugin");?></p>
<p>
<?php _e("Manual record matching allows WP All Import to update any records, even records that were not imported with WP All Import, or are part of a different import.","pmxi_plugin");?>
</p>
</div>
|
gpl-2.0
|
legacysurvey/pipeline
|
validationtests/desi_image_validation3.py
|
76050
|
#
import os
import numpy as np
import healpy as hp
import astropy.io.fits as pyfits
from multiprocessing import Pool
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from quicksipManera3 import *
import fitsio
from random import random
import matplotlib.colors as colors
### ------------ A couple of useful conversions -----------------------
def zeropointToScale(zp):
return 10.**((zp - 22.5)/2.5)
def nanomaggiesToMag(nm):
return -2.5 * (log(nm,10.) - 9.)
def Magtonanomaggies(m):
return 10.**(-m/2.5+9.)
#-2.5 * (log(nm,10.) - 9.)
def thphi2radec(theta,phi):
return 180./pi*phi,-(180./pi*theta-90)
# --------- Definitions for polinomial footprints -------
def convertCoordsToPoly (ra, dec) :
poly = []
for i in range(0,len(ra)) :
poly.append((ra[i], dec[i]))
return poly
def point_in_poly(x,y,poly):
n = len(poly)
inside = False
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
return inside
#### Class for plotting diverging colours to choosen mid point
# set the colormap and centre the colorbar
class MidpointNormalize(colors.Normalize):
"""
Normalise the colorbar so that diverging bars work there way either side from a prescribed midpoint value)
e.g. im=ax1.imshow(array, norm=MidpointNormalize(midpoint=0.,vmin=-100, vmax=100))
"""
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
colors.Normalize.__init__(self, vmin, vmax, clip)
def __call__(self, value, clip=None):
# I'm ignoring masked values and all kinds of edge cases to make a
# simple example...
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y), np.isnan(value))
### ------------ SHARED CLASS: HARDCODED INPUTS GO HERE ------------------------
### Please, add here your own harcoded values if any, so other may use them
class mysample(object):
"""
This class mantains the basic information of the sample
to minimize hardcoded parameters in the test functions
Everyone is meant to call mysample to obtain information like
- path to ccd-annotated files : ccds
- zero points : zp0
- magnitude limits (recm) : recm
- photoz requirements : phreq
- extintion coefficient : extc
- extintion index : be
- mask var eqv. to blacklist_ok : maskname
- predicted frac exposures : FracExp
- footprint poly (in some cases) : polyFoot
Current Inputs are: survey, DR, band, localdir)
survey: DECaLS, MZLS, BASS, DEShyb, NGCproxy
DR: DR3, DR4, DR5
band: g,r,z
localdir: output directory
(DEShyb is some DES proxy area; NGC is a proxy of North Gal Cap)
"""
def __init__(self,survey,DR,band,localdir,verb):
"""
Initialize image survey, data release, band, output path
Calculate variables and paths
"""
self.survey = survey
self.DR = DR
self.band = band
self.localdir = localdir
self.verbose =verb
# Check bands
if(self.band != 'g' and self.band !='r' and self.band!='z'):
raise RuntimeError("Band seems wrong options are 'g' 'r' 'z'")
# Check surveys
if(self.survey !='DECaLS' and self.survey !='BASS' and self.survey !='MZLS' and self.survey !='DEShyb' and self.survey !='NGCproxy'):
raise RuntimeError("Survey seems wrong options are 'DECAaLS' 'BASS' MZLS' ")
# Annotated CCD paths
if(self.DR == 'DR3'):
inputdir = '/global/project/projectdirs/cosmo/data/legacysurvey/dr3/'
self.ccds =inputdir+'ccds-annotated-decals.fits.gz'
self.catalog = 'DECaLS_DR3'
if(self.survey != 'DECaLS'): raise RuntimeError("Survey name seems inconsistent; only DECaLS accepted")
elif(self.DR == 'DR4'):
inputdir = '/global/project/projectdirs/cosmo/data/legacysurvey/dr4/'
if (band == 'g' or band == 'r'):
#self.ccds = inputdir+'ccds-annotated-dr4-90prime.fits.gz'
self.ccds = inputdir+'ccds-annotated-bass.fits.gz'
self.catalog = 'BASS_DR4'
if(self.survey != 'BASS'): raise RuntimeError("Survey name seems inconsistent")
elif(band == 'z'):
#self.ccds = inputdir+'ccds-annotated-dr4-mzls.fits.gz'
self.ccds = inputdir+'ccds-annotated-mzls.fits.gz'
self.catalog = 'MZLS_DR4'
if(self.survey != 'MZLS'): raise RuntimeError("Survey name seems inconsistent")
else: raise RuntimeError("Input sample band seems inconsisent")
elif(self.DR == 'DR5'):
inputdir = '/global/project/projectdirs/cosmo/data/legacysurvey/dr5/'
self.ccds =inputdir+'ccds-annotated-dr5.fits.gz'
if(self.survey == 'DECaLS') :
self.catalog = 'DECaLS_DR5'
elif(self.survey == 'DEShyb') :
self.catalog = 'DEShyb_DR5'
elif(self.survey == 'NGCproxy' ) :
self.catalog = 'NGCproxy_DR5'
else: raise RuntimeError("Survey name seems inconsistent")
elif(self.DR == 'DR6'):
inputdir = '/global/cscratch1/sd/dstn/dr6plus/'
if (band == 'g'):
self.ccds = inputdir+'ccds-annotated-90prime-g.fits.gz'
self.catalog = 'BASS_DR6'
if(self.survey != 'BASS'): raise RuntimeError("Survey name seems inconsistent")
elif (band == 'r'):
self.ccds = inputdir+'ccds-annotated-90prime-r.fits.gz'
self.catalog = 'BASS_DR6'
if(self.survey != 'BASS'): raise RuntimeError("Survey name seems inconsistent")
elif(band == 'z'):
self.ccds = inputdir+'ccds-annotated-mosaic-z.fits.gz'
self.catalog = 'MZLS_DR6'
if(self.survey != 'MZLS'): raise RuntimeError("Survey name seems inconsistent")
else: raise RuntimeError("Input sample band seems inconsisent")
elif(self.DR == 'DR7'):
inputdir = '/global/project/projectdirs/cosmo/data/legacysurvey/dr7/'
self.ccds =inputdir+'ccds-annotated-dr7.fits.gz'
if(self.survey == 'DECaLS') :
self.catalog = 'DECaLS_DR7'
elif(self.survey == 'DEShyb') :
self.catalog = 'DEShyb_DR7'
elif(self.survey == 'NGCproxy' ) :
self.catalog = 'NGCproxy_DR7'
else: raise RuntimeError("Survey name seems inconsistent")
else: raise RuntimeError("Data Realease seems wrong")
# Make directory for outputs if it doesn't exist
dirplots = localdir + self.catalog
try:
os.makedirs(dirplots)
print("creating directory for plots", dirplots)
except OSError:
if not os.path.isdir(dirplots):
raise
# Predicted survey exposure fractions
if(self.survey =='DECaLS' or self.survey =='DEShyb' or self.survey =='NGCproxy'):
# DECALS final survey will be covered by
# 1, 2, 3, 4, and 5 exposures in the following fractions:
self.FracExp=[0.02,0.24,0.50,0.22,0.02]
elif(self.survey == 'BASS'):
# BASS coverage fractions for 1,2,3,4,5 exposures are:
self.FracExp=[0.0014,0.0586,0.8124,0.1203,0.0054,0.0019]
elif(self.survey == 'MZLS'):
# For MzLS fill factors of 100% with a coverage of at least 1,
# 99.5% with a coverage of at least 2, and 85% with a coverage of 3.
self.FracExp=[0.005,0.145,0.85,0,0]
else:
raise RuntimeError("Survey seems to have wrong options for fraction of exposures ")
#Bands inputs
if band == 'g':
self.be = 1
self.extc = 3.303 #/2.751
self.zp0 = 25.08
self.recm = 24.
self.phreq = 0.01
if band == 'r':
self.be = 2
self.extc = 2.285 #/2.751
self.zp0 = 25.29
self.recm = 23.4
self.phreq = 0.01
if band == 'z':
self.be = 4
self.extc = 1.263 #/2.751
self.zp0 = 24.92
self.recm = 22.5
self.phreq = 0.02
if(self.survey =='DECaLS' or self.survey =='DEShyb' or self.survey !='NGCproxy'):
self.pixsize = 0.2637 #arcsec
if(self.survey =='BASS'):
self.pixsize = 0.454
if(self.survey =='MZLS'):
self.pixsize = 0.26
# ------------------------------------------------------------------
# --- Footprints ----
polyDEScoord=np.loadtxt('/global/homes/m/manera/round13-poly-radec.dat')
polyDES = convertCoordsToPoly(polyDEScoord[:,0], polyDEScoord[:,1])
def InDEShybFootprint(RA,DEC):
''' Decides if it is in DES footprint '''
# The DES footprint
if(RA > 180) : RA = RA -360
return point_in_poly(RA, DEC, polyDES)
def InNGCproxyFootprint(RA):
if(RA < -180 ) : RA = RA + 360
if( 100 <= RA <= 300 ) : return True
return False
def plot_fwhm2D(sample,ral,decl,fwhm,mapfile,mytitle):
# Plot depth
from matplotlib import pyplot as plt
import matplotlib.cm as cm
ralB = [ ra-360 if ra > 300 else ra for ra in ral ]
#vmax = sample.recm + 2.0
#vmin = sample.recm - 2.0
##mapa = plt.scatter(ralB,decl,c=depth, cmap=cm.gnuplot,s=2., vmin=vmin, vmax=vmax, lw=0,edgecolors='none')
#mapa = plt.scatter(ralB,decl,c=depth, cmap=cm.RdYlBu_r,s=2., vmin=vmin, vmax=vmax, lw=0,edgecolors='none')
#mapa = plt.scatter(ralB,decl,c=fwhm, cmap=cm.RdYlBu_r,s=2., lw=0,edgecolors='none')
mapa = plt.scatter(ralB,decl,c=fwhm, cmap=cm.bwr_r,s=2.,vmin=0.5, vmax=1.8, lw=0,edgecolors='none')
mapa.cmap.set_over('lawngreen')
cbar = plt.colorbar(mapa,extend='both')
plt.xlabel('r.a. (degrees)')
plt.ylabel('declination (degrees)')
plt.title(mytitle)
plt.xlim(-60,300)
plt.ylim(-30,90)
print('saving plot image to %s', mapfile)
plt.savefig(mapfile)
plt.close()
return
def plot_magdepth2D(sample,ral,decl,depth,mapfile,mytitle):
# Plot depth
from matplotlib import pyplot as plt
import matplotlib.cm as cm
ralB = [ ra-360 if ra > 300 else ra for ra in ral ]
vmax = sample.recm + 2.0
vmin = sample.recm - 2.0
##mapa = plt.scatter(ralB,decl,c=depth, cmap=cm.gnuplot,s=2., vmin=vmin, vmax=vmax, lw=0,edgecolors='none')
mapa = plt.scatter(ralB,decl,c=depth, cmap=cm.RdYlBu_r,s=2., vmin=vmin, vmax=vmax, lw=0,edgecolors='none')
mapa.cmap.set_over('lawngreen')
cbar = plt.colorbar(mapa,extend='both')
plt.xlabel('r.a. (degrees)')
plt.ylabel('declination (degrees)')
plt.title(mytitle)
plt.xlim(-60,300)
plt.ylim(-30,90)
print('saving plot image to %s', mapfile)
plt.savefig(mapfile)
plt.close()
return
def plot_magdepth2Db(sample,ral,decl,depth,mapfile,mytitle):
# Plot depth
from matplotlib import pyplot as plt
import matplotlib.cm as cm
#ralB = [ ra-360 if ra > 300 else ra for ra in ral ]
#vmax = sample.recm
#vmin = vmax - 2.0
# test
# plt.imshow(ras, cmap=cmap, clim=(elev_min, elev_max), norm=MidpointNormalize(midpoint=mid_val,vmin=elev_min, vmax=elev_max))
# test
#vmaxext=vmax+2.0
# mapa = plt.scatter(ralB,decl,c=depth, cmap=cm.gnuplot,s=2., norm=MidpointNormalize(midpoint=vmax,vmin=vmin,vmax=vmaxext), vmin=vmin, vmax=vmaxext, lw=0,edgecolors='none')
#mapa = plt.scatter(ralB,decl,c=depth, cmap=cm.gnuplot,s=2., vmin=vmin, vmax=vmax, lw=0,edgecolors='none')
#mapa = plt.scatter(ralB,decl,c=depth, cmap=cm.gnuplot,s=2., vmin=vmin, vmax=vmax, lw=0,edgecolors='none')
mapa = plt.scatter(ral,decl,c=depth, cmap=cm.gnuplot,s=2,vmax=23.0)
mapa.cmap.set_over('lawngreen')
cbar = plt.colorbar(mapa,extend='both')
#plt.xlabel('r.a. (degrees)')
#plt.ylabel('declination (degrees)')
#plt.title(mytitle)
#plt.xlim(-60,300)
#plt.ylim(-30,90)
print('saving plot to ', mapfile)
plt.savefig(mapfile)
plt.close()
return
def prova(sample):
magaux = [20.0+i*0.005 for i in range(1001)]
xaux = [100.0 + float(i%100) for i in range(1001)]
yaux = [100.0 + float(i)/100 for i in range(1001)]
mytitle = 'prova'
mapfile = '/global/homes/m/manera/DESI/validation-outputs/prova.png'
plot_magdepth2Db(sample,xaux,yaux,magaux,mapfile,mytitle)
#plot_magdepth2Db(sample,ral,decl,depth,mapfile,mytitle):
# ------------------------------------------------------------------
# ------------ VALIDATION TESTS ------------------------------------
# ------------------------------------------------------------------
# Note: part of the name of the function should startw with number valXpX
def val3p4c_depthfromIvarOLD(sample):
"""
Requirement V3.4
90% filled to g=24, r=23.4 and z=22.5 and 95% and 98% at 0.3/0.6 mag shallower.
Produces extinction correction magnitude maps for visual inspection
MARCM stable version, improved from AJR quick hack
This now included extinction from the exposures
Uses quicksip subroutines from Boris, corrected
for a bug I found for BASS and MzLS ccd orientation
"""
nside = 1024 # Resolution of output maps
nsideSTR='1024' # same as nside but in string format
nsidesout = None # if you want full sky degraded maps to be written
ratiores = 1 # Superresolution/oversampling ratio, simp mode doesn't allow anything other than 1
mode = 1 # 1: fully sequential, 2: parallel then sequential, 3: fully parallel
pixoffset = 0 # How many pixels are being removed on the edge of each CCD? 15 for DES.
oversamp='1' # ratiores in string format
band = sample.band
catalogue_name = sample.catalog
fname = sample.ccds
localdir = sample.localdir
extc = sample.extc
#Read ccd file
tbdata = pyfits.open(fname)[1].data
# ------------------------------------------------------
# Obtain indices
auxstr='band_'+band
sample_names = [auxstr]
if(sample.DR == 'DR3'):
inds = np.where((tbdata['filter'] == band) & (tbdata['photometric'] == True) & (tbdata['blacklist_ok'] == True))
elif(sample.DR == 'DR4'):
inds = np.where((tbdata['filter'] == band) & (tbdata['photometric'] == True) & (tbdata['bitmask'] == 0))
elif(sample.DR == 'DR5'):
if(sample.survey == 'DECaLS'):
inds = np.where((tbdata['filter'] == band) & (tbdata['photometric'] == True) & (tbdata['blacklist_ok'] == True))
elif(sample.survey == 'DEShyb'):
inds = np.where((tbdata['filter'] == band) & (tbdata['photometric'] == True) & (tbdata['blacklist_ok'] == True) & (list(map(InDEShybFootprint,tbdata['ra'],tbdata['dec']))))
elif(sample.survey == 'NGCproxy'):
inds = np.where((tbdata['filter'] == band) & (tbdata['photometric'] == True) & (tbdata['blacklist_ok'] == True) & (list(map(InNGCproxyFootprint,tbdata['ra']))))
elif(sample.DR == 'DR6'):
inds = np.where((tbdata['filter'] == band))
elif(sample.DR == 'DR7'):
if(sample.survey == 'DECaLS'):
inds = np.where((tbdata['filter'] == band))
elif(sample.survey == 'DEShyb'):
inds = np.where((tbdata['filter'] == band) & (list(map(InDEShybFootprint,tbdata['ra'],tbdata['dec']))))
elif(sample.survey == 'NGCproxy'):
inds = np.where((tbdata['filter'] == band) & (list(map(InNGCproxyFootprint,tbdata['ra']))))
#Read data
#obtain invnoisesq here, including extinction
nmag = Magtonanomaggies(tbdata['galdepth']-extc*tbdata['EBV'])/5.
ivar= 1./nmag**2.
hits=np.ones(np.shape(ivar))
# What properties do you want mapped?
# Each each tuple has [(quantity to be projected, weighting scheme, operation),(etc..)]
propertiesandoperations = [ ('ivar', '', 'total'), ('hits','','total') ]
# What properties to keep when reading the images?
# Should at least contain propertiesandoperations and the image corners.
# MARCM - actually no need for ra dec image corners.
# Only needs ra0 ra1 ra2 ra3 dec0 dec1 dec2 dec3 only if fast track appropriate quicksip subroutines were implemented
#propertiesToKeep = [ 'filter', 'FWHM','mjd_obs'] \
# + ['RA', 'DEC', 'crval1', 'crval2', 'crpix1', 'crpix2', 'cd1_1', 'cd1_2', 'cd2_1', 'cd2_2','width','height']
propertiesToKeep = [ 'filter', 'FWHM','mjd_obs'] \
+ ['RA', 'DEC', 'ra0','ra1','ra2','ra3','dec0','dec1','dec2','dec3']
# Create big table with all relevant properties.
tbdata = np.core.records.fromarrays([tbdata[prop] for prop in propertiesToKeep] + [ivar] + [hits], names = propertiesToKeep + [ 'ivar', 'hits'])
# Read the table, create Healtree, project it into healpix maps, and write these maps.
# Done with Quicksip library, note it has quite a few hardcoded values (use new version by MARCM for BASS and MzLS)
# project_and_write_maps_simp(mode, propertiesandoperations, tbdata, catalogue_name, outroot, sample_names, inds, nside)
#project_and_write_maps(mode, propertiesandoperations, tbdata, catalogue_name, localdir, sample_names, inds, nside, ratiores, pixoffset, nsidesout)
project_and_write_maps_simp(mode, propertiesandoperations, tbdata, catalogue_name, localdir, sample_names, inds, nside)
# Read Haelpix maps from quicksip
prop='ivar'
op='total'
vmin=21.0
vmax=24.0
fname2=localdir+catalogue_name+'/nside'+nsideSTR+'_oversamp'+oversamp+'/'+\
catalogue_name+'_band_'+band+'_nside'+nsideSTR+'_oversamp'+oversamp+'_'+prop+'__'+op+'.fits.gz'
f = fitsio.read(fname2)
# HEALPIX DEPTH MAPS
# convert ivar to depth
import healpy as hp
from healpix3 import pix2ang_ring,thphi2radec
ral = []
decl = []
val = f['SIGNAL']
pix = f['PIXEL']
# Obtain values to plot
if (prop == 'ivar'):
myval = []
mylabel='depth'
below=0
for i in range(0,len(val)):
depth=nanomaggiesToMag(sqrt(1./val[i]) * 5.)
if(depth < vmin):
below=below+1
else:
myval.append(depth)
th,phi = hp.pix2ang(int(nside),pix[i])
ra,dec = thphi2radec(th,phi)
ral.append(ra)
decl.append(dec)
npix=len(pix)
print('Area is ', npix/(float(nside)**2.*12)*360*360./pi, ' sq. deg.')
print(below, 'of ', npix, ' pixels are not plotted as their ', mylabel,' < ', vmin)
print('Within the plot, min ', mylabel, '= ', min(myval), ' and max ', mylabel, ' = ', max(myval))
# Plot depth
from matplotlib import pyplot as plt
import matplotlib.cm as cm
mapa = plt.scatter(ral,decl,c=myval, cmap=cm.rainbow,s=2., vmin=vmin, vmax=vmax, lw=0,edgecolors='none')
cbar = plt.colorbar(mapa)
plt.xlabel('r.a. (degrees)')
plt.ylabel('declination (degrees)')
plt.title('Map of '+ mylabel +' for '+catalogue_name+' '+band+'-band')
plt.xlim(0,360)
plt.ylim(-30,90)
mapfile=localdir+mylabel+'_'+band+'_'+catalogue_name+str(nside)+'.png'
print('saving plot to ', mapfile)
plt.savefig(mapfile)
plt.close()
#plt.show()
#cbar.set_label(r'5$\sigma$ galaxy depth', rotation=270,labelpad=1)
#plt.xscale('log')
# Statistics depths
deptharr=np.array(myval)
p90=np.percentile(deptharr,10)
p95=np.percentile(deptharr,5)
p98=np.percentile(deptharr,2)
med=np.percentile(deptharr,50)
mean = sum(deptharr)/float(np.size(deptharr)) # 1M array, too long for precision
std = sqrt(sum(deptharr**2.)/float(len(deptharr))-mean**2.)
ndrawn=np.size(deptharr)
print("Total pixels", np.size(deptharr), "probably too many for exact mean and std")
print("Mean = ", mean, "; Median = ", med ,"; Std = ", std)
print("Results for 90% 95% and 98% are: ", p90, p95, p98)
# Statistics pases
prop = 'hits'
op = 'total'
fname2=localdir+catalogue_name+'/nside'+nsideSTR+'_oversamp'+oversamp+'/'+\
catalogue_name+'_band_'+band+'_nside'+nsideSTR+'_oversamp'+oversamp+'_'+prop+'__'+op+'.fits.gz'
f = fitsio.read(fname2)
hitsb=f['SIGNAL']
hist, bin_edges =np.histogram(hitsb,bins=[-0.5,0.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5,8.5,100],density=True)
#print hitsb[1000:10015]
#hist, bin_edges =np.histogram(hitsb,density=True)
print("Percentage of hits for 0,1,2., to >7 pases\n", end=' ')
#print bin_edges
print(hist)
#print 100*hist
return mapfile
def val4p1_bandquality(sample,minfwhm=1.3,Nexpmin=1,Nexpmax=500,depthmin=21.0):
"""
Requirement v4.1
z-band image quality will be smaller than 1.3 arcsec FWHM in at least one pass.
allow to be tested in all bands
"""
nside = 1024 # Resolution of output maps
nsideSTR='1024' # same as nside but in string format
nsidesout = None # if you want full sky degraded maps to be written
ratiores = 1 # Superresolution/oversampling ratio, simp mode doesn't allow anything other than 1
mode = 1 # 1: fully sequential, 2: parallel then sequential, 3: fully parallel
pixoffset = 0 # How many pixels are being removed on the edge of each CCD? 15 for DES.
oversamp='1' # ratiores in string format
band = sample.band
catalogue_name = sample.catalog
fname = sample.ccds
localdir = sample.localdir
extc = sample.extc
#Read ccd file
tbdata = pyfits.open(fname)[1].data
# ------------------------------------------------------
# Obtain indices
auxstr='band_'+band
sample_names = [auxstr]
if(sample.DR == 'DR3'):
inds = np.where((tbdata['filter'] == band) & (tbdata['photometric'] == True) & (tbdata['blacklist_ok'] == True))
elif(sample.DR == 'DR4'):
inds = np.where((tbdata['filter'] == band) & (tbdata['photometric'] == True) & (tbdata['bitmask'] == 0))
elif(sample.DR == 'DR5'):
if(sample.survey == 'DECaLS'):
inds = np.where((tbdata['filter'] == band) & (tbdata['photometric'] == True) & (tbdata['blacklist_ok'] == True))
elif(sample.survey == 'DEShyb'):
inds = np.where((tbdata['filter'] == band) & (tbdata['photometric'] == True) & (tbdata['blacklist_ok'] == True) & (list(map(InDEShybFootprint,tbdata['ra'],tbdata['dec']))))
elif(sample.survey == 'NGCproxy'):
inds = np.where((tbdata['filter'] == band) & (tbdata['photometric'] == True) & (tbdata['blacklist_ok'] == True) & (list(map(InNGCproxyFootprint,tbdata['ra']))))
elif(sample.DR == 'DR6'):
inds = np.where((tbdata['filter'] == band))
elif(sample.DR == 'DR7'):
if(sample.survey == 'DECaLS'):
inds = np.where((tbdata['filter'] == band))
elif(sample.survey == 'DEShyb'):
inds = np.where((tbdata['filter'] == band) & (list(map(InDEShybFootprint,tbdata['ra'],tbdata['dec']))))
elif(sample.survey == 'NGCproxy'):
inds = np.where((tbdata['filter'] == band) & (list(map(InNGCproxyFootprint,tbdata['ra']))))
#Read data
#obtain fwhm
myfwhm = tbdata['fwhm']*sample.pixsize
hits=np.ones(np.shape(myfwhm))
print(myfwhm[0:25])
nmag = Magtonanomaggies(tbdata['galdepth']-extc*tbdata['EBV'])/5.
ivar= 1./nmag**2.
# What properties do you want mapped?
# Each each tuple has [(quantity to be projected, weighting scheme, operation),(etc..)]
propertiesandoperations = [ ('myfwhm', '', 'min'), ('hits','','total'),('ivar', '','total') ]
# What properties to keep when reading the images?
# Should at least contain propertiesandoperations and the image corners.
# MARCM - actually no need for ra dec image corners.
# Only needs ra0 ra1 ra2 ra3 dec0 dec1 dec2 dec3 only if fast track appropriate quicksip subroutines were implemented
#propertiesToKeep = [ 'filter', 'FWHM','mjd_obs'] \
# + ['RA', 'DEC', 'crval1', 'crval2', 'crpix1', 'crpix2', 'cd1_1', 'cd1_2', 'cd2_1', 'cd2_2','width','height']
propertiesToKeep = [ 'filter', 'FWHM','mjd_obs'] \
+ ['RA', 'DEC', 'ra0','ra1','ra2','ra3','dec0','dec1','dec2','dec3']
# Create big table with all relevant properties.
tbdata = np.core.records.fromarrays([tbdata[prop] for prop in propertiesToKeep] + [myfwhm] + [hits] + [ivar], names = propertiesToKeep + [ 'myfwhm', 'hits', 'ivar'])
# Read the table, create Healtree, project it into healpix maps, and write these maps.
# Done with Quicksip library, note it has quite a few hardcoded values (use new version by MARCM for BASS and MzLS)
# project_and_write_maps_simp(mode, propertiesandoperations, tbdata, catalogue_name, outroot, sample_names, inds, nside)
#project_and_write_maps(mode, propertiesandoperations, tbdata, catalogue_name, localdir, sample_names, inds, nside, ratiores, pixoffset, nsidesout)
project_and_write_maps_simp(mode, propertiesandoperations, tbdata, catalogue_name, localdir, sample_names, inds, nside)
# HEALPIX DEPTH MAPS
# convert ivar to depth
import healpy as hp
from healpix3 import pix2ang_ring,thphi2radec
# Read Haelpix maps from quicksip
prop='myfwhm'
op='min'
fname2=localdir+catalogue_name+'/nside'+nsideSTR+'_oversamp'+oversamp+'/'+\
catalogue_name+'_band_'+band+'_nside'+nsideSTR+'_oversamp'+oversamp+'_'+prop+'__'+op+'.fits.gz'
f = fitsio.read(fname2)
ral = []
decl = []
val = f['SIGNAL']
pix = f['PIXEL']
#get hits
prop = 'hits'
op = 'total'
fname2=localdir+catalogue_name+'/nside'+nsideSTR+'_oversamp'+oversamp+'/'+\
catalogue_name+'_band_'+band+'_nside'+nsideSTR+'_oversamp'+oversamp+'_'+prop+'__'+op+'.fits.gz'
f = fitsio.read(fname2)
hitsb=f['SIGNAL']
# get depth
prop='ivar'
op='total'
fname2=localdir+catalogue_name+'/nside'+nsideSTR+'_oversamp'+oversamp+'/'+\
catalogue_name+'_band_'+band+'_nside'+nsideSTR+'_oversamp'+oversamp+'_'+prop+'__'+op+'.fits.gz'
f = fitsio.read(fname2)
ivarxx = f['SIGNAL']
# Obtain values to plot
#if (prop == 'ivar'):
myval = []
mylabel='minfwhm'
above=0
for i in range(0,len(val)):
seeing= val[i]
npases=hitsb[i]
mydepth = nanomaggiesToMag(np.sqrt(1./ivarxx[i] * 5.))
if(npases >= Nexpmin and npases <= Nexpmax and mydepth >= depthmin ):
myval.append(seeing)
th,phi = hp.pix2ang(int(nside),pix[i])
ra,dec = thphi2radec(th,phi)
ral.append(ra)
decl.append(dec)
if(seeing > minfwhm):
above=above+1
npix=len(myval)
# plot histogram
from matplotlib import pyplot as plt
import matplotlib.cm as cm
plt.hist(myval,bins=20,range=(0.5,1.5))
histfile = localdir+mylabel+'_'+band+'_hist_'+catalogue_name+str(nside)+'.png'
plt.savefig(histfile)
plt.close()
#
# write some numbers
print('Area is ', npix/(float(nside)**2.*12)*360*360./pi, ' sq. deg.')
print('Area with fwhm above ', minfwhm, 'is', above/(float(nside)**2.*12)*360*360./pi, ' sq. deg.')
print('Corresponding to ', above, 'of ', npix, ' pixels')
print('Within the plot, min ', mylabel, '= ', min(myval), ' and max ', mylabel, ' = ', max(myval))
# plot map
mapfile=localdir+mylabel+'_'+band+'_'+catalogue_name+str(nside)+'.png'
mytitle='Map of '+ mylabel +' for '+catalogue_name+' '+band+'-band \n with '+str(Nexpmin)+\
' or more exposures'
plot_fwhm2D(sample,ral,decl,myval,mapfile,mytitle)
return mapfile, histfile
def val3p4c_depthfromIvar(sample,Nexpmin=1,Nexpmax=500):
"""
Requirement V3.4
90% filled to g=24, r=23.4 and z=22.5 and 95% and 98% at 0.3/0.6 mag shallower.
Produces extinction correction magnitude maps for visual inspection
MARCM includes min number of exposures
MARCM stable version, improved from AJR quick hack
This now included extinction from the exposures
Uses quicksip subroutines from Boris, corrected
for a bug I found for BASS and MzLS ccd orientation
"""
nside = 1024 # Resolution of output maps
nsideSTR='1024' # same as nside but in string format
nsidesout = None # if you want full sky degraded maps to be written
ratiores = 1 # Superresolution/oversampling ratio, simp mode doesn't allow anything other than 1
mode = 1 # 1: fully sequential, 2: parallel then sequential, 3: fully parallel
pixoffset = 0 # How many pixels are being removed on the edge of each CCD? 15 for DES.
oversamp='1' # ratiores in string format
band = sample.band
catalogue_name = sample.catalog
fname = sample.ccds
localdir = sample.localdir
extc = sample.extc
#Read ccd file
tbdata = pyfits.open(fname)[1].data
# ------------------------------------------------------
# Obtain indices
auxstr='band_'+band
sample_names = [auxstr]
if(sample.DR == 'DR3'):
inds = np.where((tbdata['filter'] == band) & (tbdata['photometric'] == True) & (tbdata['blacklist_ok'] == True))
elif(sample.DR == 'DR4'):
inds = np.where((tbdata['filter'] == band) & (tbdata['photometric'] == True) & (tbdata['bitmask'] == 0))
elif(sample.DR == 'DR5'):
if(sample.survey == 'DECaLS'):
inds = np.where((tbdata['filter'] == band) & (tbdata['photometric'] == True) & (tbdata['blacklist_ok'] == True))
elif(sample.survey == 'DEShyb'):
inds = np.where((tbdata['filter'] == band) & (tbdata['photometric'] == True) & (tbdata['blacklist_ok'] == True) & (list(map(InDEShybFootprint,tbdata['ra'],tbdata['dec']))))
elif(sample.survey == 'NGCproxy'):
inds = np.where((tbdata['filter'] == band) & (tbdata['photometric'] == True) & (tbdata['blacklist_ok'] == True) & (list(map(InNGCproxyFootprint,tbdata['ra']))))
elif(sample.DR == 'DR6'):
inds = np.where((tbdata['filter'] == band))
elif(sample.DR == 'DR7'):
if(sample.survey == 'DECaLS'):
inds = np.where((tbdata['filter'] == band))
elif(sample.survey == 'DEShyb'):
inds = np.where((tbdata['filter'] == band) & (list(map(InDEShybFootprint,tbdata['ra'],tbdata['dec']))))
elif(sample.survey == 'NGCproxy'):
inds = np.where((tbdata['filter'] == band) & (list(map(InNGCproxyFootprint,tbdata['ra']))))
#Read data
#obtain invnoisesq here, including extinction
nmag = Magtonanomaggies(tbdata['galdepth']-extc*tbdata['EBV'])/5.
ivar= 1./nmag**2.
hits=np.ones(np.shape(ivar))
# What properties do you want mapped?
# Each each tuple has [(quantity to be projected, weighting scheme, operation),(etc..)]
propertiesandoperations = [ ('ivar', '', 'total'), ('hits','','total') ]
# What properties to keep when reading the images?
# Should at least contain propertiesandoperations and the image corners.
# MARCM - actually no need for ra dec image corners.
# Only needs ra0 ra1 ra2 ra3 dec0 dec1 dec2 dec3 only if fast track appropriate quicksip subroutines were implemented
#propertiesToKeep = [ 'filter', 'FWHM','mjd_obs'] \
# + ['RA', 'DEC', 'crval1', 'crval2', 'crpix1', 'crpix2', 'cd1_1', 'cd1_2', 'cd2_1', 'cd2_2','width','height']
propertiesToKeep = [ 'filter', 'FWHM','mjd_obs'] \
+ ['RA', 'DEC', 'ra0','ra1','ra2','ra3','dec0','dec1','dec2','dec3']
# Create big table with all relevant properties.
tbdata = np.core.records.fromarrays([tbdata[prop] for prop in propertiesToKeep] + [ivar] + [hits], names = propertiesToKeep + [ 'ivar', 'hits'])
# Read the table, create Healtree, project it into healpix maps, and write these maps.
# Done with Quicksip library, note it has quite a few hardcoded values (use new version by MARCM for BASS and MzLS)
# project_and_write_maps_simp(mode, propertiesandoperations, tbdata, catalogue_name, outroot, sample_names, inds, nside)
#project_and_write_maps(mode, propertiesandoperations, tbdata, catalogue_name, localdir, sample_names, inds, nside, ratiores, pixoffset, nsidesout)
project_and_write_maps_simp(mode, propertiesandoperations, tbdata, catalogue_name, localdir, sample_names, inds, nside)
# Read Haelpix maps from quicksip
prop='ivar'
op='total'
vmin=21.0
vmax=24.0
fname2=localdir+catalogue_name+'/nside'+nsideSTR+'_oversamp'+oversamp+'/'+\
catalogue_name+'_band_'+band+'_nside'+nsideSTR+'_oversamp'+oversamp+'_'+prop+'__'+op+'.fits.gz'
f = fitsio.read(fname2)
# HEALPIX DEPTH MAPS
# convert ivar to depth
import healpy as hp
from healpix3 import pix2ang_ring,thphi2radec
ral = []
decl = []
val = f['SIGNAL']
pix = f['PIXEL']
#get hits
prop = 'hits'
op = 'total'
fname2=localdir+catalogue_name+'/nside'+nsideSTR+'_oversamp'+oversamp+'/'+\
catalogue_name+'_band_'+band+'_nside'+nsideSTR+'_oversamp'+oversamp+'_'+prop+'__'+op+'.fits.gz'
f = fitsio.read(fname2)
hitsb=f['SIGNAL']
# Obtain values to plot
#if (prop == 'ivar'):
myval = []
mylabel='depth'
below=0
for i in range(0,len(val)):
depth=nanomaggiesToMag(sqrt(1./val[i]) * 5.)
npases=hitsb[i]
if(npases >= Nexpmin and npases <= Nexpmax ):
myval.append(depth)
th,phi = hp.pix2ang(int(nside),pix[i])
ra,dec = thphi2radec(th,phi)
ral.append(ra)
decl.append(dec)
if(depth < vmin):
below=below+1
npix=len(myval)
print('Area is ', npix/(float(nside)**2.*12)*360*360./pi, ' sq. deg.')
print(below, 'of ', npix, ' pixels are not plotted as their ', mylabel,' < ', vmin)
print('Within the plot, min ', mylabel, '= ', min(myval), ' and max ', mylabel, ' = ', max(myval))
# Plot depth
#from matplotlib import pyplot as plt
#import matplotlib.cm as cm
#ralB = [ ra-360 if ra > 300 else ra for ra in ral ]
#vmax = sample.recm
#vmin = vmax - 2.0
#mapa = plt.scatter(ralB,decl,c=myval, cmap=cm.rainbow,s=2., vmin=vmin, vmax=vmax, lw=0,edgecolors='none')
#mapa = plt.scatter(ralB,decl,c=myval, cmap=cm.gnuplot,s=2., vmin=vmin, vmax=vmax, lw=0,edgecolors='none')
#mapa.cmap.set_over('yellowgreen')
#cbar = plt.colorbar(mapa,extend='both')
#plt.xlabel('r.a. (degrees)')
#plt.ylabel('declination (degrees)')
#plt.title('Map of '+ mylabel +' for '+catalogue_name+' '+band+'-band \n with 3 or more exposures')
#plt.xlim(-60,300)
#plt.ylim(-30,90)
#mapfile=localdir+mylabel+'_'+band+'_'+catalogue_name+str(nside)+'.png'
#print 'saving plot to ', mapfile
#plt.savefig(mapfile)
#plt.close()
#plt.show()
#cbar.set_label(r'5$\sigma$ galaxy depth', rotation=270,labelpad=1)
#plt.xscale('log')
mapfile=localdir+mylabel+'_'+band+'_'+catalogue_name+str(nside)+'.png'
mytitle='Map of '+ mylabel +' for '+catalogue_name+' '+band+'-band \n with '+str(Nexpmin)+\
' or more exposures'
plot_magdepth2D(sample,ral,decl,myval,mapfile,mytitle)
# Statistics depths
deptharr=np.array(myval)
p90=np.percentile(deptharr,10)
p95=np.percentile(deptharr,5)
p98=np.percentile(deptharr,2)
med=np.percentile(deptharr,50)
mean = sum(deptharr)/float(np.size(deptharr)) # 1M array, too long for precision
std = sqrt(sum(deptharr**2.)/float(len(deptharr))-mean**2.)
ndrawn=np.size(deptharr)
print("Total pixels", np.size(deptharr), "probably too many for exact mean and std")
print("Mean = ", mean, "; Median = ", med ,"; Std = ", std)
print("Results for 90% 95% and 98% are: ", p90, p95, p98)
# Statistics pases
#prop = 'hits'
#op = 'total'
#fname2=localdir+catalogue_name+'/nside'+nsideSTR+'_oversamp'+oversamp+'/'+\
#catalogue_name+'_band_'+band+'_nside'+nsideSTR+'_oversamp'+oversamp+'_'+prop+'__'+op+'.fits.gz'
#f = fitsio.read(fname2)
#hitsb=f['SIGNAL']
hist, bin_edges =np.histogram(hitsb,bins=[-0.5,0.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5,8.5,9.5,10.5, 11.5,12.5, 13.5, 14.5, 15.5, 16.15,17.5,18.5,19.5,20.5,21.5,22.5,23.5,24.5,25.5,100],density=True)
#print hitsb[1000:10015]
#hist, bin_edges =np.histogram(hitsb,density=True)
print("Percentage of hits for 0,1,2., to >7 pases\n", end=' ')
#print bin_edges
print(hist)
#print 100*hist
return mapfile
#def plot_magdepth2D(sample,ral,decl,depth,mapfile,mytitle):
# # Plot depth
# from matplotlib import pyplot as plt
# import matplotlib.cm as cm
# ralB = [ ra-360 if ra > 300 else ra for ra in ral ]
# vmax = sample.recm
# vmin = vmax - 2.0
# #test
# vmaxup= vmax+2.0
# mapa = plt.scatter(ralB,decl,c=depth, cmap=cm.gnuplot,s=2., norm=MidpointNormalize(midpoint=vmax,vmin=vmin, vmax=vmaxup), vmin=vmin, vmax=vmaxup, lw=0,edgecolors='none')
# mapa = plt.scatter(ralB,decl,c=depth, cmap=cm.gnuplot,s=2., vmin=vmin, vmax=vmax, lw=0,edgecolors='none')
# mapa.cmap.set_over('yellowgreen')
# cbar = plt.colorbar(mapa,extend='both')
# plt.xlabel('r.a. (degrees)')
# plt.ylabel('declination (degrees)')
# plt.title(mytitle)
# plt.xlim(-60,300)
# plt.ylim(-30,90)
# print('saving plot to ', mapfile)
# plt.savefig(mapfile)
# plt.close()
# return mapfile
def val3p4b_maghist_pred(sample,ndraw=1e5, nbin=100, vmin=21.0, vmax=25.0, Nexpmin=1,enterFrac=False,fraclist=[0,0]):
"""
Requirement V3.4
90% filled to g=24, r=23.4 and z=22.5 and 95% and 98% at 0.3/0.6 mag shallower.
MARCM
Makes histogram of predicted magnitudes
by MonteCarlo from exposures converving fraction of number of exposures
This produces the histogram for Dustin's processed galaxy depth
"""
myfrac = sample.FracExp
if( enterFrac == True ) : myfrac = fraclist
# Check fraction of number of exposures adds to 1.
#if( abs(sum(sample.FracExp) - 1.0) > 1e-5 ):
if( abs(sum(myfrac) - 1.0) > 1e-5 ):
raise ValueError("Fration of number of exposures don't add to one")
# Survey inputs
rel = sample.DR
catalogue_name = sample.catalog
band = sample.band
be = sample.be
zp0 = sample.zp0
recm = sample.recm
verbose = sample.verbose
f = fitsio.read(sample.ccds)
#read in magnitudes including extinction
counts2014 = 0
counts20 = 0
nl = []
for i in range(0,len(f)):
#year = int(f[i]['date_obs'].split('-')[0])
#if (year <= 2014): counts2014 = counts2014 + 1
if f[i]['dec'] < -20 : counts20 = counts20 + 1
if(sample.DR == 'DR3'):
if f[i]['filter'] == sample.band and f[i]['photometric'] == True and f[i]['blacklist_ok'] == True :
magext = f[i]['galdepth'] - f[i]['decam_extinction'][be]
nmag = Magtonanomaggies(magext)/5. #total noise
nl.append(nmag)
if(sample.DR == 'DR4'):
if f[i]['filter'] == sample.band and f[i]['photometric'] == True and f[i]['bitmask'] == 0 :
magext = f[i]['galdepth'] - f[i]['decam_extinction'][be]
nmag = Magtonanomaggies(magext)/5. #total noise
nl.append(nmag)
if(sample.DR == 'DR5'):
if f[i]['filter'] == sample.band and f[i]['photometric'] == True and f[i]['blacklist_ok'] == True :
if(sample.survey == 'DEShyb'):
RA = f[i]['ra']
DEC = f[i]['dec'] # more efficient to put this inside the function directly
if(not InDEShybFootprint(RA,DEC) ): continue # skip if not in DEShyb
if(sample.survey == 'NGCproxy'):
RA = f[i]['ra'] # more efficient to put this inside the function directly
if(not InNGCproxyFootprint(RA) ): continue # skip if not in NGC
magext = f[i]['galdepth'] - f[i]['decam_extinction'][be]
nmag = Magtonanomaggies(magext)/5. #total noise
nl.append(nmag)
if(sample.DR == 'DR6'):
if f[i]['filter'] == sample.band :
magext = f[i]['galdepth'] - f[i]['decam_extinction'][be]
nmag = Magtonanomaggies(magext)/5. #total noise
nl.append(nmag)
if(sample.DR == 'DR7'):
#if f[i]['filter'] == sample.band:
if(sample.band == 'r'): band_aux = b'r'
if(sample.band == 'g'): band_aux = b'g'
if(sample.band == 'z'): band_aux = b'z'
if f[i]['filter'] == band_aux:
if(sample.survey == 'DEShyb'):
RA = f[i]['ra']
DEC = f[i]['dec'] # more efficient to put this inside the function directly
if(not InDEShybFootprint(RA,DEC) ): continue # skip if not in DEShyb
if(sample.survey == 'NGCproxy'):
RA = f[i]['ra'] # more efficient to put this inside the function directly
if(not InNGCproxyFootprint(RA) ): continue # skip if not in NGC
magext = f[i]['galdepth'] - f[i]['decam_extinction'][be]
nmag = Magtonanomaggies(magext)/5. #total noise
nl.append(nmag)
ng = len(nl)
print("-----------")
if(verbose) : print("Number of objects = ", len(f))
#if(verbose) : print "Counts before or during 2014 = ", counts2014
if(verbose) : print("Counts with dec < -20 = ", counts20)
print("Number of objects in the sample = ", ng)
#Monte Carlo to predict magnitudes histogram
ndrawn = 0
nbr = 0
NTl = []
n = 0
#for indx, f in enumerate(sample.FracExp,1) :
for indx, f in enumerate(myfrac,1) :
Nexp = indx # indx starts at 1 bc argument on enumearate :-), thus is the number of exposures
nd = int(round(ndraw * f))
if(Nexp < Nexpmin): nd=0
ndrawn=ndrawn+nd
for i in range(0,nd):
detsigtoti = 0
for j in range(0,Nexp):
ind = int(random()*ng)
#if(ind >= len(nl)): print("%d %d %d",ind,len(nl),ng)
#if(ind < 0 ): print("%d %d %d",ind,len(nl),ng)
#print("%d",ind)
detsig1 = nl[ind]
detsigtoti += 1./detsig1**2.
detsigtot = sqrt(1./detsigtoti)
m = nanomaggiesToMag(detsigtot * 5.)
if m > recm: # pass requirement
nbr += 1.
NTl.append(m)
n += 1.
# Run some statistics
NTl=np.array(NTl)
p90=np.percentile(NTl,10)
p95=np.percentile(NTl,5)
p98=np.percentile(NTl,2)
mean = sum(NTl)/float(len(NTl))
std = sqrt(sum(NTl**2.)/float(len(NTl))-mean**2.)
NTl.sort()
#if len(NTl) /2. != len(NTl)/2:
if len(NTl) % 2 != 0:
med = NTl[len(NTl)//2+1]
else:
med = (NTl[len(NTl)//2+1]+NTl[len(NTl)//2])/2.
print("Total images drawn with either ", Nexpmin, " to 5 exposures", ndrawn)
print("We are in fact runing with a minimum of", Nexpmin, "exposures")
print("Mean = ", mean, "; Median = ", med ,"; Std = ", std)
print('percentage better than requirements = '+str(nbr/float(ndrawn)))
if(sample.band =='g'): print("Requirements are > 90%, 95% and 98% at 24, 23.7, 23.4")
if(sample.band =='r'): print("Requirements are > 90%, 95% and 98% at 23.4, 23.1, 22.8")
if(sample.band =='z'): print("Requirements are > 90%, 95% and 98% at 22.5, 22.2, 21.9")
print("Results are: ", p90, p95, p98)
# Prepare historgram
minN = max(min(NTl),vmin)
maxN = max(NTl)+.0001
hl = np.zeros((nbin)) # histogram counts
lowcounts=0
for i in range(0,len(NTl)):
bin = int(nbin*(NTl[i]-minN)/(maxN-minN))
if(bin >= 0) :
hl[bin] += 1
else:
lowcounts +=1
Nl = [] # x bin centers
for i in range(0,len(hl)):
Nl.append(minN+i*(maxN-minN)/float(nbin)+0.5*(maxN-minN)/float(nbin))
NTl = np.array(NTl)
print("min,max depth = ",min(NTl), max(NTl))
print("counts below ", minN, " = ", lowcounts)
#### Ploting histogram
fname=sample.localdir+'validationplots/'+sample.catalog+sample.band+'_pred_exposures.png'
print("saving histogram plot in", fname)
#--- pdf version ---
#from matplotlib.backends.backend_pdf import PdfPages
#pp = PdfPages(fname)
plt.clf()
plt.plot(Nl,hl,'k-')
plt.xlabel(r'5$\sigma$ '+sample.band+ ' depth')
plt.ylabel('# of images')
plt.title('MC combined exposure depth '+str(mean)[:5]+r'$\pm$'+str(std)[:4]+r', $f_{\rm pass}=$'+str(nbr/float(ndrawn))[:5]+'\n '+catalogue_name)
#plt.xscale('log') # --- pdf ---
plt.savefig(fname) #pp.savefig()
plt.close #pp.close()
return fname
def v5p1e_photometricReqPlot(sample):
"""
No region > 3deg will be based upon non-photometric observations
Produces a plot of zero-point variations across the survey to inspect visually
MARCM It can be extended to check the 3deg later if is necessary
"""
nside = 1024 # Resolution of output maps
nsideSTR = '1024' # String value for nside
nsidesout = None # if you want full sky degraded maps to be written
ratiores = 1 # Superresolution/oversampling ratio, simp mode doesn't allow anything other than 1
oversamp = '1' # string oversaple value
mode = 1 # 1: fully sequential, 2: parallel then sequential, 3: fully parallel
pixoffset = 0 # How many pixels are being removed on the edge of each CCD
mjd_max = 10e10
mjdw = ''
rel = sample.DR
catalogue_name = sample.catalog
band = sample.band
sample_names = ['band_'+band]
localdir = sample.localdir
verbose = sample.verbose
tbdata = pyfits.open(sample.ccds)[1].data
if(sample.DR == 'DR3'):
inds = np.where((tbdata['filter'] == band) & (tbdata['blacklist_ok'] == True))
if(sample.DR == 'DR4'):
inds = np.where((tbdata['filter'] == band) & (tbdata['bitmask'] == 0))
elif(sample.DR == 'DR5'):
if(sample.survey == 'DECaLS'):
inds = np.where((tbdata['filter'] == band) & (tbdata['blacklist_ok'] == True))
elif(sample.survey == 'DEShyb'):
inds = np.where((tbdata['filter'] == band) & (tbdata['blacklist_ok'] == True) & (list(map(InDEShybFootprint,tbdata['ra'],tbdata['dec']))))
elif(sample.survey == 'NGCproxy'):
inds = np.where((tbdata['filter'] == band) & (tbdata['blacklist_ok'] == True) & (list(map(InNGCproxyFootprint,tbdata['ra']))))
if(sample.DR == 'DR6'):
inds = np.where((tbdata['filter'] == band))
elif(sample.DR == 'DR7'):
if(sample.survey == 'DECaLS'):
inds = np.where((tbdata['filter'] == band))
elif(sample.survey == 'DEShyb'):
inds = np.where((tbdata['filter'] == band) & (list(map(InDEShybFootprint,tbdata['ra'],tbdata['dec']))))
elif(sample.survey == 'NGCproxy'):
inds = np.where((tbdata['filter'] == band) & (list(map(InNGCproxyFootprint,tbdata['ra']))))
#Read data
#obtain invnoisesq here, including extinction
zptvar = tbdata['CCDPHRMS']**2/tbdata['CCDNMATCH']
zptivar = 1./zptvar
nccd = np.ones(len(tbdata))
# What properties do you want mapped?
# Each each tuple has [(quantity to be projected, weighting scheme, operation),(etc..)]
quicksipVerbose(sample.verbose)
propertiesandoperations = [('zptvar','','min')]
#propertiesandoperations = [ ('zptvar', '', 'total') , ('zptvar','','min') , ('nccd','','total') , ('zptivar','','total')]
# What properties to keep when reading the images?
#Should at least contain propertiesandoperations and the image corners.
# MARCM - actually no need for ra dec image corners.
# Only needs ra0 ra1 ra2 ra3 dec0 dec1 dec2 dec3 only if fast track appropriate quicksip subroutines were implemented
propertiesToKeep = [ 'filter', 'AIRMASS', 'FWHM','mjd_obs'] \
+ ['RA', 'DEC', 'crval1', 'crval2', 'crpix1', 'crpix2', 'cd1_1', 'cd1_2', 'cd2_1', 'cd2_2','width','height']
# Create big table with all relevant properties.
tbdata = np.core.records.fromarrays([tbdata[prop] for prop in propertiesToKeep] + [zptvar,zptivar,nccd], names = propertiesToKeep + [ 'zptvar','zptivar','nccd'])
# Read the table, create Healtree, project it into healpix maps, and write these maps.
# Done with Quicksip library, note it has quite a few hardcoded values (use new version by MARCM for BASS and MzLS)
# project_and_write_maps_simp(mode, propertiesandoperations, tbdata, catalogue_name, outroot, sample_names, inds, nside)
project_and_write_maps(mode, propertiesandoperations, tbdata, catalogue_name, localdir, sample_names, inds, nside, ratiores, pixoffset, nsidesout)
# ----- Read healpix maps for first case [zptvar min]-------------------------
prop='zptvar'
op= 'min'
fname=localdir+catalogue_name+'/nside'+nsideSTR+'_oversamp'+oversamp+'/'+catalogue_name+'_band_'+band+'_nside'+nsideSTR+'_oversamp'+oversamp+'_'+prop+'__'+op+'.fits.gz'
f = fitsio.read(fname)
ral = []
decl = []
val = f['SIGNAL']
pix = f['PIXEL']
# -------------- plot of values ------------------
print('Plotting min zpt rms')
myval = []
for i in range(0,len(val)):
myval.append(1.086 * np.sqrt(val[i])) #1.086 converts d(mag) into d(flux)
th,phi = hp.pix2ang(int(nside),pix[i])
ra,dec = thphi2radec(th,phi)
ral.append(ra)
decl.append(dec)
mylabel = 'min-zpt-rms-flux'
vmin = 0.0 #min(myval)
vmax = 0.03 #max(myval)
npix = len(myval)
below = 0
print('Min and Max values of ', mylabel, ' values is ', min(myval), max(myval))
print('Number of pixels is ', npix)
print('Area is ', npix/(float(nside)**2.*12)*360*360./pi, ' sq. deg.')
import matplotlib.cm as cm
mapa = plt.scatter(ral,decl,c=myval, cmap=cm.rainbow,s=2., vmin=vmin, vmax=vmax, lw=0,edgecolors='none')
fname = localdir+mylabel+'_'+band+'_'+catalogue_name+str(nside)+'.png'
cbar = plt.colorbar(mapa)
plt.xlabel('r.a. (degrees)')
plt.ylabel('declination (degrees)')
plt.title('Map of '+ mylabel +' for '+catalogue_name+' '+band+'-band')
plt.xlim(0,360)
plt.ylim(-30,90)
plt.savefig(fname)
plt.close()
#-plot of status in udgrade maps: nside64 = 1.406 deg pix size
phreq = sample.phreq
# Obtain values to plot
nside2 = 64 # 1.40625 deg per pixel
npix2 = hp.nside2npix(nside2)
myreq = np.zeros(npix2) # 0 off footprint, 1 at least one pass requirement, -1 none pass requirement
ral = np.zeros(npix2)
decl = np.zeros(npix2)
mylabel = 'photometric-pixels'
if(verbose) : print('Plotting photometric requirement')
for i in range(0,len(val)):
th,phi = hp.pix2ang(int(nside),pix[i])
ipix = hp.ang2pix(nside2,th,phi)
dF= 1.086 * (sqrt(val[i])) # 1.086 converts d(magnitudes) into d(flux)
if(dF < phreq):
myreq[ipix]=1
else:
if(myreq[ipix] == 0): myreq[ipix]=-1
below=sum( x for x in myreq if x < 0)
below=-below
print('Number of udegrade pixels with ', mylabel,' > ', phreq, ' for all subpixels =', below)
print('nside of udgraded pixels is : ', nside2)
return fname
def v3p5_Areas(sample1,sample2):
"""
450 sq deg overlap between all instruments (R3.5)
14000 sq deg filled (R3.1)
MARCM
Uses healpix pixels projected from ccd to count standing, join and overlap areas
Produces a map of the overlap
It can be extended to 3 samples if necessary
"""
nside = 1024 # Resolution of output maps
nsideSTR = '1024' # String value for nside
nsidesout = None # if you want full sky degraded maps to be written
ratiores = 1 # Superresolution/oversampling ratio, simp mode doesn't allow anything other than 1
oversamp = '1' # string oversaple value
mode = 1 # 1: fully sequential, 2: parallel then sequential, 3: fully parallel
pixoffset = 0 # How many pixels are being removed on the edge of each CCD
mjdw = ''
# ----- sample1 ------
tbdata = pyfits.open(sample1.ccds)[1].data
if(sample1.DR == 'DR3'):
inds = np.where((tbdata['filter'] == sample1.band) & (tbdata['blacklist_ok'] == True))
if(sample1.DR == 'DR4'):
inds = np.where((tbdata['filter'] == sample1.band) & (tbdata['bitmask'] == 0))
elif(sample.DR == 'DR5'):
if(sample.survey == 'DECaLS'):
inds = np.where((tbdata['filter'] == band) & (tbdata['blacklist_ok'] == True))
elif(sample.survey == 'DEShyb'):
inds = np.where((tbdata['filter'] == band) & (tbdata['blacklist_ok'] == True) & (list(map(InDEShybFootprint,tbdata['ra'],tbdata['dec']))))
elif(sample.survey == 'NGCproxy'):
inds = np.where((tbdata['filter'] == band) & (tbdata['blacklist_ok'] == True) & (list(map(InNGCproxyFootprint,tbdata['ra']))))
if(sample1.DR == 'DR6'):
inds = np.where((tbdata['filter'] == sample1.band))
elif(sample.DR == 'DR5'):
if(sample.survey == 'DECaLS'):
inds = np.where((tbdata['filter'] == band))
elif(sample.survey == 'DEShyb'):
inds = np.where((tbdata['filter'] == band) & (list(map(InDEShybFootprint,tbdata['ra'],tbdata['dec']))))
elif(sample.survey == 'NGCproxy'):
inds = np.where((tbdata['filter'] == band) & (list(map(InNGCproxyFootprint,tbdata['ra']))))
#number of ccds at each point
nccd1=np.ones(len(tbdata))
catalogue_name=sample1.catalog
band = sample1.band
sample_names = ['band_'+band]
localdir=sample1.localdir
# What properties do you want mapped?
# Each each tuple has [(quantity to be projected, weighting scheme, operation),(etc..)]
quicksipVerbose(sample1.verbose)
propertiesandoperations = [('nccd1','','total')]
# What properties to keep when reading the images?
#Should at least contain propertiesandoperations and the image corners.
# MARCM - actually no need for ra dec image corners.
# Only needs ra0 ra1 ra2 ra3 dec0 dec1 dec2 dec3 only if fast track appropriate quicksip subroutines were implemented
#propertiesToKeep = [ 'filter', 'AIRMASS', 'FWHM','mjd_obs'] \
# + ['RA', 'DEC', 'crval1', 'crval2', 'crpix1', 'crpix2', 'cd1_1', 'cd1_2', 'cd2_1', 'cd2_2','width','height']
propertiesToKeep = ['RA', 'DEC', 'crval1', 'crval2', 'crpix1', 'crpix2', 'cd1_1', 'cd1_2', 'cd2_1', 'cd2_2','width','height']
# Create big table with all relevant properties.
tbdata = np.core.records.fromarrays([tbdata[prop] for prop in propertiesToKeep] + [nccd1], names = propertiesToKeep + [ 'nccd1'])
# Read the table, create Healtree, project it into healpix maps, and write these maps.
# Done with Quicksip library, note it has quite a few hardcoded values (use new version by MARCM for BASS and MzLS)
# project_and_write_maps_simp(mode, propertiesandoperations, tbdata, catalogue_name, outroot, sample_names, inds, nside)
project_and_write_maps(mode, propertiesandoperations, tbdata, catalogue_name, localdir, sample_names, inds, nside, ratiores, pixoffset, nsidesout)
# ----- sample2 ------
tbdata = pyfits.open(sample2.ccds)[1].data
if(sample2.DR == 'DR3'):
inds = np.where((tbdata['filter'] == sample2.band) & (tbdata['blacklist_ok'] == True))
if(sample2.DR == 'DR4'):
inds = np.where((tbdata['filter'] == sample2.band) & (tbdata['bitmask'] == 0))
if(sample2.DR == 'DR5'):
inds = np.where((tbdata['filter'] == sample2.band) & (tbdata['blacklist_ok'] == True))
if(sample2.DR == 'DR6'):
inds = np.where((tbdata['filter'] == sample2.band))
if(sample2.DR == 'DR7'):
inds = np.where((tbdata['filter'] == sample2.band))
#number of ccds at each point
nccd2=np.ones(len(tbdata))
catalogue_name=sample2.catalog
band = sample2.band
sample_names = ['band_'+band]
localdir=sample2.localdir
# Quick sip projections
quicksipVerbose(sample2.verbose)
propertiesandoperations = [('nccd2','','total')]
propertiesToKeep = ['RA', 'DEC', 'crval1', 'crval2', 'crpix1', 'crpix2', 'cd1_1', 'cd1_2', 'cd2_1', 'cd2_2','width','height']
tbdata = np.core.records.fromarrays([tbdata[prop] for prop in propertiesToKeep] + [nccd2], names = propertiesToKeep + [ 'nccd2'])
project_and_write_maps(mode, propertiesandoperations, tbdata, catalogue_name, localdir, sample_names, inds, nside, ratiores, pixoffset, nsidesout)
# --- read ccd counts per pixel sample 1 ----
prop='nccd1'
op='total'
localdir=sample1.localdir
band=sample1.band
catalogue_name1=sample1.catalog
fname=localdir+catalogue_name1+'/nside'+nsideSTR+'_oversamp'+oversamp+'/'+catalogue_name1+'_band_'+band+'_nside'+nsideSTR+'_oversamp'+oversamp+'_'+prop+'__'+op+'.fits.gz'
f = fitsio.read(fname)
val1 = f['SIGNAL']
pix1 = f['PIXEL']
npix1 = np.size(pix1)
# ---- read ccd counts per pixel sample 2 ----
prop='nccd2'
opt='total'
localdir=sample2.localdir
band=sample2.band
catalogue_name2=sample2.catalog
fname=localdir+catalogue_name2+'/nside'+nsideSTR+'_oversamp'+oversamp+'/'+catalogue_name2+'_band_'+band+'_nside'+nsideSTR+'_oversamp'+oversamp+'_'+prop+'__'+op+'.fits.gz'
f = fitsio.read(fname)
val2 = f['SIGNAL']
pix2 = f['PIXEL']
npix2 = np.size(pix2)
# ---- compute common healpix pixels #this is python 2.7 use isin for 3.X
commonpix = np.in1d(pix1,pix2,assume_unique=True) #unique: no pixel indicies are repeated
npix=np.sum(commonpix) #sum of bolean in array size pix1
area1 = npix1/(float(nside)**2.*12)*360*360./pi
area2 = npix2/(float(nside)**2.*12)*360*360./pi
area = npix/(float(nside)**2.*12)*360*360./pi
print('Area of sample', sample1.catalog,' is ', np.round(area1) , ' sq. deg.')
print('Area of sample', sample2.catalog,' is ', np.round(area2) , ' sq. deg.')
print('The total JOINT area is ', np.round(area1+area2-area) ,'sq. deg.')
print('The INTERSECTING area is ', np.round(area) , ' sq. deg.')
# ----- plot join area using infomration from sample1 ---
ral = []
decl = []
myval = []
for i in range(0,len(pix1)):
if(commonpix[i]):
th,phi = hp.pix2ang(int(nside),pix1[i])
ra,dec = thphi2radec(th,phi)
ral.append(ra)
decl.append(dec)
myval.append(1)
mylabel = 'join-area'
import matplotlib.cm as cm
mapa = plt.scatter(ral,decl,c=myval, cmap=cm.rainbow,s=2.,lw=0,edgecolors='none')
fname = localdir+mylabel+'_'+band+'_'+catalogue_name1+'_'+catalogue_name2+str(nside)+'.png'
cbar = plt.colorbar(mapa)
plt.xlabel('r.a. (degrees)')
plt.ylabel('declination (degrees)')
plt.title('Map of '+ mylabel +' for '+catalogue_name1+' and '+catalogue_name2+' '+band+'-band; Area = '+str(area))
plt.xlim(0,360)
plt.ylim(-30,90)
plt.savefig(fname)
plt.close()
return fname
def val3p4c_seeing(sample,passmin=3,nbin=100,nside=1024):
"""
Requirement V4.1: z-band image quality will be smaller than 1.3 arcsec FWHM in at least one pass.
Produces FWHM maps and histograms for visual inspection
H-JS's addition to MARCM stable version.
MARCM stable version, improved from AJR quick hack
This now included extinction from the exposures
Uses quicksip subroutines from Boris, corrected
for a bug I found for BASS and MzLS ccd orientation
"""
#nside = 1024 # Resolution of output maps
nsideSTR=str(nside)
#nsideSTR='1024' # same as nside but in string format
nsidesout = None # if you want full sky degraded maps to be written
ratiores = 1 # Superresolution/oversampling ratio, simp mode doesn't allow anything other than 1
mode = 1 # 1: fully sequential, 2: parallel then sequential, 3: fully parallel
pixoffset = 0 # How many pixels are being removed on the edge of each CCD? 15 for DES.
oversamp='1' # ratiores in string format
band = sample.band
catalogue_name = sample.catalog
fname = sample.ccds
localdir = sample.localdir
extc = sample.extc
#Read ccd file
tbdata = pyfits.open(fname)[1].data
# ------------------------------------------------------
# Obtain indices
auxstr='band_'+band
sample_names = [auxstr]
if(sample.DR == 'DR3'):
inds = np.where((tbdata['filter'] == band) & (tbdata['photometric'] == True) & (tbdata['blacklist_ok'] == True))
elif(sample.DR == 'DR4'):
inds = np.where((tbdata['filter'] == band) & (tbdata['photometric'] == True) & (tbdata['bitmask'] == 0))
elif(sample.DR == 'DR5'):
inds = np.where((tbdata['filter'] == band) & (tbdata['photometric'] == True) & (tbdata['blacklist_ok'] == True))
elif(sample.DR == 'DR6'):
inds = np.where((tbdata['filter'] == band))
elif(sample.DR == 'DR7'):
inds = np.where((tbdata['filter'] == band))
#Read data
#obtain invnoisesq here, including extinction
nmag = Magtonanomaggies(tbdata['galdepth']-extc*tbdata['EBV'])/5.
ivar= 1./nmag**2.
# What properties do you want mapped?
# Each each tuple has [(quantity to be projected, weighting scheme, operation),(etc..)]
propertiesandoperations = [
('FWHM', '', 'min'),
('FWHM', '', 'num')]
# What properties to keep when reading the images?
# Should at least contain propertiesandoperations and the image corners.
# MARCM - actually no need for ra dec image corners.
# Only needs ra0 ra1 ra2 ra3 dec0 dec1 dec2 dec3 only if fast track appropriate quicksip subroutines were implemented
propertiesToKeep = [ 'filter', 'AIRMASS', 'FWHM','mjd_obs'] \
+ ['RA', 'DEC', 'crval1', 'crval2', 'crpix1', 'crpix2', 'cd1_1', 'cd1_2', 'cd2_1', 'cd2_2','width','height']
# Create big table with all relevant properties.
#tbdata = np.core.records.fromarrays([tbdata[prop] for prop in propertiesToKeep] + [ivar], names = propertiesToKeep + [ 'ivar'])
tbdata = np.core.records.fromarrays([tbdata[prop] for prop in propertiesToKeep], names = propertiesToKeep)
# Read the table, create Healtree, project it into healpix maps, and write these maps.
# Done with Quicksip library, note it has quite a few hardcoded values (use new version by MARCM for BASS and MzLS)
# project_and_write_maps_simp(mode, propertiesandoperations, tbdata, catalogue_name, outroot, sample_names, inds, nside)
project_and_write_maps(mode, propertiesandoperations, tbdata, catalogue_name, localdir, sample_names, inds, nside, ratiores, pixoffset, nsidesout)
# Read Haelpix maps from quicksip
prop='FWHM'
op='min'
vmin=21.0
vmax=24.0
fname2=localdir+catalogue_name+'/nside'+nsideSTR+'_oversamp'+oversamp+'/'+\
catalogue_name+'_band_'+band+'_nside'+nsideSTR+'_oversamp'+oversamp+'_'+prop+'__'+op+'.fits.gz'
f = fitsio.read(fname2)
prop='FWHM'
op1='num'
fname2=localdir+catalogue_name+'/nside'+nsideSTR+'_oversamp'+oversamp+'/'+\
catalogue_name+'_band_'+band+'_nside'+nsideSTR+'_oversamp'+oversamp+'_'+prop+'__'+op1+'.fits.gz'
f1 = fitsio.read(fname2)
# HEALPIX DEPTH MAPS
# convert ivar to depth
import healpy as hp
from healpix3 import pix2ang_ring,thphi2radec
ral = []
decl = []
valf = []
val = f['SIGNAL']
npass = f1['SIGNAL']
pixelarea = (180./np.pi)**2*4*np.pi/(12*nside**2)
pix = f['PIXEL']
print(min(val),max(val))
print(min(npass),max(npass))
# Obtain values to plot
j = 0
for i in range(0,len(f)):
if (npass[i] >= passmin):
#th,phi = pix2ang_ring(4096,f[i]['PIXEL'])
th,phi = hp.pix2ang(nside,f[i]['PIXEL'])
ra,dec = thphi2radec(th,phi)
ral.append(ra)
decl.append(dec)
valf.append(val[i])
print(len(val),len(valf))
# print len(val),len(valf),valf[0],valf[1],valf[len(valf)-1]
minv = np.min(valf)
maxv = np.max(valf)
print(minv,maxv)
# Draw the map
from matplotlib import pyplot as plt
import matplotlib.cm as cm
mylabel= prop + op
mapa = plt.scatter(ral,decl,c=valf, cmap=cm.rainbow,s=2., vmin=minv, vmax=maxv, lw=0,edgecolors='none')
cbar = plt.colorbar(mapa)
plt.xlabel('r.a. (degrees)')
plt.ylabel('declination (degrees)')
plt.title('Map of '+ mylabel +' for '+catalogue_name+' '+band+'-band pass >='+str(passmin))
plt.xlim(0,360)
plt.ylim(-30,90)
mapfile=localdir+mylabel+'pass'+str(passmin)+'_'+band+'_'+catalogue_name+str(nside)+'map.png'
print('saving plot to ', mapfile)
plt.savefig(mapfile)
plt.close()
#plt.show()
#cbar.set_label(r'5$\sigma$ galaxy depth', rotation=270,labelpad=1)
#plt.xscale('log')
npix=len(pix)
print('The total area is ', npix/(float(nside)**2.*12)*360*360./pi, ' sq. deg.')
# Draw the histogram
minN = minv-0.0001
maxN = maxv+.0001
hl = np.zeros((nbin))
for i in range(0,len(valf)):
bin = int(nbin*(valf[i]-minN)/(maxN-minN))
hl[bin] += 1
Nl = []
for i in range(0,len(hl)):
Nl.append(minN+i*(maxN-minN)/float(nbin)+0.5*(maxN-minN)/float(nbin))
#When an array object is printed or converted to a string, it is represented as array(typecode, initializer)
NTl = np.array(valf)
Nl = np.array(Nl)*0.262 # in arcsec
hl = np.array(hl)*pixelarea
hlcs = np.sum(hl)-np.cumsum(hl)
print("A total of ",np.sum(hl),"squaredegrees with pass >=",str(passmin))
# print "#FWHM Area(>FWHM)"
# print np.column_stack((Nl,hlcs))
idx = (np.abs(Nl-1.3)).argmin()
print("#FWHM Area(>FWHM) Fractional Area(>FWHM)")
print(Nl[idx], hlcs[idx], hlcs[idx]/hlcs[0])
mean = np.sum(NTl)/float(len(NTl))
std = sqrt(np.sum(NTl**2.)/float(len(NTl))-mean**2.)
print("#mean STD")
print(mean,std)
plt.plot(Nl,hl,'k-')
#plt.xscale('log')
plt.xlabel(op+' '+band+ ' seeing (")')
plt.ylabel('Area (squaredegrees)')
plt.title('Historam of '+mylabel+' for '+catalogue_name+' '+band+'-band: pass >='+str(passmin))
ax2 = plt.twinx()
ax2.plot(Nl,hlcs,'r')
y0 = np.arange(0,10000, 100)
x0 = y0*0+1.3
shlcs = '%.2f' % (hlcs[idx])
shlcsr = '%.2f' % (hlcs[idx]/hlcs[0])
print("Area with FWHM greater than 1.3 arcsec fraction")
print(shlcs, shlcsr)
ax2.plot(x0,y0,'r--', label = r'$Area_{\rm FWHM > 1.3arcsec}= $'+shlcs+r'$deg^2$ ( $f_{\rm fail}=$'+ shlcsr+')')
legend = ax2.legend(loc='upper center', shadow=True)
ax2.set_ylabel('Cumulative Area sqdegrees', color='r')
#plt.show()
histofile = localdir+mylabel+'pass'+str(passmin)+'_'+band+'_'+catalogue_name+str(nside)+'histo.png'
print('saving plot to ', histofile)
plt.savefig(histofile)
# fig.savefig(histofile)
plt.close()
return mapfile,histofile
def val3p4c_seeingplots(sample,passmin=3,nbin=100,nside=1024):
"""
Requirement V4.1: z-band image quality will be smaller than 1.3 arcsec FWHM in at least one pass.
Produces FWHM maps and histograms for visual inspection
H-JS's addition to MARCM stable version.
MARCM stable version, improved from AJR quick hack
This now included extinction from the exposures
Uses quicksip subroutines from Boris, corrected
for a bug I found for BASS and MzLS ccd orientation
The same as val3p4c_seeing, but this makes only plots without regenerating input files for the plots
"""
#nside = 1024 # Resolution of output maps
nsideSTR=str(nside)
#nsideSTR='1024' # same as nside but in string format
nsidesout = None # if you want full sky degraded maps to be written
ratiores = 1 # Superresolution/oversampling ratio, simp mode doesn't allow anything other than 1
mode = 1 # 1: fully sequential, 2: parallel then sequential, 3: fully parallel
pixoffset = 0 # How many pixels are being removed on the edge of each CCD? 15 for DES.
oversamp='1' # ratiores in string format
band = sample.band
catalogue_name = sample.catalog
fname = sample.ccds
localdir = sample.localdir
extc = sample.extc
#Read ccd file
tbdata = pyfits.open(fname)[1].data
# ------------------------------------------------------
# Obtain indices
auxstr='band_'+band
sample_names = [auxstr]
if(sample.DR == 'DR3'):
inds = np.where((tbdata['filter'] == band) & (tbdata['photometric'] == True) & (tbdata['blacklist_ok'] == True))
elif(sample.DR == 'DR4'):
inds = np.where((tbdata['filter'] == band) & (tbdata['photometric'] == True) & (tbdata['bitmask'] == 0))
elif(sample.DR == 'DR5'):
if(sample.survey == 'DECaLS'):
inds = np.where((tbdata['filter'] == band) & (tbdata['photometric'] == True) & (tbdata['blacklist_ok'] == True))
elif(sample.survey == 'DEShyb'):
inds = np.where((tbdata['filter'] == band) & (tbdata['photometric'] == True) & (tbdata['blacklist_ok'] == True) & (list(map(InDEShybFootprint,tbdata['ra'],tbdata['dec']))))
elif(sample.survey == 'NGCproxy'):
inds = np.where((tbdata['filter'] == band) & (tbdata['photometric'] == True) & (tbdata['blacklist_ok'] == True) & (list(map(InNGCproxyFootprint,tbdata['ra']))))
elif(sample.DR == 'DR6'):
inds = np.where((tbdata['filter'] == band))
elif(sample.DR == 'DR7'):
if(sample.survey == 'DECaLS'):
inds = np.where((tbdata['filter'] == band))
elif(sample.survey == 'DEShyb'):
inds = np.where((tbdata['filter'] == band) & (list(map(InDEShybFootprint,tbdata['ra'],tbdata['dec']))))
elif(sample.survey == 'NGCproxy'):
inds = np.where((tbdata['filter'] == band) & (list(map(InNGCproxyFootprint,tbdata['ra']))))
#Read data
#obtain invnoisesq here, including extinction
nmag = Magtonanomaggies(tbdata['galdepth']-extc*tbdata['EBV'])/5.
ivar= 1./nmag**2.
# What properties do you want mapped?
# Each each tuple has [(quantity to be projected, weighting scheme, operation),(etc..)]
propertiesandoperations = [
('FWHM', '', 'min'),
('FWHM', '', 'num')]
# Read Haelpix maps from quicksip
print("Generating only plots using the existing intermediate outputs")
prop='FWHM'
op='min'
vmin=21.0
vmax=24.0
fname2=localdir+catalogue_name+'/nside'+nsideSTR+'_oversamp'+oversamp+'/'+\
catalogue_name+'_band_'+band+'_nside'+nsideSTR+'_oversamp'+oversamp+'_'+prop+'__'+op+'.fits.gz'
f = fitsio.read(fname2)
prop='FWHM'
op1='num'
fname2=localdir+catalogue_name+'/nside'+nsideSTR+'_oversamp'+oversamp+'/'+\
catalogue_name+'_band_'+band+'_nside'+nsideSTR+'_oversamp'+oversamp+'_'+prop+'__'+op1+'.fits.gz'
f1 = fitsio.read(fname2)
# HEALPIX DEPTH MAPS
# convert ivar to depth
import healpy as hp
from healpix3 import pix2ang_ring,thphi2radec
ral = []
decl = []
valf = []
val = f['SIGNAL']
npass = f1['SIGNAL']
pixelarea = (180./np.pi)**2*4*np.pi/(12*nside**2)
pix = f['PIXEL']
print(min(val),max(val))
print(min(npass),max(npass))
# Obtain values to plot
j = 0
for i in range(0,len(f)):
if (npass[i] >= passmin):
#th,phi = pix2ang_ring(4096,f[i]['PIXEL'])
th,phi = hp.pix2ang(nside,f[i]['PIXEL'])
ra,dec = thphi2radec(th,phi)
ral.append(ra)
decl.append(dec)
valf.append(val[i])
print(len(val),len(valf))
# print len(val),len(valf),valf[0],valf[1],valf[len(valf)-1]
minv = np.min(valf)
maxv = np.max(valf)
print(minv,maxv)
# Draw the map
from matplotlib import pyplot as plt
import matplotlib.cm as cm
mylabel= prop + op
mapa = plt.scatter(ral,decl,c=valf, cmap=cm.rainbow,s=2., vmin=minv, vmax=maxv, lw=0,edgecolors='none')
cbar = plt.colorbar(mapa)
plt.xlabel('r.a. (degrees)')
plt.ylabel('declination (degrees)')
plt.title('Map of '+ mylabel +' for '+catalogue_name+' '+band+'-band pass >='+str(passmin))
plt.xlim(0,360)
plt.ylim(-30,90)
mapfile=localdir+mylabel+'pass'+str(passmin)+'_'+band+'_'+catalogue_name+str(nside)+'map.png'
print('saving plot to ', mapfile)
plt.savefig(mapfile)
plt.close()
#plt.show()
#cbar.set_label(r'5$\sigma$ galaxy depth', rotation=270,labelpad=1)
#plt.xscale('log')
npix=len(pix)
print('The total area is ', npix/(float(nside)**2.*12)*360*360./pi, ' sq. deg.')
# Draw the histogram
minN = minv-0.0001
maxN = maxv+.0001
hl = np.zeros((nbin))
for i in range(0,len(valf)):
bin = int(nbin*(valf[i]-minN)/(maxN-minN))
hl[bin] += 1
Nl = []
for i in range(0,len(hl)):
Nl.append(minN+i*(maxN-minN)/float(nbin)+0.5*(maxN-minN)/float(nbin))
#When an array object is printed or converted to a string, it is represented as array(typecode, initializer)
NTl = np.array(valf)
Nl = np.array(Nl)*0.262 # in arcsec
hl = np.array(hl)*pixelarea
hlcs = np.sum(hl)-np.cumsum(hl)
print("A total of ",np.sum(hl),"squaredegrees with pass >=",str(passmin))
# print "#FWHM Area(>FWHM)"
# print np.column_stack((Nl,hlcs))
idx = (np.abs(Nl-1.3)).argmin()
print("#FWHM Area(>FWHM) Fractional Area(>FWHM)")
print(Nl[idx], hlcs[idx], hlcs[idx]/hlcs[0])
mean = np.sum(NTl)/float(len(NTl))
std = sqrt(np.sum(NTl**2.)/float(len(NTl))-mean**2.)
print("#mean STD")
print(mean,std)
plt.plot(Nl,hl,'k-')
#plt.xscale('log')
plt.xlabel(op+' '+band+ ' seeing (")')
plt.ylabel('Area (squaredegrees)')
plt.title('Historam of '+mylabel+' for '+catalogue_name+' '+band+'-band: pass >='+str(passmin))
ax2 = plt.twinx()
ax2.plot(Nl,hlcs,'r')
y0 = np.arange(0,10000, 100)
x0 = y0*0+1.3
shlcs = '%.2f' % (hlcs[idx])
shlcsr = '%.2f' % (hlcs[idx]/hlcs[0])
print("Area with FWHM greater than 1.3 arcsec fraction")
print(shlcs, shlcsr)
ax2.plot(x0,y0,'r--', label = r'$Area_{\rm FWHM > 1.3arcsec}= $'+shlcs+r'$deg^2$ ( $f_{\rm fail}=$'+ shlcsr+')')
legend = ax2.legend(loc='upper center', shadow=True)
ax2.set_ylabel('Cumulative Area sqdegrees', color='r')
#plt.show()
# fig = plt.gcf()
histofile = localdir+mylabel+'pass'+str(passmin)+'_'+band+'_'+catalogue_name+str(nside)+'histo.png'
print('saving plot to ', histofile)
plt.savefig(histofile)
# fig.savefig(histofile)
plt.close()
return mapfile,histofile
|
gpl-2.0
|
algorythmic/bash-completion
|
test/t/test_spovray.py
|
133
|
import pytest
class TestSpovray:
@pytest.mark.complete("spovray ")
def test_1(self, completion):
assert completion
|
gpl-2.0
|
star-app/starcloud
|
src/com/owncloud/android/ui/FragmentListView.java
|
3577
|
/* ownCloud Android client application
* Copyright (C) 2012 Bartek Przybylski
* Copyright (C) 2012-2013 ownCloud Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.owncloud.android.ui;
import com.actionbarsherlock.app.SherlockFragment;
import com.owncloud.android.R;
import com.owncloud.android.ui.fragment.LocalFileListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class FragmentListView extends SherlockFragment implements
OnItemClickListener, OnItemLongClickListener {
protected ExtendedListView mList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void setListAdapter(ListAdapter listAdapter) {
mList.setAdapter(listAdapter);
mList.invalidate();
}
public ListView getListView() {
return mList;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//mList = new ExtendedListView(getActivity());
View v = inflater.inflate(R.layout.list_fragment, null);
mList = (ExtendedListView)(v.findViewById(R.id.list_root));
mList.setOnItemClickListener(this);
mList.setOnItemLongClickListener(this);
//mList.setEmptyView(v.findViewById(R.id.empty_list_view)); // looks like it's not a cool idea
mList.setDivider(getResources().getDrawable(R.drawable.uploader_list_separator));
mList.setDividerHeight(1);
return v;
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
}
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
return false;
}
/**
* Calculates the position of the item that will be used as a reference to reposition the visible items in the list when
* the device is turned to other position.
*
* THe current policy is take as a reference the visible item in the center of the screen.
*
* @return The position in the list of the visible item in the center of the screen.
*/
protected int getReferencePosition() {
return (mList.getFirstVisiblePosition() + mList.getLastVisiblePosition()) / 2;
}
/**
* Sets the visible part of the list from the reference position.
*
* @param position Reference position previously returned by {@link LocalFileListFragment#getReferencePosition()}
*/
protected void setReferencePosition(int position) {
mList.setAndCenterSelection(position);
}
}
|
gpl-2.0
|
komunikator/komunikator_bitrix
|
tests/get_didsTest.php
|
3917
|
<?php
/*
* | RUS | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* ยซKomunikatorยป โ Web-ะธะฝัะตััะตะนั ะดะปั ะฝะฐัััะพะนะบะธ ะธ ัะฟัะฐะฒะปะตะฝะธั ะฟัะพะณัะฐะผะผะฝะพะน IP-ะะขะก ยซYATEยป
* Copyright (C) 2012-2013, ะะะ ยซะขะตะปะตัะพะฝะฝัะต ัะธััะตะผัยป
* ะญะขะะข ะคะะะ ัะฒะปัะตััั ัะฐัััั ะฟัะพะตะบัะฐ ยซKomunikatorยป
* ะกะฐะนั ะฟัะพะตะบัะฐ ยซKomunikatorยป: http://komunikator.ru/
* ะกะปัะถะฑะฐ ัะตั
ะฝะธัะตัะบะพะน ะฟะพะดะดะตัะถะบะธ ะฟัะพะตะบัะฐ ยซKomunikatorยป: E-mail: support@komunikator.ru
* ะ ะฟัะพะตะบัะต ยซKomunikatorยป ะธัะฟะพะปัะทััััั:
* ะธัั
ะพะดะฝัะต ะบะพะดั ะฟัะพะตะบัะฐ ยซYATEยป, http://yate.null.ro/pmwiki/
* ะธัั
ะพะดะฝัะต ะบะพะดั ะฟัะพะตะบัะฐ ยซFREESENTRALยป, http://www.freesentral.com/
* ะฑะธะฑะปะธะพัะตะบะธ ะฟัะพะตะบัะฐ ยซSencha Ext JSยป, http://www.sencha.com/products/extjs
* Web-ะฟัะธะปะพะถะตะฝะธะต ยซKomunikatorยป ัะฒะปัะตััั ัะฒะพะฑะพะดะฝัะผ ะธ ะพัะบััััะผ ะฟัะพะณัะฐะผะผะฝัะผ ะพะฑะตัะฟะตัะตะฝะธะตะผ. ะขะตะผ ัะฐะผัะผ
* ะดะฐะฒะฐั ะฟะพะปัะทะพะฒะฐัะตะปั ะฟัะฐะฒะพ ะฝะฐ ัะฐัะฟัะพัััะฐะฝะตะฝะธะต ะธ (ะธะปะธ) ะผะพะดะธัะธะบะฐัะธั ะดะฐะฝะฝะพะณะพ Web-ะฟัะธะปะพะถะตะฝะธั (ะฐ ัะฐะบะถะต
* ะธ ะธะฝัะต ะฟัะฐะฒะฐ) ัะพะณะปะฐัะฝะพ ััะปะพะฒะธัะผ GNU General Public License, ะพะฟัะฑะปะธะบะพะฒะฐะฝะฝะพะน
* Free Software Foundation, ะฒะตััะธะธ 3.
* ะ ัะปััะฐะต ะพััััััะฒะธั ัะฐะนะปะฐ ยซLicenseยป (ะธะดััะตะณะพ ะฒะผะตััะต ั ะธัั
ะพะดะฝัะผะธ ะบะพะดะฐะผะธ ะฟัะพะณัะฐะผะผะฝะพะณะพ ะพะฑะตัะฟะตัะตะฝะธั)
* ะพะฟะธััะฒะฐััะตะณะพ ััะปะพะฒะธั GNU General Public License ะฒะตััะธะธ 3, ะผะพะถะฝะพ ะฟะพัะตัะธัั ะพัะธัะธะฐะปัะฝัะน ัะฐะนั
* http://www.gnu.org/licenses/ , ะณะดะต ะพะฟัะฑะปะธะบะพะฒะฐะฝั ััะปะพะฒะธั GNU General Public License
* ัะฐะทะปะธัะฝัั
ะฒะตััะธะน (ะฒ ัะพะผ ัะธัะปะต ะธ ะฒะตััะธะธ 3).
* | ENG | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* "Komunikator" is a web interface for IP-PBX "YATE" configuration and management
* Copyright (C) 2012-2013, "Telephonnyie sistemy" Ltd.
* THIS FILE is an integral part of the project "Komunikator"
* "Komunikator" project site: http://komunikator.ru/
* "Komunikator" technical support e-mail: support@komunikator.ru
* The project "Komunikator" are used:
* the source code of "YATE" project, http://yate.null.ro/pmwiki/
* the source code of "FREESENTRAL" project, http://www.freesentral.com/
* "Sencha Ext JS" project libraries, http://www.sencha.com/products/extjs
* "Komunikator" web application is a free/libre and open-source software. Therefore it grants user rights
* for distribution and (or) modification (including other rights) of this programming solution according
* to GNU General Public License terms and conditions published by Free Software Foundation in version 3.
* In case the file "License" that describes GNU General Public License terms and conditions,
* version 3, is missing (initially goes with software source code), you can visit the official site
* http://www.gnu.org/licenses/ and find terms specified in appropriate GNU General Public License
* version (version 3 as well).
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/
?><?php
class get_didsTest extends PHPUnit_Framework_TestCase {
public function testDids() {
$params = array('action' => 'get_dids', 'session' => file_get_contents(sys_get_temp_dir().'/session'));
$out = shell_exec("php data_.php " . addslashes(json_encode($params)));
$res = json_decode($out);
$this->assertEquals(true, $res->success);
}
}
?>
|
gpl-2.0
|
aedansilver/Ri-Core
|
src/server/scripts/EasternKingdoms/western_plaguelands.cpp
|
15740
|
/*
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program 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 Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Western_Plaguelands
SD%Complete: 90
SDComment: Quest support: 5097, 5098, 5216, 5219, 5222, 5225, 5229, 5231, 5233, 5235. To obtain Vitreous Focuser (could use more spesifics about gossip items)
SDCategory: Western Plaguelands
EndScriptData */
/* ContentData
npcs_dithers_and_arbington
npc_myranda_the_hag
npc_the_scourge_cauldron
npc_andorhal_tower
EndContentData */
#include "ScriptPCH.h"
#include "ScriptedEscortAI.h"
/*######
## npcs_dithers_and_arbington
######*/
#define GOSSIP_HDA1 "What does the Felstone Field Cauldron need?"
#define GOSSIP_HDA2 "What does the Dalson's Tears Cauldron need?"
#define GOSSIP_HDA3 "What does the Writhing Haunt Cauldron need?"
#define GOSSIP_HDA4 "What does the Gahrron's Withering Cauldron need?"
#define GOSSIP_SDA1 "Thanks, i need a Vitreous Focuser"
class npcs_dithers_and_arbington : public CreatureScript
{
public:
npcs_dithers_and_arbington() : CreatureScript("npcs_dithers_and_arbington") { }
bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action)
{
player->PlayerTalkClass->ClearMenus();
switch (action)
{
case GOSSIP_ACTION_TRADE:
player->GetSession()->SendListInventory(creature->GetGUID());
break;
case GOSSIP_ACTION_INFO_DEF+1:
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SDA1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+5);
player->SEND_GOSSIP_MENU(3980, creature->GetGUID());
break;
case GOSSIP_ACTION_INFO_DEF+2:
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SDA1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+5);
player->SEND_GOSSIP_MENU(3981, creature->GetGUID());
break;
case GOSSIP_ACTION_INFO_DEF+3:
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SDA1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+5);
player->SEND_GOSSIP_MENU(3982, creature->GetGUID());
break;
case GOSSIP_ACTION_INFO_DEF+4:
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SDA1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+5);
player->SEND_GOSSIP_MENU(3983, creature->GetGUID());
break;
case GOSSIP_ACTION_INFO_DEF+5:
player->CLOSE_GOSSIP_MENU();
creature->CastSpell(player, 17529, false);
break;
}
return true;
}
bool OnGossipHello(Player* player, Creature* creature)
{
if (creature->isQuestGiver())
player->PrepareQuestMenu(creature->GetGUID());
if (creature->isVendor())
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_VENDOR, GOSSIP_TEXT_BROWSE_GOODS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_TRADE);
if (player->GetQuestRewardStatus(5237) || player->GetQuestRewardStatus(5238))
{
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_HDA1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1);
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_HDA2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2);
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_HDA3, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+3);
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_HDA4, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+4);
player->SEND_GOSSIP_MENU(3985, creature->GetGUID());
}else
player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID());
return true;
}
};
/*######
## npc_myranda_the_hag
######*/
enum eMyranda
{
QUEST_SUBTERFUGE = 5862,
QUEST_IN_DREAMS = 5944,
SPELL_SCARLET_ILLUSION = 17961
};
#define GOSSIP_ITEM_ILLUSION "I am ready for the illusion, Myranda."
class npc_myranda_the_hag : public CreatureScript
{
public:
npc_myranda_the_hag() : CreatureScript("npc_myranda_the_hag") { }
bool OnGossipSelect(Player* player, Creature* /*creature*/, uint32 /*sender*/, uint32 action)
{
player->PlayerTalkClass->ClearMenus();
if (action == GOSSIP_ACTION_INFO_DEF + 1)
{
player->CLOSE_GOSSIP_MENU();
player->CastSpell(player, SPELL_SCARLET_ILLUSION, false);
}
return true;
}
bool OnGossipHello(Player* player, Creature* creature)
{
if (creature->isQuestGiver())
player->PrepareQuestMenu(creature->GetGUID());
if (player->GetQuestStatus(QUEST_SUBTERFUGE) == QUEST_STATUS_COMPLETE &&
!player->GetQuestRewardStatus(QUEST_IN_DREAMS) && !player->HasAura(SPELL_SCARLET_ILLUSION))
{
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_ILLUSION, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1);
player->SEND_GOSSIP_MENU(4773, creature->GetGUID());
return true;
}
else
player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID());
return true;
}
};
/*######
## npc_the_scourge_cauldron
######*/
class npc_the_scourge_cauldron : public CreatureScript
{
public:
npc_the_scourge_cauldron() : CreatureScript("npc_the_scourge_cauldron") { }
CreatureAI* GetAI(Creature* creature) const
{
return new npc_the_scourge_cauldronAI (creature);
}
struct npc_the_scourge_cauldronAI : public ScriptedAI
{
npc_the_scourge_cauldronAI(Creature* c) : ScriptedAI(c) {}
void Reset() {}
void EnterCombat(Unit* /*who*/) {}
void DoDie()
{
//summoner dies here
me->DealDamage(me, me->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
//override any database `spawntimesecs` to prevent duplicated summons
uint32 rTime = me->GetRespawnDelay();
if (rTime<600)
me->SetRespawnDelay(600);
}
void MoveInLineOfSight(Unit* who)
{
if (!who || who->GetTypeId() != TYPEID_PLAYER)
return;
if (who->GetTypeId() == TYPEID_PLAYER)
{
switch (me->GetAreaId())
{
case 199: //felstone
if (CAST_PLR(who)->GetQuestStatus(5216) == QUEST_STATUS_INCOMPLETE ||
CAST_PLR(who)->GetQuestStatus(5229) == QUEST_STATUS_INCOMPLETE)
{
me->SummonCreature(11075, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 600000);
DoDie();
}
break;
case 200: //dalson
if (CAST_PLR(who)->GetQuestStatus(5219) == QUEST_STATUS_INCOMPLETE ||
CAST_PLR(who)->GetQuestStatus(5231) == QUEST_STATUS_INCOMPLETE)
{
me->SummonCreature(11077, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 600000);
DoDie();
}
break;
case 201: //gahrron
if (CAST_PLR(who)->GetQuestStatus(5225) == QUEST_STATUS_INCOMPLETE ||
CAST_PLR(who)->GetQuestStatus(5235) == QUEST_STATUS_INCOMPLETE)
{
me->SummonCreature(11078, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 600000);
DoDie();
}
break;
case 202: //writhing
if (CAST_PLR(who)->GetQuestStatus(5222) == QUEST_STATUS_INCOMPLETE ||
CAST_PLR(who)->GetQuestStatus(5233) == QUEST_STATUS_INCOMPLETE)
{
me->SummonCreature(11076, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 600000);
DoDie();
}
break;
}
}
}
};
};
/*######
## npcs_andorhal_tower
######*/
enum eAndorhalTower
{
GO_BEACON_TORCH = 176093
};
class npc_andorhal_tower : public CreatureScript
{
public:
npc_andorhal_tower() : CreatureScript("npc_andorhal_tower") { }
CreatureAI* GetAI(Creature* creature) const
{
return new npc_andorhal_towerAI (creature);
}
struct npc_andorhal_towerAI : public Scripted_NoMovementAI
{
npc_andorhal_towerAI(Creature* c) : Scripted_NoMovementAI(c) {}
void MoveInLineOfSight(Unit* who)
{
if (!who || who->GetTypeId() != TYPEID_PLAYER)
return;
if (me->FindNearestGameObject(GO_BEACON_TORCH, 10.0f))
CAST_PLR(who)->KilledMonsterCredit(me->GetEntry(), me->GetGUID());
}
};
};
/*######
## npc_anchorite_truuen
######*/
enum eTruuen
{
NPC_GHOST_UTHER = 17233,
NPC_THEL_DANIS = 1854,
NPC_GHOUL = 1791, //ambush
QUEST_TOMB_LIGHTBRINGER = 9446,
SAY_WP_0 = -1800064, //Beware! We are attacked!
SAY_WP_1 = -1800065, //It must be the purity of the Mark of the Lightbringer that is drawing forth the Scourge to attack us. We must proceed with caution lest we be overwhelmed!
SAY_WP_2 = -1800066, //This land truly needs to be cleansed by the Light! Let us continue on to the tomb. It isn't far now...
SAY_WP_3 = -1800067, //Be welcome, friends!
SAY_WP_4 = -1800068, //Thank you for coming here in remembrance of me. Your efforts in recovering that symbol, while unnecessary, are certainly touching to an old man's heart.
SAY_WP_5 = -1800069, //Please, rise my friend. Keep the Blessing as a symbol of the strength of the Light and how heroes long gone might once again rise in each of us to inspire.
SAY_WP_6 = -1800070 //Thank you my friend for making this possible. This is a day that I shall never forget! I think I will stay a while. Please return to High Priestess MacDonnell at the camp. I know that she'll be keenly interested to know of what has transpired here.
};
class npc_anchorite_truuen : public CreatureScript
{
public:
npc_anchorite_truuen() : CreatureScript("npc_anchorite_truuen") { }
bool OnQuestAccept(Player* player, Creature* creature, Quest const* quest)
{
npc_escortAI* pEscortAI = CAST_AI(npc_anchorite_truuen::npc_anchorite_truuenAI, creature->AI());
if (quest->GetQuestId() == QUEST_TOMB_LIGHTBRINGER)
pEscortAI->Start(true, true, player->GetGUID());
return false;
}
CreatureAI* GetAI(Creature* creature) const
{
return new npc_anchorite_truuenAI(creature);
}
struct npc_anchorite_truuenAI : public npc_escortAI
{
npc_anchorite_truuenAI(Creature* creature) : npc_escortAI(creature) { }
uint32 m_uiChatTimer;
uint64 UghostGUID;
uint64 TheldanisGUID;
Creature* Ughost;
Creature* Theldanis;
void Reset()
{
m_uiChatTimer = 7000;
}
void JustSummoned(Creature* summoned)
{
if (summoned->GetEntry() == NPC_GHOUL)
summoned->AI()->AttackStart(me);
}
void WaypointReached(uint32 i)
{
Player* player = GetPlayerForEscort();
switch (i)
{
case 8:
DoScriptText(SAY_WP_0, me);
me->SummonCreature(NPC_GHOUL, me->GetPositionX()+7.0f, me->GetPositionY()+7.0f, me->GetPositionZ(), 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 90000);
me->SummonCreature(NPC_GHOUL, me->GetPositionX()+5.0f, me->GetPositionY()+5.0f, me->GetPositionZ(), 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 90000);
break;
case 9:
DoScriptText(SAY_WP_1, me);
break;
case 14:
me->SummonCreature(NPC_GHOUL, me->GetPositionX()+7.0f, me->GetPositionY()+7.0f, me->GetPositionZ(), 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 90000);
me->SummonCreature(NPC_GHOUL, me->GetPositionX()+5.0f, me->GetPositionY()+5.0f, me->GetPositionZ(), 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 90000);
me->SummonCreature(NPC_GHOUL, me->GetPositionX()+10.0f, me->GetPositionY()+10.0f, me->GetPositionZ(), 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 90000);
me->SummonCreature(NPC_GHOUL, me->GetPositionX()+8.0f, me->GetPositionY()+8.0f, me->GetPositionZ(), 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 90000);
break;
case 15:
DoScriptText(SAY_WP_2, me);
case 21:
Theldanis = GetClosestCreatureWithEntry(me, NPC_THEL_DANIS, 150);
DoScriptText(SAY_WP_3, Theldanis);
break;
case 22:
break;
case 23:
Ughost = me->SummonCreature(NPC_GHOST_UTHER, 971.86f, -1825.42f, 81.99f, 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 30000);
Ughost->SetDisableGravity(true);
DoScriptText(SAY_WP_4, Ughost, me);
m_uiChatTimer = 4000;
break;
case 24:
DoScriptText(SAY_WP_5, Ughost, me);
m_uiChatTimer = 4000;
break;
case 25:
DoScriptText(SAY_WP_6, Ughost, me);
m_uiChatTimer = 4000;
break;
case 26:
if (player)
player->GroupEventHappens(QUEST_TOMB_LIGHTBRINGER, me);
break;
}
}
void EnterCombat(Unit* /*who*/){}
void JustDied(Unit* /*killer*/)
{
Player* player = GetPlayerForEscort();
if (player)
player->FailQuest(QUEST_TOMB_LIGHTBRINGER);
}
void UpdateAI(const uint32 uiDiff)
{
npc_escortAI::UpdateAI(uiDiff);
DoMeleeAttackIfReady();
if (HasEscortState(STATE_ESCORT_ESCORTING))
m_uiChatTimer = 6000;
}
};
};
/*######
##
######*/
void AddSC_western_plaguelands()
{
new npcs_dithers_and_arbington();
new npc_myranda_the_hag();
new npc_the_scourge_cauldron();
new npc_andorhal_tower();
new npc_anchorite_truuen();
}
|
gpl-2.0
|
crc-corp/iris-its
|
src/us/mn/state/dot/tms/client/camera/VideoMonitorModel.java
|
2529
|
/*
* IRIS -- Intelligent Roadway Information System
* Copyright (C) 2007-2014 Minnesota Department of Transportation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 Public License for more details.
*/
package us.mn.state.dot.tms.client.camera;
import java.util.ArrayList;
import us.mn.state.dot.tms.VideoMonitor;
import us.mn.state.dot.tms.client.Session;
import us.mn.state.dot.tms.client.proxy.ProxyColumn;
import us.mn.state.dot.tms.client.proxy.ProxyTableModel;
/**
* Table model for video monitors
*
* @author Douglas Lau
*/
public class VideoMonitorModel extends ProxyTableModel<VideoMonitor> {
/** Create the columns in the model */
@Override
protected ArrayList<ProxyColumn<VideoMonitor>> createColumns() {
ArrayList<ProxyColumn<VideoMonitor>> cols =
new ArrayList<ProxyColumn<VideoMonitor>>(3);
cols.add(new ProxyColumn<VideoMonitor>("video.monitor", 160) {
public Object getValueAt(VideoMonitor vm) {
return vm.getName();
}
});
cols.add(new ProxyColumn<VideoMonitor>("device.description",
300)
{
public Object getValueAt(VideoMonitor vm) {
return vm.getDescription();
}
public boolean isEditable(VideoMonitor vm) {
return canUpdate(vm);
}
public void setValueAt(VideoMonitor vm, Object value) {
vm.setDescription(value.toString());
}
});
cols.add(new ProxyColumn<VideoMonitor>("video.restricted", 120,
Boolean.class)
{
public Object getValueAt(VideoMonitor vm) {
return vm.getRestricted();
}
public boolean isEditable(VideoMonitor vm) {
return canUpdate(vm);
}
public void setValueAt(VideoMonitor vm, Object value) {
if (value instanceof Boolean)
vm.setRestricted((Boolean)value);
}
});
return cols;
}
/** Create a new video monitor table model */
public VideoMonitorModel(Session s) {
super(s, s.getSonarState().getCamCache().getVideoMonitors(),
false, /* has_properties */
true, /* has_create_delete */
true); /* has_name */
}
/** Get the SONAR type name */
@Override
protected String getSonarType() {
return VideoMonitor.SONAR_TYPE;
}
}
|
gpl-2.0
|
coolo/open-build-service
|
src/api/spec/models/download_repository_spec.rb
|
954
|
require 'rails_helper'
RSpec.describe DownloadRepository do
describe 'validations' do
subject(:download_repository) { create(:download_repository) }
it { is_expected.to validate_presence_of(:url) }
it { is_expected.to validate_presence_of(:arch) }
it { is_expected.to validate_presence_of(:repotype) }
it { is_expected.to validate_presence_of(:repository) }
it { is_expected.to validate_uniqueness_of(:arch).scoped_to(:repository_id) }
it { is_expected.to validate_inclusion_of(:repotype).in_array(['rpmmd', 'susetags', 'deb', 'arch', 'mdk']) }
describe 'architecture_inclusion validation' do
subject(:download_repository) { create(:download_repository) }
it {
expect { download_repository.update_attributes!(arch: 's390x') }.to raise_error(
ActiveRecord::RecordInvalid, 'Validation failed: Architecture has to be available via repository association'
)
}
end
end
end
|
gpl-2.0
|
skyHALud/codenameone
|
Ports/iOSPort/xmlvm/src/ios/org/xmlvm/ios/UITextInputDelegate.java
|
699
|
package org.xmlvm.ios;
import java.util.*;
import org.xmlvm.XMLVMSkeletonOnly;
@XMLVMSkeletonOnly
public interface UITextInputDelegate {
/*
* Instance methods
*/
/**
* - (void)selectionWillChange:(id <UITextInput>)textInput;
*/
public abstract void selectionWillChange(UITextInput textInput);
/**
* - (void)selectionDidChange:(id <UITextInput>)textInput;
*/
public abstract void selectionDidChange(UITextInput textInput);
/**
* - (void)textWillChange:(id <UITextInput>)textInput;
*/
public abstract void textWillChange(UITextInput textInput);
/**
* - (void)textDidChange:(id <UITextInput>)textInput;
*/
public abstract void textDidChange(UITextInput textInput);
}
|
gpl-2.0
|
lucaswerkmeister/ceylon-compiler
|
src/com/redhat/ceylon/compiler/java/codegen/AnnotationInvocation.java
|
12308
|
package com.redhat.ceylon.compiler.java.codegen;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Functional;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.util.ListBuffer;
/**
* The invocation of an annotation constructor or annocation class
*/
public class AnnotationInvocation {
private Method constructorDeclaration;
private List<AnnotationConstructorParameter> constructorParameters = new ArrayList<AnnotationConstructorParameter>();
private Declaration primary;
private List<AnnotationArgument> annotationArguments = new ArrayList<AnnotationArgument>();
private boolean interop;
public AnnotationInvocation() {
}
/**
* The annotation constructor, if this is the invocation of an annotation constructor
*/
public Method getConstructorDeclaration() {
return constructorDeclaration;
}
public void setConstructorDeclaration(Method constructorDeclaration) {
this.constructorDeclaration = constructorDeclaration;
}
/**
* The parameters of the annotation constructor
*/
public List<AnnotationConstructorParameter> getConstructorParameters() {
return constructorParameters;
}
public int indexOfConstructorParameter(Parameter parameter) {
int index = 0;
for (AnnotationConstructorParameter acp : getConstructorParameters()) {
if (acp.getParameter().equals(parameter)) {
return index;
}
index++;
}
return -1;
}
/**
* The primary of the invocation:
* Either an annotation constructor ({@code Method})
* or an annotation class ({@code Class}).
*/
public Declaration getPrimary() {
return primary;
}
public void setPrimary(Class primary) {
this.primary = primary;
}
public void setPrimary(Method primary) {
this.primary = primary;
}
/**
* Is this an annotation class instantiation (i.e. is the primay a Class)?
*/
public boolean isInstantiation() {
return getPrimary() instanceof Class;
}
/**
* The type of the annotation class ultimately being instantiated
*/
public ProducedType getAnnotationClassType() {
if (isInstantiation()) {
return ((Class)getPrimary()).getType();
} else {
// TODO Method may not be declared to return this!
return ((Method)getPrimary()).getType();
}
}
/**
* The parameters of the primary
*/
public List<Parameter> getParameters() {
return ((Functional)primary).getParameterLists().get(0).getParameters();
}
/**
* The parameters of the class ultimately being instantiated
*/
public List<Parameter> getClassParameters() {
return ((Class)getAnnotationClassType().getDeclaration()).getParameterList().getParameters();
}
/**
* The arguments of the invocation
*/
public List<AnnotationArgument> getAnnotationArguments() {
return annotationArguments;
}
/**
* True if this is an interop annotation constructor
* (i.e. one invented by the model loader for the purposes of being able
* to use a Java annotation).
*/
public boolean isInterop() {
return interop;
}
public void setInterop(boolean interop) {
this.interop = interop;
}
public String toString() {
StringBuilder sb = new StringBuilder();
if (getConstructorDeclaration() != null) {
sb.append(getConstructorDeclaration().getName()).append("(");
List<AnnotationConstructorParameter> ctorParams = getConstructorParameters();
for (AnnotationConstructorParameter param : ctorParams) {
sb.append(param).append(", ");
}
if (!ctorParams.isEmpty()) {
sb.setLength(sb.length()-2);
}
sb.append(")\n\t=> ");
}
sb.append(primary != null ? primary.getName() : "NULL").append("{");
for (AnnotationArgument argument : annotationArguments) {
sb.append(argument).append(";\n");
}
return sb.append("}").toString();
}
/**
* Make a type expression for the underlying annotation class
*/
public JCExpression makeAnnotationType(ExpressionTransformer exprGen) {
ProducedType type = getAnnotationClassType();
if (isInterop()) {
return exprGen.makeJavaType(type.getSatisfiedTypes().get(0));
} else {
return exprGen.makeJavaType(type, ExpressionTransformer.JT_ANNOTATION);
}
}
public JCExpression makeAnnotation(
ExpressionTransformer exprGen,
AnnotationInvocation ai,
com.sun.tools.javac.util.List<AnnotationFieldName> parameterPath) {
ListBuffer<JCExpression> args = ListBuffer.<JCExpression>lb();
for (AnnotationArgument aa : getAnnotationArguments()) {
Parameter name = aa.getParameter();
if (!isInstantiation()) {
AnnotationInvocation annotationInvocation = (AnnotationInvocation)getConstructorDeclaration().getAnnotationConstructor();
for (AnnotationArgument a2 : annotationInvocation.getAnnotationArguments()) {
if (a2.getTerm() instanceof ParameterAnnotationTerm) {
if (((ParameterAnnotationTerm)a2.getTerm()).getSourceParameter().equals(aa.getParameter())) {
name = a2.getParameter();
break;
}
}
}
}
args.append(makeAnnotationArgument(exprGen, ai,
name,
parameterPath.append(aa), aa.getTerm()));
}
return exprGen.make().Annotation(makeAnnotationType(exprGen),
args.toList());
}
/**
* Make an annotation argument (@code member = value) for the given term
*/
public JCExpression makeAnnotationArgument(ExpressionTransformer exprGen, AnnotationInvocation ai,
Parameter bind,
com.sun.tools.javac.util.List<AnnotationFieldName> fieldPath, AnnotationTerm term) {
return exprGen.make().Assign(
exprGen.naming.makeName(bind.getModel(),
Naming.NA_ANNOTATION_MEMBER | Naming.NA_MEMBER),
term.makeAnnotationArgumentValue(exprGen, ai,
fieldPath));
}
/**
* Encode this invocation into a {@code @AnnotationInstantiation}
* (if the annotation constructors just calls the annotation class)
* or {@code @AnnotationInstantiationTree}
* (if the annotation constructor calls another annotation constructor)
*/
public JCAnnotation encode(AbstractTransformer gen, ListBuffer<JCExpression> instantiations) {
ListBuffer<JCExpression> arguments = ListBuffer.lb();
for (AnnotationArgument argument : getAnnotationArguments()) {
arguments.append(gen.make().Literal(
argument.getTerm().encode(gen, instantiations)));
}
JCExpression primary;
if (isInstantiation()) {
primary = gen.makeJavaType(getAnnotationClassType());
} else {
primary = gen.naming.makeName((Method)getPrimary(), Naming.NA_FQ | Naming.NA_WRAPPER);
}
JCAnnotation atInstantiation = gen.make().Annotation(
gen.make().Type(gen.syms().ceylonAtAnnotationInstantiationType),
com.sun.tools.javac.util.List.<JCExpression>of(
gen.make().Assign(
gen.naming.makeUnquotedIdent("arguments"),
gen.make().NewArray(null, null, arguments.toList())),
gen.make().Assign(
gen.naming.makeUnquotedIdent("primary"),
gen.naming.makeQualIdent(primary, "class"))
));
if (instantiations.isEmpty()) {
return atInstantiation;
} else {
return gen.make().Annotation(
gen.make().Type(gen.syms().ceylonAtAnnotationInstantiationTreeType),
com.sun.tools.javac.util.List.<JCExpression>of(
gen.make().NewArray(null, null, instantiations.prepend(atInstantiation).toList())));
}
}
public Iterable<AnnotationArgument> findAnnotationArgumentForClassParameter(Parameter classParameter) {
List<AnnotationArgument> result = new ArrayList<AnnotationArgument>(1);
if (isInstantiation()) {
for (AnnotationArgument aa : getAnnotationArguments()) {
if (aa.getParameter().equals(classParameter)) {
result.add(aa);
}
}
} else {
// we're invoking another constructor
AnnotationInvocation ctor = (AnnotationInvocation)((Method)getPrimary()).getAnnotationConstructor();
// find it's arguments
for (AnnotationArgument otherArgument : ctor.findAnnotationArgumentForClassParameter(classParameter)) {
if (otherArgument.getTerm() instanceof ParameterAnnotationTerm) {
Parameter sourceParameter = ((ParameterAnnotationTerm)otherArgument.getTerm()).getSourceParameter();
for (AnnotationArgument aa : getAnnotationArguments()) {
if (aa.getParameter().equals(sourceParameter)) {
result.add(aa);
}
}
}
}
}
return result;
}
public com.sun.tools.javac.util.List<JCAnnotation> makeExprAnnotations(ExpressionTransformer exprGen,
AnnotationInvocation toplevel,
com.sun.tools.javac.util.List<AnnotationFieldName> fieldPath) {
// Collect into groups according to their type
Map<java.lang.Class<?>, List<AnnotationArgument>> groups = new LinkedHashMap<java.lang.Class<?>, List<AnnotationArgument>>();
for (AnnotationArgument aa : getAnnotationArguments()) {
AnnotationTerm term = aa.getTerm();
List<AnnotationArgument> group = groups.get(term.getClass());
if (group == null) {
group = new ArrayList<AnnotationArgument>(1);
groups.put(term.getClass(), group);
}
group.add(aa);
}
// Make a @*Exprs annotation for each type
ListBuffer<JCAnnotation> exprsAnnos = ListBuffer.<JCAnnotation>lb();
for (List<AnnotationArgument> group : groups.values()) {
AnnotationTerm factory = null;
ListBuffer<JCAnnotation> valueAnnos = ListBuffer.<JCAnnotation>lb();
for (AnnotationArgument aa : group) {
AnnotationTerm term = aa.getTerm();
com.sun.tools.javac.util.List<JCAnnotation> annos = term.makeExprAnnotations(exprGen, this, fieldPath.append(aa));
if (annos != null) {
factory = group.get(0).getTerm();
valueAnnos.appendList(annos);
}
}
if (!valueAnnos.isEmpty()) {
com.sun.tools.javac.util.List<JCAnnotation> exprs = factory.makeExprs(exprGen, valueAnnos.toList());
if (exprs != null) {
exprsAnnos.appendList(exprs);
} else {
exprs = factory.makeExprs(exprGen, valueAnnos.toList());
}
}
}
return exprsAnnos.toList();
}
}
|
gpl-2.0
|
Distrotech/icedtea6-1.12
|
src/jtreg/com/sun/interview/StringListQuestion.java
|
7697
|
/*
* $Id$
*
* Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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 Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.interview;
import java.util.Map;
import java.util.Vector;
/**
* A {@link Question question} to which the response is an array of strings.
*/
public abstract class StringListQuestion extends Question
{
/**
* Create a question with a nominated tag.
* @param interview The interview containing this question.
* @param tag A unique tag to identify this specific question.
*/
protected StringListQuestion(Interview interview, String tag) {
super(interview, tag);
clear();
setDefaultValue(value);
}
/**
* Get the default response for this question.
* @return the default response for this question.
*
* @see #setDefaultValue
* @see #clear
*/
public String[] getDefaultValue() {
return defaultValue;
}
/**
* Set the default response for this question,
* used by the clear method.
* @param v the default response for this question.
*
* @see #getDefaultValue
* @see #clear
*/
public void setDefaultValue(String[] v) {
defaultValue = v;
}
/**
* Specify whether or not duplicates should be allowed in the list.
* By default, duplicates are allowed.
* @param b true if duplicates should be allowed, and false otherwise
* @see #isDuplicatesAllowed
*/
public void setDuplicatesAllowed(boolean b) {
duplicatesAllowed = b;
}
/**
* Check whether or not duplicates should be allowed in the list.
* @return true if duplicates should be allowed, and false otherwise
* @see #setDuplicatesAllowed
*/
public boolean isDuplicatesAllowed() {
return duplicatesAllowed;
}
/**
* Get the current (default or latest) response to this question.
* @return The current value.
*
* @see #setValue
*/
public String[] getValue() {
return value;
}
/**
* Verify this question is on the current path, and if it is,
* return the current value.
* @return the current value of this question
* @throws Interview.NotOnPathFault if this question is not on the
* current path
* @see #getValue
*/
public String[] getValueOnPath()
throws Interview.NotOnPathFault
{
interview.verifyPathContains(this);
return getValue();
}
/**
* Get the response to this question as a string.
* @return a string representing the current response to this question, or null.
* @see #setValue(String)
*/
public String getStringValue() {
if (value == null)
return null;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < value.length; i++) {
if (sb.length() > 0)
sb.append('\n');
if (value[i] != null)
sb.append(value[i]);
}
return sb.toString();
}
public boolean isValueValid() {
return true;
}
public boolean isValueAlwaysValid() {
return false;
}
public void setValue(String s) {
setValue(s == null ? ((String[]) null) : split(s));
}
/**
* Set the current value.
* @param newValue The value to be set.
*
* @see #getValue
*/
public void setValue(String[] newValue) {
if (newValue != null) {
for (int i = 0; i < newValue.length; i++) {
if (newValue[i] == null || (newValue[i].indexOf("\n") != -1))
throw new IllegalArgumentException();
}
}
if (!equal(newValue, value)) {
if (newValue == null)
value = null;
else {
value = new String[newValue.length];
System.arraycopy(newValue, 0, value, 0, newValue.length);
}
interview.updatePath(this);
interview.setEdited(true);
}
}
/**
* Clear any response to this question, resetting the value
* back to its initial state.
*/
public void clear() {
setValue(defaultValue);
}
/**
* Load the value for this question from a dictionary, using
* the tag as the key.
* @param data The map from which to load the value for this question.
*/
protected void load(Map data) {
Object o = data.get(tag);
if (o instanceof String[])
setValue((String[]) o);
else if (o instanceof String)
setValue((String) o);
}
/**
* Save the value for this question in a dictionary, using
* the tag as the key.
* @param data The map in which to save the value for this question.
*/
protected void save(Map data) {
if (value != null)
data.put(tag, getStringValue());
}
/**
* Compare two string arrays for equality.
* @param s1 the first array to be compared, or null
* @param s2 the other array to be compared, or null
* @return true if both parameters are null, or if both are non-null
* and are element-wise equal.
* @see #equal(String, String)
*/
protected static boolean equal(String[] s1, String[] s2) {
if (s1 == null || s2 == null)
return (s1 == s2);
if (s1.length != s2.length)
return false;
for (int i = 0; i < s1.length; i++) {
if (!equal(s1[i], s2[i]))
return false;
}
return true;
}
/**
* Compare two strings for equality.
* @param s1 the first string to be compared, or null
* @param s2 the other string to be compared, or null
* @return true if both parameters are null, or if both are non-null
* and equal.
*/
protected static boolean equal(String s1, String s2) {
return (s1 == null ? s2 == null : s1.equals(s2));
}
/**
* Split a string into a set of newline-separated strings.
* @param s The string to be split, or null
* @return an array of strings containing the newline-separated substrings of
* the argument.
*/
protected static String[] split(String s) {
if (s == null)
return empty;
final char sep = '\n';
Vector v = new Vector();
int start = -1;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == sep) {
if (start != -1)
v.addElement(s.substring(start, i));
start = -1;
} else
if (start == -1)
start = i;
}
if (start != -1)
v.addElement(s.substring(start));
if (v.size() == 0)
return empty;
String[] a = new String[v.size()];
v.copyInto(a);
return a;
}
private static final String[] empty = { };
/**
* The current response for this question.
*/
protected String[] value;
/**
* The default response for this question.
*/
private String[] defaultValue;
private boolean duplicatesAllowed = true;
}
|
gpl-2.0
|
gdefias/StudyC
|
VS/testCPPpython/testcpp.cpp
|
719
|
#include <iostream>
using namespace std;
class Point
{
public:
void setPoint(int x, int y); //ๅจ็ฑปๅ
ๅฏนๆๅๅฝๆฐ่ฟ่กๅฃฐๆ
void printPoint();
private:
int xPos;
int yPos;
};
void Point::setPoint(int x, int y) //้่ฟไฝ็จๅๆไฝ็ฌฆ '::' ๅฎ็ฐsetPointๅฝๆฐ
{
xPos = x;
yPos = y;
}
void Point::printPoint() //ๅฎ็ฐprintPointๅฝๆฐ
{
cout<< "x = " << xPos << endl;
cout<< "y = " << yPos << endl;
}
int main()
{
Point M; //็จๅฎไนๅฅฝ็็ฑปๅๅปบไธไธชๅฏน่ฑก ็นM
M.setPoint(10, 20); //่ฎพ็ฝฎ M็น ็x,yๅผ
M.printPoint(); //่พๅบ M็น ็ไฟกๆฏ
getchar();
return 0;
}
|
gpl-2.0
|
mrksbrg/moped
|
plugins/AP/src/main/java/plugins/AP.java
|
4603
|
package plugins;
import com.sun.squawk.VM;
import java.lang.Math;
import sics.plugin.PlugInComponent;
import sics.port.PluginPPort;
import sics.port.PluginRPort;
public class AP extends PlugInComponent {
public PluginPPort speed;
public PluginPPort steering;
public PluginRPort rspeed;
public PluginRPort rsteer;
public AP(String[] args) {
super(args);
}
public AP() {
}
public static void main(String[] args) {
VM.println("AP.main()\r\n");
AP ap = new AP(args);
ap.run();
VM.println("AP-main done\r\n");
}
// public void setSpeed(PluginPPort speed) {
// this.speed = speed;
// }
//
// public void setSteering(PluginPPort steering) {
// this.steering = steering;
// }
public void init() {
// Initiate PluginPPort
VM.println("init 1");
speed = new PluginPPort(this, "sp");
VM.println("init 2");
steering = new PluginPPort(this, "st");
VM.println("init 3");
rspeed = new PluginRPort(this, "rsp");
VM.println("init 4");
rsteer = new PluginRPort(this, "rst");
VM.println("init 5");
}
private void show(String msg, PluginRPort port) {
//VM.println("show 1");
//Object obj = port.receive();
//String obj = port.readString();
int x = port.readInt();
String obj = "(" + x + ")";
//VM.println("show 2");
if (obj == null) {
VM.println("received from port " + msg + ": " + "null");
} else {
VM.println("received from port " + msg + ": " + (String) obj);
}
}
// TODO: check getting stuck moving backwards too
public void doFunction() {
int s;
try {
for (int i = 0; i < 100; i++) {
// warmup
Thread.sleep(2000);
speed.write(0);
steering.write(0);
Thread.sleep(2000);
// forward
show("speed", rspeed);
//show("steering", rsteer);
speed.write(20);
steering.write(0);
Thread.sleep(2000);
s = rspeed.readInt();
VM.println("s = " + s);
if (s < 5) {
VM.println("reversing");
speed.write(0);
steering.write(0);
Thread.sleep(3000);
speed.write(-10);
steering.write(0);
show("speed", rspeed);
Thread.sleep(7000);
show("speed", rspeed);
}
// turn left
speed.write(20);
steering.write(-80);
Thread.sleep(3000);
s = rspeed.readInt();
VM.println("s = " + s);
//s = 1;
if (s < 5) {
VM.println("reversing");
speed.write(0);
steering.write(0);
Thread.sleep(3000);
speed.write(-30);
steering.write(0);
show("speed", rspeed);
Thread.sleep(7000);
show("speed", rspeed);
}
show("speed", rspeed);
//show("steering", rsteer);
// right, right
speed.write(20);
steering.write(80);
show("speed", rspeed);
Thread.sleep(500);
show("speed", rspeed);
Thread.sleep(500);
show("speed", rspeed);
Thread.sleep(500);
show("speed", rspeed);
Thread.sleep(500);
show("speed", rspeed);
Thread.sleep(500);
show("speed", rspeed);
Thread.sleep(500);
show("speed", rspeed);
Thread.sleep(500);
show("speed", rspeed);
Thread.sleep(500);
show("speed", rspeed);
Thread.sleep(500);
show("speed", rspeed);
Thread.sleep(500);
show("speed", rspeed);
Thread.sleep(500);
show("speed", rspeed);
Thread.sleep(500);
show("speed", rspeed);
//show("steering", rsteer);
s = rspeed.readInt();
VM.println("s = " + s);
if (s < 5) {
VM.println("reversing");
speed.write(0);
steering.write(0);
Thread.sleep(3000);
speed.write(-10);
steering.write(0);
show("speed", rspeed);
Thread.sleep(7000);
show("speed", rspeed);
}
// straight
speed.write(20);
steering.write(0);
Thread.sleep(4000);
s = rspeed.readInt();
VM.println("s = " + s);
if (s < 5) {
VM.println("reversing");
speed.write(0);
steering.write(0);
Thread.sleep(3000);
speed.write(-10);
steering.write(0);
show("speed", rspeed);
Thread.sleep(7000);
show("speed", rspeed);
}
// stop
speed.write(0);
steering.write(0);
Thread.sleep(2000);
}
} catch (InterruptedException e) {
//VM.println("Interrupted.\r\n");
}
}
// public PluginPPort getSpeedPort() { return speed; }
// public PluginPPort getSteeringPort() { return steering; }
// private int rescaleToPwm(int val) {
// return (int) (Math.ceil(100 + (0.55556 * val)) * 16.38);
// }
public void run() {
init();
doFunction();
}
}
|
gpl-2.0
|
healthcommcore/lung_cancer_site
|
survey/scripts/calendar/lang/calendar-de.js
|
3919
|
// ** I18N
// Calendar DE language
// Author: Jack (tR), <jack@jtr.de>
// Encoding: any
// Distributed under the same terms as the calendar itself.
// For translators: please use UTF-8 if possible. We strongly believe that
// Unicode is the answer to a real internationalized world. Also please
// include your contact information in the header, as can be seen above.
// full day names
Calendar._DN = new Array
("Sonntag",
"Montag",
"Dienstag",
"Mittwoch",
"Donnerstag",
"Freitag",
"Samstag",
"Sonntag");
// Please note that the following array of short day names (and the same goes
// for short month names, _SMN) isn't absolutely necessary. We give it here
// for exemplification on how one can customize the short day names, but if
// they are simply the first N letters of the full name you can simply say:
//
// Calendar._SDN_len = N; // short day name length
// Calendar._SMN_len = N; // short month name length
//
// If N = 3 then this is not needed either since we assume a value of 3 if not
// present, to be compatible with translation files that were written before
// this feature.
// short day names
Calendar._SDN = new Array
("So",
"Mo",
"Di",
"Mi",
"Do",
"Fr",
"Sa",
"So");
// First day of the week. "0" means display Sunday first, "1" means display
// Monday first, etc.
Calendar._FD = 1;
// full month names
Calendar._MN = new Array
("Januar",
"Februar",
"M\u00e4rz",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Dezember");
// short month names
Calendar._SMN = new Array
("Jan",
"Feb",
"M\u00e4r",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Okt",
"Nov",
"Dez");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "\u00DCber dieses Kalendarmodul";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this ;-)
"For latest version visit: http://www.dynarch.com/projects/calendar/\n" +
"Distributed under GNU LGPL. See http://gnu.org/licenses/lgpl.html for details." +
"\n\n" +
"Datum ausw\u00e4hlen:\n" +
"- Benutzen Sie die \xab, \xbb Buttons um das Jahr zu w\u00e4hlen\n" +
"- Benutzen Sie die " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " Buttons um den Monat zu w\u00e4hlen\n" +
"- F\u00fcr eine Schnellauswahl halten Sie die Maustaste \u00fcber diesen Buttons fest.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Zeit ausw\u00e4hlen:\n" +
"- Klicken Sie auf die Teile der Uhrzeit, um diese zu erh\u00F6hen\n" +
"- oder klicken Sie mit festgehaltener Shift-Taste um diese zu verringern\n" +
"- oder klicken und festhalten f\u00fcr Schnellauswahl.";
Calendar._TT["PREV_YEAR"] = "Voriges Jahr (Festhalten f\u00fcr Schnellauswahl)";
Calendar._TT["PREV_MONTH"] = "Voriger Monat (Festhalten f\u00fcr Schnellauswahl)";
Calendar._TT["GO_TODAY"] = "Heute ausw\u00e4hlen";
Calendar._TT["NEXT_MONTH"] = "N\u00e4chst. Monat (Festhalten f\u00fcr Schnellauswahl)";
Calendar._TT["NEXT_YEAR"] = "N\u00e4chst. Jahr (Festhalten f\u00fcr Schnellauswahl)";
Calendar._TT["SEL_DATE"] = "Datum ausw\u00e4hlen";
Calendar._TT["DRAG_TO_MOVE"] = "Zum Bewegen festhalten";
Calendar._TT["PART_TODAY"] = " (Heute)";
// the following is to inform that "%s" is to be the first day of week
// %s will be replaced with the day name.
Calendar._TT["DAY_FIRST"] = "Woche beginnt mit %s ";
// This may be locale-dependent. It specifies the week-end days, as an array
// of comma-separated numbers. The numbers are from 0 to 6: 0 means Sunday, 1
// means Monday, etc.
Calendar._TT["WEEKEND"] = "0,6";
Calendar._TT["CLOSE"] = "Schlie\u00dfen";
Calendar._TT["TODAY"] = "Heute";
Calendar._TT["TIME_PART"] = "(Shift-)Klick oder Festhalten und Ziehen um den Wert zu \u00e4ndern";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%d.%m.%Y";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %b %e";
Calendar._TT["WK"] = "kw";
Calendar._TT["TIME"] = "Zeit:";
|
gpl-2.0
|
dirtycold/git-cola
|
cola/widgets/dag.py
|
52694
|
from __future__ import division, absolute_import, unicode_literals
import collections
import math
from qtpy import QtCore
from qtpy import QtGui
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from qtpy.QtCore import Signal
from qtpy.QtCore import QPointF
from qtpy.QtCore import QRectF
from .. import core
from .. import cmds
from .. import difftool
from .. import hotkeys
from .. import icons
from .. import observable
from .. import qtcompat
from .. import qtutils
from ..compat import maxsize
from ..i18n import N_
from ..models import dag
from . import archive
from . import browse
from . import completion
from . import createbranch
from . import createtag
from . import defs
from . import diff
from . import filelist
from . import standard
def git_dag(model, args=None, settings=None):
"""Return a pre-populated git DAG widget."""
branch = model.currentbranch
# disambiguate between branch names and filenames by using '--'
branch_doubledash = branch and (branch + ' --') or ''
ctx = dag.DAG(branch_doubledash, 1000)
ctx.set_arguments(args)
view = GitDAG(model, ctx, settings=settings)
if ctx.ref:
view.display()
return view
class FocusRedirectProxy(object):
"""Redirect actions from the main widget to child widgets"""
def __init__(self, *widgets):
"""Provide proxied widgets; the default widget must be first"""
self.widgets = widgets
self.default = widgets[0]
def __getattr__(self, name):
return (lambda *args, **kwargs:
self._forward_action(name, *args, **kwargs))
def _forward_action(self, name, *args, **kwargs):
"""Forward the captured action to the focused or default widget"""
widget = QtWidgets.QApplication.focusWidget()
if widget in self.widgets and hasattr(widget, name):
fn = getattr(widget, name)
else:
fn = getattr(self.default, name)
return fn(*args, **kwargs)
class ViewerMixin(object):
"""Implementations must provide selected_items()"""
def __init__(self):
self.selected = None
self.clicked = None
self.menu_actions = None # provided by implementation
def selected_item(self):
"""Return the currently selected item"""
selected_items = self.selected_items()
if not selected_items:
return None
return selected_items[0]
def selected_sha1(self):
item = self.selected_item()
if item is None:
result = None
else:
result = item.commit.sha1
return result
def selected_sha1s(self):
return [i.commit for i in self.selected_items()]
def with_oid(self, fn):
oid = self.selected_sha1()
if oid:
result = fn(oid)
else:
result = None
return result
def diff_selected_this(self):
clicked_sha1 = self.clicked.sha1
selected_sha1 = self.selected.sha1
self.diff_commits.emit(selected_sha1, clicked_sha1)
def diff_this_selected(self):
clicked_sha1 = self.clicked.sha1
selected_sha1 = self.selected.sha1
self.diff_commits.emit(clicked_sha1, selected_sha1)
def cherry_pick(self):
self.with_oid(lambda oid: cmds.do(cmds.CherryPick, [oid]))
def copy_to_clipboard(self):
self.with_oid(lambda oid: qtutils.set_clipboard(oid))
def create_branch(self):
self.with_oid(lambda oid: createbranch.create_new_branch(revision=oid))
def create_tag(self):
self.with_oid(lambda oid: createtag.create_tag(ref=oid))
def create_tarball(self):
self.with_oid(lambda oid: archive.show_save_dialog(oid, parent=self))
def show_diff(self):
self.with_oid(lambda oid:
difftool.diff_expression(self, oid + '^!',
hide_expr=False, focus_tree=True))
def show_dir_diff(self):
self.with_oid(lambda oid:
difftool.launch(left=oid, left_take_magic=True, dir_diff=True))
def reset_branch_head(self):
self.with_oid(lambda oid: cmds.do(cmds.ResetBranchHead, ref=oid))
def reset_worktree(self):
self.with_oid(lambda oid: cmds.do(cmds.ResetWorktree, ref=oid))
def save_blob_dialog(self):
self.with_oid(lambda oid: browse.BrowseDialog.browse(oid))
def update_menu_actions(self, event):
selected_items = self.selected_items()
item = self.itemAt(event.pos())
if item is None:
self.clicked = commit = None
else:
self.clicked = commit = item.commit
has_single_selection = len(selected_items) == 1
has_selection = bool(selected_items)
can_diff = bool(commit and has_single_selection and
commit is not selected_items[0].commit)
if can_diff:
self.selected = selected_items[0].commit
else:
self.selected = None
self.menu_actions['diff_this_selected'].setEnabled(can_diff)
self.menu_actions['diff_selected_this'].setEnabled(can_diff)
self.menu_actions['diff_commit'].setEnabled(has_single_selection)
self.menu_actions['diff_commit_all'].setEnabled(has_single_selection)
self.menu_actions['cherry_pick'].setEnabled(has_single_selection)
self.menu_actions['copy'].setEnabled(has_single_selection)
self.menu_actions['create_branch'].setEnabled(has_single_selection)
self.menu_actions['create_patch'].setEnabled(has_selection)
self.menu_actions['create_tag'].setEnabled(has_single_selection)
self.menu_actions['create_tarball'].setEnabled(has_single_selection)
self.menu_actions['reset_branch_head'].setEnabled(has_single_selection)
self.menu_actions['reset_worktree'].setEnabled(has_single_selection)
self.menu_actions['save_blob'].setEnabled(has_single_selection)
def context_menu_event(self, event):
self.update_menu_actions(event)
menu = qtutils.create_menu(N_('Actions'), self)
menu.addAction(self.menu_actions['diff_this_selected'])
menu.addAction(self.menu_actions['diff_selected_this'])
menu.addAction(self.menu_actions['diff_commit'])
menu.addAction(self.menu_actions['diff_commit_all'])
menu.addSeparator()
menu.addAction(self.menu_actions['create_branch'])
menu.addAction(self.menu_actions['create_tag'])
menu.addSeparator()
menu.addAction(self.menu_actions['cherry_pick'])
menu.addAction(self.menu_actions['create_patch'])
menu.addAction(self.menu_actions['create_tarball'])
menu.addSeparator()
reset_menu = menu.addMenu(N_('Reset'))
reset_menu.addAction(self.menu_actions['reset_branch_head'])
reset_menu.addAction(self.menu_actions['reset_worktree'])
menu.addSeparator()
menu.addAction(self.menu_actions['save_blob'])
menu.addAction(self.menu_actions['copy'])
menu.exec_(self.mapToGlobal(event.pos()))
def viewer_actions(widget):
return {
'diff_this_selected':
qtutils.add_action(widget, N_('Diff this -> selected'),
widget.proxy.diff_this_selected),
'diff_selected_this':
qtutils.add_action(widget, N_('Diff selected -> this'),
widget.proxy.diff_selected_this),
'create_branch':
qtutils.add_action(widget, N_('Create Branch'),
widget.proxy.create_branch),
'create_patch':
qtutils.add_action(widget, N_('Create Patch'),
widget.proxy.create_patch),
'create_tag':
qtutils.add_action(widget, N_('Create Tag'),
widget.proxy.create_tag),
'create_tarball':
qtutils.add_action(widget, N_('Save As Tarball/Zip...'),
widget.proxy.create_tarball),
'cherry_pick':
qtutils.add_action(widget, N_('Cherry Pick'),
widget.proxy.cherry_pick),
'diff_commit':
qtutils.add_action(widget, N_('Launch Diff Tool'),
widget.proxy.show_diff, hotkeys.DIFF),
'diff_commit_all':
qtutils.add_action(widget, N_('Launch Directory Diff Tool'),
widget.proxy.show_dir_diff, hotkeys.DIFF_SECONDARY),
'reset_branch_head':
qtutils.add_action(widget, N_('Reset Branch Head'),
widget.proxy.reset_branch_head),
'reset_worktree':
qtutils.add_action(widget, N_('Reset Worktree'),
widget.proxy.reset_worktree),
'save_blob':
qtutils.add_action(widget, N_('Grab File...'),
widget.proxy.save_blob_dialog),
'copy':
qtutils.add_action(widget, N_('Copy SHA-1'),
widget.proxy.copy_to_clipboard,
QtGui.QKeySequence.Copy),
}
class CommitTreeWidgetItem(QtWidgets.QTreeWidgetItem):
def __init__(self, commit, parent=None):
QtWidgets.QTreeWidgetItem.__init__(self, parent)
self.commit = commit
self.setText(0, commit.summary)
self.setText(1, commit.author)
self.setText(2, commit.authdate)
class CommitTreeWidget(standard.TreeWidget, ViewerMixin):
diff_commits = Signal(object, object)
def __init__(self, notifier, parent):
standard.TreeWidget.__init__(self, parent=parent)
ViewerMixin.__init__(self)
self.setSelectionMode(self.ExtendedSelection)
self.setHeaderLabels([N_('Summary'), N_('Author'), N_('Date, Time')])
self.sha1map = {}
self.menu_actions = None
self.notifier = notifier
self.selecting = False
self.commits = []
self.action_up = qtutils.add_action(self, N_('Go Up'),
self.go_up, hotkeys.MOVE_UP)
self.action_down = qtutils.add_action(self, N_('Go Down'),
self.go_down, hotkeys.MOVE_DOWN)
notifier.add_observer(diff.COMMITS_SELECTED, self.commits_selected)
self.itemSelectionChanged.connect(self.selection_changed)
# ViewerMixin
def go_up(self):
self.goto(self.itemAbove)
def go_down(self):
self.goto(self.itemBelow)
def goto(self, finder):
items = self.selected_items()
item = items and items[0] or None
if item is None:
return
found = finder(item)
if found:
self.select([found.commit.sha1])
def selected_commit_range(self):
selected_items = self.selected_items()
if not selected_items:
return None, None
return selected_items[-1].commit.sha1, selected_items[0].commit.sha1
def set_selecting(self, selecting):
self.selecting = selecting
def selection_changed(self):
items = self.selected_items()
if not items:
return
self.set_selecting(True)
self.notifier.notify_observers(diff.COMMITS_SELECTED,
[i.commit for i in items])
self.set_selecting(False)
def commits_selected(self, commits):
if self.selecting:
return
with qtutils.BlockSignals(self):
self.select([commit.sha1 for commit in commits])
def select(self, sha1s):
if not sha1s:
return
self.clearSelection()
for idx, sha1 in enumerate(sha1s):
try:
item = self.sha1map[sha1]
except KeyError:
continue
self.scrollToItem(item)
item.setSelected(True)
def adjust_columns(self):
width = self.width()-20
zero = width*2//3
onetwo = width//6
self.setColumnWidth(0, zero)
self.setColumnWidth(1, onetwo)
self.setColumnWidth(2, onetwo)
def clear(self):
QtWidgets.QTreeWidget.clear(self)
self.sha1map.clear()
self.commits = []
def add_commits(self, commits):
self.commits.extend(commits)
items = []
for c in reversed(commits):
item = CommitTreeWidgetItem(c)
items.append(item)
self.sha1map[c.sha1] = item
for tag in c.tags:
self.sha1map[tag] = item
self.insertTopLevelItems(0, items)
def create_patch(self):
items = self.selectedItems()
if not items:
return
sha1s = [item.commit.sha1 for item in reversed(items)]
all_sha1s = [c.sha1 for c in self.commits]
cmds.do(cmds.FormatPatch, sha1s, all_sha1s)
# Qt overrides
def contextMenuEvent(self, event):
self.context_menu_event(event)
def mousePressEvent(self, event):
if event.button() == Qt.RightButton:
event.accept()
return
QtWidgets.QTreeWidget.mousePressEvent(self, event)
class GitDAG(standard.MainWindow):
"""The git-dag widget."""
updated = Signal()
def __init__(self, model, ctx, parent=None, settings=None):
super(GitDAG, self).__init__(parent)
self.setAttribute(Qt.WA_MacMetalStyle)
self.setMinimumSize(420, 420)
# change when widgets are added/removed
self.widget_version = 2
self.model = model
self.ctx = ctx
self.settings = settings
self.commits = {}
self.commit_list = []
self.selection = []
self.thread = ReaderThread(ctx, self)
self.revtext = completion.GitLogLineEdit()
self.maxresults = standard.SpinBox()
self.zoom_out = qtutils.create_action_button(
tooltip=N_('Zoom Out'), icon=icons.zoom_out())
self.zoom_in = qtutils.create_action_button(
tooltip=N_('Zoom In'), icon=icons.zoom_in())
self.zoom_to_fit = qtutils.create_action_button(
tooltip=N_('Zoom to Fit'), icon=icons.zoom_fit_best())
self.notifier = notifier = observable.Observable()
self.notifier.refs_updated = refs_updated = 'refs_updated'
self.notifier.add_observer(refs_updated, self.display)
self.notifier.add_observer(filelist.HISTORIES_SELECTED,
self.histories_selected)
self.notifier.add_observer(filelist.DIFFTOOL_SELECTED,
self.difftool_selected)
self.notifier.add_observer(diff.COMMITS_SELECTED, self.commits_selected)
self.treewidget = CommitTreeWidget(notifier, self)
self.diffwidget = diff.DiffWidget(notifier, self)
self.filewidget = filelist.FileWidget(notifier, self)
self.graphview = GraphView(notifier, self)
self.proxy = FocusRedirectProxy(self.treewidget,
self.graphview,
self.filewidget)
self.viewer_actions = actions = viewer_actions(self)
self.treewidget.menu_actions = actions
self.graphview.menu_actions = actions
self.controls_layout = qtutils.hbox(defs.no_margin, defs.spacing,
self.revtext, self.maxresults)
self.controls_widget = QtWidgets.QWidget()
self.controls_widget.setLayout(self.controls_layout)
self.log_dock = qtutils.create_dock(N_('Log'), self, stretch=False)
self.log_dock.setWidget(self.treewidget)
log_dock_titlebar = self.log_dock.titleBarWidget()
log_dock_titlebar.add_corner_widget(self.controls_widget)
self.file_dock = qtutils.create_dock(N_('Files'), self)
self.file_dock.setWidget(self.filewidget)
self.diff_dock = qtutils.create_dock(N_('Diff'), self)
self.diff_dock.setWidget(self.diffwidget)
self.graph_controls_layout = qtutils.hbox(
defs.no_margin, defs.button_spacing,
self.zoom_out, self.zoom_in, self.zoom_to_fit,
defs.spacing)
self.graph_controls_widget = QtWidgets.QWidget()
self.graph_controls_widget.setLayout(self.graph_controls_layout)
self.graphview_dock = qtutils.create_dock(N_('Graph'), self)
self.graphview_dock.setWidget(self.graphview)
graph_titlebar = self.graphview_dock.titleBarWidget()
graph_titlebar.add_corner_widget(self.graph_controls_widget)
self.lock_layout_action = qtutils.add_action_bool(
self, N_('Lock Layout'), self.set_lock_layout, False)
self.refresh_action = qtutils.add_action(
self, N_('Refresh'), self.refresh, hotkeys.REFRESH)
# Create the application menu
self.menubar = QtWidgets.QMenuBar(self)
# View Menu
self.view_menu = qtutils.create_menu(N_('View'), self.menubar)
self.view_menu.addAction(self.refresh_action)
self.view_menu.addAction(self.log_dock.toggleViewAction())
self.view_menu.addAction(self.graphview_dock.toggleViewAction())
self.view_menu.addAction(self.diff_dock.toggleViewAction())
self.view_menu.addAction(self.file_dock.toggleViewAction())
self.view_menu.addSeparator()
self.view_menu.addAction(self.lock_layout_action)
self.menubar.addAction(self.view_menu.menuAction())
self.setMenuBar(self.menubar)
left = Qt.LeftDockWidgetArea
right = Qt.RightDockWidgetArea
self.addDockWidget(left, self.log_dock)
self.addDockWidget(left, self.diff_dock)
self.addDockWidget(right, self.graphview_dock)
self.addDockWidget(right, self.file_dock)
# Update fields affected by model
self.revtext.setText(ctx.ref)
self.maxresults.setValue(ctx.count)
self.update_window_title()
# Also re-loads dag.* from the saved state
self.init_state(settings, self.resize_to_desktop)
qtutils.connect_button(self.zoom_out, self.graphview.zoom_out)
qtutils.connect_button(self.zoom_in, self.graphview.zoom_in)
qtutils.connect_button(self.zoom_to_fit,
self.graphview.zoom_to_fit)
thread = self.thread
thread.begin.connect(self.thread_begin, type=Qt.QueuedConnection)
thread.status.connect(self.thread_status, type=Qt.QueuedConnection)
thread.add.connect(self.add_commits, type=Qt.QueuedConnection)
thread.end.connect(self.thread_end, type=Qt.QueuedConnection)
self.treewidget.diff_commits.connect(self.diff_commits)
self.graphview.diff_commits.connect(self.diff_commits)
self.maxresults.editingFinished.connect(self.display)
self.revtext.textChanged.connect(self.text_changed)
self.revtext.activated.connect(self.display)
self.revtext.enter.connect(self.display)
self.revtext.down.connect(self.focus_tree)
# The model is updated in another thread so use
# signals/slots to bring control back to the main GUI thread
self.model.add_observer(self.model.message_updated, self.updated.emit)
self.updated.connect(self.model_updated, type=Qt.QueuedConnection)
qtutils.add_action(self, 'Focus Input', self.focus_input, hotkeys.FOCUS)
qtutils.add_close_action(self)
def focus_input(self):
self.revtext.setFocus()
def focus_tree(self):
self.treewidget.setFocus()
def text_changed(self, txt):
self.ctx.ref = txt
self.update_window_title()
def update_window_title(self):
project = self.model.project
if self.ctx.ref:
self.setWindowTitle(N_('%(project)s: %(ref)s - DAG')
% dict(project=project, ref=self.ctx.ref))
else:
self.setWindowTitle(project + N_(' - DAG'))
def export_state(self):
state = standard.MainWindow.export_state(self)
state['count'] = self.ctx.count
return state
def apply_state(self, state):
result = standard.MainWindow.apply_state(self, state)
try:
count = state['count']
if self.ctx.overridden('count'):
count = self.ctx.count
except:
count = self.ctx.count
result = False
self.ctx.set_count(count)
self.lock_layout_action.setChecked(state.get('lock_layout', False))
return result
def model_updated(self):
self.display()
def refresh(self):
cmds.do(cmds.Refresh)
def display(self):
new_ref = self.revtext.value()
new_count = self.maxresults.value()
self.thread.stop()
self.ctx.set_ref(new_ref)
self.ctx.set_count(new_count)
self.thread.start()
def show(self):
standard.MainWindow.show(self)
self.treewidget.adjust_columns()
def commits_selected(self, commits):
if commits:
self.selection = commits
def clear(self):
self.commits.clear()
self.commit_list = []
self.graphview.clear()
self.treewidget.clear()
def add_commits(self, commits):
self.commit_list.extend(commits)
# Keep track of commits
for commit_obj in commits:
self.commits[commit_obj.sha1] = commit_obj
for tag in commit_obj.tags:
self.commits[tag] = commit_obj
self.graphview.add_commits(commits)
self.treewidget.add_commits(commits)
def thread_begin(self):
self.clear()
def thread_end(self):
self.focus_tree()
self.restore_selection()
def thread_status(self, successful):
self.revtext.hint.set_error(not successful)
def restore_selection(self):
selection = self.selection
try:
commit_obj = self.commit_list[-1]
except IndexError:
# No commits, exist, early-out
return
new_commits = [self.commits.get(s.sha1, None) for s in selection]
new_commits = [c for c in new_commits if c is not None]
if new_commits:
# The old selection exists in the new state
self.notifier.notify_observers(diff.COMMITS_SELECTED, new_commits)
else:
# The old selection is now empty. Select the top-most commit
self.notifier.notify_observers(diff.COMMITS_SELECTED, [commit_obj])
self.graphview.update_scene_rect()
self.graphview.set_initial_view()
def diff_commits(self, a, b):
paths = self.ctx.paths()
if paths:
difftool.launch(left=a, right=b, paths=paths)
else:
difftool.diff_commits(self, a, b)
# Qt overrides
def closeEvent(self, event):
self.revtext.close_popup()
self.thread.stop()
standard.MainWindow.closeEvent(self, event)
def resizeEvent(self, e):
standard.MainWindow.resizeEvent(self, e)
self.treewidget.adjust_columns()
def histories_selected(self, histories):
argv = [self.model.currentbranch, '--']
argv.extend(histories)
text = core.list2cmdline(argv)
self.revtext.setText(text)
self.display()
def difftool_selected(self, files):
bottom, top = self.treewidget.selected_commit_range()
if not top:
return
difftool.launch(left=bottom, left_take_parent=True,
right=top, paths=files)
class ReaderThread(QtCore.QThread):
begin = Signal()
add = Signal(object)
end = Signal()
status = Signal(object)
def __init__(self, ctx, parent):
QtCore.QThread.__init__(self, parent)
self.ctx = ctx
self._abort = False
self._stop = False
self._mutex = QtCore.QMutex()
self._condition = QtCore.QWaitCondition()
def run(self):
repo = dag.RepoReader(self.ctx)
repo.reset()
self.begin.emit()
commits = []
for c in repo:
self._mutex.lock()
if self._stop:
self._condition.wait(self._mutex)
self._mutex.unlock()
if self._abort:
repo.reset()
return
commits.append(c)
if len(commits) >= 512:
self.add.emit(commits)
commits = []
self.status.emit(repo.returncode == 0)
if commits:
self.add.emit(commits)
self.end.emit()
def start(self):
self._abort = False
self._stop = False
QtCore.QThread.start(self)
def pause(self):
self._mutex.lock()
self._stop = True
self._mutex.unlock()
def resume(self):
self._mutex.lock()
self._stop = False
self._mutex.unlock()
self._condition.wakeOne()
def stop(self):
self._abort = True
self.wait()
class Cache(object):
pass
class Edge(QtWidgets.QGraphicsItem):
item_type = QtWidgets.QGraphicsItem.UserType + 1
def __init__(self, source, dest):
QtWidgets.QGraphicsItem.__init__(self)
self.setAcceptedMouseButtons(Qt.NoButton)
self.source = source
self.dest = dest
self.commit = source.commit
self.setZValue(-2)
dest_pt = Commit.item_bbox.center()
self.source_pt = self.mapFromItem(self.source, dest_pt)
self.dest_pt = self.mapFromItem(self.dest, dest_pt)
self.line = QtCore.QLineF(self.source_pt, self.dest_pt)
width = self.dest_pt.x() - self.source_pt.x()
height = self.dest_pt.y() - self.source_pt.y()
rect = QtCore.QRectF(self.source_pt, QtCore.QSizeF(width, height))
self.bound = rect.normalized()
# Choose a new color for new branch edges
if self.source.x() < self.dest.x():
color = EdgeColor.cycle()
line = Qt.SolidLine
elif self.source.x() != self.dest.x():
color = EdgeColor.current()
line = Qt.SolidLine
else:
color = EdgeColor.current()
line = Qt.SolidLine
self.pen = QtGui.QPen(color, 4.0, line, Qt.SquareCap, Qt.RoundJoin)
# Qt overrides
def type(self):
return self.item_type
def boundingRect(self):
return self.bound
def paint(self, painter, option, widget):
arc_rect = 10
connector_length = 5
painter.setPen(self.pen)
path = QtGui.QPainterPath()
if self.source.x() == self.dest.x():
path.moveTo(self.source.x(), self.source.y())
path.lineTo(self.dest.x(), self.dest.y())
painter.drawPath(path)
else:
# Define points starting from source
point1 = QPointF(self.source.x(), self.source.y())
point2 = QPointF(point1.x(), point1.y() - connector_length)
point3 = QPointF(point2.x() + arc_rect, point2.y() - arc_rect)
# Define points starting from dest
point4 = QPointF(self.dest.x(), self.dest.y())
point5 = QPointF(point4.x(), point3.y() - arc_rect)
point6 = QPointF(point5.x() - arc_rect, point5.y() + arc_rect)
start_angle_arc1 = 180
span_angle_arc1 = 90
start_angle_arc2 = 90
span_angle_arc2 = -90
# If the dest is at the left of the source, then we
# need to reverse some values
if self.source.x() > self.dest.x():
point5 = QPointF(point4.x(), point4.y() + connector_length)
point6 = QPointF(point5.x() + arc_rect, point5.y() + arc_rect)
point3 = QPointF(self.source.x() - arc_rect, point6.y())
point2 = QPointF(self.source.x(), point3.y() + arc_rect)
span_angle_arc1 = 90
path.moveTo(point1)
path.lineTo(point2)
path.arcTo(QRectF(point2, point3),
start_angle_arc1, span_angle_arc1)
path.lineTo(point6)
path.arcTo(QRectF(point6, point5),
start_angle_arc2, span_angle_arc2)
path.lineTo(point4)
painter.drawPath(path)
class EdgeColor(object):
"""An edge color factory"""
current_color_index = 0
colors = [
QtGui.QColor(Qt.red),
QtGui.QColor(Qt.green),
QtGui.QColor(Qt.blue),
QtGui.QColor(Qt.black),
QtGui.QColor(Qt.darkRed),
QtGui.QColor(Qt.darkGreen),
QtGui.QColor(Qt.darkBlue),
QtGui.QColor(Qt.cyan),
QtGui.QColor(Qt.magenta),
# Orange; Qt.yellow is too low-contrast
qtutils.rgba(0xff, 0x66, 0x00),
QtGui.QColor(Qt.gray),
QtGui.QColor(Qt.darkCyan),
QtGui.QColor(Qt.darkMagenta),
QtGui.QColor(Qt.darkYellow),
QtGui.QColor(Qt.darkGray),
]
@classmethod
def cycle(cls):
cls.current_color_index += 1
cls.current_color_index %= len(cls.colors)
color = cls.colors[cls.current_color_index]
color.setAlpha(128)
return color
@classmethod
def current(cls):
return cls.colors[cls.current_color_index]
@classmethod
def reset(cls):
cls.current_color_index = 0
class Commit(QtWidgets.QGraphicsItem):
item_type = QtWidgets.QGraphicsItem.UserType + 2
commit_radius = 12.0
merge_radius = 18.0
item_shape = QtGui.QPainterPath()
item_shape.addRect(commit_radius/-2.0,
commit_radius/-2.0,
commit_radius, commit_radius)
item_bbox = item_shape.boundingRect()
inner_rect = QtGui.QPainterPath()
inner_rect.addRect(commit_radius/-2.0 + 2.0,
commit_radius/-2.0 + 2.0,
commit_radius - 4.0,
commit_radius - 4.0)
inner_rect = inner_rect.boundingRect()
commit_color = QtGui.QColor(Qt.white)
outline_color = commit_color.darker()
merge_color = QtGui.QColor(Qt.lightGray)
commit_selected_color = QtGui.QColor(Qt.green)
selected_outline_color = commit_selected_color.darker()
commit_pen = QtGui.QPen()
commit_pen.setWidth(1.0)
commit_pen.setColor(outline_color)
def __init__(self, commit,
notifier,
selectable=QtWidgets.QGraphicsItem.ItemIsSelectable,
cursor=Qt.PointingHandCursor,
xpos=commit_radius/2.0 + 1.0,
cached_commit_color=commit_color,
cached_merge_color=merge_color):
QtWidgets.QGraphicsItem.__init__(self)
self.commit = commit
self.notifier = notifier
self.setZValue(0)
self.setFlag(selectable)
self.setCursor(cursor)
self.setToolTip(commit.sha1[:7] + ': ' + commit.summary)
if commit.tags:
self.label = label = Label(commit)
label.setParentItem(self)
label.setPos(xpos, -self.commit_radius/2.0)
else:
self.label = None
if len(commit.parents) > 1:
self.brush = cached_merge_color
else:
self.brush = cached_commit_color
self.pressed = False
self.dragged = False
def blockSignals(self, blocked):
self.notifier.notification_enabled = not blocked
def itemChange(self, change, value):
if change == QtWidgets.QGraphicsItem.ItemSelectedHasChanged:
# Broadcast selection to other widgets
selected_items = self.scene().selectedItems()
commits = [item.commit for item in selected_items]
self.scene().parent().set_selecting(True)
self.notifier.notify_observers(diff.COMMITS_SELECTED, commits)
self.scene().parent().set_selecting(False)
# Cache the pen for use in paint()
if value:
self.brush = self.commit_selected_color
color = self.selected_outline_color
else:
if len(self.commit.parents) > 1:
self.brush = self.merge_color
else:
self.brush = self.commit_color
color = self.outline_color
commit_pen = QtGui.QPen()
commit_pen.setWidth(1.0)
commit_pen.setColor(color)
self.commit_pen = commit_pen
return QtWidgets.QGraphicsItem.itemChange(self, change, value)
def type(self):
return self.item_type
def boundingRect(self, rect=item_bbox):
return rect
def shape(self):
return self.item_shape
def paint(self, painter, option, widget,
inner=inner_rect,
cache=Cache):
# Do not draw outside the exposed rect
painter.setClipRect(option.exposedRect)
# Draw ellipse
painter.setPen(self.commit_pen)
painter.setBrush(self.brush)
painter.drawEllipse(inner)
def mousePressEvent(self, event):
QtWidgets.QGraphicsItem.mousePressEvent(self, event)
self.pressed = True
self.selected = self.isSelected()
def mouseMoveEvent(self, event):
if self.pressed:
self.dragged = True
QtWidgets.QGraphicsItem.mouseMoveEvent(self, event)
def mouseReleaseEvent(self, event):
QtWidgets.QGraphicsItem.mouseReleaseEvent(self, event)
if (not self.dragged and
self.selected and
event.button() == Qt.LeftButton):
return
self.pressed = False
self.dragged = False
class Label(QtWidgets.QGraphicsItem):
item_type = QtWidgets.QGraphicsItem.UserType + 3
width = 72
height = 18
item_shape = QtGui.QPainterPath()
item_shape.addRect(0, 0, width, height)
item_bbox = item_shape.boundingRect()
text_options = QtGui.QTextOption()
text_options.setAlignment(Qt.AlignCenter)
text_options.setAlignment(Qt.AlignVCenter)
def __init__(self, commit,
other_color=QtGui.QColor(Qt.white),
head_color=QtGui.QColor(Qt.green)):
QtWidgets.QGraphicsItem.__init__(self)
self.setZValue(-1)
# Starts with enough space for two tags. Any more and the commit
# needs to be taller to accommodate.
self.commit = commit
if 'HEAD' in commit.tags:
self.color = head_color
else:
self.color = other_color
self.color.setAlpha(180)
self.pen = QtGui.QPen()
self.pen.setColor(self.color.darker())
self.pen.setWidth(1.0)
def type(self):
return self.item_type
def boundingRect(self, rect=item_bbox):
return rect
def shape(self):
return self.item_shape
def paint(self, painter, option, widget,
text_opts=text_options,
black=Qt.black,
cache=Cache):
try:
font = cache.label_font
except AttributeError:
font = cache.label_font = QtWidgets.QApplication.font()
font.setPointSize(6)
# Draw tags
painter.setBrush(self.color)
painter.setPen(self.pen)
painter.setFont(font)
current_width = 0
for tag in self.commit.tags:
text_rect = painter.boundingRect(
QRectF(current_width, 0, 0, 0), Qt.TextSingleLine, tag)
box_rect = text_rect.adjusted(-1, -1, 1, 1)
painter.drawRoundedRect(box_rect, 2, 2)
painter.drawText(text_rect, Qt.TextSingleLine, tag)
current_width += text_rect.width() + 5
class GraphView(QtWidgets.QGraphicsView, ViewerMixin):
diff_commits = Signal(object, object)
x_min = 24
x_max = 0
y_min = 24
x_adjust = Commit.commit_radius*4/3
y_adjust = Commit.commit_radius*4/3
x_off = 18
y_off = 24
def __init__(self, notifier, parent):
QtWidgets.QGraphicsView.__init__(self, parent)
ViewerMixin.__init__(self)
highlight = self.palette().color(QtGui.QPalette.Highlight)
Commit.commit_selected_color = highlight
Commit.selected_outline_color = highlight.darker()
self.selection_list = []
self.menu_actions = None
self.notifier = notifier
self.commits = []
self.items = {}
self.saved_matrix = self.transform()
self.x_offsets = collections.defaultdict(lambda: self.x_min)
self.is_panning = False
self.pressed = False
self.selecting = False
self.last_mouse = [0, 0]
self.zoom = 2
self.setDragMode(self.RubberBandDrag)
scene = QtWidgets.QGraphicsScene(self)
scene.setItemIndexMethod(QtWidgets.QGraphicsScene.NoIndex)
self.setScene(scene)
self.setRenderHint(QtGui.QPainter.Antialiasing)
self.setViewportUpdateMode(self.BoundingRectViewportUpdate)
self.setCacheMode(QtWidgets.QGraphicsView.CacheBackground)
self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
self.setResizeAnchor(QtWidgets.QGraphicsView.NoAnchor)
self.setBackgroundBrush(QtGui.QColor(Qt.white))
qtutils.add_action(self, N_('Zoom In'), self.zoom_in,
hotkeys.ZOOM_IN, hotkeys.ZOOM_IN_SECONDARY)
qtutils.add_action(self, N_('Zoom Out'), self.zoom_out,
hotkeys.ZOOM_OUT)
qtutils.add_action(self, N_('Zoom to Fit'),
self.zoom_to_fit, hotkeys.FIT)
qtutils.add_action(self, N_('Select Parent'),
self.select_parent, hotkeys.MOVE_DOWN_TERTIARY)
qtutils.add_action(self, N_('Select Oldest Parent'),
self.select_oldest_parent, hotkeys.MOVE_DOWN)
qtutils.add_action(self, N_('Select Child'),
self.select_child, hotkeys.MOVE_UP_TERTIARY)
qtutils.add_action(self, N_('Select Newest Child'),
self.select_newest_child, hotkeys.MOVE_UP)
notifier.add_observer(diff.COMMITS_SELECTED, self.commits_selected)
def clear(self):
EdgeColor.reset()
self.scene().clear()
self.selection_list = []
self.items.clear()
self.x_offsets.clear()
self.x_max = 24
self.y_min = 24
self.commits = []
# ViewerMixin interface
def selected_items(self):
"""Return the currently selected items"""
return self.scene().selectedItems()
def zoom_in(self):
self.scale_view(1.5)
def zoom_out(self):
self.scale_view(1.0/1.5)
def commits_selected(self, commits):
if self.selecting:
return
self.select([commit.sha1 for commit in commits])
def select(self, sha1s):
"""Select the item for the SHA-1"""
self.scene().clearSelection()
for sha1 in sha1s:
try:
item = self.items[sha1]
except KeyError:
continue
item.blockSignals(True)
item.setSelected(True)
item.blockSignals(False)
item_rect = item.sceneTransform().mapRect(item.boundingRect())
self.ensureVisible(item_rect)
def get_item_by_generation(self, commits, criteria_fn):
"""Return the item for the commit matching criteria"""
if not commits:
return None
generation = None
for commit in commits:
if (generation is None or
criteria_fn(generation, commit.generation)):
sha1 = commit.sha1
generation = commit.generation
try:
return self.items[sha1]
except KeyError:
return None
def oldest_item(self, commits):
"""Return the item for the commit with the oldest generation number"""
return self.get_item_by_generation(commits, lambda a, b: a > b)
def newest_item(self, commits):
"""Return the item for the commit with the newest generation number"""
return self.get_item_by_generation(commits, lambda a, b: a < b)
def create_patch(self):
items = self.selected_items()
if not items:
return
selected_commits = self.sort_by_generation([n.commit for n in items])
sha1s = [c.sha1 for c in selected_commits]
all_sha1s = [c.sha1 for c in self.commits]
cmds.do(cmds.FormatPatch, sha1s, all_sha1s)
def select_parent(self):
"""Select the parent with the newest generation number"""
selected_item = self.selected_item()
if selected_item is None:
return
parent_item = self.newest_item(selected_item.commit.parents)
if parent_item is None:
return
selected_item.setSelected(False)
parent_item.setSelected(True)
self.ensureVisible(
parent_item.mapRectToScene(parent_item.boundingRect()))
def select_oldest_parent(self):
"""Select the parent with the oldest generation number"""
selected_item = self.selected_item()
if selected_item is None:
return
parent_item = self.oldest_item(selected_item.commit.parents)
if parent_item is None:
return
selected_item.setSelected(False)
parent_item.setSelected(True)
scene_rect = parent_item.mapRectToScene(parent_item.boundingRect())
self.ensureVisible(scene_rect)
def select_child(self):
"""Select the child with the oldest generation number"""
selected_item = self.selected_item()
if selected_item is None:
return
child_item = self.oldest_item(selected_item.commit.children)
if child_item is None:
return
selected_item.setSelected(False)
child_item.setSelected(True)
scene_rect = child_item.mapRectToScene(child_item.boundingRect())
self.ensureVisible(scene_rect)
def select_newest_child(self):
"""Select the Nth child with the newest generation number (N > 1)"""
selected_item = self.selected_item()
if selected_item is None:
return
if len(selected_item.commit.children) > 1:
children = selected_item.commit.children[1:]
else:
children = selected_item.commit.children
child_item = self.newest_item(children)
if child_item is None:
return
selected_item.setSelected(False)
child_item.setSelected(True)
scene_rect = child_item.mapRectToScene(child_item.boundingRect())
self.ensureVisible(scene_rect)
def set_initial_view(self):
self_commits = self.commits
self_items = self.items
items = self.selected_items()
if not items:
commits = self_commits[-8:]
items = [self_items[c.sha1] for c in commits]
self.fit_view_to_items(items)
def zoom_to_fit(self):
"""Fit selected items into the viewport"""
items = self.selected_items()
self.fit_view_to_items(items)
def fit_view_to_items(self, items):
if not items:
rect = self.scene().itemsBoundingRect()
else:
x_min = y_min = maxsize
x_max = y_max = -maxsize
for item in items:
pos = item.pos()
item_rect = item.boundingRect()
x_off = item_rect.width() * 5
y_off = item_rect.height() * 10
x_min = min(x_min, pos.x())
y_min = min(y_min, pos.y()-y_off)
x_max = max(x_max, pos.x()+x_off)
y_max = max(y_max, pos.y())
rect = QtCore.QRectF(x_min, y_min, x_max-x_min, y_max-y_min)
x_adjust = GraphView.x_adjust
y_adjust = GraphView.y_adjust
rect.setX(rect.x() - x_adjust)
rect.setY(rect.y() - y_adjust)
rect.setHeight(rect.height() + y_adjust*2)
rect.setWidth(rect.width() + x_adjust*2)
self.fitInView(rect, Qt.KeepAspectRatio)
self.scene().invalidate()
def save_selection(self, event):
if event.button() != Qt.LeftButton:
return
elif Qt.ShiftModifier != event.modifiers():
return
self.selection_list = self.selected_items()
def restore_selection(self, event):
if Qt.ShiftModifier != event.modifiers():
return
for item in self.selection_list:
item.setSelected(True)
def handle_event(self, event_handler, event):
self.save_selection(event)
event_handler(self, event)
self.restore_selection(event)
self.update()
def set_selecting(self, selecting):
self.selecting = selecting
def pan(self, event):
pos = event.pos()
dx = pos.x() - self.mouse_start[0]
dy = pos.y() - self.mouse_start[1]
if dx == 0 and dy == 0:
return
rect = QtCore.QRect(0, 0, abs(dx), abs(dy))
delta = self.mapToScene(rect).boundingRect()
tx = delta.width()
if dx < 0.0:
tx = -tx
ty = delta.height()
if dy < 0.0:
ty = -ty
matrix = self.transform()
matrix.reset()
matrix *= self.saved_matrix
matrix.translate(tx, ty)
self.setTransformationAnchor(QtWidgets.QGraphicsView.NoAnchor)
self.setTransform(matrix)
def wheel_zoom(self, event):
"""Handle mouse wheel zooming."""
delta = qtcompat.wheel_delta(event)
zoom = math.pow(2.0, delta/512.0)
factor = (self.transform()
.scale(zoom, zoom)
.mapRect(QtCore.QRectF(0.0, 0.0, 1.0, 1.0))
.width())
if factor < 0.014 or factor > 42.0:
return
self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
self.zoom = zoom
self.scale(zoom, zoom)
def wheel_pan(self, event):
"""Handle mouse wheel panning."""
unit = QtCore.QRectF(0.0, 0.0, 1.0, 1.0)
factor = 1.0 / self.transform().mapRect(unit).width()
tx, ty = qtcompat.wheel_translation(event)
matrix = self.transform().translate(tx * factor, ty * factor)
self.setTransformationAnchor(QtWidgets.QGraphicsView.NoAnchor)
self.setTransform(matrix)
def scale_view(self, scale):
factor = (self.transform()
.scale(scale, scale)
.mapRect(QtCore.QRectF(0, 0, 1, 1))
.width())
if factor < 0.07 or factor > 100.0:
return
self.zoom = scale
adjust_scrollbars = True
scrollbar = self.verticalScrollBar()
if scrollbar:
value = scrollbar.value()
min_ = scrollbar.minimum()
max_ = scrollbar.maximum()
range_ = max_ - min_
distance = value - min_
nonzero_range = range_ > 0.1
if nonzero_range:
scrolloffset = distance/range_
else:
adjust_scrollbars = False
self.setTransformationAnchor(QtWidgets.QGraphicsView.NoAnchor)
self.scale(scale, scale)
scrollbar = self.verticalScrollBar()
if scrollbar and adjust_scrollbars:
min_ = scrollbar.minimum()
max_ = scrollbar.maximum()
range_ = max_ - min_
value = min_ + int(float(range_) * scrolloffset)
scrollbar.setValue(value)
def add_commits(self, commits):
"""Traverse commits and add them to the view."""
self.commits.extend(commits)
scene = self.scene()
for commit in commits:
item = Commit(commit, self.notifier)
self.items[commit.sha1] = item
for ref in commit.tags:
self.items[ref] = item
scene.addItem(item)
self.layout_commits(commits)
self.link(commits)
def link(self, commits):
"""Create edges linking commits with their parents"""
scene = self.scene()
for commit in commits:
try:
commit_item = self.items[commit.sha1]
except KeyError:
# TODO - Handle truncated history viewing
continue
for parent in reversed(commit.parents):
try:
parent_item = self.items[parent.sha1]
except KeyError:
# TODO - Handle truncated history viewing
continue
edge = Edge(parent_item, commit_item)
scene.addItem(edge)
def layout_commits(self, nodes):
positions = self.position_nodes(nodes)
for sha1, (x, y) in positions.items():
item = self.items[sha1]
item.setPos(x, y)
def position_nodes(self, nodes):
positions = {}
x_max = self.x_max
y_min = self.y_min
x_off = self.x_off
y_off = self.y_off
x_offsets = self.x_offsets
for node in nodes:
generation = node.generation
sha1 = node.sha1
if node.is_fork():
# This is a fan-out so sweep over child generations and
# shift them to the right to avoid overlapping edges
child_gens = [c.generation for c in node.children]
maxgen = max(child_gens)
for g in range(generation + 1, maxgen):
x_offsets[g] += x_off
if len(node.parents) == 1:
# Align nodes relative to their parents
parent_gen = node.parents[0].generation
parent_off = x_offsets[parent_gen]
x_offsets[generation] = max(parent_off-x_off,
x_offsets[generation])
cur_xoff = x_offsets[generation]
next_xoff = cur_xoff
next_xoff += x_off
x_offsets[generation] = next_xoff
x_pos = cur_xoff
y_pos = -generation * y_off
y_pos = min(y_pos, y_min - y_off)
# y_pos = y_off
positions[sha1] = (x_pos, y_pos)
x_max = max(x_max, x_pos)
y_min = y_pos
self.x_max = x_max
self.y_min = y_min
return positions
def update_scene_rect(self):
y_min = self.y_min
x_max = self.x_max
self.scene().setSceneRect(-GraphView.x_adjust,
y_min-GraphView.y_adjust,
x_max + GraphView.x_adjust,
abs(y_min) + GraphView.y_adjust)
def sort_by_generation(self, commits):
if len(commits) < 2:
return commits
commits.sort(key=lambda x: x.generation)
return commits
# Qt overrides
def contextMenuEvent(self, event):
self.context_menu_event(event)
def mousePressEvent(self, event):
if event.button() == Qt.MidButton:
pos = event.pos()
self.mouse_start = [pos.x(), pos.y()]
self.saved_matrix = self.transform()
self.is_panning = True
return
if event.button() == Qt.RightButton:
event.ignore()
return
if event.button() == Qt.LeftButton:
self.pressed = True
self.handle_event(QtWidgets.QGraphicsView.mousePressEvent, event)
def mouseMoveEvent(self, event):
pos = self.mapToScene(event.pos())
if self.is_panning:
self.pan(event)
return
self.last_mouse[0] = pos.x()
self.last_mouse[1] = pos.y()
self.handle_event(QtWidgets.QGraphicsView.mouseMoveEvent, event)
if self.pressed:
self.viewport().repaint()
def mouseReleaseEvent(self, event):
self.pressed = False
if event.button() == Qt.MidButton:
self.is_panning = False
return
self.handle_event(QtWidgets.QGraphicsView.mouseReleaseEvent, event)
self.selection_list = []
self.viewport().repaint()
def wheelEvent(self, event):
"""Handle Qt mouse wheel events."""
if event.modifiers() & Qt.ControlModifier:
self.wheel_zoom(event)
else:
self.wheel_pan(event)
# Glossary
# ========
# oid -- Git objects IDs (i.e. SHA-1 IDs)
# ref -- Git references that resolve to a commit-ish (HEAD, branches, tags)
|
gpl-2.0
|
webi7/buscador
|
wp-content/themes/WP/directory/taxonomy-ait-dir-item-category.php
|
2736
|
<?php
$term = $GLOBALS['wp_query']->queried_object;
$subcategories = get_terms( 'ait-dir-item-category', array('parent' => intval($term->term_id), 'hide_empty' => false) );
$posts = WpLatte::createPostEntity($GLOBALS['wp_query']->posts);
$items = get_posts( array(
'numberposts' => -1,
'post_type' => 'ait-dir-item',
'tax_query' => array(array(
'taxonomy' => 'ait-dir-item-category',
'field' => 'id',
'terms' => intval($term->term_id),
'include_children' => true
))
));
$term->icon = getCategoryMeta("icon",intval($term->term_id));
$term->marker = getCategoryMeta("marker",intval($term->term_id));
// add subcategory links
foreach ($subcategories as $category) {
$category->link = get_term_link(intval($category->term_id), 'ait-dir-item-category');
$category->icon = getCategoryMeta("icon",intval($category->term_id));
$category->excerpt = getCategoryMeta("excerpt", intval($category->term_id));
}
// add items details
foreach ($items as $item) {
$item->link = get_permalink($item->ID);
$image = wp_get_attachment_image_src( get_post_thumbnail_id($item->ID) );
if($image !== false){
$item->thumbnailDir = $image[0];
} else {
$item->thumbnailDir = $aitThemeOptions->directory->defaultItemImage;
}
$item->marker = $term->marker;
$item->optionsDir = get_post_meta($item->ID, '_ait-dir-item', true);
$item->packageClass = getItemPackageClass($item->post_author);
$item->rating = aitCalculateMeanForPost($item->ID);
}
// add posts details
foreach ($posts as $item) {
$item->link = get_permalink($item->id);
$image = wp_get_attachment_image_src( get_post_thumbnail_id($item->id) );
if($image !== false){
$item->thumbnailDir = $image[0];
} else {
$item->thumbnailDir = $aitThemeOptions->directory->defaultItemImage;
}
$item->optionsDir = get_post_meta($item->id, '_ait-dir-item', true);
//$item->excerptDir = aitGetPostExcerpt($item->excerpt,$item->content);
$item->packageClass = getItemPackageClass($item->author->id);
$item->rating = aitCalculateMeanForPost($item->id);
}
// breadcrumbs
$ancestorsIDs = array_reverse(get_ancestors(intval($term->term_id), 'ait-dir-item-category'));
$ancestors = array();
foreach ($ancestorsIDs as $anc) {
$cat = get_term($anc, 'ait-dir-item-category');
$cat->link = get_term_link($anc, 'ait-dir-item-category');
$ancestors[] = $cat;
}
$latteParams['ancestors'] = $ancestors;
$latteParams['term'] = $term;
$latteParams['subcategories'] = $subcategories;
$latteParams['items'] = $items;
$latteParams['posts'] = $posts;
$latteParams['isDirTaxonomy'] = true;
$latteParams['sidebarType'] = 'item';
WPLatte::createTemplate(basename(__FILE__, '.php'), $latteParams)->render();
|
gpl-2.0
|
hsnr-gamera/gamera
|
gamera/knn_editing.py
|
12179
|
#
# various editing techniques to improve kNN Classifier performance
# Copyright (C) 2007, 2008 Colin Baumgarten
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program 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 Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from random import randint
from gamera.args import Args, Int, Check
from gamera.knn import kNNInteractive
from gamera.util import ProgressFactory
def _randomSetElement(set):
"""Retrieve a random element from the given set
*set*
The set from which to select a random element"""
randPos = randint(0, len(set) - 1);
for pos, elem in enumerate(set):
if pos == randPos:
return elem
def _copyClassifier(original, k = 0):
"""Copy a given kNNClassifer by constructing a new one with identical
parameters.
*original*
The classifier to be copied
*k*
If the copy shall have another k-value as the original, set k accordingly.
k = 0 means, that the original's k-value will be used"""
if k == 0:
k = original.num_k
return kNNInteractive(
list(original.get_glyphs()), original.features,
original._perform_splits,
k)
def _getMainId(classificationResult):
"""Classification results returned from a kNN Classifier are in a list
containing '(confidence, className)' tuples. So to determine the 'main class',
the classname with the highest confidence has to be returned.
"""
# classificationResult is a tuple of the form
# ([idname1, idname2, ...], confidences_for_idname1)
return classificationResult[0][0][1]
class AlgoRegistry(object):
"""Registry containing a list of all available editing algorithms. Besides
the callable itself, the registry also stores its docstring, a displayname and
type-information about any additionally required arguments. This information
will be used by the gui to show a dialog to execute any of the available
algorithms on a classifier.
An editing algorithm is any callable object, that takes at least one parameter
- a *gamera.knn.kNNInteractive* classifier - and returns a new edited
*kNNInteractive* classifier.
To add your own algorithm, use one of the *register()* methods or alternatively,
let your callable inherit from *EditingAlgorithm* to register your algorithm,"""
algorithms = []
def registerData(algoData):
"""Register a new editing Algorithm using metadata from an
*AlgoData* object"""
AlgoRegistry.algorithms.append(algoData)
registerData = staticmethod(registerData)
def register(name, callable, args = Args(), doc = ""):
"""Register a new editing Algorithm: The parameters are the same as in
*AlgoData.__init__*, so see its doc for an explanation of the parameters."""
AlgoRegistry.registerData(AlgoData(name, callable, args, doc))
register = staticmethod(register)
class AlgoData(object):
"""Class holding all metadata about an editing algorithm, that is required by
*AlgoRegistry*
*name*
Name of the algorithm
*callable*
The callable object implementing the algorithm. Its first parameter has to
be a *kNNInteractive* Classifier and it has to return a new *kNNInteractive*
classifier. If the algorithm requires any additional parameters, they have
to be specified in the *args* parameter
*args*
A *gamera.args.Args* object specifying any additional parameters required by
the algorithm
*doc*
A docstring in reStructured Text format, describing the algorithm and its
parameters"""
def __init__(self, name, callable, args = Args(), doc = ""):
self.name = name
self.callable = callable
self.args = args
self.doc = doc
class EditingAlgorithm(object):
"""Convenience class to automatically register editing algorithms with the
*AlgoRegistry*. If you implement your algorithm as a callable class, you can
just inherit from this class to let it automatically be registered. Just add
two properties to the class:
*name*
The name of your algorithm
*args*
Type info about any additional required arguments (a *gamera.args.Args* object)
"""
def __init__(self):
AlgoRegistry.register(self.name, self, self.args, self.__doc__)
class EditMnn(EditingAlgorithm):
"""**edit_mnn** (kNNInteractive *classifier*, int *k* = 0, bool *protectRare*, int *rareThreshold*)
Wilson's *Modified Nearest Neighbour* (MNN, aka *Leave-one-out-editing*).
The algorithm removes 'bad' glyphs from the classifier, i.e. glyphs that
are outliers from their class in featurespace, usually because they have been
manually misclassified or are not representative for their class
*classifier*
The classifier from which to create an edited copy
*internalK*
The k value used internally by the editing algorithm. If 0 is given for
this parameter, the original classifier's k is used (recommended).
*protect rare classes*
The algorithm tends to completely delete the items of rare classes,
removing this whole class from the classifier. If this is not
desired these rare classes can be explicitly protected from deletion.
Note that enabling this option causes additional computing effort
*rare class threshold*
In case *protect rare classes* is enabled, classes with less than this
number of elements are considered to be rare
Reference: D. Wilson: 'Asymptotic Properties of NN Rules Using Edited Data'.
*IEEE Transactions on Systems, Man, and Cybernetics*, 2(3):408-421, 1972
"""
name = "Wilson's Modified Nearest Neighbour (MNN)"
args = Args([Int("Internal k", default = 0),
Check("Protect rare classes", default = True),
Int("Rare class threshold", default = 3)])
def __call__(self, classifier, k = 0, protectRare = True,
rareThreshold = 3):
editedClassifier = _copyClassifier(classifier, k)
toBeRemoved = set()
progress = ProgressFactory("Generating edited MNN classifier...",
len(classifier.get_glyphs()))
# classify each glyph with its leave-one-out classifier
for i, glyph in enumerate(classifier.get_glyphs()):
editedClassifier.get_glyphs().remove(glyph)
detectedClass = _getMainId(\
editedClassifier.guess_glyph_automatic(glyph))
# check if recognized class complies with the true class
if glyph.get_main_id() != detectedClass:
toBeRemoved.add(glyph)
editedClassifier.get_glyphs().add(glyph)
progress.step()
rareClasses = self._getRareClasses(classifier.get_glyphs(),
protectRare, rareThreshold)
# remove 'bad' glyphs, if they are not in a rare class
for glyph in toBeRemoved:
if glyph.get_main_id() in rareClasses:
continue
editedClassifier.get_glyphs().remove(glyph)
progress.kill()
return editedClassifier
def _getRareClasses(self, glyphs, protectRare, rareThreshold):
"""Produces a set containing the names of all rare classes"""
result = set()
if not protectRare:
return result
# histogram of classNames
histo = {}
for g in glyphs:
count = histo.get(g.get_main_id(), 0)
histo[g.get_main_id()] = count + 1
for className in histo:
if histo[className] < rareThreshold:
result.add(className)
return result
edit_mnn = EditMnn()
class EditCnn(EditingAlgorithm):
"""**edit_cnn** (kNNInteractive *classifier*, int *k* = 0, bool *randomize*)
Hart's *Condensed Nearest Neighbour (CNN)* editing.
This alorithm is specialized in removing superfluous glyphs - glyphs that do not
influence the recognition rate - from the classifier to improve its
classification speed. Typically glyphs far from the classifiers decision
boundaries are removed.
*classifier*
The classifier from which to create an edited copy
*internalK*
The k value used internally by the editing algorithm. 0 means, use the
same value as the given classifier (recommended)
*randomize*
Because the processing order of the glyphs in the classifier impacts the
result of this algorithm, the order will be randomized. If reproducible
results are required, turn this option off.
Reference: P.E. Hart: 'The Condensed Nearest Neighbor rule'. *IEEE Transactions on Information Theory*, 14(3):515-516, 1968
"""
name = "Hart's Condensed Nearest Neighbour (CNN)"
args = Args([Int("Internal k", default=0),
Check("Randomize", default = True)])
def __call__(self, classifier, k = 0, randomize = True):
# special case of empty classifier
if (not classifier.get_glyphs()):
return _copyClassifier(classifier)
if k == 0:
k = classifier.num_k
progress = ProgressFactory("Generating edited CNN classifier...",
len(classifier.get_glyphs()))
# initialize Store (a) with a single element
if randomize:
elem = _randomSetElement(classifier.get_glyphs())
else:
elem = classifier.get_glyphs().__iter__().next()
aGlyphs = [elem]
a = kNNInteractive(aGlyphs, classifier.features,
classifier._perform_splits, k)
progress.step()
# initialize Grabbag (b) with all other
b = classifier.get_glyphs().copy()
b.remove(aGlyphs[0]);
# Classify each glyph in b with a as the classifier
# If glyph is misclassified, add it to a, repeat until no elements are
# added to a
changed = True
while changed == True:
changed = False
# copy needed because iteration through dict is not possible while
# deleting items from it
copyOfB = b.copy()
for glyph in copyOfB:
if glyph.get_main_id() != _getMainId(a.guess_glyph_automatic(glyph)):
b.remove(glyph)
a.get_glyphs().add(glyph)
progress.step()
changed = True
progress.kill()
a.num_k = 1
return a
edit_cnn = EditCnn()
class EditMnnCnn(EditingAlgorithm):
"""**edit_mnn_cnn** (kNNInteractive *classifier*, int *k* = 0, bool *protectRare*, int *rareThreshold*, bool *randomize*)
Combined execution of Wilson's Modified Nearest Neighbour and Hart's
Condensed Nearest Neighbour. Combining the algorithms in this order is
recommended, because first bad samples are removed to improve the classifiers
accuracy, and then the remaining samples are condensed to speed up the classifier
For documentation of the parameters see the independent algorithms"""
name = "MNN, then CNN"
args = Args([Int("Internal k", default = 0),
Check("Protect rare classes", default = True),
Int("Rare class threshold", default = 3),
Check("Randomize", default = True)])
def __call__(self, classifier, k = 0, protectRare = True,
rareThreshold = 3, randomize = True):
return edit_cnn(edit_mnn(classifier, k, protectRare, rareThreshold),
randomize)
edit_mnn_cnn = EditMnnCnn()
|
gpl-2.0
|
eigentor/drupal-8-test
|
core/modules/settings_tray/tests/src/FunctionalJavascript/SettingsTrayBlockFormTest.php
|
25478
|
<?php
namespace Drupal\Tests\settings_tray\FunctionalJavascript;
use Drupal\block\Entity\Block;
use Drupal\block_content\Entity\BlockContent;
use Drupal\block_content\Entity\BlockContentType;
use Drupal\menu_link_content\Entity\MenuLinkContent;
use Drupal\settings_tray_test\Plugin\Block\SettingsTrayFormAnnotationIsClassBlock;
use Drupal\settings_tray_test\Plugin\Block\SettingsTrayFormAnnotationNoneBlock;
use Drupal\system\Entity\Menu;
use Drupal\Tests\contextual\FunctionalJavascript\ContextualLinkClickTrait;
use Drupal\user\Entity\Role;
use Drupal\user\RoleInterface;
/**
* Testing opening and saving block forms in the off-canvas dialog.
*
* @group settings_tray
*/
class SettingsTrayBlockFormTest extends SettingsTrayJavascriptTestBase {
use ContextualLinkClickTrait;
const TOOLBAR_EDIT_LINK_SELECTOR = '#toolbar-bar div.contextual-toolbar-tab button';
const LABEL_INPUT_SELECTOR = 'input[data-drupal-selector="edit-settings-label"]';
/**
* {@inheritdoc}
*/
public static $modules = [
'node',
'block',
'system',
'breakpoint',
'toolbar',
'contextual',
'settings_tray',
'search',
'block_content',
'settings_tray_test',
// Add test module to override CSS pointer-events properties because they
// cause test failures.
'settings_tray_test_css',
'settings_tray_test',
'menu_link_content',
'menu_ui',
];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->createBlockContentType('basic', TRUE);
$block_content = $this->createBlockContent('Custom Block', 'basic', TRUE);
$user = $this->createUser([
'administer blocks',
'access contextual links',
'access toolbar',
'administer nodes',
'search content',
]);
$this->drupalLogin($user);
$this->placeBlock('block_content:' . $block_content->uuid(), ['id' => 'custom']);
}
/**
* Tests opening off-canvas dialog by click blocks and elements in the blocks.
*
* @dataProvider providerTestBlocks
*/
public function testBlocks($theme, $block_plugin, $new_page_text, $element_selector, $label_selector, $button_text, $toolbar_item, $permissions) {
if ($permissions) {
$this->grantPermissions(Role::load(Role::AUTHENTICATED_ID), $permissions);
}
$web_assert = $this->assertSession();
$page = $this->getSession()->getPage();
$this->enableTheme($theme);
$block = $this->placeBlock($block_plugin);
$block_selector = str_replace('_', '-', $this->getBlockSelector($block));
$block_id = $block->id();
$this->drupalGet('user');
$link = $page->find('css', "$block_selector .contextual-links li a");
$this->assertEquals('Quick edit', $link->getText(), "'Quick edit' is the first contextual link for the block.");
$this->assertContains("/admin/structure/block/manage/$block_id/off-canvas?destination=user/2", $link->getAttribute('href'));
if (isset($toolbar_item)) {
// Check that you can open a toolbar tray and it will be closed after
// entering edit mode.
if ($element = $page->find('css', "#toolbar-administration a.is-active")) {
// If a tray was open from page load close it.
$element->click();
$this->waitForNoElement("#toolbar-administration a.is-active");
}
$page->find('css', $toolbar_item)->click();
$this->assertElementVisibleAfterWait('css', "{$toolbar_item}.is-active");
}
$this->enableEditMode();
if (isset($toolbar_item)) {
$this->waitForNoElement("{$toolbar_item}.is-active");
}
$this->openBlockForm($block_selector);
switch ($block_plugin) {
case 'system_powered_by_block':
// Confirm "Display Title" is not checked.
$web_assert->checkboxNotChecked('settings[label_display]');
// Confirm Title is not visible.
$this->assertEquals($this->isLabelInputVisible(), FALSE, 'Label is not visible');
$page->checkField('settings[label_display]');
$this->assertEquals($this->isLabelInputVisible(), TRUE, 'Label is visible');
// Fill out form, save the form.
$page->fillField('settings[label]', $new_page_text);
break;
case 'system_branding_block':
// Fill out form, save the form.
$page->fillField('settings[site_information][site_name]', $new_page_text);
break;
case 'settings_tray_test_class':
$web_assert->elementExists('css', '[data-drupal-selector="edit-settings-some-setting"]');
break;
}
if (isset($new_page_text)) {
$page->pressButton($button_text);
// Make sure the changes are present.
$new_page_text_locator = "$block_selector $label_selector:contains($new_page_text)";
$this->assertElementVisibleAfterWait('css', $new_page_text_locator);
// The page is loaded with the new change but make sure page is
// completely loaded.
$this->assertPageLoadComplete();
}
$this->openBlockForm($block_selector);
$this->disableEditMode();
// Canvas should close when editing module is closed.
$this->waitForOffCanvasToClose();
$this->enableEditMode();
// Open block form by clicking a element inside the block.
// This confirms that default action for links and form elements is
// suppressed.
$this->openBlockForm("$block_selector {$element_selector}", $block_selector);
$web_assert->elementTextContains('css', '.contextual-toolbar-tab button', 'Editing');
$web_assert->elementAttributeContains('css', '.dialog-off-canvas__main-canvas', 'class', 'js-settings-tray-edit-mode');
// Simulate press the Escape key.
$this->getSession()->executeScript('jQuery("body").trigger(jQuery.Event("keyup", { keyCode: 27 }));');
$this->waitForOffCanvasToClose();
$this->getSession()->wait(100);
$this->assertEditModeDisabled();
$web_assert->elementTextContains('css', '#drupal-live-announce', 'Exited edit mode.');
$web_assert->elementTextNotContains('css', '.contextual-toolbar-tab button', 'Editing');
$web_assert->elementAttributeNotContains('css', '.dialog-off-canvas__main-canvas', 'class', 'js-settings-tray-edit-mode');
}
/**
* Dataprovider for testBlocks().
*/
public function providerTestBlocks() {
$blocks = [];
foreach ($this->getTestThemes() as $theme) {
$blocks += [
"$theme: block-powered" => [
'theme' => $theme,
'block_plugin' => 'system_powered_by_block',
'new_page_text' => 'Can you imagine anyone showing the label on this block',
'element_selector' => 'span a',
'label_selector' => 'h2',
'button_text' => 'Save Powered by Drupal',
'toolbar_item' => '#toolbar-item-user',
NULL,
],
"$theme: block-branding" => [
'theme' => $theme,
'block_plugin' => 'system_branding_block',
'new_page_text' => 'The site that will live a very short life',
'element_selector' => "a[rel='home']:last-child",
'label_selector' => "a[rel='home']:last-child",
'button_text' => 'Save Site branding',
'toolbar_item' => '#toolbar-item-administration',
['administer site configuration'],
],
"$theme: block-search" => [
'theme' => $theme,
'block_plugin' => 'search_form_block',
'new_page_text' => NULL,
'element_selector' => '#edit-submit',
'label_selector' => 'h2',
'button_text' => 'Save Search form',
'toolbar_item' => NULL,
NULL,
],
// This is the functional JS test coverage accompanying
// \Drupal\Tests\settings_tray\Functional\SettingsTrayTest::testPossibleAnnotations().
"$theme: " . SettingsTrayFormAnnotationIsClassBlock::class => [
'theme' => $theme,
'block_plugin' => 'settings_tray_test_class',
'new_page_text' => NULL,
'element_selector' => 'span',
'label_selector' => NULL,
'button_text' => NULL,
'toolbar_item' => NULL,
NULL,
],
// This is the functional JS test coverage accompanying
// \Drupal\Tests\settings_tray\Functional\SettingsTrayTest::testPossibleAnnotations().
"$theme: " . SettingsTrayFormAnnotationNoneBlock::class => [
'theme' => $theme,
'block_plugin' => 'settings_tray_test_none',
'new_page_text' => NULL,
'element_selector' => 'span',
'label_selector' => NULL,
'button_text' => NULL,
'toolbar_item' => NULL,
NULL,
],
];
}
return $blocks;
}
/**
* Enables edit mode by pressing edit button in the toolbar.
*/
protected function enableEditMode() {
$this->pressToolbarEditButton();
$this->assertEditModeEnabled();
}
/**
* Disables edit mode by pressing edit button in the toolbar.
*/
protected function disableEditMode() {
$this->assertSession()->assertWaitOnAjaxRequest();
$this->pressToolbarEditButton();
$this->assertEditModeDisabled();
}
/**
* Asserts that Off-Canvas block form is valid.
*/
protected function assertOffCanvasBlockFormIsValid() {
$web_assert = $this->assertSession();
// Confirm that Block title display label has been changed.
$web_assert->elementTextContains('css', '.form-item-settings-label-display label', 'Display block title');
// Confirm Block title label is shown if checkbox is checked.
if ($this->getSession()->getPage()->find('css', 'input[name="settings[label_display]"]')->isChecked()) {
$this->assertEquals($this->isLabelInputVisible(), TRUE, 'Label is visible');
$web_assert->elementTextContains('css', '.form-item-settings-label label', 'Block title');
}
else {
$this->assertEquals($this->isLabelInputVisible(), FALSE, 'Label is not visible');
}
// Check that common block form elements exist.
$web_assert->elementExists('css', static::LABEL_INPUT_SELECTOR);
$web_assert->elementExists('css', 'input[data-drupal-selector="edit-settings-label-display"]');
// Check that advanced block form elements do not exist.
$web_assert->elementNotExists('css', 'input[data-drupal-selector="edit-visibility-request-path-pages"]');
$web_assert->elementNotExists('css', 'select[data-drupal-selector="edit-region"]');
}
/**
* Open block form by clicking the element found with a css selector.
*
* @param string $block_selector
* A css selector selects the block or an element within it.
* @param string $contextual_link_container
* The element that contains the contextual links. If none provide the
* $block_selector will be used.
*/
protected function openBlockForm($block_selector, $contextual_link_container = '') {
if (!$contextual_link_container) {
$contextual_link_container = $block_selector;
}
// Ensure that contextual link element is present because this is required
// to open the off-canvas dialog in edit mode.
$contextual_link = $this->assertSession()->waitForElement('css', "$contextual_link_container .contextual-links a");
$this->assertNotEmpty($contextual_link);
// When page first loads Edit Mode is not triggered until first contextual
// link is added.
$this->assertElementVisibleAfterWait('css', '.dialog-off-canvas__main-canvas.js-settings-tray-edit-mode');
// Ensure that all other Ajax activity is completed.
$this->assertSession()->assertWaitOnAjaxRequest();
$this->click($block_selector);
$this->waitForOffCanvasToOpen();
$this->assertOffCanvasBlockFormIsValid();
}
/**
* Tests QuickEdit links behavior.
*/
public function testQuickEditLinks() {
$this->container->get('module_installer')->install(['quickedit']);
$this->grantPermissions(Role::load(RoleInterface::AUTHENTICATED_ID), ['access in-place editing']);
$quick_edit_selector = '#quickedit-entity-toolbar';
$node_selector = '[data-quickedit-entity-id="node/1"]';
$body_selector = '[data-quickedit-field-id="node/1/body/en/full"]';
$web_assert = $this->assertSession();
// Create a Content type and two test nodes.
$this->createContentType(['type' => 'page']);
$auth_role = Role::load(Role::AUTHENTICATED_ID);
$this->grantPermissions($auth_role, [
'edit any page content',
'access content',
]);
$node = $this->createNode(
[
'title' => 'Page One',
'type' => 'page',
'body' => [
[
'value' => 'Regular NODE body for the test.',
'format' => 'plain_text',
],
],
]
);
$page = $this->getSession()->getPage();
$block_plugin = 'system_powered_by_block';
foreach ($this->getTestThemes() as $theme) {
$this->enableTheme($theme);
$block = $this->placeBlock($block_plugin);
$block_selector = str_replace('_', '-', $this->getBlockSelector($block));
// Load the same page twice.
foreach ([1, 2] as $page_load_times) {
$this->drupalGet('node/' . $node->id());
// The 2nd page load we should already be in edit mode.
if ($page_load_times == 1) {
$this->enableEditMode();
}
// In Edit mode clicking field should open QuickEdit toolbar.
$page->find('css', $body_selector)->click();
$this->assertElementVisibleAfterWait('css', $quick_edit_selector);
$this->disableEditMode();
// Exiting Edit mode should close QuickEdit toolbar.
$web_assert->elementNotExists('css', $quick_edit_selector);
// When not in Edit mode QuickEdit toolbar should not open.
$page->find('css', $body_selector)->click();
$web_assert->elementNotExists('css', $quick_edit_selector);
$this->enableEditMode();
$this->openBlockForm($block_selector);
$page->find('css', $body_selector)->click();
$this->assertElementVisibleAfterWait('css', $quick_edit_selector);
// Off-canvas dialog should be closed when opening QuickEdit toolbar.
$this->waitForOffCanvasToClose();
$this->openBlockForm($block_selector);
// QuickEdit toolbar should be closed when opening Off-canvas dialog.
$web_assert->elementNotExists('css', $quick_edit_selector);
}
// Check using contextual links to invoke QuickEdit and open the tray.
$this->drupalGet('node/' . $node->id());
$web_assert->assertWaitOnAjaxRequest();
$this->disableEditMode();
// Open QuickEdit toolbar before going into Edit mode.
$this->clickContextualLink($node_selector, "Quick edit");
$this->assertElementVisibleAfterWait('css', $quick_edit_selector);
// Open off-canvas and enter Edit mode via contextual link.
$this->clickContextualLink($block_selector, "Quick edit");
$this->waitForOffCanvasToOpen();
// QuickEdit toolbar should be closed when opening off-canvas dialog.
$web_assert->elementNotExists('css', $quick_edit_selector);
// Open QuickEdit toolbar via contextual link while in Edit mode.
$this->clickContextualLink($node_selector, "Quick edit", FALSE);
$this->waitForOffCanvasToClose();
$this->assertElementVisibleAfterWait('css', $quick_edit_selector);
$this->disableEditMode();
}
}
/**
* Tests enabling and disabling Edit Mode.
*/
public function testEditModeEnableDisable() {
foreach ($this->getTestThemes() as $theme) {
$this->enableTheme($theme);
$block = $this->placeBlock('system_powered_by_block');
foreach (['contextual_link', 'toolbar_link'] as $enable_option) {
$this->drupalGet('user');
$this->assertEditModeDisabled();
switch ($enable_option) {
// Enable Edit mode.
case 'contextual_link':
$this->clickContextualLink($this->getBlockSelector($block), "Quick edit");
$this->waitForOffCanvasToOpen();
$this->assertEditModeEnabled();
break;
case 'toolbar_link':
$this->enableEditMode();
break;
}
$this->disableEditMode();
// Make another page request to ensure Edit mode is still disabled.
$this->drupalGet('user');
$this->assertEditModeDisabled();
// Make sure on this page request it also re-enables and disables
// correctly.
$this->enableEditMode();
$this->disableEditMode();
}
}
}
/**
* Assert that edit mode has been properly enabled.
*/
protected function assertEditModeEnabled() {
$web_assert = $this->assertSession();
// No contextual triggers should be hidden.
$web_assert->elementNotExists('css', '.contextual .trigger.visually-hidden');
// The toolbar edit button should read "Editing".
$web_assert->elementContains('css', static::TOOLBAR_EDIT_LINK_SELECTOR, 'Editing');
// The main canvas element should have the "js-settings-tray-edit-mode" class.
$web_assert->elementExists('css', '.dialog-off-canvas__main-canvas.js-settings-tray-edit-mode');
}
/**
* Assert that edit mode has been properly disabled.
*/
protected function assertEditModeDisabled() {
$web_assert = $this->assertSession();
// Contextual triggers should be hidden.
$web_assert->elementExists('css', '.contextual .trigger.visually-hidden');
// No contextual triggers should be not hidden.
$web_assert->elementNotExists('css', '.contextual .trigger:not(.visually-hidden)');
// The toolbar edit button should read "Edit".
$web_assert->elementContains('css', static::TOOLBAR_EDIT_LINK_SELECTOR, 'Edit');
// The main canvas element should NOT have the "js-settings-tray-edit-mode"
// class.
$web_assert->elementNotExists('css', '.dialog-off-canvas__main-canvas.js-settings-tray-edit-mode');
}
/**
* Press the toolbar Edit button provided by the contextual module.
*/
protected function pressToolbarEditButton() {
$this->assertSession()->waitForElement('css', '[data-contextual-id] .contextual-links a');
$edit_button = $this->getSession()
->getPage()
->find('css', static::TOOLBAR_EDIT_LINK_SELECTOR);
$edit_button->press();
}
/**
* Creates a custom block.
*
* @param bool|string $title
* (optional) Title of block. When no value is given uses a random name.
* Defaults to FALSE.
* @param string $bundle
* (optional) Bundle name. Defaults to 'basic'.
* @param bool $save
* (optional) Whether to save the block. Defaults to TRUE.
*
* @return \Drupal\block_content\Entity\BlockContent
* Created custom block.
*/
protected function createBlockContent($title = FALSE, $bundle = 'basic', $save = TRUE) {
$title = $title ?: $this->randomName();
$block_content = BlockContent::create([
'info' => $title,
'type' => $bundle,
'langcode' => 'en',
'body' => [
'value' => 'The name "llama" was adopted by European settlers from native Peruvians.',
'format' => 'plain_text',
],
]);
if ($block_content && $save === TRUE) {
$block_content->save();
}
return $block_content;
}
/**
* Creates a custom block type (bundle).
*
* @param string $label
* The block type label.
* @param bool $create_body
* Whether or not to create the body field.
*
* @return \Drupal\block_content\Entity\BlockContentType
* Created custom block type.
*/
protected function createBlockContentType($label, $create_body = FALSE) {
$bundle = BlockContentType::create([
'id' => $label,
'label' => $label,
'revision' => FALSE,
]);
$bundle->save();
if ($create_body) {
block_content_add_body_field($bundle->id());
}
return $bundle;
}
/**
* Tests that contextual links in custom blocks are changed.
*
* "Quick edit" is quickedit.module link.
* "Quick edit settings" is settings_tray.module link.
*/
public function testCustomBlockLinks() {
$this->container->get('module_installer')->install(['quickedit']);
$this->grantPermissions(Role::load(RoleInterface::AUTHENTICATED_ID), ['access in-place editing']);
$this->drupalGet('user');
$page = $this->getSession()->getPage();
$links = $page->findAll('css', "#block-custom .contextual-links li a");
$link_labels = [];
/** @var \Behat\Mink\Element\NodeElement $link */
foreach ($links as $link) {
$link_labels[$link->getAttribute('href')] = $link->getText();
}
$href = array_search('Quick edit', $link_labels);
$this->assertEquals('', $href);
$href = array_search('Quick edit settings', $link_labels);
$this->assertTrue(strstr($href, '/admin/structure/block/manage/custom/off-canvas?destination=user/2') !== FALSE);
}
/**
* Gets the block CSS selector.
*
* @param \Drupal\block\Entity\Block $block
* The block.
*
* @return string
* The CSS selector.
*/
public function getBlockSelector(Block $block) {
return '#block-' . $block->id();
}
/**
* Determines if the label input is visible.
*
* @return bool
* TRUE if the label is visible, FALSE if it is not.
*/
protected function isLabelInputVisible() {
return $this->getSession()->getPage()->find('css', static::LABEL_INPUT_SELECTOR)->isVisible();
}
/**
* Tests access to block forms with related configuration is correct.
*/
public function testBlockConfigAccess() {
$page = $this->getSession()->getPage();
$web_assert = $this->assertSession();
// Confirm that System Branding block does not expose Site Name field
// without permission.
$block = $this->placeBlock('system_branding_block');
$this->drupalGet('user');
$this->enableEditMode();
$this->openBlockForm($this->getBlockSelector($block));
// The site name field should not appear because the user doesn't have
// permission.
$web_assert->fieldNotExists('settings[site_information][site_name]');
$page->pressButton('Save Site branding');
$this->assertElementVisibleAfterWait('css', 'div:contains(The block configuration has been saved)');
$web_assert->assertWaitOnAjaxRequest();
// Confirm we did not save changes to the configuration.
$this->assertEquals('Drupal', \Drupal::configFactory()->getEditable('system.site')->get('name'));
$this->grantPermissions(Role::load(Role::AUTHENTICATED_ID), ['administer site configuration']);
$this->drupalGet('user');
$this->openBlockForm($this->getBlockSelector($block));
// The site name field should appear because the user does have permission.
$web_assert->fieldExists('settings[site_information][site_name]');
// Confirm that the Menu block does not expose menu configuration without
// permission.
// Add a link or the menu will not render.
$menu_link_content = MenuLinkContent::create([
'title' => 'This is on the menu',
'menu_name' => 'main',
'link' => ['uri' => 'route:<front>'],
]);
$menu_link_content->save();
$this->assertNotEmpty($menu_link_content->isEnabled());
$menu_without_overrides = \Drupal::configFactory()->getEditable('system.menu.main')->get();
$block = $this->placeBlock('system_menu_block:main');
$this->drupalGet('user');
$web_assert->pageTextContains('This is on the menu');
$this->openBlockForm($this->getBlockSelector($block));
// Edit menu form should not appear because the user doesn't have
// permission.
$web_assert->pageTextNotContains('Edit menu');
$page->pressButton('Save Main navigation');
$this->assertElementVisibleAfterWait('css', 'div:contains(The block configuration has been saved)');
$web_assert->assertWaitOnAjaxRequest();
// Confirm we did not save changes to the menu or the menu link.
$this->assertEquals($menu_without_overrides, \Drupal::configFactory()->getEditable('system.menu.main')->get());
$menu_link_content = MenuLinkContent::load($menu_link_content->id());
$this->assertNotEmpty($menu_link_content->isEnabled());
// Confirm menu is still on the page.
$this->drupalGet('user');
$web_assert->pageTextContains('This is on the menu');
$this->grantPermissions(Role::load(Role::AUTHENTICATED_ID), ['administer menu']);
$this->drupalGet('user');
$web_assert->pageTextContains('This is on the menu');
$this->openBlockForm($this->getBlockSelector($block));
// Edit menu form should appear because the user does have permission.
$web_assert->pageTextContains('Edit menu');
}
/**
* Test that validation errors appear in the off-canvas dialog.
*/
public function testValidationMessages() {
$page = $this->getSession()->getPage();
$web_assert = $this->assertSession();
foreach ($this->getTestThemes() as $theme) {
$this->enableTheme($theme);
$block = $this->placeBlock('settings_tray_test_validation');
$this->drupalGet('user');
$this->enableEditMode();
$this->openBlockForm($this->getBlockSelector($block));
$page->pressButton('Save Block with validation error');
$web_assert->assertWaitOnAjaxRequest();
// The settings_tray_test_validation test plugin form always has a
// validation error.
$web_assert->elementContains('css', '#drupal-off-canvas', 'Sorry system error. Please save again');
$this->disableEditMode();
$block->delete();
}
}
}
|
gpl-2.0
|
FlisolResende/Android
|
MeusLivros/app/src/main/java/br/com/allmost/meuslivros/FormLivros.java
|
2066
|
package br.com.allmost.meuslivros;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import br.com.allmost.meuslivros.dao.LivrosDao;
import br.com.allmost.meuslivros.model.Livros;
public class FormLivros extends ActionBarActivity {
EditText titulo, autor, pagina;
Button botao;
Livros livroToEdit,livro;
LivrosDao dao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form_livros);
Intent intent = getIntent();
livroToEdit = (Livros) intent.getSerializableExtra("livro-selecionado");
livro = new Livros();
dao = new LivrosDao(FormLivros.this);
titulo = (EditText) findViewById(R.id.titulo);
autor = (EditText) findViewById(R.id.autor);
pagina = (EditText) findViewById(R.id.pagina);
botao = (Button) findViewById(R.id.botao);
if (livroToEdit != null){
botao.setText("Alterar");
titulo.setText(livroToEdit.getTitulo());
autor.setText(livroToEdit.getAutor());
pagina.setText(livroToEdit.getPagina()+"");
livro.setId(livroToEdit.getId());
}else{
botao.setText("Salvar");
}
botao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
livro.setTitulo(titulo.getText().toString());
livro.setAutor(autor.getText().toString());
livro.setPagina(Integer.parseInt(pagina.getText().toString()));
if (botao.getText().toString().equals("Salvar")){
dao.salvaLivro(livro);
dao.close();
}else{
dao.alteraLivro(livro);
dao.close();
}
finish();
}
});
}
}
|
gpl-2.0
|
openjdk/jdk7u
|
jdk/make/tools/src/build/tools/generatenimbus/Point.java
|
2016
|
/*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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 Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package build.tools.generatenimbus;
import javax.xml.bind.annotation.XmlAttribute;
class Point {
@XmlAttribute private double x;
public double getX() { return x; }
@XmlAttribute private double y;
public double getY() { return y; }
@XmlAttribute(name="cp1x") private double cp1x;
public double getCp1X() { return cp1x; }
@XmlAttribute(name="cp1y") private double cp1y;
public double getCp1Y() { return cp1y; }
@XmlAttribute(name="cp2x") private double cp2x;
public double getCp2X() { return cp2x; }
@XmlAttribute(name="cp2y") private double cp2y;
public double getCp2Y() { return cp2y; }
public boolean isP1Sharp() {
return cp1x == x && cp1y == y;
}
public boolean isP2Sharp() {
return cp2x == x && cp2y == y;
}
}
|
gpl-2.0
|
SiderZhang/p2pns3
|
libtorrent-rasterbar-0.16.12/bindings/python/src/torrent_handle.cpp
|
16537
|
// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/python.hpp>
#include <boost/python/tuple.hpp>
#include <libtorrent/torrent_handle.hpp>
#include <libtorrent/peer_info.hpp>
#include <boost/lexical_cast.hpp>
#include "gil.hpp"
using namespace boost::python;
using namespace libtorrent;
namespace
{
list url_seeds(torrent_handle& handle)
{
list ret;
std::set<std::string> urls;
{
allow_threading_guard guard;
urls = handle.url_seeds();
}
for (std::set<std::string>::iterator i(urls.begin())
, end(urls.end()); i != end; ++i)
ret.append(*i);
return ret;
}
list http_seeds(torrent_handle& handle)
{
list ret;
std::set<std::string> urls;
{
allow_threading_guard guard;
urls = handle.http_seeds();
}
for (std::set<std::string>::iterator i(urls.begin())
, end(urls.end()); i != end; ++i)
ret.append(*i);
return ret;
}
list piece_availability(torrent_handle& handle)
{
list ret;
std::vector<int> avail;
{
allow_threading_guard guard;
handle.piece_availability(avail);
}
for (std::vector<int>::iterator i(avail.begin())
, end(avail.end()); i != end; ++i)
ret.append(*i);
return ret;
}
list piece_priorities(torrent_handle& handle)
{
list ret;
std::vector<int> prio;
{
allow_threading_guard guard;
prio = handle.piece_priorities();
}
for (std::vector<int>::iterator i(prio.begin())
, end(prio.end()); i != end; ++i)
ret.append(*i);
return ret;
}
} // namespace unnamed
list file_progress(torrent_handle& handle)
{
std::vector<size_type> p;
{
allow_threading_guard guard;
p.reserve(handle.get_torrent_info().num_files());
handle.file_progress(p);
}
list result;
for (std::vector<size_type>::iterator i(p.begin()), e(p.end()); i != e; ++i)
result.append(*i);
return result;
}
list get_peer_info(torrent_handle const& handle)
{
std::vector<peer_info> pi;
{
allow_threading_guard guard;
handle.get_peer_info(pi);
}
list result;
for (std::vector<peer_info>::iterator i = pi.begin(); i != pi.end(); ++i)
result.append(*i);
return result;
}
void prioritize_pieces(torrent_handle& info, object o)
{
std::vector<int> result;
try
{
object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) ));
while( 1 )
{
object obj = extract<object>( iter_obj.attr( "next" )() );
result.push_back(extract<int const>( obj ));
}
}
catch( error_already_set )
{
PyErr_Clear();
info.prioritize_pieces(result);
return;
}
}
void prioritize_files(torrent_handle& info, object o)
{
std::vector<int> result;
try
{
object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) ));
while( 1 )
{
object obj = extract<object>( iter_obj.attr( "next" )() );
result.push_back(extract<int const>( obj ));
}
}
catch( error_already_set )
{
PyErr_Clear();
info.prioritize_files(result);
return;
}
}
list file_priorities(torrent_handle& handle)
{
list ret;
std::vector<int> priorities = handle.file_priorities();
for (std::vector<int>::iterator i = priorities.begin(); i != priorities.end(); ++i)
ret.append(*i);
return ret;
}
int file_prioritity0(torrent_handle& h, int index)
{
return h.file_priority(index);
}
void file_prioritity1(torrent_handle& h, int index, int prio)
{
return h.file_priority(index, prio);
}
void dict_to_announce_entry(dict d, announce_entry& ae)
{
ae.url = extract<std::string>(d["url"]);
if (d.has_key("tier"))
ae.tier = extract<int>(d["tier"]);
if (d.has_key("fail_limit"))
ae.fail_limit = extract<int>(d["fail_limit"]);
if (d.has_key("source"))
ae.source = extract<int>(d["source"]);
if (d.has_key("verified"))
ae.verified = extract<int>(d["verified"]);
if (d.has_key("send_stats"))
ae.send_stats = extract<int>(d["send_stats"]);
}
void replace_trackers(torrent_handle& h, object trackers)
{
object iter(trackers.attr("__iter__")());
std::vector<announce_entry> result;
for (;;)
{
handle<> entry(allow_null(PyIter_Next(iter.ptr())));
if (entry == handle<>())
break;
if (extract<announce_entry>(object(entry)).check())
{
result.push_back(extract<announce_entry>(object(entry)));
}
else
{
dict d;
d = extract<dict>(object(entry));
announce_entry ae;
dict_to_announce_entry(d, ae);
result.push_back(ae);
}
}
allow_threading_guard guard;
h.replace_trackers(result);
}
void add_tracker(torrent_handle& h, dict d)
{
announce_entry ae;
dict_to_announce_entry(d, ae);
h.add_tracker(ae);
}
list trackers(torrent_handle& h)
{
list ret;
std::vector<announce_entry> const trackers = h.trackers();
for (std::vector<announce_entry>::const_iterator i = trackers.begin(), end(trackers.end()); i != end; ++i)
{
dict d;
d["url"] = i->url;
d["tier"] = i->tier;
d["fail_limit"] = i->fail_limit;
d["fails"] = i->fails;
d["source"] = i->source;
d["verified"] = i->verified;
d["updating"] = i->updating;
d["start_sent"] = i->start_sent;
d["complete_sent"] = i->complete_sent;
d["send_stats"] = i->send_stats;
ret.append(d);
}
return ret;
}
list get_download_queue(torrent_handle& handle)
{
using boost::python::make_tuple;
list ret;
std::vector<partial_piece_info> downloading;
{
allow_threading_guard guard;
handle.get_download_queue(downloading);
}
for (std::vector<partial_piece_info>::iterator i = downloading.begin()
, end(downloading.end()); i != end; ++i)
{
dict partial_piece;
partial_piece["piece_index"] = i->piece_index;
partial_piece["blocks_in_piece"] = i->blocks_in_piece;
list block_list;
for (int k = 0; k < i->blocks_in_piece; ++k)
{
dict block_info;
block_info["state"] = i->blocks[k].state;
block_info["num_peers"] = i->blocks[k].num_peers;
block_info["bytes_progress"] = i->blocks[k].bytes_progress;
block_info["block_size"] = i->blocks[k].block_size;
block_info["peer"] = make_tuple(
boost::lexical_cast<std::string>(i->blocks[k].peer().address()), i->blocks[k].peer().port());
block_list.append(block_info);
}
partial_piece["blocks"] = block_list;
ret.append(partial_piece);
}
return ret;
}
void set_metadata(torrent_handle& handle, std::string const& buf)
{
handle.set_metadata(buf.c_str(), buf.size());
}
namespace
{
tcp::endpoint tuple_to_endpoint(tuple const& t)
{
return tcp::endpoint(address::from_string(extract<std::string>(t[0])), extract<int>(t[1]));
}
}
#if BOOST_VERSION > 104200
boost::intrusive_ptr<const torrent_info> get_torrent_info(torrent_handle const& h)
{
return boost::intrusive_ptr<const torrent_info>(&h.get_torrent_info());
}
#else
boost::intrusive_ptr<torrent_info> get_torrent_info(torrent_handle const& h)
{
// I can't figure out how to expose intrusive_ptr<const torrent_info>
// as well as supporting mutable instances. So, this hack is better
// than compilation errors. It seems to work on newer versions of boost though
return boost::intrusive_ptr<torrent_info>(const_cast<torrent_info*>(&h.get_torrent_info()));
}
#endif
void force_reannounce(torrent_handle& th, int s)
{
th.force_reannounce(boost::posix_time::seconds(s));
}
void connect_peer(torrent_handle& th, tuple ip, int source)
{
th.connect_peer(tuple_to_endpoint(ip), source);
}
#ifndef TORRENT_NO_DEPRECATE
void set_peer_upload_limit(torrent_handle& th, tuple const& ip, int limit)
{
th.set_peer_upload_limit(tuple_to_endpoint(ip), limit);
}
void set_peer_download_limit(torrent_handle& th, tuple const& ip, int limit)
{
th.set_peer_download_limit(tuple_to_endpoint(ip), limit);
}
#endif
void add_piece(torrent_handle& th, int piece, char const *data, int flags)
{
th.add_piece(piece, data, flags);
}
void bind_torrent_handle()
{
void (torrent_handle::*force_reannounce0)() const = &torrent_handle::force_reannounce;
#ifndef TORRENT_NO_DEPRECATE
bool (torrent_handle::*super_seeding0)() const = &torrent_handle::super_seeding;
#endif
void (torrent_handle::*super_seeding1)(bool) const = &torrent_handle::super_seeding;
int (torrent_handle::*piece_priority0)(int) const = &torrent_handle::piece_priority;
void (torrent_handle::*piece_priority1)(int, int) const = &torrent_handle::piece_priority;
void (torrent_handle::*move_storage0)(std::string const&) const = &torrent_handle::move_storage;
void (torrent_handle::*rename_file0)(int, std::string const&) const = &torrent_handle::rename_file;
#if TORRENT_USE_WSTRING && !defined TORRENT_NO_DEPRECATE
void (torrent_handle::*move_storage1)(std::wstring const&) const = &torrent_handle::move_storage;
void (torrent_handle::*rename_file1)(int, std::wstring const&) const = &torrent_handle::rename_file;
#endif
#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES
bool (torrent_handle::*resolve_countries0)() const = &torrent_handle::resolve_countries;
void (torrent_handle::*resolve_countries1)(bool) = &torrent_handle::resolve_countries;
#endif
#define _ allow_threads
class_<torrent_handle>("torrent_handle")
.def(self == self)
.def(self != self)
.def(self < self)
.def("get_peer_info", get_peer_info)
.def("status", _(&torrent_handle::status), arg("flags") = 0xffffffff)
.def("get_download_queue", get_download_queue)
.def("file_progress", file_progress)
.def("trackers", trackers)
.def("replace_trackers", replace_trackers)
.def("add_tracker", add_tracker)
.def("add_url_seed", _(&torrent_handle::add_url_seed))
.def("remove_url_seed", _(&torrent_handle::remove_url_seed))
.def("url_seeds", url_seeds)
.def("add_http_seed", _(&torrent_handle::add_http_seed))
.def("remove_http_seed", _(&torrent_handle::remove_http_seed))
.def("http_seeds", http_seeds)
.def("get_torrent_info", get_torrent_info)
.def("set_metadata", set_metadata)
.def("is_valid", _(&torrent_handle::is_valid))
.def("pause", _(&torrent_handle::pause), arg("flags") = 0)
.def("resume", _(&torrent_handle::resume))
.def("clear_error", _(&torrent_handle::clear_error))
.def("set_priority", _(&torrent_handle::set_priority))
.def("super_seeding", super_seeding1)
.def("auto_managed", _(&torrent_handle::auto_managed))
.def("queue_position", _(&torrent_handle::queue_position))
.def("queue_position_up", _(&torrent_handle::queue_position_up))
.def("queue_position_down", _(&torrent_handle::queue_position_down))
.def("queue_position_top", _(&torrent_handle::queue_position_top))
.def("queue_position_bottom", _(&torrent_handle::queue_position_bottom))
#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES
.def("resolve_countries", _(resolve_countries0))
.def("resolve_countries", _(resolve_countries1))
#endif
// deprecated
#ifndef TORRENT_NO_DEPRECATE
.def("super_seeding", super_seeding0)
.def("filter_piece", _(&torrent_handle::filter_piece))
.def("is_piece_filtered", _(&torrent_handle::is_piece_filtered))
.def("write_resume_data", _(&torrent_handle::write_resume_data))
.def("is_seed", _(&torrent_handle::is_seed))
.def("is_finished", _(&torrent_handle::is_finished))
.def("is_paused", _(&torrent_handle::is_paused))
.def("is_auto_managed", _(&torrent_handle::is_auto_managed))
.def("has_metadata", _(&torrent_handle::has_metadata))
#endif
.def("add_piece", add_piece)
.def("read_piece", _(&torrent_handle::read_piece))
.def("have_piece", _(&torrent_handle::have_piece))
.def("set_piece_deadline", _(&torrent_handle::set_piece_deadline)
, (arg("index"), arg("deadline"), arg("flags") = 0))
.def("reset_piece_deadline", _(&torrent_handle::reset_piece_deadline), (arg("index")))
.def("piece_availability", &piece_availability)
.def("piece_priority", _(piece_priority0))
.def("piece_priority", _(piece_priority1))
.def("prioritize_pieces", &prioritize_pieces)
.def("piece_priorities", &piece_priorities)
.def("prioritize_files", &prioritize_files)
.def("file_priorities", &file_priorities)
.def("file_priority", &file_prioritity0)
.def("file_priority", &file_prioritity1)
.def("use_interface", &torrent_handle::use_interface)
.def("save_resume_data", _(&torrent_handle::save_resume_data), arg("flags") = 0)
.def("need_save_resume_data", _(&torrent_handle::need_save_resume_data))
.def("force_reannounce", _(force_reannounce0))
.def("force_reannounce", &force_reannounce)
#ifndef TORRENT_DISABLE_DHT
.def("force_dht_announce", _(&torrent_handle::force_dht_announce))
#endif
.def("scrape_tracker", _(&torrent_handle::scrape_tracker))
.def("name", _(&torrent_handle::name))
.def("set_upload_mode", _(&torrent_handle::set_upload_mode))
.def("set_share_mode", _(&torrent_handle::set_share_mode))
.def("flush_cache", &torrent_handle::flush_cache)
.def("apply_ip_filter", &torrent_handle::apply_ip_filter)
.def("set_upload_limit", _(&torrent_handle::set_upload_limit))
.def("upload_limit", _(&torrent_handle::upload_limit))
.def("set_download_limit", _(&torrent_handle::set_download_limit))
.def("download_limit", _(&torrent_handle::download_limit))
.def("set_sequential_download", _(&torrent_handle::set_sequential_download))
#ifndef TORRENT_NO_DEPRECATE
.def("set_peer_upload_limit", &set_peer_upload_limit)
.def("set_peer_download_limit", &set_peer_download_limit)
.def("set_ratio", _(&torrent_handle::set_ratio))
#endif
.def("connect_peer", &connect_peer)
.def("save_path", _(&torrent_handle::save_path))
.def("set_max_uploads", _(&torrent_handle::set_max_uploads))
.def("max_uploads", _(&torrent_handle::max_uploads))
.def("set_max_connections", _(&torrent_handle::set_max_connections))
.def("max_connections", _(&torrent_handle::max_connections))
.def("set_tracker_login", _(&torrent_handle::set_tracker_login))
.def("move_storage", _(move_storage0))
.def("info_hash", _(&torrent_handle::info_hash))
.def("force_recheck", _(&torrent_handle::force_recheck))
.def("rename_file", _(rename_file0))
.def("set_ssl_certificate", &torrent_handle::set_ssl_certificate, (arg("cert"), arg("private_key"), arg("dh_params"), arg("passphrase")=""))
#if TORRENT_USE_WSTRING && !defined TORRENT_NO_DEPRECATE
.def("move_storage", _(move_storage1))
.def("rename_file", _(rename_file1))
#endif
;
enum_<torrent_handle::pause_flags_t>("pause_flags_t")
.value("graceful_pause", torrent_handle::graceful_pause)
;
enum_<torrent_handle::save_resume_flags_t>("save_resume_flags_t")
.value("flush_disk_cache", torrent_handle::flush_disk_cache)
;
enum_<torrent_handle::deadline_flags>("deadline_flags")
.value("alert_when_available", torrent_handle::alert_when_available)
;
enum_<torrent_handle::status_flags_t>("status_flags_t")
.value("query_distributed_copies", torrent_handle::query_distributed_copies)
.value("query_accurate_download_counters", torrent_handle::query_accurate_download_counters)
.value("query_last_seen_complete", torrent_handle::query_last_seen_complete)
.value("query_pieces", torrent_handle::query_pieces)
.value("query_verified_pieces", torrent_handle::query_verified_pieces)
;
}
|
gpl-2.0
|
shannah/cn1
|
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/jdktools/modules/jpda/src/main/native/jdwp/common/agent/commands/StackFrame.cpp
|
17298
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "StackFrame.h"
#include "PacketParser.h"
#include "ClassManager.h"
#include "ThreadManager.h"
#include "ExceptionManager.h"
using namespace jdwp;
using namespace StackFrame;
int
StackFrame::GetValuesHandler::Execute(JNIEnv *jni)
{
jthread thread = m_cmdParser->command.ReadThreadID(jni);
jint frame = m_cmdParser->command.ReadFrameID(jni);
jint slots = m_cmdParser->command.ReadInt();
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "GetValues: received: frameID=%d, threadID=%p, slots=%d", frame, thread, slots));
if (thread == 0) {
AgentException e(JDWP_ERROR_INVALID_THREAD);
JDWP_SET_EXCEPTION(e);
return JDWP_ERROR_INVALID_THREAD;
}
if (slots < 0) {
AgentException e(JDWP_ERROR_ILLEGAL_ARGUMENT);
JDWP_SET_EXCEPTION(e);
return JDWP_ERROR_ILLEGAL_ARGUMENT;
}
m_cmdParser->reply.WriteInt(slots);
for (int i = 0; i < slots; i++) {
jint slot = m_cmdParser->command.ReadInt();
jdwpTag sigbyte = static_cast<jdwpTag>(m_cmdParser->command.ReadByte());
jvmtiError err = JVMTI_ERROR_NONE;
jvalue resValue;
switch (sigbyte) {
case JDWP_TAG_BOOLEAN:
case JDWP_TAG_BYTE:
case JDWP_TAG_CHAR:
case JDWP_TAG_SHORT:
case JDWP_TAG_INT:
jint ivalue;
JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetLocalInt(thread, frame, slot, &ivalue));
if (err != JVMTI_ERROR_NONE) {
break;
}
switch (sigbyte) {
case JDWP_TAG_BOOLEAN:
resValue.z = static_cast<jboolean>(ivalue);
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "GetValues: slot#=%d, value(boolean)%d", i, resValue.z));
break;
case JDWP_TAG_BYTE:
resValue.b = static_cast<jbyte>(ivalue);
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "GetValues: slot#=%d, value(byte)%d", i, resValue.b));
break;
case JDWP_TAG_CHAR:
resValue.c = static_cast<jchar>(ivalue);
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "GetValues: slot#=%d, value(char)%d", i, resValue.c));
break;
case JDWP_TAG_SHORT:
resValue.s = static_cast<jshort>(ivalue);
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "GetValues: slot#=%d, value(short)%d", i, resValue.s));
break;
case JDWP_TAG_INT:
resValue.i = ivalue;
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "GetValues: slot#=%d, value(int)%d", i, resValue.i));
break;
}
m_cmdParser->reply.WriteValue(jni, sigbyte, resValue);
break;
case JDWP_TAG_LONG:
jlong lvalue;
JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetLocalLong(thread, frame, slot, &lvalue));
if (err != JVMTI_ERROR_NONE) {
break;
}
resValue.j = lvalue;
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "GetValues: slot#=%d, value(long)%lld", i, resValue.j));
m_cmdParser->reply.WriteValue(jni, sigbyte, resValue);
break;
case JDWP_TAG_FLOAT:
jfloat fvalue;
JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetLocalFloat(thread, frame, slot, &fvalue));
if (err != JVMTI_ERROR_NONE) {
break;
}
resValue.f = fvalue;
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "GetValues: slot#=%d, value(float)%f", i, resValue.f));
m_cmdParser->reply.WriteValue(jni, sigbyte, resValue);
break;
case JDWP_TAG_DOUBLE:
jdouble dvalue;
JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetLocalDouble(thread, frame, slot, &dvalue));
if (err != JVMTI_ERROR_NONE) {
break;
}
resValue.d = dvalue;
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "GetValues: slot#=%d, value(double)%Lf", i, resValue.d));
m_cmdParser->reply.WriteValue(jni, sigbyte, resValue);
break;
case JDWP_TAG_OBJECT:
case JDWP_TAG_ARRAY:
case JDWP_TAG_STRING:
case JDWP_TAG_THREAD:
case JDWP_TAG_THREAD_GROUP:
case JDWP_TAG_CLASS_LOADER:
case JDWP_TAG_CLASS_OBJECT: {
jobject ovalue;
JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetLocalObject(thread, frame, slot, &ovalue));
if (err != JVMTI_ERROR_NONE) {
break;
}
jdwpTag tag = GetClassManager().GetJdwpTag(jni, ovalue);
if ((sigbyte != JDWP_TAG_OBJECT) && (sigbyte != tag) && ovalue != 0) {
AgentException e(JDWP_ERROR_INVALID_TAG);
JDWP_SET_EXCEPTION(e);
return JDWP_ERROR_INVALID_TAG;
}
resValue.l = ovalue;
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "GetValues: slot#=%d, tag=%d, value(object)=%p", i, tag, resValue.l));
m_cmdParser->reply.WriteValue(jni, tag, resValue);
jni->DeleteLocalRef(ovalue);
break;
}
default:
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "GetValues: bad slot tag: slot#=%d, tag=%d", i, sigbyte));
AgentException e(JDWP_ERROR_INVALID_TAG);
JDWP_SET_EXCEPTION(e);
return JDWP_ERROR_INVALID_TAG;
}
if (err != JVMTI_ERROR_NONE) {
jdwpError error;
if (err == JVMTI_ERROR_TYPE_MISMATCH) {
error = JDWP_ERROR_INVALID_TAG;
} else if (err == JVMTI_ERROR_OPAQUE_FRAME) {
error = JDWP_ERROR_INVALID_FRAMEID;
} else if (err == JVMTI_ERROR_THREAD_NOT_ALIVE) {
error = JDWP_ERROR_INVALID_THREAD;
} else if (err == JVMTI_ERROR_ILLEGAL_ARGUMENT) {
error = JDWP_ERROR_INVALID_FRAMEID;
} else if (err == JVMTI_ERROR_NO_MORE_FRAMES) {
error = JDWP_ERROR_INVALID_FRAMEID;
} else {
error = (jdwpError)err;
}
AgentException e(error);
JDWP_SET_EXCEPTION(e);
return error;
}
}
return JDWP_ERROR_NONE;
}
int
StackFrame::SetValuesHandler::Execute(JNIEnv *jni)
{
jthread thread = m_cmdParser->command.ReadThreadID(jni);
jint frame = m_cmdParser->command.ReadFrameID(jni);
jint slotValues = m_cmdParser->command.ReadInt();
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "SetValues: received: frameID=%d, threadId=%p, slots=%d", frame, thread, slotValues));
if (thread == 0) {
AgentException e(JDWP_ERROR_INVALID_THREAD);
JDWP_SET_EXCEPTION(e);
return JDWP_ERROR_INVALID_THREAD;
}
if (slotValues < 0) {
AgentException e(JDWP_ERROR_ILLEGAL_ARGUMENT);
JDWP_SET_EXCEPTION(e);
return JDWP_ERROR_ILLEGAL_ARGUMENT;
}
for (int i = 0; i < slotValues; i++) {
jint slot = m_cmdParser->command.ReadInt();
jdwpTaggedValue taggedValue = m_cmdParser->command.ReadValue(jni);
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "SetValues: slot#%d: taggedValue=%d", i, taggedValue.tag));
jvmtiError err = JVMTI_ERROR_NONE;
switch (taggedValue.tag) {
case JDWP_TAG_BOOLEAN:
case JDWP_TAG_BYTE:
case JDWP_TAG_CHAR:
case JDWP_TAG_SHORT:
case JDWP_TAG_INT:
jint ivalue;
switch (taggedValue.tag) {
case JDWP_TAG_BOOLEAN:
ivalue = static_cast<jint>(taggedValue.value.z);
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "SetValues: slot#=%d, value=(boolean)%d", i, taggedValue.value.z));
break;
case JDWP_TAG_BYTE:
ivalue = static_cast<jint>(taggedValue.value.b);
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "SetValues: slot#=%d, value=(byte)%d", i, taggedValue.value.b));
break;
case JDWP_TAG_CHAR:
ivalue = static_cast<jint>(taggedValue.value.c);
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "SetValues: slot#=%d, value=(char)%d", i, taggedValue.value.c));
break;
case JDWP_TAG_SHORT:
ivalue = static_cast<jint>(taggedValue.value.s);
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "SetValues: slot#=%d, value=(short)%d", i, taggedValue.value.s));
break;
case JDWP_TAG_INT:
ivalue = taggedValue.value.i;
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "SetValues: slot#=%d, value=(int)%d", i, taggedValue.value.i));
break;
}
JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->SetLocalInt(thread, frame, slot, ivalue));
break;
case JDWP_TAG_LONG: {
jlong lvalue = taggedValue.value.j;
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "SetValues: slot#=%d, value=(long)%lld", i, taggedValue.value.j));
JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->SetLocalLong(thread, frame, slot, lvalue));
break;
}
case JDWP_TAG_FLOAT: {
jfloat fvalue = taggedValue.value.f;
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "SetValues: slot#=%d, value=(float)%f", i, taggedValue.value.f));
JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->SetLocalFloat(thread, frame, slot, fvalue));
break;
}
case JDWP_TAG_DOUBLE: {
jdouble dvalue = taggedValue.value.d;
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "SetValues: slot#=%d, value=(double)%Lf", i, taggedValue.value.d));
JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->SetLocalDouble(thread, frame, slot, dvalue));
break;
}
case JDWP_TAG_OBJECT:
case JDWP_TAG_ARRAY:
case JDWP_TAG_STRING:
case JDWP_TAG_THREAD:
case JDWP_TAG_THREAD_GROUP:
case JDWP_TAG_CLASS_LOADER:
case JDWP_TAG_CLASS_OBJECT: {
jobject ovalue = taggedValue.value.l;
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "SetValues: slot#=%d, value=(object)%p", i, taggedValue.value.l));
JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->SetLocalObject(thread, frame, slot, ovalue));
break;
}
default:
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "SetValues: bad value tag: slot#=%d, tag=%d", i, taggedValue.tag));
AgentException e(JDWP_ERROR_INVALID_TAG);
JDWP_SET_EXCEPTION(e);
return JDWP_ERROR_INVALID_TAG;
}
if (err != JVMTI_ERROR_NONE) {
jdwpError error;
if (err == JVMTI_ERROR_TYPE_MISMATCH) {
error = JDWP_ERROR_INVALID_TAG;
} else if (err == JVMTI_ERROR_OPAQUE_FRAME) {
error = JDWP_ERROR_INVALID_FRAMEID;
} else if (err == JVMTI_ERROR_THREAD_NOT_ALIVE) {
error = JDWP_ERROR_INVALID_THREAD;
} else if (err == JVMTI_ERROR_ILLEGAL_ARGUMENT) {
error = JDWP_ERROR_INVALID_FRAMEID;
} else if (err == JVMTI_ERROR_NO_MORE_FRAMES) {
error = JDWP_ERROR_INVALID_FRAMEID;
} else {
error = (jdwpError)err;
}
AgentException e(error);
JDWP_SET_EXCEPTION(e);
return error;
}
}
return JDWP_ERROR_NONE;
}
int
StackFrame::ThisObjectHandler::CheckErr(jvmtiError err)
{
if (err != JVMTI_ERROR_NONE) {
jdwpError error;
if (err == JVMTI_ERROR_OPAQUE_FRAME) {
error = JDWP_ERROR_INVALID_FRAMEID;
} else if (err == JVMTI_ERROR_THREAD_NOT_ALIVE) {
error = JDWP_ERROR_INVALID_THREAD;
} else if (err == JVMTI_ERROR_ILLEGAL_ARGUMENT) {
error = JDWP_ERROR_INVALID_FRAMEID;
} else if (err == JVMTI_ERROR_NO_MORE_FRAMES) {
error = JDWP_ERROR_INVALID_FRAMEID;
} else {
error = (jdwpError)err;
}
AgentException e(error);
JDWP_SET_EXCEPTION(e);
return error;
}
return JDWP_ERROR_NONE;
}
int
StackFrame::ThisObjectHandler::Execute(JNIEnv *jni)
{
jthread thread = m_cmdParser->command.ReadThreadID(jni);
if (thread == 0) {
AgentException e(JDWP_ERROR_INVALID_THREAD);
JDWP_SET_EXCEPTION(e);
return JDWP_ERROR_INVALID_THREAD;
}
if (!GetThreadManager().IsSuspended(thread)){
AgentException e(JVMTI_ERROR_THREAD_NOT_SUSPENDED);
JDWP_SET_EXCEPTION(e);
return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
}
jint frame = m_cmdParser->command.ReadFrameID(jni); // frame == depth
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "ThisObject: received: threadID=%p, frameID=%d", thread, frame));
jvmtiError err;
int ret;
jint allCount;
JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetFrameCount(thread, &allCount));
ret = CheckErr(err);
JDWP_CHECK_RETURN(ret);
JDWP_ASSERT(allCount > 0);
jvmtiFrameInfo* frames = static_cast<jvmtiFrameInfo*>
(GetMemoryManager().Allocate(allCount * sizeof(jvmtiFrameInfo) JDWP_FILE_LINE));
AgentAutoFree af(frames JDWP_FILE_LINE);
jint count;
JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetStackTrace(thread, 0, allCount, frames, &count));
ret = CheckErr(err);
JDWP_CHECK_RETURN(ret);
JDWP_ASSERT(count <= allCount);
JDWP_ASSERT(frame <= count);
jvmtiFrameInfo& frameInfo = frames[frame];
jint modifiers;
JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetMethodModifiers(frameInfo.method, &modifiers));
ret = CheckErr(err);
JDWP_CHECK_RETURN(ret);
jvalue resValue;
if ((modifiers & (ACC_STATIC | ACC_NATIVE)) != 0) {
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "ThisObject: null this for method: modifiers=%x, static=%x, native=%x",
modifiers, (modifiers & ACC_STATIC), (modifiers & ACC_NATIVE)));
resValue.l = 0;
m_cmdParser->reply.WriteValue(jni, JDWP_TAG_OBJECT, resValue);
return JDWP_ERROR_NONE;
}
jobject ovalue = 0;
JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetLocalObject(thread, frame, 0, &ovalue));
ret = CheckErr(err);
JDWP_CHECK_RETURN(ret);
JDWP_ASSERT(ovalue != 0);
jdwpTag tag = GetClassManager().GetJdwpTag(jni, ovalue);
resValue.l = ovalue;
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "ThisObject: send: tag=%d, object=%p", tag, resValue.l));
m_cmdParser->reply.WriteValue(jni, tag, resValue);
return JDWP_ERROR_NONE;
}
int
StackFrame::PopFramesHandler::Execute(JNIEnv *jni)
{
jdwpCapabilities caps = GetCapabilities();
if (caps.canPopFrames != 1) {
AgentException e(JDWP_ERROR_NOT_IMPLEMENTED);
JDWP_SET_EXCEPTION(e);
return JDWP_ERROR_NOT_IMPLEMENTED;
}
jthread thread = m_cmdParser->command.ReadThreadID(jni);
if (thread == 0) {
AgentException e(JDWP_ERROR_INVALID_THREAD);
JDWP_SET_EXCEPTION(e);
return JDWP_ERROR_INVALID_THREAD;
}
jint frame = m_cmdParser->command.ReadFrameID(jni);
jint framesToPop = frame + 1;
JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "PopFrames: received: threadID=%p, framesToPop=%d", thread, framesToPop));
int ret = GetThreadManager().PerformPopFrames(jni, framesToPop, thread);
JDWP_CHECK_RETURN(ret);
return JDWP_ERROR_NONE;
}
|
gpl-2.0
|
me-oss/me-cambozola
|
src/com/charliemouse/cambozola/shared/ImageChangeListener.java
|
1098
|
/**
** com/charliemouse/cambozola/shared/ImageChangeEvent.java
** Copyright (C) Andy Wilcock, 2001.
** Available from http://www.charliemouse.com
**
** Cambozola m_inputStream free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** Cambozola m_inputStream 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 Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Cambozola; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
**/
package com.charliemouse.cambozola.shared;
import java.util.EventListener;
public interface ImageChangeListener extends EventListener {
public void imageChanged(ImageChangeEvent ie);
}
|
gpl-2.0
|
blazegraph/database
|
bigdata-util/src/main/java/com/bigdata/util/HTMLUtility.java
|
6948
|
/*
Copyright (C) SYSTAP, LLC DBA Blazegraph 2006-2016. All rights reserved.
Contact:
SYSTAP, LLC DBA Blazegraph
2501 Calvert ST NW #106
Washington, DC 20008
licenses@blazegraph.com
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program 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 Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.bigdata.util;
/**
* Collection of some utility methods for HTML.
*
* @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan Thompson</a>
* @version $Id$
*/
public class HTMLUtility {
/**
*
*/
public HTMLUtility() {
super();
}
/**
* <p>
* Sometimes you want to escape something without using a DOM instance. This
* method escapes a String value so that it may be written as the value of
* an XML attribute in a manner that is also compatible with HTML. Note that
* the best solution is to use a DOM instance, which will automatically
* escape attribute values and PCDATA as they are inserted into the DOM
* instance.
* </p>
* <p>
* The following notes are excerpted from the HTML and XML specifications
* <ul>
* <li>HTML: By default, SGML requires that all attribute values be
* delimited using either double quotation marks (ASCII decimal 34) or
* single quotation marks (ASCII decimal 39). Single quote marks can be
* included within the attribute value when the value is delimited by double
* quote marks, and vice versa. Authors may also use numeric character
* references to represent double quotes (") and single quotes (').
* For double quotes authors can also use the character entity reference
* ".<br>
* In certain cases, authors may specify the value of an attribute without
* any quotation marks. The attribute value may only contain letters (a-z
* and A-Z), digits (0-9), hyphens (ASCII decimal 45), periods (ASCII
* decimal 46), underscores (ASCII decimal 95), and colons (ASCII decimal
* 58). We recommend using quotation marks even when it is possible to
* eliminate them.</li>
* <li>XML: The ampersand character (&) and the left angle bracket (<) may
* appear in their literal form only when used as markup delimiters, or
* within a comment, a processing instruction, or a CDATA section. If they
* are needed elsewhere, they must be escaped using either numeric character
* references or the strings "&" and "<" respectively. The right
* angle bracket (>) may be represented using the string ">", and must,
* for compatibility, be escaped using ">" or a character reference when
* it appears in the string "]]>" in content, when that string is not
* marking the end of a CDATA section.</li>
* </ul>
* </p>
*/
public static String escapeForXHTML(final String s) {
if( s == null ) {
throw new IllegalArgumentException();
}
final int len = s.length();
if (len == 0)
return s;
final StringBuffer sb = new StringBuffer(len + 20);
for (int i = 0; i < len; i++) {
final char ch = s.charAt(i);
switch (ch) {
case '"':
sb.append(""");
break;
case '\'':
sb.append("'");
break;
case '/':
sb.append("/");
break;
case '&':
sb.append("&");
break;
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
default:
sb.append(ch);
break;
}
}
return sb.toString();
}
// /**
// * Same as escapeForXHTML but respects the encoding
// * parameter.
// */
// public static String escapeForXHTML(String s, String enc)
// throws java.io.UnsupportedEncodingException
// {
//
// String retval = escapeForXHTML(s);
//
// return new String(retval.getBytes(enc), enc);
// }
public static String escapeForXMLName(String s) {
if( s == null ) {
throw new IllegalArgumentException();
}
int len = s.length();
if (len == 0)
return s;
StringBuffer sb = new StringBuffer(len + 20);
char ch = s.charAt(0);
if(Character.isDigit(ch))
{
sb.append("_num_");
}
for (int i = 0; i < len; i++) {
ch = s.charAt(i);
switch (ch) {
case '"':
sb.append("_quote_");
break;
case '\'':
sb.append("_apos_");
break;
case '&':
sb.append("_amp_");
break;
case '<':
sb.append("_lt_");
break;
case '>':
sb.append("_gt_");
break;
case '$':
sb.append("_dollar_");
break;
case ':':
sb.append("_colon_");
break;
case '~':
sb.append("_tilda_");
break;
case '(':
sb.append("_lparen_");
break;
case ')':
sb.append("_rparen_");
break;
case ',':
sb.append("_comma_");
break;
case '=':
sb.append("_eq_");
break;
case '!':
sb.append("_bang_");
break;
case '?':
sb.append("_quest_");
break;
case '/':
sb.append("_fw_slash_");
break;
case '\\':
sb.append("_bk_slash_");
break;
case ';':
sb.append("_semicolon_");
break;
case '.':
sb.append("_period_");
break;
case '`':
sb.append("_tic_");
break;
default:
sb.append(ch);
break;
}
}
return sb.toString();
}
}
|
gpl-2.0
|
adamfisk/littleshoot-client
|
server/static/build/src/main/webapp/dojo/dojox/widget/FilePicker.js
|
6635
|
dojo.provide("dojox.widget.FilePicker");
dojo.require("dojox.widget.RollingList");
dojo.require("dojo.i18n");
dojo.requireLocalization("dojox.widget", "FilePicker");
dojo.declare("dojox.widget._FileInfoPane",
[dojox.widget._RollingListPane], {
// summary: a pane to display the information for the currently-selected
// file
// templateString: string
// delete our template string
templateString: "",
// templatePath: string
// Our template path
templatePath: dojo.moduleUrl("dojox.widget", "FilePicker/_FileInfoPane.html"),
postMixInProperties: function(){
this._messages = dojo.i18n.getLocalization("dojox.widget", "FilePicker", this.lang);
this.inherited(arguments);
},
onItems: function(){
// summary:
// called after a fetch or load - at this point, this.items should be
// set and loaded.
var store = this.store, item = this.items[0];
if(!item){
this._onError("Load", new Error("No item defined"));
}else{
this.nameNode.innerHTML = store.getLabel(item);
this.pathNode.innerHTML = store.getIdentity(item);
this.sizeNode.innerHTML = store.getValue(item, "size");
this.parentWidget.scrollIntoView(this);
this.inherited(arguments);
}
}
});
dojo.declare("dojox.widget.FilePicker", dojox.widget.RollingList, {
// summary: a specialized version of RollingList that handles file information
// in a store
className: "dojoxFilePicker",
// pathSeparator: string
// Our file separator - it will be guessed if not set
pathSeparator: "",
// topDir: string
// The top directory string - it will be guessed if not set
topDir: "",
// parentAttr: string
// the attribute to read for finding our parent directory
parentAttr: "parentDir",
// pathAttr: string
// the attribute to read for getting the full path of our file
pathAttr: "path",
// preloadItems: boolean or int
// Set this to a sane number - since we expect to mostly be using the
// dojox.data.FileStore - which doesn't like loading lots of items
// all at once.
preloadItems: 50,
// selectDirectories: boolean
// whether or not we allow selection of directories - that is, whether or
// our value can be set to a directory.
selectDirectories: true,
// selectFiles: boolean
// whether or not we allow selection of files - that is, we will disable
// the file entries.
selectFiles: true,
_itemsMatch: function(/*item*/ item1, /*item*/ item2){
// Summary: returns whether or not the two items match - checks ID if
// they aren't the exact same object - ignoring trailing slashes
if(!item1 && !item2){
return true;
}else if(!item1 || !item2){
return false;
}else if(item1 == item2){
return true;
}else if (this._isIdentity){
var iArr = [ this.store.getIdentity(item1), this.store.getIdentity(item2) ];
dojo.forEach(iArr, function(i, idx){
if(i.lastIndexOf(this.pathSeparator) == (i.length - 1)){
iArr[idx] = i.substring(0, i.length - 1);
}else{
}
}, this);
return (iArr[0] == iArr[1]);
}
return false;
},
startup: function(){
if(this._started){ return; }
this.inherited(arguments);
// Figure out our file separator if we don't have it yet
var conn, child = this.getChildren()[0];
var setSeparator = dojo.hitch(this, function(){
if(conn){
this.disconnect(conn);
}
delete conn;
var item = child.items[0];
if(item){
var store = this.store;
var parent = store.getValue(item, this.parentAttr);
var path = store.getValue(item, this.pathAttr);
this.pathSeparator = this.pathSeparator || store.pathSeparator;
if(!this.pathSeparator){
this.pathSeparator = path.substring(parent.length, parent.length + 1);
}
if(!this.topDir){
this.topDir = parent;
if(this.topDir.lastIndexOf(this.pathSeparator) != (this.topDir.length - 1)){
this.topDir += this.pathSeparator;
}
}
}
});
if(!this.pathSeparator || !this.topDir){
if(!child.items){
conn = this.connect(child, "onItems", setSeparator);
}else{
setSeparator();
}
}
},
getChildItems: function(item){
var ret = this.inherited(arguments);
if(!ret && this.store.getValue(item, "directory")){
// It's an empty directory - so pass through an empty array
ret = [];
}
return ret;
},
getMenuItemForItem: function(/*item*/ item, /* dijit._Contained */ parentPane, /* item[]? */ children){
var menuOptions = {iconClass: "dojoxDirectoryItemIcon"};
if(!this.store.getValue(item, "directory")){
menuOptions.iconClass = "dojoxFileItemIcon";
var l = this.store.getLabel(item), idx = l.lastIndexOf(".");
if(idx >= 0){
menuOptions.iconClass += " dojoxFileItemIcon_" + l.substring(idx + 1);
}
if(!this.selectFiles){
menuOptions.disabled = true;
}
}
var ret = new dijit.MenuItem(menuOptions);
return ret;
},
getPaneForItem: function(/*item*/ item, /* dijit._Contained */ parentPane, /* item[]? */ children){
var ret = null;
if(!item || (this.store.isItem(item) && this.store.getValue(item, "directory"))){
ret = new dojox.widget._RollingListGroupPane({});
}else if(this.store.isItem(item) && !this.store.getValue(item, "directory")){
ret = new dojox.widget._FileInfoPane({});
}
return ret;
},
_setPathValueAttr: function(/*string*/ path, /*boolean?*/ resetLastExec, /*function?*/ onSet){
// Summary: sets the value of this widget based off the given path
if(!path){
this.attr("value", null);
return;
}
if(path.lastIndexOf(this.pathSeparator) == (path.length - 1)){
path = path.substring(0, path.length - 1);
}
this.store.fetchItemByIdentity({identity: path,
onItem: function(v){
if(resetLastExec){
this._lastExecutedValue = v;
}
this.attr("value", v);
if(onSet){ onSet(); }
},
scope: this});
},
_getPathValueAttr: function(/*item?*/val){
// summary: returns the path value of the given value (or current value
// if not passed a value)
if(!val){
val = this.value;
}
if(val && this.store.isItem(val)){
return this.store.getValue(val, this.pathAttr);
}else{
return "";
}
},
_setValue: function(/* item */ value){
// summary: internally sets the value and fires onchange
delete this._setInProgress;
var store = this.store;
if(value && store.isItem(value)){
var isDirectory = this.store.getValue(value, "directory");
if((isDirectory && !this.selectDirectories) ||
(!isDirectory && !this.selectFiles)){ return; }
}else{
value = null;
}
if(!this._itemsMatch(this.value, value)){
this.value = value;
this._onChange(value);
}
}
});
|
gpl-2.0
|
ekapujiw2002/ex4-avr-gcc-library
|
doxygen/html/search/all_6e.js
|
347
|
var searchData=
[
['new_5fadc',['new_adc',['../group__ex4__adc.html#ga91d781b98c410d6e5ccc290e20f989d5',1,'new_adc(const uint8_t Vref, const uint8_t DataBit, const uint8_t Psc): adc.c'],['../group__ex4__adc.html#ga91d781b98c410d6e5ccc290e20f989d5',1,'new_adc(const uint8_t Vref, const uint8_t DataBit, const uint8_t Psc): adc.c']]]
];
|
gpl-2.0
|
imunro/FLIMfit
|
FLIMfitLibrary/Source/lmmle.cpp
|
2706
|
#define CMINPACK_NO_DLL
#include "VariableProjection.h"
#include "levmar.h"
#include <math.h>
#include "util.h"
int lmmle(int nl, int l, int n, int nmax, int ndim, int p, double *t, float *y,
float *w, double *ws, Tada ada, double *a, double *b, double *c,
int itmax, int *gc, int thread, int *static_store,
double *alf, double *beta, int *ierr, int *niter, double *c2, int *terminate)
{
varp_param vp;
int i1 = 1;
int i0 = 0;
vp.gc = gc;
vp.s = i1;
vp.l = l;
vp.nl = nl;
vp.n = n;
vp.nmax = nmax;
vp.ndim = ndim;
vp.p = p;
vp.t = t;
vp.y = y;
vp.w = w;
vp.ws = ws;
vp.ada = ada;
vp.a = a;
vp.b = b;
vp.thread = thread;
vp.alf = alf;
vp.beta = beta;
vp.static_store = static_store;
vp.terminate = terminate;
// int lnls1 = *l + *s + *nl + 1;
// int lp1 = *l + 1;
// int nsls1 = *n * *s - *l * (*s - 1);
static double eps1 = 1e-6;
int* inc = static_store + 5;
int nfunc = n + 1; // +1 for kappa
int nvar = nl;
int csize = nl * (6 + nfunc) + nfunc;
//fvec -> [nl]
//fjac -> [nl * nfunc]
//ipvt -> [nl]
//qtf -> [nl]
//wa1 -> [nl]
//wa2 -> [nl]
//wa3 -> [nl]
//wa4 -> [nfunc]
double *dspace = c;
int dspace_idx = 0;
double *fjac = dspace + dspace_idx;
dspace_idx += nfunc * nvar;
double *fvec = dspace + dspace_idx;
dspace_idx += nfunc;
double *diag = dspace + dspace_idx;
dspace_idx += nvar;
double *qtf = dspace + dspace_idx;
dspace_idx += nvar;
double *wa1 = dspace + dspace_idx;
dspace_idx += nvar;
double *wa2 = dspace + dspace_idx;
dspace_idx += nvar;
double *wa3 = dspace + dspace_idx;
dspace_idx += nvar;
double *wa4 = dspace + dspace_idx;
dspace_idx += nfunc;
int *ipvt = (int*) (dspace + dspace_idx);
for(int i=0; i<nl; i++)
diag[i] = 1;
double ftol, xtol, gtol, factor;
//ftol = sqrt(dpmpar(1));
//xtol = sqrt(dpmpar(1));
gtol = 0.;
factor = 1;
int maxfev = 100;
int nfev;
void *vvp = (void*) &vp;
double info[LM_INFO_SZ];
double* dy = new double[nfunc];
for(int i=0; i<n; i++)
{
dy[i] = y[i];
}
dy[n] = 1;
double* err = new double[nfunc];
dlevmar_chkjac(mle_funcs, mle_jacb, alf, nvar, nfunc, vvp, err);
err[0] = err[0];
delete[] err;
dlevmar_der(mle_funcs, mle_jacb, alf, dy, nvar, nfunc, itmax, NULL, info, NULL, NULL, vvp);
delete[] dy;
if (info < 0)
*ierr = info[5];
else
*ierr = *niter;
return 0;
}
|
gpl-2.0
|
calasisqueta/calasisqueta
|
wp-content/themes/eventbrite-venue/inc/jetpack.php
|
684
|
<?php
/**
* Jetpack Compatibility File
* See: http://jetpack.me/
*
* @package Eventbrite_Event
*/
/**
* Add theme support for Infinite Scroll.
* See: http://jetpack.me/support/infinite-scroll/
*/
function eventbrite_venue_setup_infinite_scroll() {
add_theme_support( 'infinite-scroll', array(
'container' => 'content',
'render' => 'eventbrite_venue_infinite_scroll_render',
) );
}
add_action( 'after_setup_theme', 'eventbrite_venue_setup_infinite_scroll' );
/**
* Callback for rendering posts during infinite scroll.
*/
function eventbrite_venue_infinite_scroll_render() {
while ( have_posts() ) {
the_post();
get_template_part( 'tmpl/post-loop' );
}
}
|
gpl-2.0
|
ljack/ZoneMinder
|
web/skins/classic/views/devices.php
|
3585
|
<?php
//
// ZoneMinder web devices file, $Date$, $Revision$
// Copyright (C) 2001-2008 Philip Coombes
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program 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 Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
if ( !canView( 'Devices' ) )
{
$view = "error";
return;
}
$sql = "SELECT * FROM Devices WHERE Type = 'X10' ORDER BY Name";
$devices = array();
foreach( dbFetchAll( $sql ) as $row )
{
$row['Status'] = getDeviceStatusX10( $row['KeyString'] );
$devices[] = $row;
}
xhtmlHeaders(__FILE__, $SLANG['Devices'] );
?>
<body>
<div id="page">
<div id="header">
<h2><?php echo $SLANG['Devices'] ?></h2>
</div>
<div id="content">
<form name="contentForm" method="get" action="<?php echo $_SERVER['PHP_SELF'] ?>">
<input type="hidden" name="view" value="none"/>
<input type="hidden" name="action" value="device"/>
<input type="hidden" name="key" value=""/>
<input type="hidden" name="command" value=""/>
<table id="contentTable" class="major" cellspacing="0">
<tbody>
<?php
foreach( $devices as $device )
{
if ( $device['Status'] == 'ON' )
{
$fclass = "infoText";
}
elseif ( $device['Status'] == 'OFF' )
{
$fclass = "warnText";
}
else
{
$fclass = "errorText";
}
?>
<tr>
<td><?php echo makePopupLink( '?view=device&did='.$device['Id'], 'zmDevice', 'device', '<span class="'.$fclass.'">'.validHtmlStr($device['Name']).' ('.validHtmlStr($device['KeyString']).')</span>', canEdit( 'Devices' ) ) ?></td>
<td><input type="button" value="<?php echo $SLANG['On'] ?>"<?php echo ($device['Status'] != 'ON')?' class="set"':'' ?> onclick="switchDeviceOn( this, '<?php echo validHtmlStr($device['KeyString']) ?>' )"<?php echo canEdit( 'Devices' )?"":' disabled="disabled"' ?>/></td>
<td><input type="button" value="<?php echo $SLANG['Off'] ?>"<?php echo ($device['Status'] != 'OFF')?' class="set"':'' ?> onclick="switchDeviceOff( this, '<?php echo validHtmlStr($device['KeyString']) ?>' )"<?php echo canEdit( 'Devices' )?"":' disabled="disabled"' ?>/></td>
<td><input type="checkbox" name="markDids[]" value="<?php echo $device['Id'] ?>" onclick="configureButtons( this, 'markDids' );"<?php if ( !canEdit( 'Devices' ) ) {?> disabled="disabled"<?php } ?>/></td>
</tr>
<?php
}
?>
</tbody>
</table>
<div id="contentButtons">
<input type="button" value="<?php echo $SLANG['New'] ?>" onclick="createPopup( '?view=device&did=0', 'zmDevice', 'device' )"<?php echo canEdit('Devices')?'':' disabled="disabled"' ?>/>
<input type="button" name="deleteBtn" value="<?php echo $SLANG['Delete'] ?>" onclick="deleteDevice( this )" disabled="disabled"/>
<input type="button" value="<?php echo $SLANG['Cancel'] ?>" onclick="closeWindow();"/>
</div>
</form>
</div>
</div>
</body>
</html>
|
gpl-2.0
|
shamsbd71/canvas-framework
|
base/js/script.js
|
7772
|
/**
*------------------------------------------------------------------------------
* @package CANVAS Framework for Joomla!
*------------------------------------------------------------------------------
* @copyright Copyright (C) 2004-2013 ThemezArt.com. All Rights Reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
* @authors ThemezArt
* & t3-framework.org as base version
* @Link: http://themezart.com/canvas-framework
*------------------------------------------------------------------------------
*/
!function($){
// detect & add ie version to html tag
if (match = navigator.userAgent.match (/MSIE ([0-9]{1,}[\.0-9]{0,})/) || navigator.userAgent.match (/Trident.*rv:([0-9]{1,}[\.0-9]{0,})/)) {
$('html').addClass('ie'+parseInt (match[1]));
}
// Detect grid-float-breakpoint value and put to $(body) data
$(document).ready(function(){
if (!window.getComputedStyle) {
window.getComputedStyle = function(el, pseudo) {
this.el = el;
this.getPropertyValue = function(prop) {
var re = /(\-([a-z]){1})/g;
if (prop == 'float') prop = 'styleFloat';
if (re.test(prop)) {
prop = prop.replace(re, function () {
return arguments[2].toUpperCase();
});
}
return el.currentStyle[prop] ? el.currentStyle[prop] : null;
}
return this;
}
}
var fromClass = 'body-data-holder',
prop = 'content',
$inspector = $('<div>').css('display', 'none').addClass(fromClass).appendTo($('body'));
try {
var attrs = window.getComputedStyle(
$inspector[0], ':before'
).getPropertyValue(prop);
if(attrs){
var matches = attrs.match(/([\da-z\-]+)/gi),
data = {};
if (matches && matches.length) {
for (var i=0; i<matches.length; i++) {
data[matches[i++]] = i<matches.length ? matches[i] : null;
}
}
$('body').data (data);
}
} finally {
$inspector.remove(); // and remove from DOM
}
});
//detect transform (https://github.com/cubiq/)
(function(){
$.support.canvastransform = (function () {
var style = document.createElement('div').style,
vendors = ['t', 'webkitT', 'MozT', 'msT', 'OT'],
transform, i = 0, l = vendors.length;
for ( ; i < l; i++ ) {
transform = vendors[i] + 'ransform';
if ( transform in style ) {
return transform;
}
}
return false;
})();
})();
//basic detect touch
(function(){
$('html').addClass('ontouchstart' in window ? 'touch' : 'no-touch');
})();
//document ready
$(document).ready(function(){
//remove conflict of mootools more show/hide function of element
(function(){
if(window.MooTools && window.MooTools.More && Element && Element.implement){
var mthide = Element.prototype.hide,
mtshow = Element.prototype.show,
mtslide = Element.prototype.slide;
Element.implement({
show: function(args){
if(arguments.callee &&
arguments.callee.caller &&
arguments.callee.caller.toString().indexOf('isPropagationStopped') !== -1){ //jquery mark
return this;
}
return $.isFunction(mtshow) && mtshow.apply(this, args);
},
hide: function(){
if(arguments.callee &&
arguments.callee.caller &&
arguments.callee.caller.toString().indexOf('isPropagationStopped') !== -1){ //jquery mark
return this;
}
return $.isFunction(mthide) && mthide.apply(this, arguments);
},
slide: function(args){
if(arguments.callee &&
arguments.callee.caller &&
arguments.callee.caller.toString().indexOf('isPropagationStopped') !== -1){ //jquery mark
return this;
}
return $.isFunction(mtslide) && mtslide.apply(this, args);
}
})
}
})();
// overwrite default tooltip/popover behavior (same as Joomla 3.1.5)
$.fn.tooltip.Constructor && $.fn.tooltip.Constructor.DEFAULTS && ($.fn.tooltip.Constructor.DEFAULTS.html = true);
$.fn.popover.Constructor && $.fn.popover.Constructor.DEFAULTS && ($.fn.popover.Constructor.DEFAULTS.html = true);
$.fn.tooltip.defaults && ($.fn.tooltip.defaults.html = true);
$.fn.popover.defaults && ($.fn.popover.defaults.html = true);
//fix JomSocial navbar-collapse toggle
(function(){
if(window.jomsQuery && jomsQuery.fn.collapse){
$('[data-toggle="collapse"]').on('click', function(e){
//toggle manual
$($(this).attr('data-target')).eq(0).collapse('toggle');
//stop
e.stopPropagation();
return false;
});
//remove conflict on touch screen
jomsQuery('html, body').off('touchstart.dropdown.data-api');
}
})();
//fix chosen select
(function(){
if($.fn.chosen && $(document.documentElement).attr('dir') == 'rtl'){
$('select').addClass('chzn-rtl');
}
})();
});
$(window).load(function(){
//fix animation for navbar-collapse-fixed-top||bottom
if(!$(document.documentElement).hasClass('off-canvas-ready') &&
($('.navbar-collapse-fixed-top').length ||
$('.navbar-collapse-fixed-bottom').length)){
var btn = $('.btn-navbar[data-toggle="collapse"]');
if (!btn.length){
return;
}
if(btn.data('target')){
var nav = $(btn.data('target'));
if(!nav.length){
return;
}
var fixedtop = nav.closest('.navbar-collapse-fixed-top').length;
btn.on('click', function(){
var wheight = (window.innerHeight || $(window).height()),
offset = fixedtop ? parseInt(nav.css('top')) + parseInt(nav.css('margin-top')) + parseInt(nav.closest('.navbar-collapse-fixed-top').css('top')) :
parseInt(nav.css('bottom'));
if(!$.support.transition){
nav.parent().css('height', !btn.hasClass('collapsed') && btn.data('canvas-clicked') ? '' : wheight);
btn.data('canvas-clicked', 1);
}
nav
.addClass('animate')
.css('max-height', wheight - offset);
});
nav.on('shown hidden', function(){
nav.removeClass('animate');
});
}
}
});
}(jQuery);
|
gpl-2.0
|
melviso/phycpp
|
beatle/plugin/tools/ast_explorer/res/_param.py
|
711
|
# -*- coding: utf-8 -*-
_param = [
"16 16 23 1",
" c None",
". c #61C114",
"+ c #7C7C7C",
"@ c #CD2414",
"# c #C92713",
"$ c #BC3A13",
"% c #986F13",
"& c #63BB14",
"* c #63BC14",
"= c #74A214",
"- c #B14B14",
"; c #9F6414",
"> c #6CAF13",
", c #C33213",
"' c #C23113",
") c #63BD13",
"! c #74A414",
"~ c #B04C14",
"{ c #9F6314",
"] c #C92614",
"^ c #BE3813",
"/ c #9A6D14",
"( c #64BA14",
" ",
" .......... ",
" +..........+ ",
" ....@@@#$%&... ",
" ....@..*=-;... ",
" ....@....>,... ",
" ....@....>'... ",
" ....@..)!~{... ",
" ....@@@]^/(... ",
" ....@......... ",
" ....@......... ",
" ....@......... ",
" ....@......... ",
" +..........+ ",
" .......... ",
" "]
|
gpl-2.0
|
pereiracruz2002/alvestar
|
wp-content/themes/limo/comments.php
|
3052
|
<?php
/**
* The template for displaying Comments.
*
* The area of the page that contains both current comments
* and the comment form. The actual display of comments is
* handled by a callback to codex_coder_comment() which is
* located in the inc/template-tags.php file.
*
* @package Codex Coder
*/
/*
* If the current post is protected by a password and
* the visitor has not yet entered the password we will
* return early without loading the comments.
*/
if ( post_password_required() )
return;
?>
<div id="comments" class="comments-area">
<?php // You can start editing here -- including this comment! ?>
<?php if ( have_comments() ) : ?>
<h2 class="comments-title">
<?php
printf( _nx( 'One thought on “%2$s”', '%1$s thoughts on “%2$s”', get_comments_number(), 'comments title', 'codex-coder' ),
number_format_i18n( get_comments_number() ), '<span>' . get_the_title() . '</span>' );
?>
</h2>
<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?>
<nav id="comment-nav-above" class="comment-navigation" role="navigation">
<h1 class="screen-reader-text"><?php _e( 'Comment navigation', 'codex-coder' ); ?></h1>
<div class="nav-previous"><?php previous_comments_link( __( '← Older Comments', 'codex-coder' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( __( 'Newer Comments →', 'codex-coder' ) ); ?></div>
</nav><!-- #comment-nav-above -->
<?php endif; // check for comment navigation ?>
<ol class="comment-list">
<?php
/* Loop through and list the comments. Tell wp_list_comments()
* to use codex_coder_comment() to format the comments.
* If you want to override this in a child theme, then you can
* define codex_coder_comment() and that will be used instead.
* See codex_coder_comment() in inc/template-tags.php for more.
*/
wp_list_comments( array( 'callback' => 'codex_coder_comment' ) );
?>
</ol><!-- .comment-list -->
<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?>
<nav id="comment-nav-below" class="comment-navigation" role="navigation">
<h1 class="screen-reader-text"><?php _e( 'Comment navigation', 'codex-coder' ); ?></h1>
<div class="nav-previous"><?php previous_comments_link( __( '← Older Comments', 'codex-coder' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( __( 'Newer Comments →', 'codex-coder' ) ); ?></div>
</nav><!-- #comment-nav-below -->
<?php endif; // check for comment navigation ?>
<?php endif; // have_comments() ?>
<?php
// If comments are closed and there are comments, let's leave a little note, shall we?
if ( ! comments_open() && '0' != get_comments_number() && post_type_supports( get_post_type(), 'comments' ) ) :
?>
<p class="no-comments"><?php _e( 'Comments are closed.', 'codex-coder' ); ?></p>
<?php endif; ?>
<?php comment_form(); ?>
</div><!-- #comments -->
|
gpl-2.0
|
ramonrdm/agendador
|
material/frontend/context_processors.py
|
618
|
from . import modules as modules_registry
def modules(request):
"""Add current module and modules list to the template context."""
if not hasattr(request, 'user'):
raise ValueError('modules context processor requires "django.contrib.auth.context_processors.auth"'
'to be in TEMPLATE_CONTEXT_PROCESSORS in your settings file.')
module = None
if request.resolver_match:
module = getattr(request.resolver_match.url_name, 'module', None)
return {
'modules': modules_registry.available_modules(request.user),
'current_module': module,
}
|
gpl-2.0
|
typeofb/SmartTongsin
|
adm/member_list_update.php
|
1128
|
<?
$sub_menu = "200100";
include_once("./_common.php");
check_demo();
auth_check($auth[$sub_menu], "w");
check_token();
for ($i=0; $i<count($chk); $i++)
{
// ์ค์ ๋ฒํธ๋ฅผ ๋๊น
$k = $_POST['chk'][$i];
$mb = get_member($_POST['mb_id'][$k]);
if (!$mb[mb_id]) {
$msg .= "$mb[mb_id] : ํ์์๋ฃ๊ฐ ์กด์ฌํ์ง ์์ต๋๋ค.\\n";
} else if ($is_admin != "super" && $mb[mb_level] >= $member[mb_level]) {
$msg .= "$mb[mb_id] : ์์ ๋ณด๋ค ๊ถํ์ด ๋๊ฑฐ๋ ๊ฐ์ ํ์์ ์์ ํ ์ ์์ต๋๋ค.\\n";
} else if ($member[mb_id] == $mb[mb_id]) {
$msg .= "$mb[mb_id] : ๋ก๊ทธ์ธ ์ค์ธ ๊ด๋ฆฌ์๋ ์์ ํ ์ ์์ต๋๋ค.\\n";
} else {
$sql = " update $g4[member_table]
set mb_level = '{$_POST['mb_level'][$k]}',
mb_intercept_date = '{$_POST['mb_intercept_date'][$k]}'
where mb_id = '{$_POST['mb_id'][$k]}' ";
sql_query($sql);
}
}
if ($msg)
echo "<script type='text/javascript'> alert('$msg'); </script>";
goto_url("./member_list.php?$qstr");
?>
|
gpl-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.