repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
haiyangxue/EasyTracker | src/com/pratra/easyshare/ui/horizontallistview/HorizontalListView.java | 10309 | package com.pratra.easyshare.ui.horizontallistview;
/*
* HorizontalListView.java v1.5
*
*
* The MIT License
* Copyright (c) 2011 Paul Soucy (paul@dev-smart.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import java.util.LinkedList;
import java.util.Queue;
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.Scroller;
public class HorizontalListView extends AdapterView<ListAdapter> {
public boolean mAlwaysOverrideTouch = true;
protected ListAdapter mAdapter;
private int mLeftViewIndex = -1;
private int mRightViewIndex = 0;
protected int mCurrentX;
protected int mNextX;
private int mMaxX = Integer.MAX_VALUE;
private int mDisplayOffset = 0;
protected Scroller mScroller;
private GestureDetector mGesture;
private Queue<View> mRemovedViewQueue = new LinkedList<View>();
private OnItemSelectedListener mOnItemSelected;
private OnItemClickListener mOnItemClicked;
private OnItemLongClickListener mOnItemLongClicked;
private boolean mDataChanged = false;
public HorizontalListView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
private synchronized void initView() {
mLeftViewIndex = -1;
mRightViewIndex = 0;
mDisplayOffset = 0;
mCurrentX = 0;
mNextX = 0;
mMaxX = Integer.MAX_VALUE;
mScroller = new Scroller(getContext());
mGesture = new GestureDetector(getContext(), mOnGesture);
}
@Override
public void setOnItemSelectedListener(
AdapterView.OnItemSelectedListener listener) {
mOnItemSelected = listener;
}
@Override
public void setOnItemClickListener(AdapterView.OnItemClickListener listener) {
mOnItemClicked = listener;
}
@Override
public void setOnItemLongClickListener(
AdapterView.OnItemLongClickListener listener) {
mOnItemLongClicked = listener;
}
private DataSetObserver mDataObserver = new DataSetObserver() {
@Override
public void onChanged() {
synchronized (HorizontalListView.this) {
mDataChanged = true;
}
invalidate();
requestLayout();
}
@Override
public void onInvalidated() {
reset();
invalidate();
requestLayout();
}
};
@Override
public ListAdapter getAdapter() {
return mAdapter;
}
@Override
public View getSelectedView() {
// TODO: implement
return null;
}
@Override
public void setAdapter(ListAdapter adapter) {
if (mAdapter != null) {
mAdapter.unregisterDataSetObserver(mDataObserver);
}
mAdapter = adapter;
mAdapter.registerDataSetObserver(mDataObserver);
reset();
}
private synchronized void reset() {
initView();
removeAllViewsInLayout();
requestLayout();
}
@Override
public void setSelection(int position) {
// TODO: implement
}
@SuppressWarnings("deprecation")
private void addAndMeasureChild(final View child, int viewPos) {
LayoutParams params = child.getLayoutParams();
if (params == null) {
params = new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
}
addViewInLayout(child, viewPos, params, true);
child.measure(
MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.AT_MOST),
MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.AT_MOST));
}
@SuppressLint("DrawAllocation")
@Override
protected synchronized void onLayout(boolean changed, int left, int top,
int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (mAdapter == null) {
return;
}
if (mDataChanged) {
int oldCurrentX = mCurrentX;
initView();
removeAllViewsInLayout();
mNextX = oldCurrentX;
mDataChanged = false;
}
if (mScroller.computeScrollOffset()) {
int scrollx = mScroller.getCurrX();
mNextX = scrollx;
}
if (mNextX <= 0) {
mNextX = 0;
mScroller.forceFinished(true);
}
if (mNextX >= mMaxX) {
mNextX = mMaxX;
mScroller.forceFinished(true);
}
int dx = mCurrentX - mNextX;
removeNonVisibleItems(dx);
fillList(dx);
positionItems(dx);
mCurrentX = mNextX;
if (!mScroller.isFinished()) {
post(new Runnable() {
@Override
public void run() {
requestLayout();
}
});
}
}
private void fillList(final int dx) {
int edge = 0;
View child = getChildAt(getChildCount() - 1);
if (child != null) {
edge = child.getRight();
}
fillListRight(edge, dx);
edge = 0;
child = getChildAt(0);
if (child != null) {
edge = child.getLeft();
}
fillListLeft(edge, dx);
}
private void fillListRight(int rightEdge, final int dx) {
while (rightEdge + dx < getWidth()
&& mRightViewIndex < mAdapter.getCount()) {
View child = mAdapter.getView(mRightViewIndex,
mRemovedViewQueue.poll(), this);
addAndMeasureChild(child, -1);
rightEdge += child.getMeasuredWidth();
if (mRightViewIndex == mAdapter.getCount() - 1) {
mMaxX = mCurrentX + rightEdge - getWidth();
}
if (mMaxX < 0) {
mMaxX = 0;
}
mRightViewIndex++;
}
}
private void fillListLeft(int leftEdge, final int dx) {
while (leftEdge + dx > 0 && mLeftViewIndex >= 0) {
View child = mAdapter.getView(mLeftViewIndex,
mRemovedViewQueue.poll(), this);
addAndMeasureChild(child, 0);
leftEdge -= child.getMeasuredWidth();
mLeftViewIndex--;
mDisplayOffset -= child.getMeasuredWidth();
}
}
private void removeNonVisibleItems(final int dx) {
View child = getChildAt(0);
while (child != null && child.getRight() + dx <= 0) {
mDisplayOffset += child.getMeasuredWidth();
mRemovedViewQueue.offer(child);
removeViewInLayout(child);
mLeftViewIndex++;
child = getChildAt(0);
}
child = getChildAt(getChildCount() - 1);
while (child != null && child.getLeft() + dx >= getWidth()) {
mRemovedViewQueue.offer(child);
removeViewInLayout(child);
mRightViewIndex--;
child = getChildAt(getChildCount() - 1);
}
}
private void positionItems(final int dx) {
if (getChildCount() > 0) {
mDisplayOffset += dx;
int left = mDisplayOffset;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
int childWidth = child.getMeasuredWidth();
child.layout(left, 0, left + childWidth,
child.getMeasuredHeight());
left += childWidth + child.getPaddingRight();
}
}
}
public synchronized void scrollTo(int x) {
mScroller.startScroll(mNextX, 0, x - mNextX, 0);
requestLayout();
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean handled = super.dispatchTouchEvent(ev);
handled |= mGesture.onTouchEvent(ev);
return handled;
}
protected boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
synchronized (HorizontalListView.this) {
mScroller.fling(mNextX, 0, (int) -velocityX, 0, 0, mMaxX, 0, 0);
}
requestLayout();
return true;
}
protected boolean onDown(MotionEvent e) {
mScroller.forceFinished(true);
return true;
}
private OnGestureListener mOnGesture = new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
return HorizontalListView.this.onDown(e);
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return HorizontalListView.this
.onFling(e1, e2, velocityX, velocityY);
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
synchronized (HorizontalListView.this) {
mNextX += (int) distanceX;
}
requestLayout();
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (isEventWithinView(e, child)) {
if (mOnItemClicked != null) {
mOnItemClicked.onItemClick(HorizontalListView.this,
child, mLeftViewIndex + 1 + i,
mAdapter.getItemId(mLeftViewIndex + 1 + i));
}
if (mOnItemSelected != null) {
mOnItemSelected.onItemSelected(HorizontalListView.this,
child, mLeftViewIndex + 1 + i,
mAdapter.getItemId(mLeftViewIndex + 1 + i));
}
break;
}
}
return true;
}
@Override
public void onLongPress(MotionEvent e) {
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
if (isEventWithinView(e, child)) {
if (mOnItemLongClicked != null) {
mOnItemLongClicked.onItemLongClick(
HorizontalListView.this, child, mLeftViewIndex
+ 1 + i,
mAdapter.getItemId(mLeftViewIndex + 1 + i));
}
break;
}
}
}
private boolean isEventWithinView(MotionEvent e, View child) {
Rect viewRect = new Rect();
int[] childPosition = new int[2];
child.getLocationOnScreen(childPosition);
int left = childPosition[0];
int right = left + child.getWidth();
int top = childPosition[1];
int bottom = top + child.getHeight();
viewRect.set(left, top, right, bottom);
return viewRect.contains((int) e.getRawX(), (int) e.getRawY());
}
};
}
| gpl-2.0 |
SIS-Team/SIS | mobile/app/js/iscroll.js | 33958 | /*!
* iScroll v4.2.5 ~ Copyright (c) 2012 Matteo Spinelli, http://cubiq.org
* Released under MIT license, http://cubiq.org/license
*/
(function(window, doc){
var m = Math,
dummyStyle = doc.createElement('div').style,
vendor = (function () {
var vendors = 't,webkitT,MozT,msT,OT'.split(','),
t,
i = 0,
l = vendors.length;
for ( ; i < l; i++ ) {
t = vendors[i] + 'ransform';
if ( t in dummyStyle ) {
return vendors[i].substr(0, vendors[i].length - 1);
}
}
return false;
})(),
cssVendor = vendor ? '-' + vendor.toLowerCase() + '-' : '',
// Style properties
transform = prefixStyle('transform'),
transitionProperty = prefixStyle('transitionProperty'),
transitionDuration = prefixStyle('transitionDuration'),
transformOrigin = prefixStyle('transformOrigin'),
transitionTimingFunction = prefixStyle('transitionTimingFunction'),
transitionDelay = prefixStyle('transitionDelay'),
// Browser capabilities
isAndroid = (/android/gi).test(navigator.appVersion),
isIDevice = (/iphone|ipad/gi).test(navigator.appVersion),
isTouchPad = (/hp-tablet/gi).test(navigator.appVersion),
has3d = prefixStyle('perspective') in dummyStyle,
hasTouch = 'ontouchstart' in window && !isTouchPad,
hasTransform = vendor !== false,
hasTransitionEnd = prefixStyle('transition') in dummyStyle,
RESIZE_EV = 'onorientationchange' in window ? 'orientationchange' : 'resize',
START_EV = hasTouch ? 'touchstart' : 'mousedown',
MOVE_EV = hasTouch ? 'touchmove' : 'mousemove',
END_EV = hasTouch ? 'touchend' : 'mouseup',
CANCEL_EV = hasTouch ? 'touchcancel' : 'mouseup',
TRNEND_EV = (function () {
if ( vendor === false ) return false;
var transitionEnd = {
'' : 'transitionend',
'webkit' : 'webkitTransitionEnd',
'Moz' : 'transitionend',
'O' : 'otransitionend',
'ms' : 'MSTransitionEnd'
};
return transitionEnd[vendor];
})(),
nextFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) { return setTimeout(callback, 1); };
})(),
cancelFrame = (function () {
return window.cancelRequestAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
clearTimeout;
})(),
// Helpers
translateZ = has3d ? ' translateZ(0)' : '',
// Constructor
iScroll = function (el, options) {
var that = this,
i;
that.wrapper = typeof el == 'object' ? el : doc.getElementById(el);
that.wrapper.style.overflow = 'hidden';
that.scroller = that.wrapper.children[0];
// Default options
that.options = {
hScroll: true,
vScroll: true,
x: 0,
y: 0,
bounce: true,
bounceLock: false,
momentum: true,
lockDirection: true,
useTransform: true,
useTransition: false,
topOffset: 0,
checkDOMChanges: false, // Experimental
handleClick: true,
// Scrollbar
hScrollbar: true,
vScrollbar: true,
fixedScrollbar: isAndroid,
hideScrollbar: isIDevice,
fadeScrollbar: isIDevice && has3d,
scrollbarClass: '',
// Zoom
zoom: true,
zoomMin: 1,
zoomMax: 4,
doubleTapZoom: 2,
wheelAction: 'scroll',
// Snap
snap: false,
snapThreshold: 1,
// Events
onRefresh: null,
onBeforeScrollStart: function (e) { e.preventDefault(); },
onScrollStart: null,
onBeforeScrollMove: null,
onScrollMove: null,
onBeforeScrollEnd: null,
onScrollEnd: null,
onTouchEnd: null,
onDestroy: null,
onZoomStart: null,
onZoom: null,
onZoomEnd: null
};
// User defined options
for (i in options) that.options[i] = options[i];
// Set starting position
that.x = that.options.x;
that.y = that.options.y;
// Normalize options
that.options.useTransform = hasTransform && that.options.useTransform;
that.options.hScrollbar = that.options.hScroll && that.options.hScrollbar;
that.options.vScrollbar = that.options.vScroll && that.options.vScrollbar;
that.options.zoom = that.options.useTransform && that.options.zoom;
that.options.useTransition = hasTransitionEnd && that.options.useTransition;
// Helpers FIX ANDROID BUG!
// translate3d and scale doesn't work together!
// Ignoring 3d ONLY WHEN YOU SET that.options.zoom
if ( that.options.zoom && isAndroid ){
translateZ = '';
}
// Set some default styles
that.scroller.style[transitionProperty] = that.options.useTransform ? cssVendor + 'transform' : 'top left';
that.scroller.style[transitionDuration] = '0';
that.scroller.style[transformOrigin] = '0 0';
if (that.options.useTransition) that.scroller.style[transitionTimingFunction] = 'cubic-bezier(0.33,0.66,0.66,1)';
if (that.options.useTransform) that.scroller.style[transform] = 'translate(' + that.x + 'px,' + that.y + 'px)' + translateZ;
else that.scroller.style.cssText += ';position:absolute;top:' + that.y + 'px;left:' + that.x + 'px';
if (that.options.useTransition) that.options.fixedScrollbar = true;
that.refresh();
that._bind(RESIZE_EV, window);
that._bind(START_EV);
if (!hasTouch) {
if (that.options.wheelAction != 'none') {
that._bind('DOMMouseScroll');
that._bind('mousewheel');
}
}
if (that.options.checkDOMChanges) that.checkDOMTime = setInterval(function () {
that._checkDOMChanges();
}, 500);
};
// Prototype
iScroll.prototype = {
enabled: true,
x: 0,
y: 0,
steps: [],
scale: 1,
currPageX: 0, currPageY: 0,
pagesX: [], pagesY: [],
aniTime: null,
wheelZoomCount: 0,
handleEvent: function (e) {
var that = this;
switch(e.type) {
case START_EV:
if (!hasTouch && e.button !== 0) return;
that._start(e);
break;
case MOVE_EV: that._move(e); break;
case END_EV:
case CANCEL_EV: that._end(e); break;
case RESIZE_EV: that._resize(); break;
case 'DOMMouseScroll': case 'mousewheel': that._wheel(e); break;
case TRNEND_EV: that._transitionEnd(e); break;
}
},
_checkDOMChanges: function () {
if (this.moved || this.zoomed || this.animating ||
(this.scrollerW == this.scroller.offsetWidth * this.scale && this.scrollerH == this.scroller.offsetHeight * this.scale)) return;
this.refresh();
},
_scrollbar: function (dir) {
var that = this,
bar;
if (!that[dir + 'Scrollbar']) {
if (that[dir + 'ScrollbarWrapper']) {
if (hasTransform) that[dir + 'ScrollbarIndicator'].style[transform] = '';
that[dir + 'ScrollbarWrapper'].parentNode.removeChild(that[dir + 'ScrollbarWrapper']);
that[dir + 'ScrollbarWrapper'] = null;
that[dir + 'ScrollbarIndicator'] = null;
}
return;
}
if (!that[dir + 'ScrollbarWrapper']) {
// Create the scrollbar wrapper
bar = doc.createElement('div');
if (that.options.scrollbarClass) bar.className = that.options.scrollbarClass + dir.toUpperCase();
else bar.style.cssText = 'position:absolute;z-index:100;' + (dir == 'h' ? 'height:7px;bottom:1px;left:2px;right:' + (that.vScrollbar ? '7' : '2') + 'px' : 'width:7px;bottom:' + (that.hScrollbar ? '7' : '2') + 'px;top:2px;right:1px');
bar.style.cssText += ';pointer-events:none;' + cssVendor + 'transition-property:opacity;' + cssVendor + 'transition-duration:' + (that.options.fadeScrollbar ? '350ms' : '0') + ';overflow:hidden;opacity:' + (that.options.hideScrollbar ? '0' : '1');
that.wrapper.appendChild(bar);
that[dir + 'ScrollbarWrapper'] = bar;
// Create the scrollbar indicator
bar = doc.createElement('div');
if (!that.options.scrollbarClass) {
bar.style.cssText = 'position:absolute;z-index:100;background:rgba(0,0,0,0.5);border:1px solid rgba(255,255,255,0.9);' + cssVendor + 'background-clip:padding-box;' + cssVendor + 'box-sizing:border-box;' + (dir == 'h' ? 'height:100%' : 'width:100%') + ';' + cssVendor + 'border-radius:3px;border-radius:3px';
}
bar.style.cssText += ';pointer-events:none;' + cssVendor + 'transition-property:' + cssVendor + 'transform;' + cssVendor + 'transition-timing-function:cubic-bezier(0.33,0.66,0.66,1);' + cssVendor + 'transition-duration:0;' + cssVendor + 'transform: translate(0,0)' + translateZ;
if (that.options.useTransition) bar.style.cssText += ';' + cssVendor + 'transition-timing-function:cubic-bezier(0.33,0.66,0.66,1)';
that[dir + 'ScrollbarWrapper'].appendChild(bar);
that[dir + 'ScrollbarIndicator'] = bar;
}
if (dir == 'h') {
that.hScrollbarSize = that.hScrollbarWrapper.clientWidth;
that.hScrollbarIndicatorSize = m.max(m.round(that.hScrollbarSize * that.hScrollbarSize / that.scrollerW), 8);
that.hScrollbarIndicator.style.width = that.hScrollbarIndicatorSize + 'px';
that.hScrollbarMaxScroll = that.hScrollbarSize - that.hScrollbarIndicatorSize;
that.hScrollbarProp = that.hScrollbarMaxScroll / that.maxScrollX;
} else {
that.vScrollbarSize = that.vScrollbarWrapper.clientHeight;
that.vScrollbarIndicatorSize = m.max(m.round(that.vScrollbarSize * that.vScrollbarSize / that.scrollerH), 8);
that.vScrollbarIndicator.style.height = that.vScrollbarIndicatorSize + 'px';
that.vScrollbarMaxScroll = that.vScrollbarSize - that.vScrollbarIndicatorSize;
that.vScrollbarProp = that.vScrollbarMaxScroll / that.maxScrollY;
}
// Reset position
that._scrollbarPos(dir, true);
},
_resize: function () {
var that = this;
setTimeout(function () { that.refresh(); }, isAndroid ? 200 : 0);
},
_pos: function (x, y) {
if (this.zoomed) return;
x = this.hScroll ? x : 0;
y = this.vScroll ? y : 0;
if (this.options.useTransform) {
this.scroller.style[transform] = 'translate(' + x + 'px,' + y + 'px) scale(' + this.scale + ')' + translateZ;
} else {
x = m.round(x);
y = m.round(y);
this.scroller.style.left = x + 'px';
this.scroller.style.top = y + 'px';
}
this.x = x;
this.y = y;
this._scrollbarPos('h');
this._scrollbarPos('v');
},
_scrollbarPos: function (dir, hidden) {
var that = this,
pos = dir == 'h' ? that.x : that.y,
size;
if (!that[dir + 'Scrollbar']) return;
pos = that[dir + 'ScrollbarProp'] * pos;
if (pos < 0) {
if (!that.options.fixedScrollbar) {
size = that[dir + 'ScrollbarIndicatorSize'] + m.round(pos * 3);
if (size < 8) size = 8;
that[dir + 'ScrollbarIndicator'].style[dir == 'h' ? 'width' : 'height'] = size + 'px';
}
pos = 0;
} else if (pos > that[dir + 'ScrollbarMaxScroll']) {
if (!that.options.fixedScrollbar) {
size = that[dir + 'ScrollbarIndicatorSize'] - m.round((pos - that[dir + 'ScrollbarMaxScroll']) * 3);
if (size < 8) size = 8;
that[dir + 'ScrollbarIndicator'].style[dir == 'h' ? 'width' : 'height'] = size + 'px';
pos = that[dir + 'ScrollbarMaxScroll'] + (that[dir + 'ScrollbarIndicatorSize'] - size);
} else {
pos = that[dir + 'ScrollbarMaxScroll'];
}
}
that[dir + 'ScrollbarWrapper'].style[transitionDelay] = '0';
that[dir + 'ScrollbarWrapper'].style.opacity = hidden && that.options.hideScrollbar ? '0' : '1';
that[dir + 'ScrollbarIndicator'].style[transform] = 'translate(' + (dir == 'h' ? pos + 'px,0)' : '0,' + pos + 'px)') + translateZ;
},
_start: function (e) {
var that = this,
point = hasTouch ? e.touches[0] : e,
matrix, x, y,
c1, c2;
if (!that.enabled) return;
if (that.options.onBeforeScrollStart) that.options.onBeforeScrollStart.call(that, e);
if (that.options.useTransition || that.options.zoom) that._transitionTime(0);
that.moved = false;
that.animating = false;
that.zoomed = false;
that.distX = 0;
that.distY = 0;
that.absDistX = 0;
that.absDistY = 0;
that.dirX = 0;
that.dirY = 0;
// Gesture start
if (that.options.zoom && hasTouch && e.touches.length > 1) {
c1 = m.abs(e.touches[0].pageX-e.touches[1].pageX);
c2 = m.abs(e.touches[0].pageY-e.touches[1].pageY);
that.touchesDistStart = m.sqrt(c1 * c1 + c2 * c2);
that.originX = m.abs(e.touches[0].pageX + e.touches[1].pageX - that.wrapperOffsetLeft * 2) / 2 - that.x;
that.originY = m.abs(e.touches[0].pageY + e.touches[1].pageY - that.wrapperOffsetTop * 2) / 2 - that.y;
if (that.options.onZoomStart) that.options.onZoomStart.call(that, e);
}
if (that.options.momentum) {
if (that.options.useTransform) {
// Very lame general purpose alternative to CSSMatrix
matrix = getComputedStyle(that.scroller, null)[transform].replace(/[^0-9\-.,]/g, '').split(',');
x = +(matrix[12] || matrix[4]);
y = +(matrix[13] || matrix[5]);
} else {
x = +getComputedStyle(that.scroller, null).left.replace(/[^0-9-]/g, '');
y = +getComputedStyle(that.scroller, null).top.replace(/[^0-9-]/g, '');
}
if (x != that.x || y != that.y) {
if (that.options.useTransition) that._unbind(TRNEND_EV);
else cancelFrame(that.aniTime);
that.steps = [];
that._pos(x, y);
if (that.options.onScrollEnd) that.options.onScrollEnd.call(that);
}
}
that.absStartX = that.x; // Needed by snap threshold
that.absStartY = that.y;
that.startX = that.x;
that.startY = that.y;
that.pointX = point.pageX;
that.pointY = point.pageY;
that.startTime = e.timeStamp || Date.now();
if (that.options.onScrollStart) that.options.onScrollStart.call(that, e);
that._bind(MOVE_EV, window);
that._bind(END_EV, window);
that._bind(CANCEL_EV, window);
},
_move: function (e) {
var that = this,
point = hasTouch ? e.touches[0] : e,
deltaX = point.pageX - that.pointX,
deltaY = point.pageY - that.pointY,
newX = that.x + deltaX,
newY = that.y + deltaY,
c1, c2, scale,
timestamp = e.timeStamp || Date.now();
if (that.options.onBeforeScrollMove) that.options.onBeforeScrollMove.call(that, e);
// Zoom
if (that.options.zoom && hasTouch && e.touches.length > 1) {
c1 = m.abs(e.touches[0].pageX - e.touches[1].pageX);
c2 = m.abs(e.touches[0].pageY - e.touches[1].pageY);
that.touchesDist = m.sqrt(c1*c1+c2*c2);
that.zoomed = true;
scale = 1 / that.touchesDistStart * that.touchesDist * this.scale;
if (scale < that.options.zoomMin) scale = 0.5 * that.options.zoomMin * Math.pow(2.0, scale / that.options.zoomMin);
else if (scale > that.options.zoomMax) scale = 2.0 * that.options.zoomMax * Math.pow(0.5, that.options.zoomMax / scale);
that.lastScale = scale / this.scale;
newX = this.originX - this.originX * that.lastScale + this.x;
newY = this.originY - this.originY * that.lastScale + this.y;
this.scroller.style[transform] = 'translate(' + newX + 'px,' + newY + 'px) scale(' + scale + ')' + translateZ;
if (that.options.onZoom) that.options.onZoom.call(that, e);
return;
}
that.pointX = point.pageX;
that.pointY = point.pageY;
// Slow down if outside of the boundaries
if (newX > 0 || newX < that.maxScrollX) {
newX = that.options.bounce ? that.x + (deltaX / 2) : newX >= 0 || that.maxScrollX >= 0 ? 0 : that.maxScrollX;
}
if (newY > that.minScrollY || newY < that.maxScrollY) {
newY = that.options.bounce ? that.y + (deltaY / 2) : newY >= that.minScrollY || that.maxScrollY >= 0 ? that.minScrollY : that.maxScrollY;
}
that.distX += deltaX;
that.distY += deltaY;
that.absDistX = m.abs(that.distX);
that.absDistY = m.abs(that.distY);
if (that.absDistX < 6 && that.absDistY < 6) {
return;
}
// Lock direction
if (that.options.lockDirection) {
if (that.absDistX > that.absDistY + 5) {
newY = that.y;
deltaY = 0;
} else if (that.absDistY > that.absDistX + 5) {
newX = that.x;
deltaX = 0;
}
}
that.moved = true;
that._pos(newX, newY);
that.dirX = deltaX > 0 ? -1 : deltaX < 0 ? 1 : 0;
that.dirY = deltaY > 0 ? -1 : deltaY < 0 ? 1 : 0;
if (timestamp - that.startTime > 300) {
that.startTime = timestamp;
that.startX = that.x;
that.startY = that.y;
}
if (that.options.onScrollMove) that.options.onScrollMove.call(that, e);
},
_end: function (e) {
if (hasTouch && e.touches.length !== 0) return;
var that = this,
point = hasTouch ? e.changedTouches[0] : e,
target, ev,
momentumX = { dist:0, time:0 },
momentumY = { dist:0, time:0 },
duration = (e.timeStamp || Date.now()) - that.startTime,
newPosX = that.x,
newPosY = that.y,
distX, distY,
newDuration,
snap,
scale;
that._unbind(MOVE_EV, window);
that._unbind(END_EV, window);
that._unbind(CANCEL_EV, window);
if (that.options.onBeforeScrollEnd) that.options.onBeforeScrollEnd.call(that, e);
if (that.zoomed) {
scale = that.scale * that.lastScale;
scale = Math.max(that.options.zoomMin, scale);
scale = Math.min(that.options.zoomMax, scale);
that.lastScale = scale / that.scale;
that.scale = scale;
that.x = that.originX - that.originX * that.lastScale + that.x;
that.y = that.originY - that.originY * that.lastScale + that.y;
that.scroller.style[transitionDuration] = '200ms';
that.scroller.style[transform] = 'translate(' + that.x + 'px,' + that.y + 'px) scale(' + that.scale + ')' + translateZ;
that.zoomed = false;
that.refresh();
if (that.options.onZoomEnd) that.options.onZoomEnd.call(that, e);
return;
}
if (!that.moved) {
if (hasTouch) {
if (that.doubleTapTimer && that.options.zoom) {
// Double tapped
clearTimeout(that.doubleTapTimer);
that.doubleTapTimer = null;
if (that.options.onZoomStart) that.options.onZoomStart.call(that, e);
that.zoom(that.pointX, that.pointY, that.scale == 1 ? that.options.doubleTapZoom : 1);
if (that.options.onZoomEnd) {
setTimeout(function() {
that.options.onZoomEnd.call(that, e);
}, 200); // 200 is default zoom duration
}
} else if (this.options.handleClick) {
that.doubleTapTimer = setTimeout(function () {
that.doubleTapTimer = null;
// Find the last touched element
target = point.target;
while (target.nodeType != 1) target = target.parentNode;
if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA') {
ev = doc.createEvent('MouseEvents');
ev.initMouseEvent('click', true, true, e.view, 1,
point.screenX, point.screenY, point.clientX, point.clientY,
e.ctrlKey, e.altKey, e.shiftKey, e.metaKey,
0, null);
ev._fake = true;
target.dispatchEvent(ev);
}
}, that.options.zoom ? 250 : 0);
}
}
that._resetPos(400);
if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
return;
}
if (duration < 300 && that.options.momentum) {
momentumX = newPosX ? that._momentum(newPosX - that.startX, duration, -that.x, that.scrollerW - that.wrapperW + that.x, that.options.bounce ? that.wrapperW : 0) : momentumX;
momentumY = newPosY ? that._momentum(newPosY - that.startY, duration, -that.y, (that.maxScrollY < 0 ? that.scrollerH - that.wrapperH + that.y - that.minScrollY : 0), that.options.bounce ? that.wrapperH : 0) : momentumY;
newPosX = that.x + momentumX.dist;
newPosY = that.y + momentumY.dist;
if ((that.x > 0 && newPosX > 0) || (that.x < that.maxScrollX && newPosX < that.maxScrollX)) momentumX = { dist:0, time:0 };
if ((that.y > that.minScrollY && newPosY > that.minScrollY) || (that.y < that.maxScrollY && newPosY < that.maxScrollY)) momentumY = { dist:0, time:0 };
}
if (momentumX.dist || momentumY.dist) {
newDuration = m.max(m.max(momentumX.time, momentumY.time), 10);
// Do we need to snap?
if (that.options.snap) {
distX = newPosX - that.absStartX;
distY = newPosY - that.absStartY;
if (m.abs(distX) < that.options.snapThreshold && m.abs(distY) < that.options.snapThreshold) { that.scrollTo(that.absStartX, that.absStartY, 200); }
else {
snap = that._snap(newPosX, newPosY);
newPosX = snap.x;
newPosY = snap.y;
newDuration = m.max(snap.time, newDuration);
}
}
that.scrollTo(m.round(newPosX), m.round(newPosY), newDuration);
if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
return;
}
// Do we need to snap?
if (that.options.snap) {
distX = newPosX - that.absStartX;
distY = newPosY - that.absStartY;
if (m.abs(distX) < that.options.snapThreshold && m.abs(distY) < that.options.snapThreshold) that.scrollTo(that.absStartX, that.absStartY, 200);
else {
snap = that._snap(that.x, that.y);
if (snap.x != that.x || snap.y != that.y) that.scrollTo(snap.x, snap.y, snap.time);
}
if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
return;
}
that._resetPos(200);
if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
},
_resetPos: function (time) {
var that = this,
resetX = that.x >= 0 ? 0 : that.x < that.maxScrollX ? that.maxScrollX : that.x,
resetY = that.y >= that.minScrollY || that.maxScrollY > 0 ? that.minScrollY : that.y < that.maxScrollY ? that.maxScrollY : that.y;
if (resetX == that.x && resetY == that.y) {
if (that.moved) {
that.moved = false;
if (that.options.onScrollEnd) that.options.onScrollEnd.call(that); // Execute custom code on scroll end
}
if (that.hScrollbar && that.options.hideScrollbar) {
if (vendor == 'webkit') that.hScrollbarWrapper.style[transitionDelay] = '300ms';
that.hScrollbarWrapper.style.opacity = '0';
}
if (that.vScrollbar && that.options.hideScrollbar) {
if (vendor == 'webkit') that.vScrollbarWrapper.style[transitionDelay] = '300ms';
that.vScrollbarWrapper.style.opacity = '0';
}
return;
}
that.scrollTo(resetX, resetY, time || 0);
},
_wheel: function (e) {
var that = this,
wheelDeltaX, wheelDeltaY,
deltaX, deltaY,
deltaScale;
if ('wheelDeltaX' in e) {
wheelDeltaX = e.wheelDeltaX / 12;
wheelDeltaY = e.wheelDeltaY / 12;
} else if('wheelDelta' in e) {
wheelDeltaX = wheelDeltaY = e.wheelDelta / 12;
} else if ('detail' in e) {
wheelDeltaX = wheelDeltaY = -e.detail * 3;
} else {
return;
}
if (that.options.wheelAction == 'zoom') {
deltaScale = that.scale * Math.pow(2, 1/3 * (wheelDeltaY ? wheelDeltaY / Math.abs(wheelDeltaY) : 0));
if (deltaScale < that.options.zoomMin) deltaScale = that.options.zoomMin;
if (deltaScale > that.options.zoomMax) deltaScale = that.options.zoomMax;
if (deltaScale != that.scale) {
if (!that.wheelZoomCount && that.options.onZoomStart) that.options.onZoomStart.call(that, e);
that.wheelZoomCount++;
that.zoom(e.pageX, e.pageY, deltaScale, 400);
setTimeout(function() {
that.wheelZoomCount--;
if (!that.wheelZoomCount && that.options.onZoomEnd) that.options.onZoomEnd.call(that, e);
}, 400);
}
return;
}
deltaX = that.x + wheelDeltaX;
deltaY = that.y + wheelDeltaY;
if (deltaX > 0) deltaX = 0;
else if (deltaX < that.maxScrollX) deltaX = that.maxScrollX;
if (deltaY > that.minScrollY) deltaY = that.minScrollY;
else if (deltaY < that.maxScrollY) deltaY = that.maxScrollY;
if (that.maxScrollY < 0) {
that.scrollTo(deltaX, deltaY, 0);
}
},
_transitionEnd: function (e) {
var that = this;
if (e.target != that.scroller) return;
that._unbind(TRNEND_EV);
that._startAni();
},
/**
*
* Utilities
*
*/
_startAni: function () {
var that = this,
startX = that.x, startY = that.y,
startTime = Date.now(),
step, easeOut,
animate;
if (that.animating) return;
if (!that.steps.length) {
that._resetPos(400);
return;
}
step = that.steps.shift();
if (step.x == startX && step.y == startY) step.time = 0;
that.animating = true;
that.moved = true;
if (that.options.useTransition) {
that._transitionTime(step.time);
that._pos(step.x, step.y);
that.animating = false;
if (step.time) that._bind(TRNEND_EV);
else that._resetPos(0);
return;
}
animate = function () {
var now = Date.now(),
newX, newY;
if (now >= startTime + step.time) {
that._pos(step.x, step.y);
that.animating = false;
if (that.options.onAnimationEnd) that.options.onAnimationEnd.call(that); // Execute custom code on animation end
that._startAni();
return;
}
now = (now - startTime) / step.time - 1;
easeOut = m.sqrt(1 - now * now);
newX = (step.x - startX) * easeOut + startX;
newY = (step.y - startY) * easeOut + startY;
that._pos(newX, newY);
if (that.animating) that.aniTime = nextFrame(animate);
};
animate();
},
_transitionTime: function (time) {
time += 'ms';
this.scroller.style[transitionDuration] = time;
if (this.hScrollbar) this.hScrollbarIndicator.style[transitionDuration] = time;
if (this.vScrollbar) this.vScrollbarIndicator.style[transitionDuration] = time;
},
_momentum: function (dist, time, maxDistUpper, maxDistLower, size) {
var deceleration = 0.0006,
speed = m.abs(dist) / time,
newDist = (speed * speed) / (2 * deceleration),
newTime = 0, outsideDist = 0;
// Proportinally reduce speed if we are outside of the boundaries
if (dist > 0 && newDist > maxDistUpper) {
outsideDist = size / (6 / (newDist / speed * deceleration));
maxDistUpper = maxDistUpper + outsideDist;
speed = speed * maxDistUpper / newDist;
newDist = maxDistUpper;
} else if (dist < 0 && newDist > maxDistLower) {
outsideDist = size / (6 / (newDist / speed * deceleration));
maxDistLower = maxDistLower + outsideDist;
speed = speed * maxDistLower / newDist;
newDist = maxDistLower;
}
newDist = newDist * (dist < 0 ? -1 : 1);
newTime = speed / deceleration;
return { dist: newDist, time: m.round(newTime) };
},
_offset: function (el) {
var left = -el.offsetLeft,
top = -el.offsetTop;
while (el = el.offsetParent) {
left -= el.offsetLeft;
top -= el.offsetTop;
}
if (el != this.wrapper) {
left *= this.scale;
top *= this.scale;
}
return { left: left, top: top };
},
_snap: function (x, y) {
var that = this,
i, l,
page, time,
sizeX, sizeY;
// Check page X
page = that.pagesX.length - 1;
for (i=0, l=that.pagesX.length; i<l; i++) {
if (x >= that.pagesX[i]) {
page = i;
break;
}
}
if (page == that.currPageX && page > 0 && that.dirX < 0) page--;
x = that.pagesX[page];
sizeX = m.abs(x - that.pagesX[that.currPageX]);
sizeX = sizeX ? m.abs(that.x - x) / sizeX * 500 : 0;
that.currPageX = page;
// Check page Y
page = that.pagesY.length-1;
for (i=0; i<page; i++) {
if (y >= that.pagesY[i]) {
page = i;
break;
}
}
if (page == that.currPageY && page > 0 && that.dirY < 0) page--;
y = that.pagesY[page];
sizeY = m.abs(y - that.pagesY[that.currPageY]);
sizeY = sizeY ? m.abs(that.y - y) / sizeY * 500 : 0;
that.currPageY = page;
// Snap with constant speed (proportional duration)
time = m.round(m.max(sizeX, sizeY)) || 200;
return { x: x, y: y, time: time };
},
_bind: function (type, el, bubble) {
(el || this.scroller).addEventListener(type, this, !!bubble);
},
_unbind: function (type, el, bubble) {
(el || this.scroller).removeEventListener(type, this, !!bubble);
},
/**
*
* Public methods
*
*/
destroy: function () {
var that = this;
that.scroller.style[transform] = '';
// Remove the scrollbars
that.hScrollbar = false;
that.vScrollbar = false;
that._scrollbar('h');
that._scrollbar('v');
// Remove the event listeners
that._unbind(RESIZE_EV, window);
that._unbind(START_EV);
that._unbind(MOVE_EV, window);
that._unbind(END_EV, window);
that._unbind(CANCEL_EV, window);
if (!that.options.hasTouch) {
that._unbind('DOMMouseScroll');
that._unbind('mousewheel');
}
if (that.options.useTransition) that._unbind(TRNEND_EV);
if (that.options.checkDOMChanges) clearInterval(that.checkDOMTime);
if (that.options.onDestroy) that.options.onDestroy.call(that);
},
refresh: function () {
var that = this,
offset,
i, l,
els,
pos = 0,
page = 0;
if (that.scale < that.options.zoomMin) that.scale = that.options.zoomMin;
that.wrapperW = that.wrapper.clientWidth || 1;
that.wrapperH = that.wrapper.clientHeight || 1;
that.minScrollY = -that.options.topOffset || 0;
that.scrollerW = m.round(that.scroller.offsetWidth * that.scale);
that.scrollerH = m.round((that.scroller.offsetHeight + that.minScrollY) * that.scale);
that.maxScrollX = that.wrapperW - that.scrollerW;
that.maxScrollY = that.wrapperH - that.scrollerH + that.minScrollY;
that.dirX = 0;
that.dirY = 0;
if (that.options.onRefresh) that.options.onRefresh.call(that);
that.hScroll = that.options.hScroll && that.maxScrollX < 0;
that.vScroll = that.options.vScroll && (!that.options.bounceLock && !that.hScroll || that.scrollerH > that.wrapperH);
that.hScrollbar = that.hScroll && that.options.hScrollbar;
that.vScrollbar = that.vScroll && that.options.vScrollbar && that.scrollerH > that.wrapperH;
offset = that._offset(that.wrapper);
that.wrapperOffsetLeft = -offset.left;
that.wrapperOffsetTop = -offset.top;
// Prepare snap
if (typeof that.options.snap == 'string') {
that.pagesX = [];
that.pagesY = [];
els = that.scroller.querySelectorAll(that.options.snap);
for (i=0, l=els.length; i<l; i++) {
pos = that._offset(els[i]);
pos.left += that.wrapperOffsetLeft;
pos.top += that.wrapperOffsetTop;
that.pagesX[i] = pos.left < that.maxScrollX ? that.maxScrollX : pos.left * that.scale;
that.pagesY[i] = pos.top < that.maxScrollY ? that.maxScrollY : pos.top * that.scale;
}
} else if (that.options.snap) {
that.pagesX = [];
while (pos >= that.maxScrollX) {
that.pagesX[page] = pos;
pos = pos - that.wrapperW;
page++;
}
if (that.maxScrollX%that.wrapperW) that.pagesX[that.pagesX.length] = that.maxScrollX - that.pagesX[that.pagesX.length-1] + that.pagesX[that.pagesX.length-1];
pos = 0;
page = 0;
that.pagesY = [];
while (pos >= that.maxScrollY) {
that.pagesY[page] = pos;
pos = pos - that.wrapperH;
page++;
}
if (that.maxScrollY%that.wrapperH) that.pagesY[that.pagesY.length] = that.maxScrollY - that.pagesY[that.pagesY.length-1] + that.pagesY[that.pagesY.length-1];
}
// Prepare the scrollbars
that._scrollbar('h');
that._scrollbar('v');
if (!that.zoomed) {
that.scroller.style[transitionDuration] = '0';
that._resetPos(400);
}
},
scrollTo: function (x, y, time, relative) {
var that = this,
step = x,
i, l;
that.stop();
if (!step.length) step = [{ x: x, y: y, time: time, relative: relative }];
for (i=0, l=step.length; i<l; i++) {
if (step[i].relative) { step[i].x = that.x - step[i].x; step[i].y = that.y - step[i].y; }
that.steps.push({ x: step[i].x, y: step[i].y, time: step[i].time || 0 });
}
that._startAni();
},
scrollToElement: function (el, time) {
var that = this, pos;
el = el.nodeType ? el : that.scroller.querySelector(el);
if (!el) return;
pos = that._offset(el);
pos.left += that.wrapperOffsetLeft;
pos.top += that.wrapperOffsetTop;
pos.left = pos.left > 0 ? 0 : pos.left < that.maxScrollX ? that.maxScrollX : pos.left;
pos.top = pos.top > that.minScrollY ? that.minScrollY : pos.top < that.maxScrollY ? that.maxScrollY : pos.top;
time = time === undefined ? m.max(m.abs(pos.left)*2, m.abs(pos.top)*2) : time;
that.scrollTo(pos.left, pos.top, time);
},
scrollToPage: function (pageX, pageY, time) {
var that = this, x, y;
time = time === undefined ? 400 : time;
if (that.options.onScrollStart) that.options.onScrollStart.call(that);
if (that.options.snap) {
pageX = pageX == 'next' ? that.currPageX+1 : pageX == 'prev' ? that.currPageX-1 : pageX;
pageY = pageY == 'next' ? that.currPageY+1 : pageY == 'prev' ? that.currPageY-1 : pageY;
pageX = pageX < 0 ? 0 : pageX > that.pagesX.length-1 ? that.pagesX.length-1 : pageX;
pageY = pageY < 0 ? 0 : pageY > that.pagesY.length-1 ? that.pagesY.length-1 : pageY;
that.currPageX = pageX;
that.currPageY = pageY;
x = that.pagesX[pageX];
y = that.pagesY[pageY];
} else {
x = -that.wrapperW * pageX;
y = -that.wrapperH * pageY;
if (x < that.maxScrollX) x = that.maxScrollX;
if (y < that.maxScrollY) y = that.maxScrollY;
}
that.scrollTo(x, y, time);
},
disable: function () {
this.stop();
this._resetPos(0);
this.enabled = false;
// If disabled after touchstart we make sure that there are no left over events
this._unbind(MOVE_EV, window);
this._unbind(END_EV, window);
this._unbind(CANCEL_EV, window);
},
enable: function () {
this.enabled = true;
},
stop: function () {
if (this.options.useTransition) this._unbind(TRNEND_EV);
else cancelFrame(this.aniTime);
this.steps = [];
this.moved = false;
this.animating = false;
},
zoom: function (x, y, scale, time) {
var that = this,
relScale = scale / that.scale;
if (!that.options.useTransform) return;
that.zoomed = true;
time = time === undefined ? 200 : time;
x = x - that.wrapperOffsetLeft - that.x;
y = y - that.wrapperOffsetTop - that.y;
that.x = x - x * relScale + that.x;
that.y = y - y * relScale + that.y;
that.scale = scale;
that.refresh();
that.x = that.x > 0 ? 0 : that.x < that.maxScrollX ? that.maxScrollX : that.x;
that.y = that.y > that.minScrollY ? that.minScrollY : that.y < that.maxScrollY ? that.maxScrollY : that.y;
that.scroller.style[transitionDuration] = time + 'ms';
that.scroller.style[transform] = 'translate(' + that.x + 'px,' + that.y + 'px) scale(' + scale + ')' + translateZ;
that.zoomed = false;
},
isReady: function () {
return !this.moved && !this.zoomed && !this.animating;
}
};
function prefixStyle (style) {
if ( vendor === '' ) return style;
style = style.charAt(0).toUpperCase() + style.substr(1);
return vendor + style;
}
dummyStyle = null; // for the sake of it
if (typeof exports !== 'undefined') exports.iScroll = iScroll;
else window.iScroll = iScroll;
})(window, document);
| gpl-2.0 |
IgnacioBriones/Web-Informatica | webinfo/application/views/funcionarios/body_omar.php | 5026 | <!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<body id="page4">
<!-- header -->
<header>
<div class="row-top">
<div class="main">
<div class="container_12">
<div class="wrapper">
<div class="grid_9">
<h1>
<a class="logo" href="<?= base_url(); ?>">family center</a>
</h1>
</div>
<div class="grid_3">
<form id="search-form" method="post" enctype="multipart/form-data">
<fieldset>
<div class="search-field">
<input name="search" type="text" value="Search" onFocus="if (this.value == 'Search') {
this.value = ''
}" onBlur="if (this.value == '') {
this.value = 'Search'
}" />
</div>
<a class="search-button" href="#" onClick="document.getElementById('search-form').submit()"><span>search</span></a>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="row-bot">
<div class="row-bot-shadow">
<div class="main">
<div class="container_12">
<div class="grid_12">
<nav>
<ul class="menu">
<li><a href="<?= base_url(); ?>">Inicio</a><strong></strong></li>
<li class="active"><a href="<?= base_url() . "index.php/academicos"; ?>">Funcionarios</a><strong></strong></li>
<li><a href="<?= base_url() . "index.php/estudiante"; ?>">Estudiantes</a><strong></strong></li>
<li><a href="<?= base_url() . "index.php/laboral"; ?>">Laboral</a><strong></strong></li>
<li><a href="<?= base_url() . "index.php/noticia"; ?>">Noticias</a><strong></strong></li>
<li class="last"><a href="<?= base_url() . "index.php/contacto"; ?>">Contactos</a><strong></strong></li>
</ul>
</nav>
</div>
<div class="clear"></div>
</div>
</div>
</div>
</div>
</header><div class="ic">More Website Templates @ TemplateMonster.com - August 15th 2011!</div>
<!-- content -->
<section id="content">
<div class="main">
<div class="container_12">
<div class="border-bot margin-bot">
<article class="grid_12">
<div class="aligncenter inner-top">
<strong class="title-1">"Cuerpo Laboral"</strong>
<strong class="title-2">A lo largo de su desarrollo, la Unidad de Informatica,que se ha nutrido de un grupo de profesionales, han enriquecido la formacion de nuestros estudiantes con el apoyo de
nuestros funcionarios de laboratorio, academicos y secretarias.</strong>
</div>
</article>
<div class="clear"></div>
</div>
<div class="wrapper">
<article class="grid_6">
<h2 class="indent-bot">Nuestro equipo</h2>
<div class="wrapper img-indent-bot">
<figure class="img-indent"><img src="<?= base_url() . "images/ovillalobos.jpg" ?>" alt="" /></figure>
<div class="extra-wrap">
<h6 class="reg p0"><a class="link" href="#">Omar Villalobos</a></h6>
<p><strong>Director de Escuela </p></strong>
Teléfono: 78 77 100
Email: ovillalobos@utem.cl <br>
<br><h6 class="reg p0"><a class="link" href="#"></a></h6>
</div>
</div>
</div>
</div>
| gpl-2.0 |
superferg/20-Proof | CardGamesServer/TradeIn.cs | 9996 | using System;
using System.Collections.Generic;
using System.Linq;
using PlayingCards;
using System.Threading;
using System.Text.RegularExpressions;
namespace CardGamesServer
{
partial class MainForm
{
int[] TradeInCount = new int[2];
bool TrumpRound1 = false;
public void PlayTradeIn()
{
switch(TurnIndex)
{
case 0:
BroadcastAll(msg_SETMYHAND, SERVER, FacingSides.FaceUp.ToString());
BroadcastAll(msg_SETOTHERHANDS, SERVER, FacingSides.FaceDown.ToString());
BroadcastAll(msg_SETTABLEHANDS, SERVER, FacingSides.FaceDown.ToString());
Shuffle();
DealCards(true);
Card card = dealer.Deck.PeekTopCard();
BroadcastAll(msg_SENDDECK, SERVER, clients[DealerPosition].Id + ":" + card.TextValue);
foreach(Client cl in clients)
{
cl.IsReady = false;
}
BroadcastAll(msg_ENABLEHAND, SERVER, "False");
BroadcastAll(msg_ENABLETABLEHAND, SERVER, "False");
TableIndex = clients[DealerPosition].TableIndex + 1;
if(TableIndex > 3)
TableIndex -= 4;
Thread.Sleep(2000);
BroadcastAll(msg_ROLLTRADEIN, SERVER, clients.FindIndex(item => item.Team == Teams.TeamOne).ToString());
BroadcastAll(msg_INFO, SERVER, "Roll to determine the number of cards your team must trade in.");
break;
case 1:
Thread.Sleep(2000);
TradeInCount[(int)Teams.TeamOne] = DiceRollValue[TurnIndex-1];
BroadcastAll(msg_ROLLTRADEIN, SERVER, clients.FindIndex(item => item.Team == Teams.TeamTwo).ToString());
break;
case 2:
Thread.Sleep(2000);
TradeInCount[(int)Teams.TeamTwo] = DiceRollValue[TurnIndex-1];
BroadcastAll(msg_CALLTRUMP, SERVER, clients[clients.FindIndex(item => item.TableIndex == TableIndex)].Id + ":" + dealer.Deck.PeekTopCard());
TurnIndex++;
break;
case 3:
if(PickedUp == true)
{
TrumpSuit = dealer.Deck.PeekTopCard().Suit;
BroadcastAll(msg_INFO, SERVER, clients[clients.FindIndex(item => item.TableIndex == TableIndex)].Name + " called " + TrumpSuit);
trumpTeam = clients[clients.FindIndex(item => item.TableIndex == TableIndex)].Team;
TableIndex = clients[DealerPosition].TableIndex + 1;
if(TableIndex > 3)
TableIndex -= 4;
RoundIndex = 0;
WinnerIndex = clients.FindIndex(item => item.TableIndex == TableIndex);
TurnIndex = 8;
TrumpRound1 = true;
BroadcastAll(msg_INFO, SERVER, "Decide with your partner how many cards to trade in.");
BroadcastAll(msg_ENABLEHAND, SERVER, "True");
BroadcastAll(msg_ENABLETABLEHAND, SERVER, "True");
BroadcastAll(msg_ENABLEREADY, SERVER, "True");
}
else
{
BroadcastAll(msg_INFO, SERVER, clients[clients.FindIndex(item => item.TableIndex == TableIndex)].Name + " passed.");
Thread.Sleep(1000);
TableIndex++;
if(TableIndex > 3)
TableIndex -= 4;
RoundIndex++;
if(RoundIndex >= 4)
{
RoundIndex = 0;
TurnIndex++;
BroadcastAll(msg_HIDEDECK, SERVER, clients[DealerPosition].Id);
BroadcastAll(msg_CALLTRUMP2, SERVER, clients[clients.FindIndex(item => item.TableIndex == TableIndex)].Id + ":" + dealer.Deck.PeekTopCard().Suit);
}
else
{
BroadcastAll(msg_CALLTRUMP, SERVER, clients[clients.FindIndex(item => item.TableIndex == TableIndex)].Id + ":" + dealer.Deck.PeekTopCard());
}
}
break;
case 4:
CallTrumpRound2();
if(PickedUp == true)
{
TurnIndex = 8;
TrumpRound1 = false;
BroadcastAll(msg_INFO, SERVER, "Decide with your partner how many cards to trade in.");
BroadcastAll(msg_ENABLEHAND, SERVER, "True");
BroadcastAll(msg_ENABLETABLEHAND, SERVER, "True");
BroadcastAll(msg_ENABLEREADY, SERVER, "True");
}
break;
case 5:
PlayTrick(6);
break;
case 6:
double[] Value = EuchreEvaluate();
WinnerIndex = Value.ToList().IndexOf(Value.Max());
TrickCount[(int)clients[WinnerIndex].Team]++;
BroadcastAll(msg_INFO, SERVER, clients[WinnerIndex].Name + " wins.");
Thread.Sleep(2000);
BroadcastAll(msg_SETTRICKS, SERVER, TrickCount[0] + ":" + TrickCount[1]);
foreach(Client c in clients)
{
BroadcastAll(msg_CLEARTABLEHAND, SERVER, c.Id);
tableHand[clients.IndexOf(c)].Cards.Clear();
}
RoundIndex = 0;
if(clients[0].Hand.NumberOfCards == 0)
{
if(TrickCount[(int)Teams.TeamOne] > TrickCount[(int)Teams.TeamTwo])
{
TeamScore[(int)Teams.TeamOne]++;
if(TrickCount[(int)Teams.TeamOne] == 5 || trumpTeam == Teams.TeamTwo)
{
TeamScore[(int)Teams.TeamOne]++;
}
string newString = Teams.TeamOne + " wins, " + TrickCount[0] + " to " + TrickCount[1] + ".";
newString = Regex.Replace(newString, @"\B([A-Z])", " $1");
BroadcastAll(msg_INFO, SERVER, newString);
}
else
{
TeamScore[(int)Teams.TeamTwo]++;
if(TrickCount[(int)Teams.TeamTwo] == 5 || trumpTeam == Teams.TeamOne)
{
TeamScore[(int)Teams.TeamTwo]++;
}
string newString = Teams.TeamTwo + " wins, " + TrickCount[1] + " to " + TrickCount[0] + ".";
newString = Regex.Replace(newString, @"\B([A-Z])", " $1");
BroadcastAll(msg_INFO, SERVER, newString);
}
BroadcastAll(msg_SETSCORE, SERVER, TeamScore[0] + ":" + TeamScore[1]);
Thread.Sleep(2000);
BroadcastAll(msg_RESETTABLE, SERVER, "");
ClearTable();
Array.Clear(TrickCount, 0, TrickCount.Length);
TurnIndex = 0;
IncrementDealer();
if(TeamScore[0] >= 10 || TeamScore[1] >= 10)
{
State = States.GameOver;
}
else
{
State = States.Game;
}
StateFunc[(int)State]();
}
else
{
TableIndex = clients[WinnerIndex].TableIndex;
BroadcastAll(msg_TURNUPDATE, SERVER, clients[clients.FindIndex(item => item.TableIndex == TableIndex)].Id);
BroadcastTo(msg_EUCHREENABLE, SERVER, clients[clients.FindIndex(item => item.TableIndex == TableIndex)].Id, "True");
TurnIndex = 5;
}
break;
case 7:
Thread.Sleep(1000);
BroadcastAll(msg_HIDEDECK, SERVER, clients[DealerPosition].Id);
clients[DealerPosition].Hand.Cards.Add(dealer.Deck.GetTopCard());
clients[DealerPosition].Hand.Sort();
SendHandMessage(clients[DealerPosition], SERVER, false);
BroadcastAll(msg_CLEARTABLEHAND, SERVER, clients[DealerPosition].Id);
BroadcastAll(msg_SHOWTABLEHAND, SERVER, clients[DealerPosition].Id);
tableHand[DealerPosition].Cards.Clear();
BroadcastAll(msg_SETTABLEHANDS, SERVER, FacingSides.FaceUp.ToString());
BroadcastAll(msg_TURNUPDATE, SERVER, clients[clients.FindIndex(item => item.TableIndex == TableIndex)].Id);
BroadcastTo(msg_EUCHREENABLE, SERVER, clients[clients.FindIndex(item => item.TableIndex == TableIndex)].Id, "True");
TurnIndex = 5;
break;
case 8:
if(clients[0].IsReady == true && clients[1].IsReady == true &&
clients[2].IsReady == true && clients[3].IsReady == true)
{
int Team1_1 = clients.FindIndex(item => item.Team == Teams.TeamOne);
int Team1_2 = clients.FindLastIndex(item => item.Team == Teams.TeamOne);
int Team2_1 = clients.FindIndex(item => item.Team == Teams.TeamTwo);
int Team2_2 = clients.FindLastIndex(item => item.Team == Teams.TeamTwo);
if(tableHand[Team1_1].NumberOfCards + tableHand[Team1_2].NumberOfCards == TradeInCount[0] &&
tableHand[Team2_1].NumberOfCards + tableHand[Team2_2].NumberOfCards == TradeInCount[1] )
{
BroadcastAll(msg_ENABLEREADY, SERVER, "False");
foreach(Client c in clients)
{
BroadcastAll(msg_CLEARTABLEHAND, SERVER, c.Id);
tableHand[clients.IndexOf(c)].Cards.Clear();
}
foreach(Client c in clients)
{
Thread.Sleep(1000);
c.Hand = bottomDeck.Deal(c.Hand, 5-c.Hand.NumberOfCards);
c.Hand.Sort();
SendHandMessage(c, SERVER, false);
}
if(TrumpRound1)
{
BroadcastAll(msg_HIDETABLEHAND, SERVER, clients[DealerPosition].Id);
BroadcastTo(msg_ENABLEHAND, SERVER, clients[DealerPosition].Id, "True");
BroadcastTo(msg_INFO, SERVER, clients[DealerPosition].Id, "Discard a card, please.");
BroadcastAll(msg_INFO, clients[DealerPosition].Id, clients[DealerPosition].Name + " must discard a card.");
TurnIndex = 7;
}
else
{
BroadcastAll(msg_SETTABLEHANDS, SERVER, FacingSides.FaceUp.ToString());
BroadcastAll(msg_TURNUPDATE, SERVER, clients[clients.FindIndex(item => item.TableIndex == TableIndex)].Id);
BroadcastTo(msg_EUCHREENABLE, SERVER, clients[clients.FindIndex(item => item.TableIndex == TableIndex)].Id, "True");
TurnIndex = 5;
}
}
}
break;
default:
break;
}
}
}
} | gpl-2.0 |
AngersPhoenix/ReadingFun | testFile.php | 7329 | <?php
// use Project\Persistance as db;
require_once 'Chunks/general.php';
require_once "bootstrap.php";
// // require_once 'Controller/Resume.php';
spl_autoload_register('persistanceLoader');
spl_autoload_register('modelLoader');
// if (php_sapi_name () == "cli") {
// require_once "bootstrap.php";
// require_once 'Model/Client.php';
// require_once 'Model/Order.php';
// require_once 'Model/Book.php';
// require_once 'Model/orderbook.php';
// require_once 'Model/Author.php';
// require_once 'Model/Category.php';
// require_once 'Persistance/BookDaoImp.php';
// require_once 'Persistance/ClientDaoImp.php';
// require_once 'Persistance/OrderDaoImp.php';
// require_once 'vendor/autoload.php';
// } else {
// $root = $_SERVER ['DOCUMENT_ROOT'];
// require_once $root . '/phoenix/Project/bootstrap.php';
// require_once $root . '/phoenix/Project/Model/Client.php';
// require_once $root . '/phoenix/Project/Model/Order.php';
// require_once $root . '/phoenix/Project/Model/Book.php';
// require_once $root . '/phoenix/Project/Model/orderbook.php';
// require_once $root . '/phoenix/Project/Model/Author.php';
// require_once $root . '/phoenix/Project/Model/Category.php';
// require_once $root . '/phoenix/Project/Persistance/BookDaoImp.php';
// require_once $root . '/phoenix/Project/Persistance/ClientDaoImp.php';
// require_once $root . '/phoenix/Project/Persistance/OrderDaoImp.php';
// require_once $root . '/phoenix/Project/vendor/autoload.php';
// // require_once 'vendor/autoload.php';
// }
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Criteria;
use Doctrine\Common\Collections\Doctrine\Common\Collections;
// $bdi = new BookDaoImp($entityManager);
// $books = $bdi->getAllBooks();
// echo $books[0]->toJson()."\n";
// // $iterator = new ArrayIterator($books);
// // $iterator->uasort(function($a,$b){
// // return ($a->getPrice() > $b->getPrice()) ? 1:-1;
// // });
// // $books = new ArrayCollection(iterator_to_array($iterator));
// // foreach ($books as $book)
// // echo $book->getTitle()." ".$book->getPrice()."\n";
// // echo "\n".$books->get(0)->getTitle()."\n";
// $collections = new ArrayCollection($books);
// $criteria = Criteria::create()
// ->orderBy(array("price" => Criteria::ASC));
// $newbooks = $collections->matching($criteria);
// // foreach ($books as $book)
// // echo $book->getTitle()." ".$book->getPrice()."\n";
// for($i=0;$i<6;$i++)
// echo $newbooks[$i]->getTitle()." ".$newbooks[$i]->getPrice()."\n";
// // echo "\n".$books->get(0)->getTitle()."\n";
// $cdi = new ClientDaoImp($entityManager);
// $client = $cdi->getClientById(3);
// echo "Password ".$client->getPassword();
// echo md5('1991');
// $tab = [12.3,353.3,15];
// echo "\n".join($tab,',')."\n";
// if (($client->getOrders()[2]->getOrderBook()[2]) === null) echo "indeed !";
// echo "hao : ".count($client->getOrders()[2]->getOrderBook());
// $array = array();
// $final = array();
// $clients = $cdi->getAllClients();
// foreach($clients as $client)
// foreach ($client->getOrders() as $order)
// if(count($order->getOrderBook()) == 0){
// $array["Order Id"] = $order->getId();
// $array["Order Date"] = $order->getDate()->format('d/m/Y H:i:s');
// $array["Valid"] = $order->getValid();
// $array["Client Id"] = $order->getClient()->getId();
// $array["Client Name"] = $order->getClient()->getName();
// $array["Order Book Id"] = "none";
// $final [] = $array;
// }else{
// foreach($order->getOrderBook() as $orderbook){
// $array["Order Id"] = $order->getId();
// $array["Order Date"] = $order->getDate()->format('d/m/Y H:i:s');
// $array["Valid"] = $order->getValid();
// $array["Client Id"] = $order->getClient()->getId();
// $array["Client Name"] = $order->getClient()->getName();
// $array["Order Book Id"] = $orderbook->getId();
// $final [] = $array;
// }
// }
// print_r($final);
// $odi = new OrderDaoImp($entityManager);
// $orders = $odi->getAllOrders();
// $cdi = new ClientDaoImp($entityManager);
// $array = array();
// $final = array();
// foreach ($cdi->getAllClients() as $client)
// if($client->getLevel()===0){
// $array['Client Name'] = $client->getName();
// $array['Client Age'] = "".$client->getAge()."";
// $array['Client Email'] = $client->getEmail();
// $array['Client Password'] = $client->getPassword();
// $array['Client Level'] = 'User';
// $final[] = $array;
// }
// echo json_encode(array('data'=>$final));
$odi = new OrderDaoImp($entityManager);
$array = array ();
$inter = array();
$demi = array ();
$final = array ();
$cpt = 0;
// echo count($odi->getAllOrders());
// $orders = $odi->getAllOrders();
// foreach($orders as $k)
// echo "--> ".$k->getId()."\n";
// $see = array();
// $seeall = array();
// $ffinale = array();
// $innerclients = array();
// $clients = array();
// $tmp = array();
// $tmpp = array();
// $cpt = 0;
// foreach ( $odi->getAllOrders() as $order ) {
// if (count ( $order->getOrderBook () ) === 0) {
// $array ['DT_RowId'] = "" . $order->getId () . "";
// json_encode ( $array );
// $inter ["Order Date"] = $order->getDate ()->format ( 'd/m/Y' );
// if($order->getValid ())$inter ["Valid"] = "true";
// else $inter ["Valid"] = "false";
// $inter ["Client Id"] = "".$cpt."";
// $inter ["Client Name"] = $order->getClient ()->getName ();
// $inter ["Order Book Id"] = "" . $cpt . "";
// $array ['orders'] = $inter;
// json_encode ( $array );
// $demi ["id"] = "none";
// $array ["Order Book Ids"] = $demi;
// json_encode ( $array );
// $innerclients['id'] = "".$order->getClient()->getId()."";
// $array['Client Ids'] = $innerclients;
// json_encode($array);
// $see['value'] = "".$cpt."";
// $see['label'] = "none";
// $seeall[] = $see;
// $tmp['value'] = "".$cpt."";
// $tmp['label']="".$order->getClient()->getId()."";
// $tmpp[] = $tmp;
// } else {
// foreach ( $order->getOrderBook () as $orderbook ) {
// $array ["DT_RowId"] = "" . $order->getId () . "";
// json_encode ( $array );
// $inter ["Order Date"] = $order->getDate ()->format ( 'd/m/Y' );
// if($order->getValid ())$inter ["Valid"] = "true";
// else $inter ["Valid"] = "false";
// $inter ["Client Id"] = $order->getClient ()->getId ();
// $inter ["Client Name"] = $order->getClient ()->getName ();
// $inter ["Order Book Ids"] = "" . $cpt . "";
// $array ['orders'] = $inter;
// json_encode ( $array );
// $demi ["id"] = "" . $orderbook->getId () . "";
// $array ["Order Book Ids"] = $demi;
// json_encode ( $array );
// $see['value'] = "".$cpt."";
// $see['label'] = "" . $orderbook->getId () . "";
// $seeall[] = $see;
// }
// }
// $cpt ++;
// $final [] = $array;
// }
// $ffinal['orders.Order Book Id'] = $seeall;
// $ffinal['orders.Client Id'] = $tmpp;
// echo json_encode ( array (
// 'data' => $final,'options'=>$ffinal
// ) );
$order = $odi->getOrderById(4);
$order->removeOrderBook($orderbook);
?> | gpl-2.0 |
iSECPartners/sqlperms | SqlPermissions.Core/Trace/Event/AddDbUserEvent.g.cs | 12666 | // Copyright (c) 2011-2015 iSEC Partners
// Author: Peter Oehlert
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Data;
using System.Diagnostics.Contracts;
using System.Text;
using SqlPermissions.Core.Utility;
namespace SqlPermissions.Core.Trace.Event
{
public partial class AddDbUserEvent : AbstractEventBase
{
internal AddDbUserEvent(IDataRecord record, AddDbUserEventLoaderInfo loaderInfo)
{
Contract.Requires(null != record, "The record must be valid.");
Contract.Requires(null != loaderInfo, "The loaderInfo must be valid.");
if (null != loaderInfo.TextDataOrdinal)
_textData = record.GetNullableString(loaderInfo.TextDataOrdinal.Value);
if (null != loaderInfo.DatabaseIDOrdinal)
_databaseID = record.GetNullableInt32(loaderInfo.DatabaseIDOrdinal.Value);
if (null != loaderInfo.TransactionIDOrdinal)
_transactionID = record.GetNullableInt64(loaderInfo.TransactionIDOrdinal.Value);
if (null != loaderInfo.NTUserNameOrdinal)
_nTUserName = record.GetNullableString(loaderInfo.NTUserNameOrdinal.Value);
if (null != loaderInfo.NTDomainNameOrdinal)
_nTDomainName = record.GetNullableString(loaderInfo.NTDomainNameOrdinal.Value);
if (null != loaderInfo.HostNameOrdinal)
_hostName = record.GetNullableString(loaderInfo.HostNameOrdinal.Value);
if (null != loaderInfo.ClientProcessIDOrdinal)
_clientProcessID = record.GetNullableInt32(loaderInfo.ClientProcessIDOrdinal.Value);
if (null != loaderInfo.ApplicationNameOrdinal)
_applicationName = record.GetNullableString(loaderInfo.ApplicationNameOrdinal.Value);
if (null != loaderInfo.LoginNameOrdinal)
_loginName = record.GetNullableString(loaderInfo.LoginNameOrdinal.Value);
if (null != loaderInfo.SPIDOrdinal)
_sPID = record.GetNullableInt32(loaderInfo.SPIDOrdinal.Value);
if (null != loaderInfo.StartTimeOrdinal)
_startTime = record.GetNullableDateTime(loaderInfo.StartTimeOrdinal.Value);
if (null != loaderInfo.EventSubClassOrdinal)
_eventSubClass = record.GetNullableInt32(loaderInfo.EventSubClassOrdinal.Value);
if (null != loaderInfo.SuccessOrdinal)
_success = record.GetNullableInt32(loaderInfo.SuccessOrdinal.Value);
if (null != loaderInfo.ServerNameOrdinal)
_serverName = record.GetNullableString(loaderInfo.ServerNameOrdinal.Value);
if (null != loaderInfo.ObjectTypeOrdinal)
_objectType = record.GetNullableInt32(loaderInfo.ObjectTypeOrdinal.Value);
if (null != loaderInfo.NestLevelOrdinal)
_nestLevel = record.GetNullableInt32(loaderInfo.NestLevelOrdinal.Value);
if (null != loaderInfo.DatabaseNameOrdinal)
_databaseName = record.GetNullableString(loaderInfo.DatabaseNameOrdinal.Value);
if (null != loaderInfo.OwnerNameOrdinal)
_ownerName = record.GetNullableString(loaderInfo.OwnerNameOrdinal.Value);
if (null != loaderInfo.RoleNameOrdinal)
_roleName = record.GetNullableString(loaderInfo.RoleNameOrdinal.Value);
if (null != loaderInfo.TargetUserNameOrdinal)
_targetUserName = record.GetNullableString(loaderInfo.TargetUserNameOrdinal.Value);
if (null != loaderInfo.DBUserNameOrdinal)
_dBUserName = record.GetNullableString(loaderInfo.DBUserNameOrdinal.Value);
if (null != loaderInfo.LoginSidOrdinal)
_loginSid = (Byte[])record.GetValue(loaderInfo.LoginSidOrdinal.Value);
if (null != loaderInfo.TargetLoginNameOrdinal)
_targetLoginName = record.GetNullableString(loaderInfo.TargetLoginNameOrdinal.Value);
if (null != loaderInfo.TargetLoginSidOrdinal)
_targetLoginSid = (Byte[])record.GetValue(loaderInfo.TargetLoginSidOrdinal.Value);
if (null != loaderInfo.ColumnPermissionsOrdinal)
_columnPermissions = record.GetNullableInt32(loaderInfo.ColumnPermissionsOrdinal.Value);
if (null != loaderInfo.RequestIDOrdinal)
_requestID = record.GetNullableInt32(loaderInfo.RequestIDOrdinal.Value);
if (null != loaderInfo.XactSequenceOrdinal)
_xactSequence = record.GetNullableInt64(loaderInfo.XactSequenceOrdinal.Value);
if (null != loaderInfo.EventSequenceOrdinal)
_eventSequence = record.GetNullableInt64(loaderInfo.EventSequenceOrdinal.Value);
if (null != loaderInfo.IsSystemOrdinal)
_isSystem = record.GetNullableInt32(loaderInfo.IsSystemOrdinal.Value);
if (null != loaderInfo.SessionLoginNameOrdinal)
_sessionLoginName = record.GetNullableString(loaderInfo.SessionLoginNameOrdinal.Value);
}
public override String Name
{ get { return EventName; } }
private const String EventName = "Audit Add DB User Event";
public override Int32 Id
{ get { return EventId; } }
private const Int32 EventId = 109;
public override String TextData
{
get { return _textData; }
set { _textData = value; }
}
private String _textData;
public override Int32? DatabaseID
{
get { return _databaseID; }
set { _databaseID = value; }
}
private Int32? _databaseID;
public Int64? TransactionID
{
get { return _transactionID; }
set { _transactionID = value; }
}
private Int64? _transactionID;
public override String NTUserName
{
get { return _nTUserName; }
set { _nTUserName = value; }
}
private String _nTUserName;
public override String NTDomainName
{
get { return _nTDomainName; }
set { _nTDomainName = value; }
}
private String _nTDomainName;
public String HostName
{
get { return _hostName; }
set { _hostName = value; }
}
private String _hostName;
public Int32? ClientProcessID
{
get { return _clientProcessID; }
set { _clientProcessID = value; }
}
private Int32? _clientProcessID;
public String ApplicationName
{
get { return _applicationName; }
set { _applicationName = value; }
}
private String _applicationName;
public override String LoginName
{
get { return _loginName; }
set { _loginName = value; }
}
private String _loginName;
public Int32? SPID
{
get { return _sPID; }
set { _sPID = value; }
}
private Int32? _sPID;
public DateTime? StartTime
{
get { return _startTime; }
set { _startTime = value; }
}
private DateTime? _startTime;
public Int32? EventSubClass
{
get { return _eventSubClass; }
set { _eventSubClass = value; }
}
private Int32? _eventSubClass;
public Int32? Success
{
get { return _success; }
set { _success = value; }
}
private Int32? _success;
public String ServerName
{
get { return _serverName; }
set { _serverName = value; }
}
private String _serverName;
public Int32? ObjectType
{
get { return _objectType; }
set { _objectType = value; }
}
private Int32? _objectType;
public Int32? NestLevel
{
get { return _nestLevel; }
set { _nestLevel = value; }
}
private Int32? _nestLevel;
public String DatabaseName
{
get { return _databaseName; }
set { _databaseName = value; }
}
private String _databaseName;
public String OwnerName
{
get { return _ownerName; }
set { _ownerName = value; }
}
private String _ownerName;
public String RoleName
{
get { return _roleName; }
set { _roleName = value; }
}
private String _roleName;
public String TargetUserName
{
get { return _targetUserName; }
set { _targetUserName = value; }
}
private String _targetUserName;
public String DBUserName
{
get { return _dBUserName; }
set { _dBUserName = value; }
}
private String _dBUserName;
public Byte[] LoginSid
{
get { return _loginSid; }
set { _loginSid = value; }
}
private Byte[] _loginSid;
public String TargetLoginName
{
get { return _targetLoginName; }
set { _targetLoginName = value; }
}
private String _targetLoginName;
public Byte[] TargetLoginSid
{
get { return _targetLoginSid; }
set { _targetLoginSid = value; }
}
private Byte[] _targetLoginSid;
public Int32? ColumnPermissions
{
get { return _columnPermissions; }
set { _columnPermissions = value; }
}
private Int32? _columnPermissions;
public Int32? RequestID
{
get { return _requestID; }
set { _requestID = value; }
}
private Int32? _requestID;
public Int64? XactSequence
{
get { return _xactSequence; }
set { _xactSequence = value; }
}
private Int64? _xactSequence;
public Int64? EventSequence
{
get { return _eventSequence; }
set { _eventSequence = value; }
}
private Int64? _eventSequence;
public Int32? IsSystem
{
get { return _isSystem; }
set { _isSystem = value; }
}
private Int32? _isSystem;
public String SessionLoginName
{
get { return _sessionLoginName; }
set { _sessionLoginName = value; }
}
private String _sessionLoginName;
public override String ToString()
{
const Boolean IsDetailed = false;
return ToString(IsDetailed);
}
public override String ToString(bool isDetailed)
{
const String Line1 = "Event Class: Audit Add DB User Event (AddDbUserEvent)";
// return the short version if requested
if (!isDetailed)
return Line1;
const Int32 ExpectedCapacity = 0x100;
var sb = new StringBuilder(ExpectedCapacity);
sb.AppendLine(Line1);
sb.AppendLine("\tEventClassId: 109");
sb.Append("\tTextData: ").AppendLine(Convert.ToString(TextData));
sb.Append("\tDatabaseID: ").AppendLine(Convert.ToString(DatabaseID));
sb.Append("\tTransactionID: ").AppendLine(Convert.ToString(TransactionID));
sb.Append("\tNTUserName: ").AppendLine(Convert.ToString(NTUserName));
sb.Append("\tNTDomainName: ").AppendLine(Convert.ToString(NTDomainName));
sb.Append("\tHostName: ").AppendLine(Convert.ToString(HostName));
sb.Append("\tClientProcessID: ").AppendLine(Convert.ToString(ClientProcessID));
sb.Append("\tApplicationName: ").AppendLine(Convert.ToString(ApplicationName));
sb.Append("\tLoginName: ").AppendLine(Convert.ToString(LoginName));
sb.Append("\tSPID: ").AppendLine(Convert.ToString(SPID));
sb.Append("\tStartTime: ").AppendLine(Convert.ToString(StartTime));
sb.Append("\tEventSubClass: ").AppendLine(Convert.ToString(EventSubClass));
sb.Append("\tSuccess: ").AppendLine(Convert.ToString(Success));
sb.Append("\tServerName: ").AppendLine(Convert.ToString(ServerName));
sb.Append("\tObjectType: ").AppendLine(Convert.ToString(ObjectType));
sb.Append("\tNestLevel: ").AppendLine(Convert.ToString(NestLevel));
sb.Append("\tDatabaseName: ").AppendLine(Convert.ToString(DatabaseName));
sb.Append("\tOwnerName: ").AppendLine(Convert.ToString(OwnerName));
sb.Append("\tRoleName: ").AppendLine(Convert.ToString(RoleName));
sb.Append("\tTargetUserName: ").AppendLine(Convert.ToString(TargetUserName));
sb.Append("\tDBUserName: ").AppendLine(Convert.ToString(DBUserName));
sb.Append("\tLoginSid: ").AppendLine(null != LoginSid ? "0x" + BitConverter.ToString(LoginSid).Replace("-", String.Empty) : "");
sb.Append("\tTargetLoginName: ").AppendLine(Convert.ToString(TargetLoginName));
sb.Append("\tTargetLoginSid: ").AppendLine(null != TargetLoginSid ? "0x" + BitConverter.ToString(TargetLoginSid).Replace("-", String.Empty) : "");
sb.Append("\tColumnPermissions: ").AppendLine(Convert.ToString(ColumnPermissions));
sb.Append("\tRequestID: ").AppendLine(Convert.ToString(RequestID));
sb.Append("\tXactSequence: ").AppendLine(Convert.ToString(XactSequence));
sb.Append("\tEventSequence: ").AppendLine(Convert.ToString(EventSequence));
sb.Append("\tIsSystem: ").AppendLine(Convert.ToString(IsSystem));
sb.Append("\tSessionLoginName: ").AppendLine(Convert.ToString(SessionLoginName));
return sb.ToString();
}
}
}
| gpl-2.0 |
jrounsav/fac-sites-tmp | profiles/openscholar/libraries/git/composer/autoload_real.php | 1762 | <?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderIniteede5e01eb40ccdc215e240b2ca05cda
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderIniteede5e01eb40ccdc215e240b2ca05cda', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderIniteede5e01eb40ccdc215e240b2ca05cda', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require_once __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticIniteede5e01eb40ccdc215e240b2ca05cda::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
}
$loader->register(true);
return $loader;
}
}
| gpl-2.0 |
sourcepole/kadas-albireo | tests/src/core/testqgscomposition.cpp | 9366 | /***************************************************************************
testqgscomposition.cpp
----------------------
begin : September 2014
copyright : (C) 2014 by Nyall Dawson
email : nyall dot dawson at gmail dot 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. *
* *
***************************************************************************/
#include "qgsapplication.h"
#include "qgscomposition.h"
#include "qgscomposerlabel.h"
#include "qgscomposershape.h"
#include "qgscomposerarrow.h"
#include "qgscomposerhtml.h"
#include "qgscomposerframe.h"
#include "qgsmapsettings.h"
#include <QObject>
#include <QtTest/QtTest>
class TestQgsComposition : public QObject
{
Q_OBJECT
public:
TestQgsComposition();
private slots:
void initTestCase();// will be called before the first testfunction is executed.
void cleanupTestCase();// will be called after the last testfunction was executed.
void init();// will be called before each testfunction is executed.
void cleanup();// will be called after every testfunction.
void itemsOnPage(); //test fetching matching items on a set page
void shouldExportPage(); //test the shouldExportPage method
void pageIsEmpty(); //test the pageIsEmpty method
private:
QgsComposition* mComposition;
QgsMapSettings mMapSettings;
QString mReport;
};
TestQgsComposition::TestQgsComposition()
: mComposition( NULL )
{
}
void TestQgsComposition::initTestCase()
{
QgsApplication::init();
QgsApplication::initQgis();
//create composition
mMapSettings.setCrsTransformEnabled( true );
mMapSettings.setMapUnits( QGis::Meters );
mComposition = new QgsComposition( mMapSettings );
mComposition->setPaperSize( 297, 210 ); //A4 landscape
mComposition->setNumPages( 3 );
mReport = "<h1>Composition Tests</h1>\n";
}
void TestQgsComposition::cleanupTestCase()
{
delete mComposition;
QString myReportFile = QDir::tempPath() + QDir::separator() + "qgistest.html";
QFile myFile( myReportFile );
if ( myFile.open( QIODevice::WriteOnly | QIODevice::Append ) )
{
QTextStream myQTextStream( &myFile );
myQTextStream << mReport;
myFile.close();
}
QgsApplication::exitQgis();
}
void TestQgsComposition::init()
{
}
void TestQgsComposition::cleanup()
{
}
void TestQgsComposition::itemsOnPage()
{
//add some items to the composition
QgsComposerLabel* label1 = new QgsComposerLabel( mComposition );
mComposition->addComposerItem( label1 );
label1->setItemPosition( 10, 10, 50, 50, QgsComposerItem::UpperLeft, false, 1 );
QgsComposerLabel* label2 = new QgsComposerLabel( mComposition );
mComposition->addComposerItem( label2 );
label2->setItemPosition( 10, 10, 50, 50, QgsComposerItem::UpperLeft, false, 1 );
QgsComposerLabel* label3 = new QgsComposerLabel( mComposition );
mComposition->addComposerItem( label3 );
label3->setItemPosition( 10, 10, 50, 50, QgsComposerItem::UpperLeft, false, 2 );
QgsComposerShape* shape1 = new QgsComposerShape( mComposition );
mComposition->addComposerItem( shape1 );
shape1->setItemPosition( 10, 10, 50, 50, QgsComposerItem::UpperLeft, false, 1 );
QgsComposerShape* shape2 = new QgsComposerShape( mComposition );
mComposition->addComposerItem( shape2 );
shape2->setItemPosition( 10, 10, 50, 50, QgsComposerItem::UpperLeft, false, 2 );
QgsComposerArrow* arrow1 = new QgsComposerArrow( mComposition );
mComposition->addComposerItem( arrow1 );
arrow1->setItemPosition( 10, 10, 50, 50, QgsComposerItem::UpperLeft, false, 3 );
QgsComposerArrow* arrow2 = new QgsComposerArrow( mComposition );
mComposition->addComposerItem( arrow2 );
arrow2->setItemPosition( 10, 10, 50, 50, QgsComposerItem::UpperLeft, false, 3 );
//fetch items - remember that these numbers include the paper item!
QList<QgsComposerItem*> items;
mComposition->composerItemsOnPage( items, 0 );
//should be 4 items on page 1
QCOMPARE( items.length(), 4 );
mComposition->composerItemsOnPage( items, 1 );
//should be 3 items on page 2
QCOMPARE( items.length(), 3 );
mComposition->composerItemsOnPage( items, 2 );
//should be 3 items on page 3
QCOMPARE( items.length(), 3 );
//check fetching specific item types
QList<QgsComposerLabel*> labels;
mComposition->composerItemsOnPage( labels, 0 );
//should be 2 labels on page 1
QCOMPARE( labels.length(), 2 );
mComposition->composerItemsOnPage( labels, 1 );
//should be 1 label on page 2
QCOMPARE( labels.length(), 1 );
mComposition->composerItemsOnPage( labels, 2 );
//should be no label on page 3
QCOMPARE( labels.length(), 0 );
QList<QgsComposerShape*> shapes;
mComposition->composerItemsOnPage( shapes, 0 );
//should be 1 shapes on page 1
QCOMPARE( shapes.length(), 1 );
mComposition->composerItemsOnPage( shapes, 1 );
//should be 1 shapes on page 2
QCOMPARE( shapes.length(), 1 );
mComposition->composerItemsOnPage( shapes, 2 );
//should be no shapes on page 3
QCOMPARE( shapes.length(), 0 );
QList<QgsComposerArrow*> arrows;
mComposition->composerItemsOnPage( arrows, 0 );
//should be no arrows on page 1
QCOMPARE( arrows.length(), 0 );
mComposition->composerItemsOnPage( arrows, 1 );
//should be no arrows on page 2
QCOMPARE( arrows.length(), 0 );
mComposition->composerItemsOnPage( arrows, 2 );
//should be 2 arrows on page 3
QCOMPARE( arrows.length(), 2 );
mComposition->removeComposerItem( label1 );
mComposition->removeComposerItem( label2 );
mComposition->removeComposerItem( label3 );
mComposition->removeComposerItem( shape1 );
mComposition->removeComposerItem( shape2 );
mComposition->removeComposerItem( arrow1 );
mComposition->removeComposerItem( arrow2 );
//check again with removed items
mComposition->composerItemsOnPage( labels, 0 );
QCOMPARE( labels.length(), 0 );
mComposition->composerItemsOnPage( labels, 1 );
QCOMPARE( labels.length(), 0 );
mComposition->composerItemsOnPage( labels, 2 );
QCOMPARE( labels.length(), 0 );
}
void TestQgsComposition::shouldExportPage()
{
mComposition->setPaperSize( 297, 200 );
mComposition->setNumPages( 2 );
QgsComposerHtml* htmlItem = new QgsComposerHtml( mComposition, false );
//frame on page 1
QgsComposerFrame* frame1 = new QgsComposerFrame( mComposition, htmlItem, 0, 0, 100, 100 );
//frame on page 2
QgsComposerFrame* frame2 = new QgsComposerFrame( mComposition, htmlItem, 0, 320, 100, 100 );
frame2->setHidePageIfEmpty( true );
htmlItem->addFrame( frame1 );
htmlItem->addFrame( frame2 );
htmlItem->setContentMode( QgsComposerHtml::ManualHtml );
//short content, so frame 2 should be empty
htmlItem->setHtml( QString( "<p><i>Test manual <b>html</b></i></p>" ) );
htmlItem->loadHtml();
QCOMPARE( mComposition->shouldExportPage( 1 ), true );
QCOMPARE( mComposition->shouldExportPage( 2 ), false );
//long content, so frame 2 should not be empty
htmlItem->setHtml( QString( "<p style=\"height: 10000px\"><i>Test manual <b>html</b></i></p>" ) );
htmlItem->loadHtml();
QCOMPARE( mComposition->shouldExportPage( 1 ), true );
QCOMPARE( mComposition->shouldExportPage( 2 ), true );
//...and back again...
htmlItem->setHtml( QString( "<p><i>Test manual <b>html</b></i></p>" ) );
htmlItem->loadHtml();
QCOMPARE( mComposition->shouldExportPage( 1 ), true );
QCOMPARE( mComposition->shouldExportPage( 2 ), false );
mComposition->removeMultiFrame( htmlItem );
delete htmlItem;
}
void TestQgsComposition::pageIsEmpty()
{
//add some items to the composition
QgsComposerLabel* label1 = new QgsComposerLabel( mComposition );
mComposition->addComposerItem( label1 );
label1->setItemPosition( 10, 10, 50, 50, QgsComposerItem::UpperLeft, false, 1 );
QgsComposerLabel* label2 = new QgsComposerLabel( mComposition );
mComposition->addComposerItem( label2 );
label2->setItemPosition( 10, 10, 50, 50, QgsComposerItem::UpperLeft, false, 1 );
QgsComposerLabel* label3 = new QgsComposerLabel( mComposition );
mComposition->addComposerItem( label3 );
label3->setItemPosition( 10, 10, 50, 50, QgsComposerItem::UpperLeft, false, 3 );
//only page 2 should be empty
QCOMPARE( mComposition->pageIsEmpty( 1 ), false );
QCOMPARE( mComposition->pageIsEmpty( 2 ), true );
QCOMPARE( mComposition->pageIsEmpty( 3 ), false );
//remove the items
mComposition->removeComposerItem( label1 );
mComposition->removeComposerItem( label2 );
mComposition->removeComposerItem( label3 );
//expect everything to be empty now
QCOMPARE( mComposition->pageIsEmpty( 1 ), true );
QCOMPARE( mComposition->pageIsEmpty( 2 ), true );
QCOMPARE( mComposition->pageIsEmpty( 3 ), true );
}
QTEST_MAIN( TestQgsComposition )
#include "testqgscomposition.moc"
| gpl-2.0 |
zxk123/-News | News/libraries/loadinglibrary/src/main/java/app/dinus/com/loadingdrawable/render/circle/jump/DanceLoadingRenderer.java | 14451 | package app.dinus.com.loadingdrawable.render.circle.jump;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import app.dinus.com.loadingdrawable.render.LoadingRenderer;
public class DanceLoadingRenderer extends LoadingRenderer {
private static final Interpolator MATERIAL_INTERPOLATOR = new FastOutSlowInInterpolator();
private static final Interpolator ACCELERATE_INTERPOLATOR = new AccelerateInterpolator();
private static final Interpolator DECELERATE_INTERPOLATOR = new DecelerateInterpolator();
private static final long ANIMATION_DURATION = 1888;
private static final float DEFAULT_STROKE_WIDTH = 1.5f;
private static final float DEFAULT_DANCE_BALL_RADIUS = 2.0f;
private static final int NUM_POINTS = 3;
private static final int DEGREE_360 = 360;
private static final int RING_START_ANGLE = -90;
private static final int DANCE_START_ANGLE = 0;
private static final int DANCE_INTERVAL_ANGLE = 60;
private static final int DEFAULT_COLOR = Color.WHITE;
//the center coordinate of the oval
private static final float[] POINT_X = new float[NUM_POINTS];
private static final float[] POINT_Y = new float[NUM_POINTS];
//1: the coordinate x from small to large; -1: the coordinate x from large to small
private static final int[] DIRECTION = new int[] {1, 1, -1};
private static final float BALL_FORWARD_START_ENTER_DURATION_OFFSET = 0f;
private static final float BALL_FORWARD_END_ENTER_DURATION_OFFSET = 0.125f;
private static final float RING_FORWARD_START_ROTATE_DURATION_OFFSET = 0.125f;
private static final float RING_FORWARD_END_ROTATE_DURATION_OFFSET = 0.375f;
private static final float CENTER_CIRCLE_FORWARD_START_SCALE_DURATION_OFFSET = 0.225f;
private static final float CENTER_CIRCLE_FORWARD_END_SCALE_DURATION_OFFSET = 0.475f;
private static final float BALL_FORWARD_START_EXIT_DURATION_OFFSET = 0.375f;
private static final float BALL_FORWARD_END_EXIT_DURATION_OFFSET = 0.54f;
private static final float RING_REVERSAL_START_ROTATE_DURATION_OFFSET = 0.5f;
private static final float RING_REVERSAL_END_ROTATE_DURATION_OFFSET = 0.75f;
private static final float BALL_REVERSAL_START_ENTER_DURATION_OFFSET = 0.6f;
private static final float BALL_REVERSAL_END_ENTER_DURATION_OFFSET = 0.725f;
private static final float CENTER_CIRCLE_REVERSAL_START_SCALE_DURATION_OFFSET = 0.675f;
private static final float CENTER_CIRCLE_REVERSAL_END_SCALE_DURATION_OFFSET = 0.875f;
private static final float BALL_REVERSAL_START_EXIT_DURATION_OFFSET = 0.875f;
private static final float BALL_REVERSAL_END_EXIT_DURATION_OFFSET = 1.0f;
private final Paint mPaint = new Paint();
private final RectF mTempBounds = new RectF();
private final RectF mCurrentBounds = new RectF();
private float mScale;
private float mRotation;
private float mStrokeInset;
private float mDanceBallRadius;
private float mShapeChangeWidth;
private float mShapeChangeHeight;
private int mColor;
private int mArcColor;
public DanceLoadingRenderer(Context context) {
super(context);
init(context);
setupPaint();
}
private void init(Context context) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
mStrokeWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_STROKE_WIDTH, displayMetrics);
mDanceBallRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_DANCE_BALL_RADIUS, displayMetrics);
setColor(DEFAULT_COLOR);
setInsets((int) getWidth(), (int) getHeight());
setDuration(ANIMATION_DURATION);
}
private void setupPaint() {
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(getStrokeWidth());
mPaint.setStyle(Paint.Style.STROKE);
}
@Override
public void draw(Canvas canvas, Rect bounds) {
int saveCount = canvas.save();
mTempBounds.set(bounds);
mTempBounds.inset(mStrokeInset, mStrokeInset);
mCurrentBounds.set(mTempBounds);
float outerCircleRadius = Math.min(mTempBounds.height(), mTempBounds.width()) / 2.0f;
float interCircleRadius = outerCircleRadius / 2.0f;
float centerRingWidth = interCircleRadius - getStrokeWidth() / 2;
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(mColor);
mPaint.setStrokeWidth(getStrokeWidth());
canvas.drawCircle(mTempBounds.centerX(), mTempBounds.centerY(), outerCircleRadius, mPaint);
mPaint.setStyle(Paint.Style.FILL);
canvas.drawCircle(mTempBounds.centerX(), mTempBounds.centerY(), interCircleRadius * mScale, mPaint);
if (mRotation != 0) {
mPaint.setColor(mArcColor);
mPaint.setStyle(Paint.Style.STROKE);
//strokeWidth / 2.0f + getStrokeWidth() / 2.0f is the center of the inter circle width
mTempBounds.inset(centerRingWidth / 2.0f + getStrokeWidth() / 2.0f, centerRingWidth / 2.0f + getStrokeWidth() / 2.0f);
mPaint.setStrokeWidth(centerRingWidth);
canvas.drawArc(mTempBounds, RING_START_ANGLE, mRotation, false, mPaint);
}
mPaint.setColor(mColor);
mPaint.setStyle(Paint.Style.FILL);
for (int i = 0; i < NUM_POINTS; i++) {
canvas.rotate(i * DANCE_INTERVAL_ANGLE, POINT_X[i], POINT_Y[i]);
RectF rectF = new RectF(POINT_X[i] - mDanceBallRadius - mShapeChangeWidth / 2.0f,
POINT_Y[i] - mDanceBallRadius - mShapeChangeHeight / 2.0f,
POINT_X[i] + mDanceBallRadius + mShapeChangeWidth / 2.0f,
POINT_Y[i] + mDanceBallRadius + mShapeChangeHeight / 2.0f);
canvas.drawOval(rectF, mPaint);
canvas.rotate(-i * DANCE_INTERVAL_ANGLE, POINT_X[i], POINT_Y[i]);
}
canvas.restoreToCount(saveCount);
}
@Override
public void computeRender(float renderProgress) {
float radius = Math.min(mCurrentBounds.height(), mCurrentBounds.width()) / 2.0f;
//the origin coordinate is the centerLeft of the field mCurrentBounds
float originCoordinateX = mCurrentBounds.left;
float originCoordinateY = mCurrentBounds.top + radius ;
if (renderProgress <= BALL_FORWARD_END_ENTER_DURATION_OFFSET && renderProgress > BALL_FORWARD_START_ENTER_DURATION_OFFSET) {
final float ballForwardEnterProgress = (renderProgress - BALL_FORWARD_START_ENTER_DURATION_OFFSET) / (BALL_FORWARD_END_ENTER_DURATION_OFFSET - BALL_FORWARD_START_ENTER_DURATION_OFFSET);
mShapeChangeHeight = (0.5f - ballForwardEnterProgress) * mDanceBallRadius / 2.0f;
mShapeChangeWidth = -mShapeChangeHeight;
//y = k(x - r)--> k = tan(angle)
//(x - r)^2 + y^2 = r^2
// compute crossover point --> (k(x -r)) ^ 2 + (x - )^2 = r^2
// so x --> [r + r / sqrt(k ^ 2 + 1), r - r / sqrt(k ^ 2 + 1)]
for (int i = 0; i < NUM_POINTS; i++) {
float k = (float) Math.tan((DANCE_START_ANGLE + DANCE_INTERVAL_ANGLE * i) / 360.0f * (2.0f * Math.PI));
// progress[-1, 1]
float progress = (ACCELERATE_INTERPOLATOR.getInterpolation(ballForwardEnterProgress) / 2.0f - 0.5f) * 2.0f * DIRECTION[i];
POINT_X[i] = (float) (radius + progress * (radius / Math.sqrt(Math.pow(k, 2.0f) + 1.0f)));
POINT_Y[i] = k * (POINT_X[i] - radius);
POINT_X[i] += originCoordinateX;
POINT_Y[i] += originCoordinateY;
}
}
if (renderProgress <= RING_FORWARD_END_ROTATE_DURATION_OFFSET && renderProgress > RING_FORWARD_START_ROTATE_DURATION_OFFSET) {
final float forwardRotateProgress = (renderProgress - RING_FORWARD_START_ROTATE_DURATION_OFFSET) / (RING_FORWARD_END_ROTATE_DURATION_OFFSET - RING_FORWARD_START_ROTATE_DURATION_OFFSET);
mRotation = DEGREE_360 * MATERIAL_INTERPOLATOR.getInterpolation(forwardRotateProgress);
}
if (renderProgress <= CENTER_CIRCLE_FORWARD_END_SCALE_DURATION_OFFSET && renderProgress > CENTER_CIRCLE_FORWARD_START_SCALE_DURATION_OFFSET) {
final float centerCircleScaleProgress = (renderProgress - CENTER_CIRCLE_FORWARD_START_SCALE_DURATION_OFFSET) / (CENTER_CIRCLE_FORWARD_END_SCALE_DURATION_OFFSET - CENTER_CIRCLE_FORWARD_START_SCALE_DURATION_OFFSET);
if (centerCircleScaleProgress <= 0.5f) {
mScale = 1.0f + DECELERATE_INTERPOLATOR.getInterpolation(centerCircleScaleProgress * 2.0f) * 0.2f;
} else {
mScale = 1.2f - ACCELERATE_INTERPOLATOR.getInterpolation((centerCircleScaleProgress - 0.5f) * 2.0f) * 0.2f;
}
}
if (renderProgress <= BALL_FORWARD_END_EXIT_DURATION_OFFSET && renderProgress > BALL_FORWARD_START_EXIT_DURATION_OFFSET) {
final float ballForwardExitProgress = (renderProgress - BALL_FORWARD_START_EXIT_DURATION_OFFSET) / (BALL_FORWARD_END_EXIT_DURATION_OFFSET - BALL_FORWARD_START_EXIT_DURATION_OFFSET);
mShapeChangeHeight = (ballForwardExitProgress - 0.5f) * mDanceBallRadius / 2.0f;
mShapeChangeWidth = -mShapeChangeHeight;
for (int i = 0; i < NUM_POINTS; i++) {
float k = (float) Math.tan((DANCE_START_ANGLE + DANCE_INTERVAL_ANGLE * i) / 360.0f * (2.0f * Math.PI));
float progress = (DECELERATE_INTERPOLATOR.getInterpolation(ballForwardExitProgress) / 2.0f) * 2.0f * DIRECTION[i];
POINT_X[i] = (float) (radius + progress * (radius / Math.sqrt(Math.pow(k, 2.0f) + 1.0f)));
POINT_Y[i] = k * (POINT_X[i] - radius);
POINT_X[i] += originCoordinateX;
POINT_Y[i] += originCoordinateY;
}
}
if (renderProgress <= RING_REVERSAL_END_ROTATE_DURATION_OFFSET && renderProgress > RING_REVERSAL_START_ROTATE_DURATION_OFFSET) {
float scaledTime = (renderProgress - RING_REVERSAL_START_ROTATE_DURATION_OFFSET) / (RING_REVERSAL_END_ROTATE_DURATION_OFFSET - RING_REVERSAL_START_ROTATE_DURATION_OFFSET);
mRotation = DEGREE_360 * MATERIAL_INTERPOLATOR.getInterpolation(scaledTime) - 360;
} else if (renderProgress > RING_REVERSAL_END_ROTATE_DURATION_OFFSET) {
mRotation = 0.0f;
}
if (renderProgress <= BALL_REVERSAL_END_ENTER_DURATION_OFFSET && renderProgress > BALL_REVERSAL_START_ENTER_DURATION_OFFSET) {
final float ballReversalEnterProgress = (renderProgress - BALL_REVERSAL_START_ENTER_DURATION_OFFSET) / (BALL_REVERSAL_END_ENTER_DURATION_OFFSET - BALL_REVERSAL_START_ENTER_DURATION_OFFSET);
mShapeChangeHeight = (0.5f - ballReversalEnterProgress) * mDanceBallRadius / 2.0f;
mShapeChangeWidth = -mShapeChangeHeight;
for (int i = 0; i < NUM_POINTS; i++) {
float k = (float) Math.tan((DANCE_START_ANGLE + DANCE_INTERVAL_ANGLE * i) / 360.0f * (2.0f * Math.PI));
float progress = (0.5f - ACCELERATE_INTERPOLATOR.getInterpolation(ballReversalEnterProgress) / 2.0f) * 2.0f * DIRECTION[i];
POINT_X[i] = (float) (radius + progress * (radius / Math.sqrt(Math.pow(k, 2.0f) + 1.0f)));
POINT_Y[i] = k * (POINT_X[i] - radius);
POINT_X[i] += originCoordinateX;
POINT_Y[i] += originCoordinateY;
}
}
if (renderProgress <= CENTER_CIRCLE_REVERSAL_END_SCALE_DURATION_OFFSET && renderProgress > CENTER_CIRCLE_REVERSAL_START_SCALE_DURATION_OFFSET) {
final float centerCircleScaleProgress = (renderProgress - CENTER_CIRCLE_REVERSAL_START_SCALE_DURATION_OFFSET) / (CENTER_CIRCLE_REVERSAL_END_SCALE_DURATION_OFFSET - CENTER_CIRCLE_REVERSAL_START_SCALE_DURATION_OFFSET);
if (centerCircleScaleProgress <= 0.5f) {
mScale = 1.0f + DECELERATE_INTERPOLATOR.getInterpolation(centerCircleScaleProgress * 2.0f) * 0.2f;
} else {
mScale = 1.2f - ACCELERATE_INTERPOLATOR.getInterpolation((centerCircleScaleProgress - 0.5f) * 2.0f) * 0.2f;
}
}
if (renderProgress <= BALL_REVERSAL_END_EXIT_DURATION_OFFSET && renderProgress > BALL_REVERSAL_START_EXIT_DURATION_OFFSET) {
final float ballReversalExitProgress = (renderProgress - BALL_REVERSAL_START_EXIT_DURATION_OFFSET) / (BALL_REVERSAL_END_EXIT_DURATION_OFFSET - BALL_REVERSAL_START_EXIT_DURATION_OFFSET);
mShapeChangeHeight = (ballReversalExitProgress - 0.5f) * mDanceBallRadius / 2.0f;
mShapeChangeWidth = -mShapeChangeHeight;
for (int i = 0; i < NUM_POINTS; i++) {
float k = (float) Math.tan((DANCE_START_ANGLE + DANCE_INTERVAL_ANGLE * i) / 360.0f * (2.0f * Math.PI));
float progress = (0.0f - DECELERATE_INTERPOLATOR.getInterpolation(ballReversalExitProgress) / 2.0f) * 2.0f * DIRECTION[i];
POINT_X[i] = (float) (radius + progress * (radius / Math.sqrt(Math.pow(k, 2.0f) + 1.0f)));
POINT_Y[i] = k * (POINT_X[i] - radius);
POINT_X[i] += originCoordinateX;
POINT_Y[i] += originCoordinateY;
}
}
}
@Override
public void setAlpha(int alpha) {
mPaint.setAlpha(alpha);
invalidateSelf();
}
@Override
public void setColorFilter(ColorFilter cf) {
mPaint.setColorFilter(cf);
invalidateSelf();
}
@Override
public void reset() {
mScale = 1.0f;
mRotation = 0;
}
public void setColor(int color) {
mColor = color;
mArcColor = halfAlphaColor(mColor);
}
@Override
public void setStrokeWidth(float strokeWidth) {
super.setStrokeWidth(strokeWidth);
mPaint.setStrokeWidth(strokeWidth);
invalidateSelf();
}
public void setRotation(float rotation) {
mRotation = rotation;
invalidateSelf();
}
public void setDanceBallRadius(float danceBallRadius) {
this.mDanceBallRadius = danceBallRadius;
invalidateSelf();
}
public float getDanceBallRadius() {
return mDanceBallRadius;
}
public float getRotation() {
return mRotation;
}
public void setInsets(int width, int height) {
final float minEdge = (float) Math.min(width, height);
float insets;
if (getCenterRadius() <= 0 || minEdge < 0) {
insets = (float) Math.ceil(getStrokeWidth() / 2.0f);
} else {
insets = minEdge / 2.0f - getCenterRadius();
}
mStrokeInset = insets;
}
private int halfAlphaColor(int colorValue) {
int startA = (colorValue >> 24) & 0xff;
int startR = (colorValue >> 16) & 0xff;
int startG = (colorValue >> 8) & 0xff;
int startB = colorValue & 0xff;
return ((startA / 2) << 24)
| (startR << 16)
| (startG << 8)
| startB;
}
}
| gpl-2.0 |
exponentcms/exponent-cms-1 | external/mimetype.php | 9183 | <?php
/**
Copyright (C) 2002 Jason Sheets <jsheets@shadonet.com>.
All rights reserved.
THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the project nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
**/
/**
Name: PHP MimeType Class
Version: 1.0
Date Released: 10/20/02
Description: This class allows a PHP script to determine the mime type
a file based on the file extension. This class is handy for PHP versions
without the benefit of other tools to determine the mime type. The class
defaults to octet-stream so if the file type is not recognized the user
is presented with a file download prompt.
NOTES: The mime types for this version are based on Apache 1.3.27
mime types may change or need to be added in the future, the mime types
are stored in an array so that an awk or other script can automatically
generate the code to make the array.
Usage:
First an instance of the mimetype class must be created, then the
getType method should be called with the filename. It will return
the mime type, an example follows.
Example:
$mimetype = new filemimetype();
print $mimetype->getType('acrobat.pdf');
Author: Jason Sheets <jsheets@shadonet.com>
License: This script is distributed under the BSD License, you are free
to use, or modify it however you like. If you find this script useful please
e-mail me.
**/
class filemimetype {
function getType($filename) {
// get base name of the filename provided by user
$filename = basename($filename);
// break file into parts seperated by .
$filename = explode('.', $filename);
// take the last part of the file to get the file extension
$filename = $filename[count($filename)-1];
// find mime type
return $this->privFindType($filename);
}
function privFindType($ext) {
// create mimetypes array
$mimetypes = $this->privBuildMimeArray();
// return mime type for extension
if (isset($mimetypes[$ext])) {
return $mimetypes[$ext];
// if the extension wasn't found return octet-stream
} else {
return 'application/octet-stream';
}
}
function privBuildMimeArray() {
return array(
"ez" => "application/andrew-inset",
"hqx" => "application/mac-binhex40",
"cpt" => "application/mac-compactpro",
"doc" => "application/msword",
"bin" => "application/octet-stream",
"dms" => "application/octet-stream",
"lha" => "application/octet-stream",
"lzh" => "application/octet-stream",
"exe" => "application/octet-stream",
"class" => "application/octet-stream",
"so" => "application/octet-stream",
"dll" => "application/octet-stream",
"oda" => "application/oda",
"pdf" => "application/pdf",
"ai" => "application/postscript",
"eps" => "application/postscript",
"ps" => "application/postscript",
"smi" => "application/smil",
"smil" => "application/smil",
"wbxml" => "application/vnd.wap.wbxml",
"wmlc" => "application/vnd.wap.wmlc",
"wmlsc" => "application/vnd.wap.wmlscriptc",
"bcpio" => "application/x-bcpio",
"vcd" => "application/x-cdlink",
"pgn" => "application/x-chess-pgn",
"cpio" => "application/x-cpio",
"csh" => "application/x-csh",
"dcr" => "application/x-director",
"dir" => "application/x-director",
"dxr" => "application/x-director",
"dvi" => "application/x-dvi",
"spl" => "application/x-futuresplash",
"gtar" => "application/x-gtar",
"hdf" => "application/x-hdf",
"js" => "application/x-javascript",
"skp" => "application/x-koan",
"skd" => "application/x-koan",
"skt" => "application/x-koan",
"skm" => "application/x-koan",
"latex" => "application/x-latex",
"nc" => "application/x-netcdf",
"cdf" => "application/x-netcdf",
"sh" => "application/x-sh",
"shar" => "application/x-shar",
"swf" => "application/x-shockwave-flash",
"sit" => "application/x-stuffit",
"sv4cpio" => "application/x-sv4cpio",
"sv4crc" => "application/x-sv4crc",
"tar" => "application/x-tar",
"tcl" => "application/x-tcl",
"tex" => "application/x-tex",
"texinfo" => "application/x-texinfo",
"texi" => "application/x-texinfo",
"t" => "application/x-troff",
"tr" => "application/x-troff",
"roff" => "application/x-troff",
"man" => "application/x-troff-man",
"me" => "application/x-troff-me",
"ms" => "application/x-troff-ms",
"ustar" => "application/x-ustar",
"src" => "application/x-wais-source",
"xhtml" => "application/xhtml+xml",
"xht" => "application/xhtml+xml",
"zip" => "application/zip",
"au" => "audio/basic",
"snd" => "audio/basic",
"mid" => "audio/midi",
"midi" => "audio/midi",
"kar" => "audio/midi",
"mpga" => "audio/mpeg",
"mp2" => "audio/mpeg",
"mp3" => "audio/mpeg",
"aif" => "audio/x-aiff",
"aiff" => "audio/x-aiff",
"aifc" => "audio/x-aiff",
"m3u" => "audio/x-mpegurl",
"ram" => "audio/x-pn-realaudio",
"rm" => "audio/x-pn-realaudio",
"rpm" => "audio/x-pn-realaudio-plugin",
"ra" => "audio/x-realaudio",
"wav" => "audio/x-wav",
"pdb" => "chemical/x-pdb",
"xyz" => "chemical/x-xyz",
"bmp" => "image/bmp",
"gif" => "image/gif",
"ief" => "image/ief",
"jpeg" => "image/jpeg",
"jpg" => "image/jpeg",
"jpe" => "image/jpeg",
"png" => "image/png",
"tiff" => "image/tiff",
"tif" => "image/tif",
"djvu" => "image/vnd.djvu",
"djv" => "image/vnd.djvu",
"wbmp" => "image/vnd.wap.wbmp",
"ras" => "image/x-cmu-raster",
"pnm" => "image/x-portable-anymap",
"pbm" => "image/x-portable-bitmap",
"pgm" => "image/x-portable-graymap",
"ppm" => "image/x-portable-pixmap",
"rgb" => "image/x-rgb",
"xbm" => "image/x-xbitmap",
"xpm" => "image/x-xpixmap",
"xwd" => "image/x-windowdump",
"igs" => "model/iges",
"iges" => "model/iges",
"msh" => "model/mesh",
"mesh" => "model/mesh",
"silo" => "model/mesh",
"wrl" => "model/vrml",
"vrml" => "model/vrml",
"css" => "text/css",
"html" => "text/html",
"htm" => "text/html",
"asc" => "text/plain",
"txt" => "text/plain",
"rtx" => "text/richtext",
"rtf" => "text/rtf",
"sgml" => "text/sgml",
"sgm" => "text/sgml",
"tsv" => "text/tab-seperated-values",
"wml" => "text/vnd.wap.wml",
"wmls" => "text/vnd.wap.wmlscript",
"etx" => "text/x-setext",
"xml" => "text/xml",
"xsl" => "text/xml",
"mpeg" => "video/mpeg",
"mpg" => "video/mpeg",
"mpe" => "video/mpeg",
"qt" => "video/quicktime",
"mov" => "video/quicktime",
"mxu" => "video/vnd.mpegurl",
"avi" => "video/x-msvideo",
"movie" => "video/x-sgi-movie",
"ice" => "x-conference-xcooltalk"
);
}
}
?> | gpl-2.0 |
xen2/mcs | class/corlib/System.Threading/CompressedStackSwitcher.cs | 2873 | //
// System.Threading.CompressedStackSwitcher structure
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Globalization;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
namespace System.Threading {
[ComVisibleAttribute (false)]
public struct CompressedStackSwitcher : IDisposable {
private CompressedStack _cs;
private Thread _t;
internal CompressedStackSwitcher (CompressedStack cs, Thread t)
{
_cs = cs;
_t = t;
}
public override bool Equals (object obj)
{
if (obj == null)
return false;
if (obj is CompressedStackSwitcher)
return op_Equality (this, (CompressedStackSwitcher)obj);
return false;
}
public override int GetHashCode ()
{
// documented as always the same for all instances
return typeof (CompressedStackSwitcher).GetHashCode ();
// Microsoft seems to return 1404280835 every time
// (even between executions).
}
[ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
public void Undo ()
{
if ((_cs != null) && (_t != null)) {
lock (_cs) {
if ((_cs != null) && (_t != null)) {
_t.SetCompressedStack (_cs);
}
_t = null;
_cs = null;
}
}
}
public static bool op_Equality (CompressedStackSwitcher c1, CompressedStackSwitcher c2)
{
if (c1._cs == null)
return (c2._cs == null);
if (c2._cs == null)
return false;
if (c1._t.ManagedThreadId != c2._t.ManagedThreadId)
return false;
return c1._cs.Equals (c2._cs);
}
public static bool op_Inequality (CompressedStackSwitcher c1, CompressedStackSwitcher c2)
{
return !op_Equality (c1, c2);
}
void IDisposable.Dispose ()
{
Undo ();
}
}
}
| gpl-2.0 |
bibishte/firmwares | stepper_firmowares/doc/html/search/all_63.js | 2179 | var searchData=
[
['config_20library',['config Library',['../group__biba__config.html',1,'']]],
['calworkparam',['CalWorkParam',['../group__biba__drv.html#ga3389079a7106f1e741c0bc447dfbcbca',1,'CalWorkParam(void): drv_8825.c'],['../group__biba__drv.html#ga3389079a7106f1e741c0bc447dfbcbca',1,'CalWorkParam(void): drv_8825.c']]],
['check_5fpin',['check_pin',['../group__biba__config.html#ga65a9fed63ff97399d2b08295253076f3',1,'config.h']]],
['checkpin',['CHECKPIN',['../group__biba__config.html#ga1d47feb8b05cf197117763115ac90485',1,'config.h']]],
['clr_5fbit',['clr_bit',['../group__biba__config.html#gaf2f231c38a29a96bac24f174fe7bf8b0',1,'config.h']]],
['clr_5fport',['clr_port',['../group__biba__config.html#ga984f41d756890774ffc7ce744024a000',1,'config.h']]],
['cmd_5fstruct',['cmd_struct',['../structcmd__struct.html',1,'']]],
['cmd_5ftbl',['cmd_tbl',['../interpreter_8c.html#a298c6b7406a09661fcde064ac4d344e0',1,'interpreter.c']]],
['config_2eh',['config.h',['../config_8h.html',1,'']]],
['constspd',['CONSTSPD',['../interpreter_8h.html#a06fc87d81c62e9abb8790b6e5713c55baf6acafdeb6976b7ff675ea2ef6944c9f',1,'CONSTSPD(): interpreter.h'],['../drv__8825_8c.html#a295a33258d6c0cfd0dd62f0574952f21',1,'ConstSpd(): drv_8825.c']]],
['convertascitouint64',['ConvertASCItouint64',['../group__biba__utils.html#gade0d11aaaeeeb0b4369bcef0819dd8f9',1,'ConvertASCItouint64(char *in): utils.c'],['../group__biba__utils.html#gade0d11aaaeeeb0b4369bcef0819dd8f9',1,'ConvertASCItouint64(char *in): utils.c']]],
['count_5fstep',['Count_Step',['../group__biba__drv.html#ga961e1c89176d3c56101bb4eddf6642dc',1,'Count_Step(step_type step, uint64_t step_count): drv_8825.c'],['../group__biba__drv.html#ga961e1c89176d3c56101bb4eddf6642dc',1,'Count_Step(step_type step, uint64_t step_count): drv_8825.c']]],
['currentdecay',['CurrentDecay',['../drv__8825_8c.html#a1cc7e950196402ba79f3e5098b08fa33',1,'drv_8825.c']]],
['currentmode',['CurrentMode',['../drv__8825_8c.html#ab08e51d202664c8cc9434eac6c46f1f3',1,'drv_8825.c']]],
['currentspeed',['CurrentSpeed',['../structMotion.html#a50860ebd661de5d104a36a92cd5f17c7',1,'Motion']]]
];
| gpl-2.0 |
HuangYuNan/thcsvr | expansions/script/c200112.lua | 1991 | --天候-晴岚
function c200112.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_TOHAND)
e2:SetDescription(aux.Stringid(200112,0))
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetProperty(EFFECT_FLAG_BOTH_SIDE)
e2:SetRange(LOCATION_SZONE)
e2:SetCountLimit(1,200112)
e2:SetLabelObject(e1)
e2:SetTarget(c200112.tg)
e2:SetOperation(c200112.op)
c:RegisterEffect(e2)
end
function c200112.tg(e,tp,eg,ep,ev,re,r,rp,chk)
local tc=Duel.GetDecktopGroup(tp,1):GetFirst()
local tc2=Duel.GetDecktopGroup(1-tp,1):GetFirst()
if chk==0 then return tc and tc:IsAbleToHand() and tc2 and tc2:IsAbleToHand() end
Duel.Hint(HINT_SELECTMSG,tp,aux.Stringid(200112,1))
e:SetLabel(Duel.SelectOption(tp,70,71,72))
Duel.Hint(HINT_SELECTMSG,1-tp,aux.Stringid(200112,1))
e:GetLabelObject():SetLabel(Duel.SelectOption(1-tp,70,71,72))
end
function c200112.op(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetDecktopGroup(tp,1):GetFirst()
local tc2=Duel.GetDecktopGroup(1-tp,1):GetFirst()
if e:GetHandler():IsOnField() and tc and tc:IsAbleToHand() and tc2 and tc2:IsAbleToHand() then
local right1=0
local right2=0
local t=0
local opt=e:GetLabel()
if opt==0 then t=TYPE_MONSTER
else if opt==1 then t=TYPE_SPELL
else t=TYPE_TRAP end
end
Duel.ConfirmDecktop(tp,1)
if tc:IsType(t) then
Duel.SendtoHand(tc,tp,REASON_EFFECT)
right1=1
else
Duel.ShuffleDeck(tp)
end
opt=e:GetLabelObject():GetLabel()
if opt==0 then t=TYPE_MONSTER
else if opt==1 then t=TYPE_SPELL
else t=TYPE_TRAP end
end
Duel.ConfirmDecktop(1-tp,1)
if tc2:IsType(t) then
Duel.SendtoHand(tc2,1-tp,REASON_EFFECT)
right2=1
else
Duel.ShuffleDeck(1-tp)
end
if right1==1 and right2==0 then
Duel.Draw(tp,1,REASON_EFFECT)
end
end
end
function c200112.efilter(e,re)
return e:GetHandlerPlayer()~=re:GetHandlerPlayer() and re:IsActiveType(TYPE_SPELL+TYPE_TRAP)
end | gpl-2.0 |
jfbvm/planigle | vendor/plugins/acts_as_audited/lib/audit_sweeper.rb | 1673 |
module CollectiveIdea #:nodoc:
module ActionController #:nodoc:
module Audited #:nodoc:
def self.included(base) # :nodoc:
base.extend ClassMethods
end
module ClassMethods
# Declare models that should be audited in your controller
#
# class ApplicationController < ActionController::Base
# audit User, Widget
# end
#
# You can also specify an options hash which will be passed on to
# Rails' cache_sweeper call:
#
# audit User, :only => [:create, :edit, :destroy]
#
def audit(*models)
options = models.last.is_a?(Hash) ? models.pop : {}
models.each do |clazz|
clazz.send :acts_as_audited unless clazz.respond_to?(:disable_auditing)
# disable ActiveRecord callbacks, which are replaced by the AuditSweeper
clazz.send :disable_auditing
end
AuditSweeper.class_eval do
observe *models
end
class_eval do
cache_sweeper :audit_sweeper, options
end
end
end
end
end
end
class AuditSweeper < ActionController::Caching::Sweeper #:nodoc:
def after_create(record)
record.send(:write_audit, :create, current_user)
end
def after_destroy(record)
record.send(:write_audit, :destroy, current_user)
end
def after_update(record)
record.send(:write_audit, :update, current_user)
end
def after_save(record)
record.send(:clear_changed_attributes)
end
def current_user
controller.send :current_user if controller.respond_to?(:current_user)
end
end
| gpl-2.0 |
paranoiacblack/gcc | libstdc++-v3/testsuite/23_containers/unordered_multiset/requirements/explicit_instantiation/3.cc | 981 | // { dg-do compile { target c++11 } }
// Copyright (C) 2007-2016 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 3, 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 COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#include <unordered_set>
using namespace std;
template class std::unordered_multiset<int, hash<int>, equal_to<int>,
allocator<char>>;
| gpl-2.0 |
Doap/acopio | wp-content/plugins/store-locator-le/include/class.csvimport.php | 11004 | <?php
if (!defined( 'ABSPATH' )) { exit; } // Exit if accessed directly, dang hackers
// Make sure the class is only defined once.
//
if (!class_exists('CSVImport')) {
/**
* CSV Import
*
* @package StoreLocatorPlus\CSVImport
* @author Lance Cleveland <lance@charlestonsw.com>
* @copyright 2013 Charleston Software Associates, LLC
*/
class CSVImport {
//----------------------------------------------------------------------------
// Properties : Private (only accessed by defining class)
//----------------------------------------------------------------------------
/**
* The CSV file handle.
*
* @var file $filehandle
*/
private $filehandle;
//----------------------------------------------------------------------------
// Properties : Protected (access by defining class, inherited class, parents)
//----------------------------------------------------------------------------
/**
* The current CSV data array.
*
* @var string[] $data
*/
protected $data;
/**
* List of field names being processed.
*
* @var string[] $fieldnames
*/
protected $fieldnames;
/**
* Does the first line contain field names?
*
* @var boolean $firstline_has_fieldname
*/
protected $firstline_has_fieldname = false;
/**
* True if the first line has already been skipped.
*
* @var boolean $first_has_been_skipped
*/
protected $first_has_been_skipped = false;
/**
* What is the maximum data columns allowed for this CSV file?
*
* @var int $maxcols
*/
protected $maxcols;
/**
* The parent object.
*
* @var object $parent
*/
protected $parent;
/**
* The main SLP Plugin object.
*
* @var SLPlus $plugin
*/
protected $plugin;
/**
*
* @var mixed[]
*/
protected $processing_counts;
/**
* Skip the first line in the file?
*
* @var boolean $skip_firstline
*/
protected $skip_firstline = false;
/**
* The prefix to strip from field name in header row.
*
* @var string $strip_prefix
*/
protected $strip_prefix = '';
//-------------------------
// Methods
//-------------------------
/**
* Invoke the CSV Import object using a named array to configure behavior parameters.
*
* Parameters:
* - firstline_has_fieldname <boolean> true if first line has field names for the columns
* - parent <object> pointer to the invoked add-on object
* - plugin <object> pointer to the invoked base plugin (\SLPlus) object
* - skip_firstline <boolean> true if the first line does not have data to process
* - strip_prefix <string> prefix to strip out of field names if first line has field names
*
* Example:
* $this->importer = new CSVImport(array('parent'=>$this,'plugin'=>$this->plugin));
*
* @param object $parent
*/
function __construct($params) {
foreach ($params as $property=>$value) {
if (property_exists($this,$property)) { $this->$property = $value; }
else { die("import property $property does not exist<br/>\n"); }
}
if ($this->firstline_has_fieldname) { $this->skip_firstline = true; }
}
/**
* Create the bulk upload form using wpCSL settings methods.
*
* This should be overriden.
*/
function create_BulkUploadForm() {
die( 'function CSVImport::'.__FUNCTION__.' must be over-ridden in a sub-class.' );
}
/**
* Allows WordPress to process csv file types
*
* @param array $existing_mimes
* @return string
*/
function filter_AddMimeType ( $existing_mimes=array() ) {
$existing_mimes['csv'] = 'text/csv';
return $existing_mimes;
}
/**
* Process a CSV File.
*
* This should be extended.
*
*/
function process_File() {
// Is the file name set? If not, exit.
//
if (!isset($_FILES['csvfile']['name']) || empty($_FILES['csvfile']['name'])) {
print "<div class='updated fade'>".__('Import file name not set.','csa-slplus').'</div>';
return;
}
// Does the file have any content? If not, exit.
//
if ($_FILES['csvfile']['size'] <= 0) {
print "<div class='updated fade'>".__('Import file was empty.','csa-slplus').'</div>';
return;
}
// Is the file CSV? If not, exit.
//
$arr_file_type = wp_check_filetype( basename( $_FILES['csvfile']['name'] ) , array( 'csv' => 'text/csv' ) );
if ($arr_file_type['type'] != 'text/csv') {
print "<div class='updated fade'>".
__('Uploaded file needs to be in CSV format.','csa-slplus') .
sprintf(__('Type was %s.','csa-slplus'),$arr_file_type['type']) .
'</div>';
return;
}
// Can the file be saved to disk? If not, exit.
//
$updir = wp_upload_dir();
$updir = $updir['basedir'].'/slplus_csv';
if (!is_dir($updir)) { mkdir($updir,0755); }
if (!move_uploaded_file($_FILES['csvfile']['tmp_name'],$updir.'/'.$_FILES['csvfile']['name'])) {
return;
}
// Line Endings
//
$adle_setting = ini_get('auto_detect_line_endings');
ini_set('auto_detect_line_endings', true);
// Can the file be opened? If not, exit.
//
if (($this->filehandle = fopen($updir.'/'.$_FILES['csvfile']['name'], "r")) === FALSE) {
print "<div class='updated fade'>".
__('Could not open CSV file for processing.','csa-slplus') . '<br/>' .
$updir.'/'.$_FILES['csvfile']['name'] .
'</div>';
ini_set('auto_detect_line_endings', $adle_setting);
return;
}
// Set first line processing flag.
//
$this->first_has_been_skipped = false;
// Set the field names.
//
$this->set_FieldNames();
// Reset the notification message to get a clean message stack.
//
$this->plugin->notifications->delete_all_notices();
// Add CSV as a mime type
//
add_filter('upload_mimes', array($this,'filter_AddMimeType'));
$reccount = 0;
$this->maxcols = count($this->fieldnames);
$this->processing_counts = array(
'added' => 0,
'exists' => 0,
'not_updated' => 0,
'skipped' => 0,
'updated' => 0,
);
// FILTER: slp_csv_processing_messages
// Set the message array to be printed out for the above counters.
//
$location_processing_types = apply_filters('slp_csv_processing_messages',array());
// Turn off notifications for OK addresses.
//
if ( is_object( $this->plugin->AdminUI->ManageLocations ) ) {
$this->plugin->AdminUI->ManageLocations->geocodeSkipOKNotices = true;
}
// Loop through all records
//
while (($this->data = fgetcsv($this->filehandle)) !== FALSE) {
// Skip First Line
//
if (!$this->first_has_been_skipped && $this->skip_firstline){
$this->first_has_been_skipped = true;
continue;
}
// HOOK: slp_csv_processing
// Process the CSV data.
//
do_action('slp_csv_processing');
$reccount++;
}
fclose($this->filehandle);
ini_set('auto_detect_line_endings', $adle_setting);
// Show Notices
//
$this->plugin->notifications->display();
// Tell them how many locations were added
//
if ($reccount > 0) {
print "<div class='updated fade'>".
sprintf("%d",$reccount) ." " .
__(" processed.",'csa-slplus') .
'</div>';
}
foreach ($this->processing_counts as $count_type=>$count) {
if ($count > 0) {
print "<div class='updated fade'>".sprintf("%d %s",$count,$location_processing_types[$count_type]).'</div>';
}
}
}
/**
* Set the field names array for the fields being processed.
*
*/
function set_FieldNames() {
// Special header processing
//
if ($this->skip_firstline && $this->firstline_has_fieldname) {
if (($headerColumns = fgetcsv($this->filehandle)) !== FALSE) {
foreach($headerColumns as $label) {
$clean_label = trim(sanitize_key($label));
$label = preg_replace('/\W/','_',$clean_label);
if (!empty($this->strip_prefix)) {
if (preg_match('/^'.$this->strip_prefix.'/',$label)!==1) { $label = $this->strip_prefix.$label; }
}
$this->fieldnames[] = $label;
}
$this->first_has_been_skipped = true;
}
// FILTER: slp_csv_fieldnames
// Modify the field names read in via the CSV header line.
//
$this->fieldnames = apply_filters('slp_csv_fieldnames',$this->fieldnames);
}
// Set the default
//
if (!isset($this->fieldnames)) {
// FILTER: slp_csv_default_fieldnames
// Set default field names if the header line does not have field names.
//
$this->fieldnames = apply_filters('slp_csv_default_fieldnames',array());
}
}
}
} | gpl-2.0 |
damasiorafael/inppnet | cache/t3_pages/53bbb79b4980f60ea0786b85df096904-cache-t3_pages-534b7a4d0666d1f79341690fb8aa3002.php | 1003 | <?php die("Access Denied"); ?>#x#s:961:" 1404855065<?xml version="1.0" encoding="utf-8"?>
<!-- generator="Joomla! - Open Source Content Management" -->
<?xml-stylesheet href="/media/system/css/modal.css" type="text/css"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="pt-br">
<title type="text">Inppnet - Instituto Nacional de Parapsicologia Psicometafísica - Inppnet - Instituto Nacional de Parapsicologia Psicometafísica</title>
<subtitle type="text">Instituto Nacional de Parapsicologia Psicometafísica. Cursos Online</subtitle>
<link rel="alternate" type="text/html" href="http://www.inppnet.com.br"/>
<id>http://www.inppnet.com.br/index.php</id>
<updated>2014-07-08T21:31:05+00:00</updated>
<generator uri="http://joomla.org" version="2.5">Joomla! - Open Source Content Management</generator>
<link rel="self" type="application/atom+xml" href="http://www.inppnet.com.br/index.php?option=com_content&view=category&id=20&format=feed&type=atom"/>
</feed>
"; | gpl-2.0 |
Songbird0/PasswordGenerator | src/fr/songbird/launcher/Launcher.java | 2816 | package fr.songbird.launcher;
import fr.songbird.generator.cmdmanager.CmdManager;
import fr.songbird.survivalDevKit.Downloader;
import fr.songbird.tools.ScannerHM;
import fr.songbird.survivalDevKit.Cookies;
/**
*
* @author songbird
* @version 0.2_0-ALPHA
*/
public class Launcher {
/**
* Good boy, cookie.
*/
private Cookies cookie = new Cookies();
private static String[] argsOfMethodMain = null;
private Downloader dl = null;
/**
* Reference of current instance.
*/
private final ScannerHM readerKeyBoard = new ScannerHM (System.in);
public Launcher(){
aLittleFormality();
if(CmdManager.argDetection(getArgsOfMethodMain())){
new CmdManager();
}
else{
Runtime.getRuntime().exit(1);
}
}
//###### PRIVATE METHODS ######
/**
* This method downloads and reads the documents.
* @param filename
* @see Downloader
*/
private void downloadInformationUser(String filename, String fileURL, String[] repositories){
dl= new Downloader(fileURL, filename, repositories);
}
private static String[] getArgsOfMethodMain(){
return Launcher.argsOfMethodMain;
}
/**
* Downloads necessaries files.
*/
private void aLittleFormality(){
Cookies.setPathFileSerial(cookie.buildingOfThePath(new String[]{".PasswordGenerator", "Informations"}, "lang.ser"));
if(!Cookies.getPathFileSerial().exists()){
String lang = null;
String response = new String("");
System.out.println("French or english speaker ? [FR/EN]:");
lang = readerKeyBoard.ReadInputKeyboard();
//TODO Structure conditionnelle provisoire
if(lang.equals("FR")){
cookie.setLang(lang);
Cookies.serializeCookies(cookie, Cookies.getPathFileSerial());
downloadInformationUser((lang.equals("FR")? "LISEZ_MOI_FR": "READ_ME_EN"),
lang.equals("FR")? "https://www.dropbox.com/s/khocq519rsyuzj0/LISEZ_MOI_FR.html?&dl=1" : "sorry, but the 'readme' in english isn't yet avalable. Soon ;-)", new String[]{".PasswordGenerator", "Informations"});
while(!response.equals("y") || !response.equals("Y")){
System.out.println("Avez-vous lu la documentation téléchargée ? y/n");
response = readerKeyBoard.ReadInputKeyboard();
if(response.equals("n") || response.equals("N")){
System.out.println("Alors allez-y ! :-)\nPour rappel, elle se trouve ici: "+dl.getDefinitivePath()+"\n\n");
continue;
}
else if(response.equals("y") || response.equals("Y")){
break;
}
}
}
else{
cookie.setLang(lang);
Cookies.serializeCookies(cookie, Cookies.getPathFileSerial());
System.out.println("sorry, but the 'readme' in english isn't yet avalable. Soon ;-)\n\n");
}
}
}
//###### PUBLIC METHODS ######
public static void main(String[] args) {
Launcher.argsOfMethodMain = args;
new Launcher();
}
}
| gpl-2.0 |
tyraela/NetherCore | src/server/scripts/Northrend/Naxxramas/boss_sapphiron.cpp | 16377 | /*
* Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.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 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/>.
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "Player.h"
#include "SpellInfo.h"
#include "naxxramas.h"
enum Yells
{
EMOTE_AIR_PHASE = 0,
EMOTE_GROUND_PHASE = 1,
EMOTE_BREATH = 2,
EMOTE_ENRAGE = 3
};
enum Spells
{
SPELL_FROST_AURA = 28531,
SPELL_CLEAVE = 19983,
SPELL_TAIL_SWEEP = 55697,
SPELL_SUMMON_BLIZZARD = 28560,
SPELL_LIFE_DRAIN = 28542,
SPELL_ICEBOLT = 28522,
SPELL_FROST_BREATH = 29318,
SPELL_FROST_EXPLOSION = 28524,
SPELL_FROST_MISSILE = 30101,
SPELL_BERSERK = 26662,
SPELL_DIES = 29357,
SPELL_CHILL = 28547,
};
enum Phases
{
PHASE_NULL = 0,
PHASE_BIRTH,
PHASE_GROUND,
PHASE_FLIGHT
};
enum Events
{
EVENT_BERSERK = 1,
EVENT_CLEAVE,
EVENT_TAIL,
EVENT_DRAIN,
EVENT_BLIZZARD,
EVENT_FLIGHT,
EVENT_LIFTOFF,
EVENT_ICEBOLT,
EVENT_BREATH,
EVENT_EXPLOSION,
EVENT_LAND,
EVENT_GROUND,
EVENT_BIRTH
};
enum Misc
{
NPC_BLIZZARD = 16474,
GO_ICEBLOCK = 181247,
// The Hundred Club
DATA_THE_HUNDRED_CLUB = 21462147,
MAX_FROST_RESISTANCE = 100
};
typedef std::map<uint64, uint64> IceBlockMap;
class boss_sapphiron : public CreatureScript
{
public:
boss_sapphiron() : CreatureScript("boss_sapphiron") { }
struct boss_sapphironAI : public BossAI
{
boss_sapphironAI(Creature* creature) :
BossAI(creature, BOSS_SAPPHIRON), _phase(PHASE_NULL),
_map(me->GetMap())
{ }
void InitializeAI() override
{
_canTheHundredClub = true;
float x, y, z;
me->GetPosition(x, y, z);
me->SummonGameObject(GO_BIRTH, x, y, z, 0, 0, 0, 0, 0, 0);
me->SetVisible(false);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
me->SetReactState(REACT_PASSIVE);
BossAI::InitializeAI();
}
void Reset() override
{
_Reset();
if (_phase == PHASE_FLIGHT)
ClearIceBlock();
_phase = PHASE_NULL;
_canTheHundredClub = true;
_checkFrostResistTimer = 5 * IN_MILLISECONDS;
}
void EnterCombat(Unit* /*who*/) override
{
_EnterCombat();
me->CastSpell(me, SPELL_FROST_AURA, true);
events.ScheduleEvent(EVENT_BERSERK, 15 * MINUTE * IN_MILLISECONDS);
EnterPhaseGround();
CheckPlayersFrostResist();
}
void SpellHitTarget(Unit* target, SpellInfo const* spell) override
{
if (spell->Id == SPELL_ICEBOLT)
{
IceBlockMap::iterator itr = _iceblocks.find(target->GetGUID());
if (itr != _iceblocks.end() && !itr->second)
{
if (GameObject* iceblock = me->SummonGameObject(GO_ICEBLOCK, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0, 0, 0, 0, 0, 25))
itr->second = iceblock->GetGUID();
}
}
}
void JustDied(Unit* /*killer*/) override
{
_JustDied();
me->CastSpell(me, SPELL_DIES, true);
CheckPlayersFrostResist();
}
void MovementInform(uint32 /*type*/, uint32 id) override
{
if (id == 1)
events.ScheduleEvent(EVENT_LIFTOFF, 0);
}
void DoAction(int32 param) override
{
if (param == DATA_SAPPHIRON_BIRTH)
{
_phase = PHASE_BIRTH;
events.ScheduleEvent(EVENT_BIRTH, 23 * IN_MILLISECONDS);
}
}
void CheckPlayersFrostResist()
{
if (_canTheHundredClub && _map && _map->IsRaid())
{
Map::PlayerList const &players = _map->GetPlayers();
for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr)
{
if (itr->GetSource()->GetResistance(SPELL_SCHOOL_FROST) > MAX_FROST_RESISTANCE)
{
_canTheHundredClub = false;
break;
}
}
}
}
void EnterPhaseGround()
{
_phase = PHASE_GROUND;
me->SetReactState(REACT_AGGRESSIVE);
events.SetPhase(PHASE_GROUND);
events.ScheduleEvent(EVENT_CLEAVE, urand(5, 15) * IN_MILLISECONDS, 0, PHASE_GROUND);
events.ScheduleEvent(EVENT_TAIL, urand(5, 15) * IN_MILLISECONDS, 0, PHASE_GROUND);
events.ScheduleEvent(EVENT_DRAIN, 24 * IN_MILLISECONDS, 0, PHASE_GROUND);
events.ScheduleEvent(EVENT_BLIZZARD, urand(5, 10) * IN_MILLISECONDS, 0, PHASE_GROUND);
events.ScheduleEvent(EVENT_FLIGHT, 45 * IN_MILLISECONDS);
}
void ClearIceBlock()
{
for (IceBlockMap::const_iterator itr = _iceblocks.begin(); itr != _iceblocks.end(); ++itr)
{
if (Player* player = ObjectAccessor::GetPlayer(*me, itr->first))
player->RemoveAura(SPELL_ICEBOLT);
if (GameObject* go = ObjectAccessor::GetGameObject(*me, itr->second))
go->Delete();
}
_iceblocks.clear();
}
uint32 GetData(uint32 data) const override
{
if (data == DATA_THE_HUNDRED_CLUB)
return _canTheHundredClub;
return 0;
}
void UpdateAI(uint32 diff) override
{
if (!_phase)
return;
events.Update(diff);
if ((_phase != PHASE_BIRTH && !UpdateVictim()) || !CheckInRoom())
return;
if (_canTheHundredClub)
{
if (_checkFrostResistTimer <= diff)
{
CheckPlayersFrostResist();
_checkFrostResistTimer = 5 * IN_MILLISECONDS;
}
else
_checkFrostResistTimer -= diff;
}
if (_phase == PHASE_GROUND)
{
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_BERSERK:
Talk(EMOTE_ENRAGE);
DoCast(me, SPELL_BERSERK);
return;
case EVENT_CLEAVE:
DoCastVictim(SPELL_CLEAVE);
events.ScheduleEvent(EVENT_CLEAVE, urand(5, 15) * IN_MILLISECONDS, 0, PHASE_GROUND);
return;
case EVENT_TAIL:
DoCastAOE(SPELL_TAIL_SWEEP);
events.ScheduleEvent(EVENT_TAIL, urand(5, 15) * IN_MILLISECONDS, 0, PHASE_GROUND);
return;
case EVENT_DRAIN:
DoCastAOE(SPELL_LIFE_DRAIN);
events.ScheduleEvent(EVENT_DRAIN, 24 * IN_MILLISECONDS, 0, PHASE_GROUND);
return;
case EVENT_BLIZZARD:
{
//DoCastAOE(SPELL_SUMMON_BLIZZARD);
if (Creature* summon = DoSummon(NPC_BLIZZARD, me, 0.0f, urand(25, 30) * IN_MILLISECONDS, TEMPSUMMON_TIMED_DESPAWN))
summon->GetMotionMaster()->MoveRandom(40);
events.ScheduleEvent(EVENT_BLIZZARD, RAID_MODE(20, 7) * IN_MILLISECONDS, 0, PHASE_GROUND);
break;
}
case EVENT_FLIGHT:
if (HealthAbovePct(10))
{
_phase = PHASE_FLIGHT;
events.SetPhase(PHASE_FLIGHT);
me->SetReactState(REACT_PASSIVE);
me->AttackStop();
float x, y, z, o;
me->GetHomePosition(x, y, z, o);
me->GetMotionMaster()->MovePoint(1, x, y, z);
return;
}
break;
}
}
DoMeleeAttackIfReady();
}
else
{
if (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_LIFTOFF:
Talk(EMOTE_AIR_PHASE);
me->SetDisableGravity(true);
events.ScheduleEvent(EVENT_ICEBOLT, 1500);
_iceboltCount = RAID_MODE(2, 3);
return;
case EVENT_ICEBOLT:
{
std::vector<Unit*> targets;
std::list<HostileReference*>::const_iterator i = me->getThreatManager().getThreatList().begin();
for (; i != me->getThreatManager().getThreatList().end(); ++i)
if ((*i)->getTarget()->GetTypeId() == TYPEID_PLAYER && !(*i)->getTarget()->HasAura(SPELL_ICEBOLT))
targets.push_back((*i)->getTarget());
if (targets.empty())
_iceboltCount = 0;
else
{
std::vector<Unit*>::const_iterator itr = targets.begin();
advance(itr, rand32() % targets.size());
_iceblocks.insert(std::make_pair((*itr)->GetGUID(), 0));
DoCast(*itr, SPELL_ICEBOLT);
--_iceboltCount;
}
if (_iceboltCount)
events.ScheduleEvent(EVENT_ICEBOLT, 1 * IN_MILLISECONDS);
else
events.ScheduleEvent(EVENT_BREATH, 1 * IN_MILLISECONDS);
return;
}
case EVENT_BREATH:
{
Talk(EMOTE_BREATH);
DoCastAOE(SPELL_FROST_MISSILE);
events.ScheduleEvent(EVENT_EXPLOSION, 8 * IN_MILLISECONDS);
return;
}
case EVENT_EXPLOSION:
CastExplosion();
ClearIceBlock();
events.ScheduleEvent(EVENT_LAND, 3 * IN_MILLISECONDS);
return;
case EVENT_LAND:
me->HandleEmoteCommand(EMOTE_ONESHOT_LAND);
Talk(EMOTE_GROUND_PHASE);
me->SetDisableGravity(false);
events.ScheduleEvent(EVENT_GROUND, 1500);
return;
case EVENT_GROUND:
EnterPhaseGround();
return;
case EVENT_BIRTH:
me->SetVisible(true);
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
me->SetReactState(REACT_AGGRESSIVE);
return;
}
}
}
}
void CastExplosion()
{
DoZoneInCombat(); // make sure everyone is in threatlist
std::vector<Unit*> targets;
std::list<HostileReference*>::const_iterator i = me->getThreatManager().getThreatList().begin();
for (; i != me->getThreatManager().getThreatList().end(); ++i)
{
Unit* target = (*i)->getTarget();
if (target->GetTypeId() != TYPEID_PLAYER)
continue;
if (target->HasAura(SPELL_ICEBOLT))
{
target->ApplySpellImmune(0, IMMUNITY_ID, SPELL_FROST_EXPLOSION, true);
targets.push_back(target);
continue;
}
for (IceBlockMap::const_iterator itr = _iceblocks.begin(); itr != _iceblocks.end(); ++itr)
{
if (GameObject* go = GameObject::GetGameObject(*me, itr->second))
{
if (go->IsInBetween(me, target, 2.0f)
&& me->GetExactDist2d(target->GetPositionX(), target->GetPositionY()) - me->GetExactDist2d(go->GetPositionX(), go->GetPositionY()) < 5.0f)
{
target->ApplySpellImmune(0, IMMUNITY_ID, SPELL_FROST_EXPLOSION, true);
targets.push_back(target);
break;
}
}
}
}
me->CastSpell(me, SPELL_FROST_EXPLOSION, true);
for (std::vector<Unit*>::const_iterator itr = targets.begin(); itr != targets.end(); ++itr)
(*itr)->ApplySpellImmune(0, IMMUNITY_ID, SPELL_FROST_EXPLOSION, false);
}
private:
Phases _phase;
uint32 _iceboltCount;
IceBlockMap _iceblocks;
bool _canTheHundredClub;
uint32 _checkFrostResistTimer;
Map* _map;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new boss_sapphironAI(creature);
}
};
class achievement_the_hundred_club : public AchievementCriteriaScript
{
public:
achievement_the_hundred_club() : AchievementCriteriaScript("achievement_the_hundred_club") { }
bool OnCheck(Player* /*source*/, Unit* target) override
{
return target && target->GetAI()->GetData(DATA_THE_HUNDRED_CLUB);
}
};
void AddSC_boss_sapphiron()
{
new boss_sapphiron();
new achievement_the_hundred_club();
}
| gpl-2.0 |
sj5/viwbaw | lib/viwbaw/buffer.rb | 26140 | require 'digest'
require 'pathname'
$paste_lines = false
class BufferList < Array
def <<(_buf)
super
$buffer =_buf
@current_buf = self.size - 1
end
def switch()
debug "SWITCH BUF. bufsize:#{self.size}, curbuf: #{@current_buf}"
@current_buf += 1
@current_buf = 0 if @current_buf >= self.size
#$buffer = self[@current_buf]
#$buffer.need_redraw!
m = method("switch")
set_last_command({method: m, params: []})
set_current_buffer(@current_buf)
#set_window_title("VIwbaw - #{File.basename($buffer.fname)}")
# TODO: set window title
end
def get_buffer_by_filename(fname)
#TODO: check using stat/inode? http://ruby-doc.org/core-1.9.3/File/Stat.html#method-i-ino
buf_idx = self.index{|b| b.fname == fname}
return buf_idx
end
def set_current_buffer(buffer_i)
$buffer = self[buffer_i]
@current_buf = buffer_i
#$buffer = buf
debug "SWITCH BUF2. bufsize:#{self.size}, curbuf: #{@current_buf}"
set_window_title("VIwbaw - #{$buffer.basename}")
$buffer.need_redraw!
end
def close_buffer(buffer_i)
self.slice!(buffer_i)
@current_buf = 0 if @current_buf >= self.size
if self.size==0
self << Buffer.new("emptybuf\n")
end
set_current_buffer(@current_buf)
end
def close_current_buffer
close_buffer(@current_buf)
end
end
class Buffer < String
#attr_reader (:pos, :cpos, :lpos)
attr_reader :pos, :lpos, :cpos, :deltas, :edit_history, :fname, :call_func, :pathname, :basename
attr_writer :call_func
def initialize(str="\n",fname=nil)
if(str[-1] != "\n")
str << "\n"
end
super(str)
t1 = Time.now
@line_ends = scan_indexes(self,/\n/)
puts @line_ends
puts str.inspect
@fname = fname
@basename = ""
@pathname = Pathname.new(fname) if @fname
@basename = @pathname.basename if @fname
@pos = 0 # Position in whole string
@cpos = 0 # Column position on current line
@lpos = 0 # Number of current line
@edit_version = 0 # +1 for every buffer modification
@larger_cpos = 0
@need_redraw = 1
@call_func = nil
@deltas = []
@edit_history = []
@redo_stack = []
@edit_pos_history = []
@edit_pos_history_i = 0
puts Time.now - t1
# TODO: add \n when chars are added after last \n
self << "\n" if self[-1] != "\n"
end
def revert()
puts @fname.inspect
str = read_file("",@fname)
self.set_content(str)
end
def set_content(str)
self.replace(str)
@line_ends = scan_indexes(self,/\n/)
#puts str.inspect
@fname = fname
@basename = ""
@pathname = Pathname.new(fname) if @fname
@basename = @pathname.basename if @fname
@pos = 0 # Position in whole string
@cpos = 0 # Column position on current line
@lpos = 0 # Number of current line
@edit_version = 0 # +1 for every buffer modification
@larger_cpos = 0
@need_redraw = 1
@call_func = nil
@deltas = []
@edit_history = []
@redo_stack = []
@edit_pos_history = []
@edit_pos_history_i = 0
end
def set_filename(filename)
@fname = filename
@pathname = Pathname.new(fname) if @fname
@basename = @pathname.basename if @fname
end
def line(lpos)
#TODO: implement using line_range()
if lpos >= @line_ends.size
debug("lpos too large") #TODO
return ""
elsif lpos == @line_ends.size
end
start = @line_ends[lpos - 1] + 1 if lpos > 0
start = 0 if lpos == 0
_end = @line_ends[lpos]
debug "start: _#{start}, end: #{_end}"
return self[start.._end]
end
#TODO: change to apply=true as default
def add_delta(delta,apply=false)
@edit_version += 1
@redo_stack = []
if apply
delta = run_delta(delta)
else
@deltas << delta
end
@edit_history << delta
end
def run_delta(delta)
pos = delta[0]
if @edit_pos_history.any? and (@edit_pos_history.last - pos).abs <= 2
@edit_pos_history.pop
end
@edit_pos_history << pos
@edit_pos_history_i = 0
if delta[1] == DELETE
delta[3] = self.slice!(delta[0],delta[2])
@deltas << delta
update_index(pos,-delta[2])
update_line_ends(pos,-delta[2],delta[3])
elsif delta[1] == INSERT
self.insert(delta[0],delta[3])
@deltas << delta
puts [pos,+delta[2]].inspect
update_index(pos,+delta[2])
update_line_ends(pos,+delta[2],delta[3])
end
sanity_check_line_ends
return delta
end
def update_index(pos,changeamount)
puts @edit_pos_history.inspect
@edit_pos_history.collect!{|x| return x if x <= pos; return x + changeamount if x > pos}
end
def jump_to_last_edit()
@edit_pos_history_i += 1
puts @edit_pos_history.inspect
if @edit_pos_history.size >= @edit_pos_history_i
set_pos(@edit_pos_history[-@edit_pos_history_i])
end
end
def undo()
puts @edit_history.inspect
return if !@edit_history.any?
last_delta = @edit_history.pop
@redo_stack << last_delta
puts last_delta.inspect
if last_delta[1] == DELETE
d = [last_delta[0],INSERT,0,last_delta[3]]
run_delta(d)
elsif last_delta[1] == INSERT
d = [last_delta[0],DELETE,last_delta[3].size]
run_delta(d)
else
return #TODO: assert?
end
@pos = last_delta[0]
#recalc_line_ends #TODO: optimize?
calculate_line_and_column_pos
end
def redo()
return if !@redo_stack.any?
#last_delta = @edit_history[-1].pop
redo_delta = @redo_stack.pop
#printf("==== UNDO ====\n")
puts redo_delta.inspect
run_delta(redo_delta)
@edit_history << redo_delta
@pos = redo_delta[0]
#recalc_line_ends #TODO: optimize?
calculate_line_and_column_pos
end
def current_char()
return self[@pos]
end
def current_line()
range = line_range(@lpos,1)
return self[range]
end
def current_line_range()
range = line_range(@lpos,1)
return range
end
def line_range(start_line,num_lines)
end_line = start_line + num_lines - 1
if end_line >= @line_ends.size
debug("lpos too large") #TODO
end_line = @line_ends.size - 1
end
start = @line_ends[start_line - 1] + 1 if start_line > 0
start = 0 if start_line == 0
_end = @line_ends[end_line]
debug "line range: start=#{start}, end=#{_end}"
return start.._end
end
def copy(range_id)
$paste_lines = false
puts "range_id: #{range_id}"
puts range_id.inspect
range = get_range(range_id)
puts range.inspect
set_clipboard(self[range])
end
def recalc_line_ends()
t1 = Time.now
leo = @line_ends.clone
@line_ends = scan_indexes(self,/\n/)
if @line_ends == leo
puts "No change to line ends"
else
puts "CHANGES to line ends"
end
puts "Scan line_end time: #{Time.now - t1}"
#puts @line_ends
end
def sanity_check_line_ends()
leo = @line_ends.clone
@line_ends = scan_indexes(self,/\n/)
if @line_ends == leo
puts "No change to line ends"
else
puts "CHANGES to line ends"
puts leo.inspect
puts @line_ends.inspect
exit
end
end
def update_line_ends(pos,changeamount,changestr)
puts @line_ends.inspect
puts pos
if changeamount > -1
changeamount=changestr.size
i = scan_indexes(changestr,/\n/)
i.collect!{|x|x+pos}
puts "new LINE ENDS:#{i.inspect}"
end
puts "change:#{changeamount}"
#@line_ends.collect!{|x| return x if x <= pos; return x + changeamount if x > pos}
@line_ends.collect!{|x| r=nil;
r=x if x < pos;
r=x + changeamount if changeamount < 0 && x +changeamount >= pos;
r=x + changeamount if changeamount > 0 && x >= pos;
r}.compact!
if changeamount > -1
@line_ends.concat(i)
@line_ends.sort!
end
end
def at_end_of_line?()
return ( self[@pos] == "\n" or at_end_of_buffer? )
end
def at_end_of_buffer?()
return @pos == self.size
end
def set_pos(new_pos)
if new_pos >= self.size
@pos = self.size # right side of last char
elsif new_pos >= 0
@pos = new_pos
end
calculate_line_and_column_pos
end
# Calculate the two dimensional column and line positions based on current
# (one dimensional) position in the buffer.
def calculate_line_and_column_pos()
@pos = self.size if @pos > self.size
@pos = 0 if @pos < 0
#puts @line_ends
next_line_end = @line_ends.bsearch {|x| x >= @pos } #=> 4
#puts @line_ends
#puts "nle: #{next_line_end}"
@lpos = @line_ends.index(next_line_end)
if @lpos == nil
@lpos = @line_ends.size
else
#@lpos += 1
end
@cpos = @pos
if @lpos > 0
@cpos -= @line_ends[@lpos - 1] #TODO??
end
end
# Calculate the one dimensional array index based on column and line positions
def calculate_pos_from_cpos_lpos()
if @lpos > 0
new_pos = @line_ends[@lpos - 1] + 1
else
new_pos = 0
end
if @cpos > (line(@lpos).size - 1)
debug("$cpos too large: #{@cpos} #{@lpos}")
if @larger_cpos < @cpos
@larger_cpos = @cpos
end
@cpos = line(@lpos).size - 1
end
new_pos += @cpos
@pos = new_pos
end
def delete(op)
# Delete selection
if op== SELECTION && visual_mode?
(startpos,endpos) = get_visual_mode_range2
delete_range(startpos,endpos)
@pos = [@pos,@selection_start].min
end_visual_mode
return
# Delete current char
elsif op == CURRENT_CHAR_FORWARD
return if @pos >= self.size - 1 # May not delete last '\n'
add_delta([@pos,DELETE,1],true)
# Delete current char and then move backward
elsif op == CURRENT_CHAR_BACKWARD
add_delta([@pos,DELETE,1],true)
@pos -= 1
# Delete the char before current char and move backward
elsif op == BACKWARD_CHAR
add_delta([@pos - 1,DELETE,1],true)
@pos -= 1
elsif op == FORWARD_CHAR #TODO: ok?
add_delta([@pos+1,DELETE,1],true)
end
#recalc_line_ends
calculate_line_and_column_pos
#need_redraw!
end
def delete_range(startpos,endpos)
#s = self.slice!(startpos..endpos)
set_clipboard(self[startpos..endpos])
add_delta([startpos,DELETE,(endpos - startpos + 1)],true)
#recalc_line_ends
calculate_line_and_column_pos
end
def get_range(range_id)
#if range_id == :current_to_next_word_end
if range_id == :to_word_end
wmarks = get_word_end_marks(@pos,@pos+150)
if wmarks.any?
range = @pos..wmarks[0]
end
elsif range_id == :to_line_end
puts "TO LINE END"
range = @pos..(@line_ends[@lpos] -1)
elsif range_id == :to_line_start
puts "TO LINE START"
if @lpos == 0
startpos = 0
else
startpos = @line_ends[@lpos - 1] + 1
end
range = startpos..(@pos - 1)
else
puts "INVALID RANGE"
exit
end
if range.last < range.first
range.last = range.first
end
if range.first < 0
range.first = 0
end
if range.last >= self.size
range.last = self.size - 1
end
#TODO: sanity check
return range
end
def delete2(range_id)
range = get_range(range_id)
puts "RANGE"
puts range.inspect
puts range.inspect
puts "------"
delete_range(range.first,range.last)
@pos = [range.first,@pos].min
end
def move(direction)
if direction == :forward_page
puts "FORWARD PAGE"
visible_range = get_visible_area()
set_pos(visible_range[1])
top_where_cursor()
end
if direction == :backward_page
puts "backward PAGE"
visible_range = get_visible_area()
set_pos(visible_range[0])
bottom_where_cursor()
end
if direction == FORWARD_CHAR
return if @pos >= self.size - 1
@pos += 1
puts "FORWARD: #{@pos}"
calculate_line_and_column_pos
end
if direction == BACKWARD_CHAR
@pos -= 1
calculate_line_and_column_pos
end
if direction == FORWARD_LINE
if @lpos >= @line_ends.size - 1 # Cursor is on last line
debug("ON LAST LINE")
return
else
@lpos += 1
end
end
if direction == BACKWARD_LINE
if @lpos == 0 # Cursor is on first line
return
else
@lpos -= 1
end
end
if direction == BACKWARD_LINE or direction == FORWARD_LINE
if @lpos > 0
new_pos = @line_ends[@lpos - 1] - 1
else
new_pos = 0
end
_line = self.line(@lpos)
if @cpos > (_line.size - 1)
debug("$cpos too large: #{@cpos} #{@lpos}")
if @larger_cpos < @cpos
@larger_cpos = @cpos
end
@cpos = line(@lpos).size - 1
end
#new_pos += @cpos
#@pos = new_pos
calculate_pos_from_cpos_lpos
end
end
# Get positions of last characters in words
def get_word_end_marks(startpos,endpos)
search_str = self[(startpos)..(endpos)]
return if search_str == nil
wsmarks = scan_indexes(search_str,/(?<=\p{Word})[^\p{Word}]/)
wsmarks = wsmarks.collect{|x| x+startpos - 1}
return wsmarks
end
def jump_to_next_instance_of_word()
start_search = [@pos - 150,0].max
search_str1 = self[start_search..(@pos)]
wsmarks = scan_indexes(search_str1,/(?<=[^\p{Word}])\p{Word}/)
a = wsmarks[-1]
a = 0 if a == nil
search_str2 = self[(@pos)..(@pos + 150)]
wemarks = scan_indexes(search_str2,/(?<=\p{Word})[^\p{Word}]/)
b = wemarks[0]
puts search_str1.inspect
word_start = (@pos - search_str1.size + a + 1)
word_start = 0 if !(word_start >= 0)
current_word = self[word_start..(@pos+b - 1)]
#printf("CURRENT WORD: '#{current_word}' a:#{a} b:#{b}\n")
#TODO: search for /[^\p{Word}]WORD[^\p{Word}]/
position_of_next_word = self.index(current_word,@pos + 1)
if position_of_next_word != nil
set_pos(position_of_next_word)
else #Search from beginning
position_of_next_word = self.index(current_word)
set_pos(position_of_next_word) if position_of_next_word != nil
end
center_on_current_line
end
def jump_word(direction,wordpos)
offset = 0
if direction == FORWARD
debug "POS: #{@pos},"
search_str = self[(@pos)..(@pos + 150)]
return if search_str == nil
if wordpos == WORD_START # vim 'w'
wsmarks = scan_indexes(search_str,/(?<=[^\p{Word}])\p{Word}|\Z/) # \Z = end of string, just before last newline.
wsmarks2 = scan_indexes(search_str,/\n[ \t]*\n/) # "empty" lines that have whitespace
wsmarks2 = wsmarks2.collect{|x| x+1}
wsmarks = (wsmarks2 + wsmarks).sort.uniq
offset = 0
elsif wordpos == WORD_END
wsmarks = scan_indexes(search_str,/(?<=\p{Word})[^\p{Word}]/)
offset = 0
end
if wsmarks.any?
#puts wsmarks.inspect
next_pos = @pos + wsmarks[0] + offset
set_pos(next_pos)
end
end
if direction == BACKWARD # vim 'b'
start_search = @pos - 150 #TODO 150 length limit
start_search = 0 if start_search < 0
search_str = self[start_search..(@pos - 1)]
return if search_str == nil
wsmarks = scan_indexes(search_str,
#/(^|(\W)\w|\n)/) #TODO 150 length limit
#/^|(?<=[^\p{Word}])\p{Word}|(?<=\n)\n/) #include empty lines?
/\A|(?<=[^\p{Word}])\p{Word}/) # Start of string or nonword,word.
offset = 0
if wsmarks.any?
next_pos = start_search + wsmarks.last + offset
set_pos(next_pos)
end
end
end
def jump(target)
if target == START_OF_BUFFER
set_pos(0)
end
if target == END_OF_BUFFER
set_pos(self.size - 1)
end
if target == BEGINNING_OF_LINE
@cpos = 0
calculate_pos_from_cpos_lpos
end
if target == END_OF_LINE
@cpos = line(@lpos).size - 1
calculate_pos_from_cpos_lpos
end
if target == FIRST_NON_WHITESPACE
l = current_line()
puts l.inspect
@cpos = line(@lpos).size - 1
a = scan_indexes(l,/\S/)
puts a.inspect
if a.any?
@cpos = a[0]
else
@cpos = 0
end
calculate_pos_from_cpos_lpos
end
end
def jump_to_line(line_n=1)
$method_handles_repeat = true
if !$next_command_count.nil? and $next_command_count > 0
line_n = $next_command_count
debug "jump to line:#{line_n}"
end
if line_n > @line_ends.size
debug("lpos too large") #TODO
return
end
if line_n == 1
set_pos(0)
else
set_pos(@line_ends[line_n-2]+1)
end
end
def join_lines()
if @lpos >= @line_ends.size - 1 # Cursor is on last line
debug("ON LAST LINE")
return
else
# TODO: replace all whitespace between lines with ' '
jump(END_OF_LINE)
delete(CURRENT_CHAR_FORWARD)
#insert_char(' ',AFTER)
insert_char(' ',BEFORE)
end
end
def jump_to_next_instance_of_char(char,direction=FORWARD)
#return if at_end_of_line?
if direction == FORWARD
position_of_next_char = self.index(char,@pos + 1)
if position_of_next_char != nil
@pos = position_of_next_char
end
elsif direction == BACKWARD
start_search = @pos - 250
start_search = 0 if start_search < 0
search_substr = self[start_search..(@pos - 1)]
_pos = search_substr.reverse.index(char)
if _pos != nil
@pos -= ( _pos + 1 )
end
end
m = method("jump_to_next_instance_of_char")
set_last_command({method: m, params: [char,direction]})
$last_find_command = {char: char,direction:direction}
calculate_line_and_column_pos
end
def replace_with_char(char)
d1 = [@pos,DELETE,1]
d2 = [@pos,INSERT,1,char]
add_delta(d1,true)
add_delta(d2,true)
puts "DELTAS:#{$buffer.deltas.inspect} "
end
def insert_char(c,mode = BEFORE)
#Sometimes we get ASCII-8BIT although actually UTF-8 "incompatible character encodings: UTF-8 and ASCII-8BIT (Encoding::CompatibilityError)"
c=c.force_encoding("UTF-8"); #TODO:correct?
c = "\n" if c == "\r"
if $cnf[:indent_based_on_last_line] and c == "\n" and @lpos > 0
# Indent start of new line based on last line
last_line = line(@lpos)
m = /^( +)([^ ]+|$)/.match(last_line)
puts m.inspect
c = c+" "*m[1].size if m
end
if mode == BEFORE
insert_pos = @pos
@pos += c.size
elsif mode == AFTER
insert_pos = @pos +1
else
return
end
#self.insert(insert_pos,c)
add_delta([insert_pos,INSERT,0,c],true)
#puts("encoding: #{c.encoding}")
#puts "c.size: #{c.size}"
#recalc_line_ends #TODO: optimize?
calculate_line_and_column_pos
#need_redraw!
#@pos += c.size
end
def need_redraw!
@need_redraw = true
end
def need_redraw?
return @need_redraw
end
def set_redrawed
@need_redraw = false
end
def paste()
return if !$clipboard.any?
if $paste_lines
l = current_line_range()
puts "------------"
puts l.inspect
puts "------------"
#$buffer.move(FORWARD_LINE)
set_pos(l.end+1)
insert_char($clipboard[-1])
set_pos(l.end+1)
else
insert_char($clipboard[-1])
end
#TODO: AFTER does not work
#insert_char($clipboard[-1],AFTER)
#recalc_line_ends #TODO: bug when run twice?
end
def insert_new_line()
insert_char("\n")
end
def delete_line()
$method_handles_repeat = true
$paste_lines = true
num_lines = 1
if !$next_command_count.nil? and $next_command_count > 0
num_lines = $next_command_count
debug "copy num_lines:#{num_lines}"
end
lrange = line_range(@lpos,num_lines)
s = self[lrange]
add_delta([lrange.begin,DELETE,lrange.end - lrange.begin + 1],true)
set_clipboard(s)
#recalc_line_ends
end
def delete_cur_line() #TODO: remove
#TODO: implement using delete_range
start = @line_ends[@lpos - 1] + 1 if @lpos > 0
start = 0 if @lpos == 0
_end = @line_ends[@lpos]
s = self.slice!(start.._end)
add_delta([start,DELETE,_end - start + 1,s])
set_clipboard(s)
#recalc_line_ends #TODO: optimize?
calculate_pos_from_cpos_lpos
#need_redraw!
end
def start_visual_mode()
@visual_mode = true
@selection_start=@pos
$at.set_mode(VISUAL)
end
def copy_active_selection()
puts "!COPY SELECTION"
$paste_lines = false
return if !@visual_mode
puts "COPY SELECTION"
#_start = @selection_start
#_end = @pos
#_start,_end = _end,_start if _start > _end
#_start,_end = get_visual_mode_range
# TODO: Jump to start pos
#TODO: check if range ok
set_clipboard(self[get_visual_mode_range])
end_visual_mode
end
def copy_line()
$method_handles_repeat = true
$paste_lines = true
num_lines = 1
if !$next_command_count.nil? and $next_command_count > 0
num_lines = $next_command_count
debug "copy num_lines:#{num_lines}"
end
set_clipboard(self[line_range(@lpos,num_lines)])
end
def delete_active_selection() #TODO: remove this function
return if !@visual_mode #TODO: this should not happen
_start,_end = get_visual_mode_range
set_clipboard(self[_start,_end])
end_visual_mode
end
def end_visual_mode()
#TODO:take previous mode (insert|command) from stack?
$at.set_mode(COMMAND)
@visual_mode = false
end
def get_visual_mode_range2()
_start = @selection_start
_end = @pos
_start,_end = _end,_start if _start > _end
return [_start,_end - 1]
end
def get_visual_mode_range()
_start = @selection_start
_end = @pos
_start,_end = _end,_start if _start > _end
return _start..(_end - 1)
end
def selection_start()
return -1 if !@visual_mode
return @selection_start if @visual_mode
end
def visual_mode?()
return @visual_mode
end
def value()
return self.to_s
end
# https://github.com/manveru/ver
def save()
if !@fname
puts "TODO: SAVE AS"
qt_file_saveas()
return
end
message("Saving file #{@fname}")
Thread.new {
contents = self.to_s
File.open(@fname, 'w+') do |io|
#io.set_encoding(self.encoding)
begin
io.write(contents)
rescue Encoding::UndefinedConversionError => ex
# this might happen when trying to save UTF-8 as US-ASCII
# so just warn, try to save as UTF-8 instead.
warn("Saving as UTF-8 because of: #{ex.class}: #{ex}")
io.rewind
io.set_encoding(Encoding::UTF_8)
io.write(contents)
#self.encoding = Encoding::UTF_8
end
end
sleep 3
}
end
end
| gpl-2.0 |
YiMAproject/typoPages | src/typoPages/Pages/PageAbstract.php | 865 | <?php
namespace typoPages\Pages;
use yimaWidgetator\Widget\AbstractWidget;
/**
* Class Simple
*
* @package typoPages\Pages
*/
abstract class PageAbstract extends AbstractWidget
{
/**
* Page Columns
* : Assoc Array with `column_name` => (bool) is_translatable
*
* @var array
*/
protected $columns = array(
//'content' => true,
//'style' => false,
);
/**
* Get Page Columns
*
* @return array
*/
public function getColumns()
{
return array_keys($this->columns);
}
/**
* Get Translatable Columns
*
* @return array
*/
public function getTranslatableColumns()
{
$transColumns = array();
foreach($this->columns as $c => $t) {
if ($t) $transColumns[] = $c;
}
return $transColumns;
}
}
| gpl-2.0 |
sdl/Sdl-Community | StarTransit/Sdl.Community.StarTransit.UI/Helpers/WindowCloseOnClickBehaviour.cs | 1630 | using System.Windows;
using System.Windows.Controls;
namespace Sdl.Community.StarTransit.UI.Helpers
{
public static class WindowCloseOnClickBehaviour
{
public static readonly DependencyProperty IsEnabledProperty =
DependencyProperty.RegisterAttached(
"IsEnabled",
typeof(bool),
typeof(WindowCloseOnClickBehaviour),
new PropertyMetadata(false, OnIsEnabledPropertyChanged)
);
public static bool GetIsEnabled(DependencyObject obj)
{
var val = obj.GetValue(IsEnabledProperty);
return (bool)val;
}
public static void SetIsEnabled(DependencyObject obj, bool value)
{
obj.SetValue(IsEnabledProperty, value);
}
static void OnIsEnabledPropertyChanged(DependencyObject dpo, DependencyPropertyChangedEventArgs args)
{
var button = dpo as Button;
if (button is null)
return;
var oldValue = (bool)args.OldValue;
var newValue = (bool)args.NewValue;
if (!oldValue && newValue)
{
button.Click += OnClick;
}
else if (oldValue && !newValue)
{
button.PreviewMouseLeftButtonDown -= OnClick;
}
}
static void OnClick(object sender, RoutedEventArgs e)
{
var button = sender as Button;
if (button is null)
return;
var win = Window.GetWindow(button);
win?.Close();
}
}
}
| gpl-2.0 |
Quartermain/providores | components/com_mijoshop/opencart/catalog/controller/payment/worldpay.php | 6351 | <?php
/*
* @package MijoShop
* @copyright 2009-2013 Mijosoft LLC, mijosoft.com
* @license GNU/GPL http://www.gnu.org/copyleft/gpl.html
* @license GNU/GPL based on AceShop www.joomace.net
*/
// No Permission
defined('_JEXEC') or die('Restricted access');
class ControllerPaymentWorldPay extends Controller {
protected function index() {
$this->data['button_confirm'] = $this->language->get('button_confirm');
$this->load->model('checkout/order');
$order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);
if (!$this->config->get('worldpay_test')){
$this->data['action'] = 'https://secure.worldpay.com/wcc/purchase';
}else{
$this->data['action'] = 'https://secure-test.worldpay.com/wcc/purchase';
}
$this->data['merchant'] = $this->config->get('worldpay_merchant');
$this->data['order_id'] = $order_info['order_id'];
$this->data['amount'] = $this->currency->format($order_info['total'], $order_info['currency_code'], $order_info['currency_value'], false);
$this->data['currency'] = $order_info['currency_code'];
$this->data['description'] = $this->config->get('config_name') . ' - #' . $order_info['order_id'];
$this->data['name'] = $order_info['payment_firstname'] . ' ' . $order_info['payment_lastname'];
if (!$order_info['payment_address_2']) {
$this->data['address'] = $order_info['payment_address_1'] . ', ' . $order_info['payment_city'] . ', ' . $order_info['payment_zone'];
} else {
$this->data['address'] = $order_info['payment_address_1'] . ', ' . $order_info['payment_address_2'] . ', ' . $order_info['payment_city'] . ', ' . $order_info['payment_zone'];
}
$this->data['postcode'] = $order_info['payment_postcode'];
$this->data['country'] = $order_info['payment_iso_code_2'];
$this->data['telephone'] = $order_info['telephone'];
$this->data['email'] = $order_info['email'];
$this->data['test'] = $this->config->get('worldpay_test');
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/payment/worldpay.tpl')) {
$this->template = $this->config->get('config_template') . '/template/payment/worldpay.tpl';
} else {
$this->template = 'default/template/payment/worldpay.tpl';
}
$this->render();
}
public function callback() {
$this->language->load('payment/worldpay');
$this->data['title'] = sprintf($this->language->get('heading_title'), $this->config->get('config_name'));
if (!isset($this->request->server['HTTPS']) || ($this->request->server['HTTPS'] != 'on')) {
$this->data['base'] = $this->config->get('config_url');
} else {
$this->data['base'] = $this->config->get('config_ssl');
}
$this->data['language'] = $this->language->get('code');
$this->data['direction'] = $this->language->get('direction');
$this->data['heading_title'] = sprintf($this->language->get('heading_title'), $this->config->get('config_name'));
$this->data['text_response'] = $this->language->get('text_response');
$this->data['text_success'] = $this->language->get('text_success');
$this->data['text_success_wait'] = sprintf($this->language->get('text_success_wait'), $this->url->link('checkout/success'));
$this->data['text_failure'] = $this->language->get('text_failure');
$this->data['text_failure_wait'] = sprintf($this->language->get('text_failure_wait'), $this->url->link('checkout/checkout', '', 'SSL'));
if (isset($this->request->post['transStatus']) && $this->request->post['transStatus'] == 'Y') {
$this->load->model('checkout/order');
// If returned successful but callbackPW doesn't match, set order to pendind and record reason
if (isset($this->request->post['callbackPW']) && ($this->request->post['callbackPW'] == $this->config->get('worldpay_password'))) {
$this->model_checkout_order->confirm($this->request->post['cartId'], $this->config->get('worldpay_order_status_id'));
} else {
$this->model_checkout_order->confirm($this->request->post['cartId'], $this->config->get('config_order_status_id'), $this->language->get('text_pw_mismatch'));
}
$message = '';
if (isset($this->request->post['transId'])) {
$message .= 'transId: ' . $this->request->post['transId'] . "\n";
}
if (isset($this->request->post['transStatus'])) {
$message .= 'transStatus: ' . $this->request->post['transStatus'] . "\n";
}
if (isset($this->request->post['countryMatch'])) {
$message .= 'countryMatch: ' . $this->request->post['countryMatch'] . "\n";
}
if (isset($this->request->post['AVS'])) {
$message .= 'AVS: ' . $this->request->post['AVS'] . "\n";
}
if (isset($this->request->post['rawAuthCode'])) {
$message .= 'rawAuthCode: ' . $this->request->post['rawAuthCode'] . "\n";
}
if (isset($this->request->post['authMode'])) {
$message .= 'authMode: ' . $this->request->post['authMode'] . "\n";
}
if (isset($this->request->post['rawAuthMessage'])) {
$message .= 'rawAuthMessage: ' . $this->request->post['rawAuthMessage'] . "\n";
}
if (isset($this->request->post['wafMerchMessage'])) {
$message .= 'wafMerchMessage: ' . $this->request->post['wafMerchMessage'] . "\n";
}
$this->model_checkout_order->update($this->request->post['cartId'], $this->config->get('worldpay_order_status_id'), $message, false);
$this->data['continue'] = $this->url->link('checkout/success');
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/payment/worldpay_success.tpl')) {
$this->template = $this->config->get('config_template') . '/template/payment/worldpay_success.tpl';
} else {
$this->template = 'default/template/payment/worldpay_success.tpl';
}
$this->response->setOutput($this->render());
} else {
$this->data['continue'] = $this->url->link('checkout/cart');
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/payment/worldpay_failure.tpl')) {
$this->template = $this->config->get('config_template') . '/template/payment/worldpay_failure.tpl';
} else {
$this->template = 'default/template/payment/worldpay_failure.tpl';
}
$this->response->setOutput($this->render());
}
}
}
?> | gpl-2.0 |
sanger/labwhere | config/initializers/03_string.rb | 365 | # frozen_string_literal: true
class String
##
# remove tabs, carriage returns and returns from a string
def remove_control_chars
self.tr("\t\r\n", '')
end
##
# must be camel case.
# will deconstruct word by capitals and reform it into a string without the last word.
def remove_last_word
self.scan(/[A-Z][a-z]+/).tap(&:pop).join
end
end
| gpl-2.0 |
stumposs/flightgear-2.8.0-teamboeing | src/FDM/YASim/Model.cpp | 15243 |
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "Atmosphere.hpp"
#include "Thruster.hpp"
#include "Math.hpp"
#include "RigidBody.hpp"
#include "Integrator.hpp"
#include "Propeller.hpp"
#include "PistonEngine.hpp"
#include "Gear.hpp"
#include "Hook.hpp"
#include "Launchbar.hpp"
#include "Surface.hpp"
#include "Rotor.hpp"
#include "Rotorpart.hpp"
#include "Hitch.hpp"
#include "Glue.hpp"
#include "Ground.hpp"
#include "Model.hpp"
namespace yasim {
#if 0
void printState(State* s)
{
State tmp = *s;
Math::vmul33(tmp.orient, tmp.v, tmp.v);
Math::vmul33(tmp.orient, tmp.acc, tmp.acc);
Math::vmul33(tmp.orient, tmp.rot, tmp.rot);
Math::vmul33(tmp.orient, tmp.racc, tmp.racc);
printf("\nNEW STATE (LOCAL COORDS)\n");
printf("pos: %10.2f %10.2f %10.2f\n", tmp.pos[0], tmp.pos[1], tmp.pos[2]);
printf("o: ");
int i;
for(i=0; i<3; i++) {
if(i != 0) printf(" ");
printf("%6.2f %6.2f %6.2f\n",
tmp.orient[3*i+0], tmp.orient[3*i+1], tmp.orient[3*i+2]);
}
printf("v: %6.2f %6.2f %6.2f\n", tmp.v[0], tmp.v[1], tmp.v[2]);
printf("acc: %6.2f %6.2f %6.2f\n", tmp.acc[0], tmp.acc[1], tmp.acc[2]);
printf("rot: %6.2f %6.2f %6.2f\n", tmp.rot[0], tmp.rot[1], tmp.rot[2]);
printf("rac: %6.2f %6.2f %6.2f\n", tmp.racc[0], tmp.racc[1], tmp.racc[2]);
}
#endif
Model::Model()
{
int i;
for(i=0; i<3; i++) _wind[i] = 0;
_integrator.setBody(&_body);
_integrator.setEnvironment(this);
// Default value of 30 Hz
_integrator.setInterval(1.0f/30.0f);
_agl = 0;
_crashed = false;
_turb = 0;
_ground_cb = new Ground();
_hook = 0;
_launchbar = 0;
_groundEffectSpan = 0;
_groundEffect = 0;
for(i=0; i<3; i++) _wingCenter[i] = 0;
_global_ground[0] = 0; _global_ground[1] = 0; _global_ground[2] = 1;
_global_ground[3] = -100000;
}
Model::~Model()
{
// FIXME: who owns these things? Need a policy
delete _ground_cb;
delete _hook;
delete _launchbar;
for(int i=0; i<_hitches.size();i++)
delete (Hitch*)_hitches.get(i);
}
void Model::getThrust(float* out)
{
float tmp[3];
out[0] = out[1] = out[2] = 0;
int i;
for(i=0; i<_thrusters.size(); i++) {
Thruster* t = (Thruster*)_thrusters.get(i);
t->getThrust(tmp);
Math::add3(tmp, out, out);
}
}
void Model::initIteration()
{
// Precompute torque and angular momentum for the thrusters
int i;
for(i=0; i<3; i++)
_gyro[i] = _torque[i] = 0;
// Need a local altitude for the wind calculation
float lground[4];
_s->planeGlobalToLocal(_global_ground, lground);
float alt = Math::abs(lground[3]);
for(i=0; i<_thrusters.size(); i++) {
Thruster* t = (Thruster*)_thrusters.get(i);
// Get the wind velocity at the thruster location
float pos[3], v[3];
t->getPosition(pos);
localWind(pos, _s, v, alt);
t->setWind(v);
t->setAir(_pressure, _temp, _rho);
t->integrate(_integrator.getInterval());
t->getTorque(v);
Math::add3(v, _torque, _torque);
t->getGyro(v);
Math::add3(v, _gyro, _gyro);
}
// Displace the turbulence coordinates according to the local wind.
if(_turb) {
float toff[3];
Math::mul3(_integrator.getInterval(), _wind, toff);
_turb->offset(toff);
}
for(i=0; i<_hitches.size(); i++) {
Hitch* h = (Hitch*)_hitches.get(i);
h->integrate(_integrator.getInterval());
}
}
// This function initializes some variables for the rotor calculation
// Furthermore it integrates in "void Rotorpart::inititeration
// (float dt,float *rot)" the "rotor orientation" by omega*dt for the
// 3D-visualization of the heli only. and it compensates the rotation
// of the fuselage. The rotor does not follow the rotation of the fuselage.
// Therefore its rotation must be subtracted from the orientation of the
// rotor.
// Maik
void Model::initRotorIteration()
{
float dt = _integrator.getInterval();
float lrot[3];
if (!_rotorgear.isInUse()) return;
Math::vmul33(_s->orient, _s->rot, lrot);
Math::mul3(dt,lrot,lrot);
_rotorgear.initRotorIteration(lrot,dt);
}
void Model::iterate()
{
initIteration();
initRotorIteration();
_body.recalc(); // FIXME: amortize this, somehow
_integrator.calcNewInterval();
}
bool Model::isCrashed()
{
return _crashed;
}
void Model::setCrashed(bool crashed)
{
_crashed = crashed;
}
float Model::getAGL()
{
return _agl;
}
State* Model::getState()
{
return _s;
}
void Model::setState(State* s)
{
_integrator.setState(s);
_s = _integrator.getState();
}
RigidBody* Model::getBody()
{
return &_body;
}
Integrator* Model::getIntegrator()
{
return &_integrator;
}
Surface* Model::getSurface(int handle)
{
return (Surface*)_surfaces.get(handle);
}
Rotorgear* Model::getRotorgear(void)
{
return &_rotorgear;
}
int Model::addThruster(Thruster* t)
{
return _thrusters.add(t);
}
Hook* Model::getHook(void)
{
return _hook;
}
Launchbar* Model::getLaunchbar(void)
{
return _launchbar;
}
int Model::numThrusters()
{
return _thrusters.size();
}
Thruster* Model::getThruster(int handle)
{
return (Thruster*)_thrusters.get(handle);
}
void Model::setThruster(int handle, Thruster* t)
{
_thrusters.set(handle, t);
}
int Model::addSurface(Surface* surf)
{
return _surfaces.add(surf);
}
int Model::addGear(Gear* gear)
{
return _gears.add(gear);
}
void Model::addHook(Hook* hook)
{
_hook = hook;
}
void Model::addLaunchbar(Launchbar* launchbar)
{
_launchbar = launchbar;
}
int Model::addHitch(Hitch* hitch)
{
return _hitches.add(hitch);
}
void Model::setGroundCallback(Ground* ground_cb)
{
delete _ground_cb;
_ground_cb = ground_cb;
}
Ground* Model::getGroundCallback(void)
{
return _ground_cb;
}
void Model::setGroundEffect(float* pos, float span, float mul)
{
Math::set3(pos, _wingCenter);
_groundEffectSpan = span;
_groundEffect = mul;
}
void Model::setAir(float pressure, float temp, float density)
{
_pressure = pressure;
_temp = temp;
_rho = density;
}
void Model::setWind(float* wind)
{
Math::set3(wind, _wind);
}
void Model::updateGround(State* s)
{
float dummy[3];
_ground_cb->getGroundPlane(s->pos, _global_ground, dummy);
int i;
// The landing gear
for(i=0; i<_gears.size(); i++) {
Gear* g = (Gear*)_gears.get(i);
// Get the point of ground contact
float pos[3], cmpr[3];
g->getPosition(pos);
g->getCompression(cmpr);
Math::mul3(g->getCompressFraction(), cmpr, cmpr);
Math::add3(cmpr, pos, pos);
// Transform the local coordinates of the contact point to
// global coordinates.
double pt[3];
s->posLocalToGlobal(pos, pt);
// Ask for the ground plane in the global coordinate system
double global_ground[4];
float global_vel[3];
const SGMaterial* material;
_ground_cb->getGroundPlane(pt, global_ground, global_vel, &material);
g->setGlobalGround(global_ground, global_vel, pt[0], pt[1], material);
}
for(i=0; i<_hitches.size(); i++) {
Hitch* h = (Hitch*)_hitches.get(i);
// Get the point of interest
float pos[3];
h->getPosition(pos);
// Transform the local coordinates of the contact point to
// global coordinates.
double pt[3];
s->posLocalToGlobal(pos, pt);
// Ask for the ground plane in the global coordinate system
double global_ground[4];
float global_vel[3];
_ground_cb->getGroundPlane(pt, global_ground, global_vel);
h->setGlobalGround(global_ground, global_vel);
}
for(i=0; i<_rotorgear.getRotors()->size(); i++) {
Rotor* r = (Rotor*)_rotorgear.getRotors()->get(i);
r->findGroundEffectAltitude(_ground_cb,s);
}
// The arrester hook
if(_hook) {
double pt[3];
_hook->getTipGlobalPosition(s, pt);
double global_ground[4];
_ground_cb->getGroundPlane(pt, global_ground, dummy);
_hook->setGlobalGround(global_ground);
}
// The launchbar/holdback
if(_launchbar) {
double pt[3];
_launchbar->getTipGlobalPosition(s, pt);
double global_ground[4];
_ground_cb->getGroundPlane(pt, global_ground, dummy);
_launchbar->setGlobalGround(global_ground);
}
}
void Model::calcForces(State* s)
{
// Add in the pre-computed stuff. These values aren't part of the
// Runge-Kutta integration (they don't depend on position or
// velocity), and are therefore constant across the four calls to
// calcForces. They get computed before we begin the integration
// step.
_body.setGyro(_gyro);
_body.addTorque(_torque);
int i,j;
for(i=0; i<_thrusters.size(); i++) {
Thruster* t = (Thruster*)_thrusters.get(i);
float thrust[3], pos[3];
t->getThrust(thrust);
t->getPosition(pos);
_body.addForce(pos, thrust);
}
// Get a ground plane in local coordinates. The first three
// elements are the normal vector, the final one is the distance
// from the local origin along that vector to the ground plane
// (negative for objects "above" the ground)
float ground[4];
s->planeGlobalToLocal(_global_ground, ground);
float alt = Math::abs(ground[3]);
// Gravity, convert to a force, then to local coordinates
float grav[3];
Glue::geodUp(s->pos, grav);
Math::mul3(-9.8f * _body.getTotalMass(), grav, grav);
Math::vmul33(s->orient, grav, grav);
_body.addForce(grav);
// Do each surface, remembering that the local velocity at each
// point is different due to rotation.
float faero[3];
faero[0] = faero[1] = faero[2] = 0;
for(i=0; i<_surfaces.size(); i++) {
Surface* sf = (Surface*)_surfaces.get(i);
// Vsurf = wind - velocity + (rot cross (cg - pos))
float vs[3], pos[3];
sf->getPosition(pos);
localWind(pos, s, vs, alt);
float force[3], torque[3];
sf->calcForce(vs, _rho, force, torque);
Math::add3(faero, force, faero);
_body.addForce(pos, force);
_body.addTorque(torque);
}
for (j=0; j<_rotorgear.getRotors()->size();j++)
{
Rotor* r = (Rotor *)_rotorgear.getRotors()->get(j);
float vs[3], pos[3];
r->getPosition(pos);
localWind(pos, s, vs, alt);
r->calcLiftFactor(vs, _rho,s);
float tq=0;
// total torque of rotor (scalar) for calculating new rotor rpm
for(i=0; i<r->_rotorparts.size(); i++) {
float torque_scalar=0;
Rotorpart* rp = (Rotorpart*)r->_rotorparts.get(i);
// Vsurf = wind - velocity + (rot cross (cg - pos))
float vs[3], pos[3];
rp->getPosition(pos);
localWind(pos, s, vs, alt,true);
float force[3], torque[3];
rp->calcForce(vs, _rho, force, torque, &torque_scalar);
tq+=torque_scalar;
rp->getPositionForceAttac(pos);
_body.addForce(pos, force);
_body.addTorque(torque);
}
r->setTorque(tq);
}
if (_rotorgear.isInUse())
{
float torque[3];
_rotorgear.calcForces(torque);
_body.addTorque(torque);
}
// Account for ground effect by multiplying the vertical force
// component by an amount linear with the fraction of the wingspan
// above the ground.
if ((_groundEffectSpan != 0) && (_groundEffect != 0 ))
{
float dist = ground[3] - Math::dot3(ground, _wingCenter);
if(dist > 0 && dist < _groundEffectSpan) {
float fz = Math::dot3(faero, ground);
fz *= (_groundEffectSpan - dist) / _groundEffectSpan;
fz *= _groundEffect;
Math::mul3(fz, ground, faero);
_body.addForce(faero);
}
}
// Convert the velocity and rotation vectors to local coordinates
float lrot[3], lv[3];
Math::vmul33(s->orient, s->rot, lrot);
Math::vmul33(s->orient, s->v, lv);
// The landing gear
for(i=0; i<_gears.size(); i++) {
float force[3], contact[3];
Gear* g = (Gear*)_gears.get(i);
g->calcForce(&_body, s, lv, lrot);
g->getForce(force, contact);
_body.addForce(contact, force);
}
// The arrester hook
if(_hook) {
_hook->calcForce(_ground_cb, &_body, s, lv, lrot);
float force[3], contact[3];
_hook->getForce(force, contact);
_body.addForce(contact, force);
}
// The launchbar/holdback
if(_launchbar) {
_launchbar->calcForce(_ground_cb, &_body, s, lv, lrot);
float forcelb[3], contactlb[3], forcehb[3], contacthb[3];
_launchbar->getForce(forcelb, contactlb, forcehb, contacthb);
_body.addForce(contactlb, forcelb);
_body.addForce(contacthb, forcehb);
}
// The hitches
for(i=0; i<_hitches.size(); i++) {
float force[3], contact[3];
Hitch* h = (Hitch*)_hitches.get(i);
h->calcForce(_ground_cb,&_body, s);
h->getForce(force, contact);
_body.addForce(contact, force);
}
}
void Model::newState(State* s)
{
_s = s;
// Some simple collision detection
float min = 1e8;
int i;
for(i=0; i<_gears.size(); i++) {
Gear* g = (Gear*)_gears.get(i);
if (!g->getSubmergable())
{
// Get the point of ground contact
float pos[3], cmpr[3];
g->getPosition(pos);
g->getCompression(cmpr);
Math::mul3(g->getCompressFraction(), cmpr, cmpr);
Math::add3(cmpr, pos, pos);
// The plane transformed to local coordinates.
double global_ground[4];
g->getGlobalGround(global_ground);
float ground[4];
s->planeGlobalToLocal(global_ground, ground);
float dist = ground[3] - Math::dot3(pos, ground);
// Find the lowest one
if(dist < min)
min = dist;
}
}
_agl = min;
if(_agl < -1) // Allow for some integration slop
_crashed = true;
}
// Calculates the airflow direction at the given point and for the
// specified aircraft velocity.
void Model::localWind(float* pos, State* s, float* out, float alt, bool is_rotor)
{
float tmp[3], lwind[3], lrot[3], lv[3];
// Get a global coordinate for our local position, and calculate
// turbulence.
if(_turb) {
double gpos[3]; float up[3];
Math::tmul33(s->orient, pos, tmp);
for(int i=0; i<3; i++) {
gpos[i] = s->pos[i] + tmp[i];
}
Glue::geodUp(gpos, up);
_turb->getTurbulence(gpos, alt, up, lwind);
Math::add3(_wind, lwind, lwind);
} else {
Math::set3(_wind, lwind);
}
// Convert to local coordinates
Math::vmul33(s->orient, lwind, lwind);
Math::vmul33(s->orient, s->rot, lrot);
Math::vmul33(s->orient, s->v, lv);
_body.pointVelocity(pos, lrot, out); // rotational velocity
Math::mul3(-1, out, out); // (negated)
Math::add3(lwind, out, out); // + wind
Math::sub3(out, lv, out); // - velocity
//add the downwash of the rotors if it is not self a rotor
if (_rotorgear.isInUse()&&!is_rotor)
{
_rotorgear.getDownWash(pos,lv,tmp);
Math::add3(out,tmp, out); // + downwash
}
}
}; // namespace yasim
| gpl-2.0 |
leonelllagumbay/bdg | app/model/queryoutput/FBC/NS_48C81A8AD318C16C571F095320D0A3CF/Model.js | 519 | Ext.define('Form.model.queryoutput.FBC.NS_48C81A8AD318C16C571F095320D0A3CF.Model', {
extend: 'Ext.data.Model',
fields: [{
name: 'egintestquery-ADATETIME',
type: 'date'
},{
name: 'egintestquery-AFLOAT',
type: 'float'
},{
name: 'egintestquery-ANUMBER',
type: 'int'
},{
name: 'egintestquery-ASTRING',
type: 'string'
},{
name: 'egintestquery-ATEXT',
type: 'string'
},{
name: 'egintestquery-ATIME',
type: 'string'
},{
name: 'egintestquery-TESTID',
type: 'int'
}]
}); | gpl-2.0 |
mambax7/publisher | blocks/search.php | 6942 | <?php declare(strict_types=1);
/*
You may not change or alter any portion of this comment or credits
of supporting developers from this source code or any supporting source code
which is considered copyrighted (c) material of the original comment or credit authors.
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.
*/
/**
* @copyright XOOPS Project (https://xoops.org)
* @license https://www.fsf.org/copyleft/gpl.html GNU public license
* @since 1.0
* @author trabis <lusopoemas@gmail.com>
* @author phppp
*/
use Xmf\Request;
use XoopsModules\Publisher\CategoryHandler;
use XoopsModules\Publisher\Helper;
require_once \dirname(__DIR__) . '/include/common.php';
/**
* @param $options
*
* @return array
*/
function publisher_search_show($options)
{
$block = [];
$helper = Helper::getInstance();
/** @var CategoryHandler $categoryHandler */
$categoryHandler = $helper->getHandler('Category');
$categories = $categoryHandler->getCategoriesForSearch();
if (0 === count($categories)) {
return $block;
}
xoops_loadLanguage('search');
$andor = Request::getString('andor', Request::getString('andor', '', 'GET'), 'POST');
$username = Request::getString('uname', Request::getString('uname', null, 'GET'), 'POST');
// $searchin = isset($_POST["searchin"]) ? $_POST["searchin"] : (isset($_GET["searchin"]) ? explode("|", $_GET["searchin"]) : array());
// $searchin = Request::getArray('searchin', (explode("|", Request::getString('searchin', array(), 'GET'))), 'POST');
$searchin = Request::getArray('searchin', '', 'POST');
if (!isset($searchin)) {
$searchin = Request::getString('searchin', [], 'GET');
$searchin = isset($searchin) ? explode('|', $searchin) : [];
}
$sortby = Request::getString('sortby', Request::getString('sortby', null, 'GET'), 'POST');
$term = Request::getString('term', Request::getString('term', '', 'GET'));
//mb TODO simplify next lines with category
$category = Request::getArray('category', [], 'POST') ?: Request::getArray('category', null, 'GET');
if (empty($category) || (is_array($category) && in_array('all', $category, true))) {
$category = [];
} else {
$category = (!is_array($category)) ? explode(',', $category) : $category;
$category = array_map('\intval', $category);
}
$andor = in_array(mb_strtoupper($andor), ['OR', 'AND', 'EXACT'], true) ? \mb_strtoupper($andor) : 'OR';
$sortby = in_array(mb_strtolower($sortby), ['itemid', 'datesub', 'title', 'categoryid'], true) ? \mb_strtolower($sortby) : 'itemid';
/* type */
$typeSelect = '<select name="andor">';
$typeSelect .= '<option value="OR"';
if ('OR' === $andor) {
$typeSelect .= ' selected="selected"';
}
$typeSelect .= '>' . _SR_ANY . '</option>';
$typeSelect .= '<option value="AND"';
if ('AND' === $andor) {
$typeSelect .= ' selected="selected"';
}
$typeSelect .= '>' . _SR_ALL . '</option>';
$typeSelect .= '<option value="EXACT"';
if ('exact' === $andor) {
$typeSelect .= ' selected="selected"';
}
$typeSelect .= '>' . _SR_EXACT . '</option>';
$typeSelect .= '</select>';
/* category */
$categorySelect = '<select name="category[]" size="5" multiple="multiple" width="150" style="width:150px;">';
$categorySelect .= '<option value="all"';
if (empty($category) || 0 === count($category)) {
$categorySelect .= 'selected="selected"';
}
$categorySelect .= '>' . _ALL . '</option>';
foreach ($categories as $id => $cat) {
$categorySelect .= '<option value="' . $id . '"';
if (in_array($id, $category, true)) {
$categorySelect .= 'selected="selected"';
}
$categorySelect .= '>' . $cat . '</option>';
}
unset($id);
$categorySelect .= '</select>';
/* scope */
$searchSelect = '';
$searchSelect .= '<input type="checkbox" name="searchin[]" value="title"';
if (is_array($searchin) && in_array('title', $searchin, true)) {
$searchSelect .= ' checked';
}
$searchSelect .= '>' . _CO_PUBLISHER_TITLE . ' ';
$searchSelect .= '<input type="checkbox" name="searchin[]" value="subtitle"';
if (is_array($searchin) && in_array('subtitle', $searchin, true)) {
$searchSelect .= ' checked';
}
$searchSelect .= '>' . _CO_PUBLISHER_SUBTITLE . ' ';
$searchSelect .= '<input type="checkbox" name="searchin[]" value="summary"';
if (is_array($searchin) && in_array('summary', $searchin, true)) {
$searchSelect .= ' checked';
}
$searchSelect .= '>' . _CO_PUBLISHER_SUMMARY . ' ';
$searchSelect .= '<input type="checkbox" name="searchin[]" value="text"';
if (is_array($searchin) && in_array('body', $searchin, true)) {
$searchSelect .= ' checked';
}
$searchSelect .= '>' . _CO_PUBLISHER_BODY . ' ';
$searchSelect .= '<input type="checkbox" name="searchin[]" value="keywords"';
if (is_array($searchin) && in_array('meta_keywords', $searchin, true)) {
$searchSelect .= ' checked';
}
$searchSelect .= '>' . _CO_PUBLISHER_ITEM_META_KEYWORDS . ' ';
$searchSelect .= '<input type="checkbox" name="searchin[]" value="all"';
if (empty($searchin) || (is_array($searchin) && in_array('all', $searchin, true))) {
$searchSelect .= ' checked';
}
$searchSelect .= '>' . _ALL . ' ';
/* sortby */
$sortbySelect = '<select name="sortby">';
$sortbySelect .= '<option value="itemid"';
if ('itemid' === $sortby || empty($sortby)) {
$sortbySelect .= ' selected="selected"';
}
$sortbySelect .= '>' . _NONE . '</option>';
$sortbySelect .= '<option value="datesub"';
if ('datesub' === $sortby) {
$sortbySelect .= ' selected="selected"';
}
$sortbySelect .= '>' . _CO_PUBLISHER_DATESUB . '</option>';
$sortbySelect .= '<option value="title"';
if ('title' === $sortby) {
$sortbySelect .= ' selected="selected"';
}
$sortbySelect .= '>' . _CO_PUBLISHER_TITLE . '</option>';
$sortbySelect .= '<option value="categoryid"';
if ('categoryid' === $sortby) {
$sortbySelect .= ' selected="selected"';
}
$sortbySelect .= '>' . _CO_PUBLISHER_CATEGORY . '</option>';
$sortbySelect .= '</select>';
$block['typeSelect'] = $typeSelect;
$block['searchSelect'] = $searchSelect;
$block['categorySelect'] = $categorySelect;
$block['sortbySelect'] = $sortbySelect;
$block['search_term'] = htmlspecialchars($term, ENT_QUOTES);
$block['search_user'] = $username;
$block['publisher_url'] = PUBLISHER_URL;
return $block;
}
| gpl-2.0 |
woyaofacai/GameFinal | Race/SceneEditor/CListNodesWindow.cpp | 3057 | #include "stdafx.h"
#include "ControlIDs.h"
#include "CListNodesWindow.h"
#include "EditorWindow.h"
#include "EditorScene.h"
void CListNodesWindow::OnCreate(HWND parent, int xPos, int yPos, int width, int height)
{
CSubWindow::OnCreate(parent, xPos, yPos, width, height);
HINSTANCE hInst = GetModuleHandle(NULL);
RECT rect;
GetWindowRect(mParentHwnd, &rect);
mHeight = rect.bottom - rect.top - yPos;
mNodesList = CreateWindow(TEXT("listbox"), NULL,
WS_CHILD | WS_VISIBLE | LBS_NOTIFY | WS_VSCROLL | WS_BORDER,
xPos + 10, yPos + 10, 220, 600,
mParentHwnd, (HMENU)IDC_NODES_LIST, hInst, NULL);
}
void CListNodesWindow::Init()
{
}
void CListNodesWindow::OnCommand(WORD id, WORD event, WPARAM wParam, LPARAM lParam)
{
if (id == IDC_NODES_LIST)
{
if (event == LBN_SELCHANGE)
{
OnClickListItem();
}
else if (event == LBN_DBLCLK)
{
OnDoubleClickListItem();
}
}
}
void CListNodesWindow::AddListItem(u32 id)
{
TCHAR szNodeName[256];
HWND hNodeNameTextField = GetDlgItem(mParentHwnd, IDC_NODE_NAME_TEXTFIELD);
GetWindowText(hNodeNameTextField, szNodeName, -1);
int itemIndex = ListBox_AddString(mNodesList, szNodeName);
if (itemIndex != LB_ERR)
{
ListBox_SetItemData(mNodesList, itemIndex, id);
}
}
void CListNodesWindow::OnClickListItem()
{
int itemIndex = ListBox_GetCurSel(mNodesList);
if (itemIndex != LB_ERR)
{
u32 id = ListBox_GetItemData(mNodesList, itemIndex);
EditorScene* scene = EditorScene::getInstance();
EditorWindow* window = EditorWindow::getInstance();
SNodeInfo* info = scene->GetNodeInfoById(id);
if (info->Category == MESH_CATEGORY)
{
scene->SelectObject(id);
window->ShowNodeInfo(id);
window->mMeshNodePanel.mInstanceNodeWindow.SetVisible(false);
}
else if (info->Category == COLLECTION_CATEGORY)
{
window->mMeshNodePanel.mInstanceNodeWindow.SetVisible(true);
window->mMeshNodePanel.mInstanceNodeWindow.UpdateListBoxItems(id);
}
SetFocus(mParentHwnd);
}
}
void CListNodesWindow::OnDoubleClickListItem()
{
int itemIndex = ListBox_GetCurSel(mNodesList);
if (itemIndex != LB_ERR)
{
u32 id = ListBox_GetItemData(mNodesList, itemIndex);
EditorScene* scene = EditorScene::getInstance();
EditorWindow* window = EditorWindow::getInstance();
if (scene->SelectObject(id))
{
scene->FocusSelectedObject();
window->ShowNodeInfo(id);
}
SetFocus(mParentHwnd);
}
}
void CListNodesWindow::SelectListItem(u32 id)
{
u32 count = ListBox_GetCount(mNodesList);
for (u32 i = 0; i < count; i++)
{
u32 data = ListBox_GetItemData(mNodesList, i);
if (data == id)
{
ListBox_SetCurSel(mNodesList, i);
return;
}
}
}
int CListNodesWindow::GetSelectedItemId()
{
int itemIndex = ListBox_GetCurSel(mNodesList);
if (itemIndex != LB_ERR)
{
u32 id = ListBox_GetItemData(mNodesList, itemIndex);
return id;
}
return -1;
}
SNodeInfo* CListNodesWindow::GetSelectedItemNodeInfo()
{
int id = GetSelectedItemId();
if (id == -1)
return nullptr;
EditorScene* scene = EditorScene::getInstance();
return scene->GetNodeInfoById(id);
}
| gpl-2.0 |
risingsunm/Contacts_4.0 | tests/src/com/android/contacts/voicemail/VoicemailStatusHelperImplTest.java | 13552 | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.contacts.voicemail;
import static android.provider.VoicemailContract.Status.CONFIGURATION_STATE;
import static android.provider.VoicemailContract.Status.CONFIGURATION_STATE_CAN_BE_CONFIGURED;
import static android.provider.VoicemailContract.Status.CONFIGURATION_STATE_NOT_CONFIGURED;
import static android.provider.VoicemailContract.Status.DATA_CHANNEL_STATE;
import static android.provider.VoicemailContract.Status.DATA_CHANNEL_STATE_NO_CONNECTION;
import static android.provider.VoicemailContract.Status.DATA_CHANNEL_STATE_OK;
import static android.provider.VoicemailContract.Status.NOTIFICATION_CHANNEL_STATE;
import static android.provider.VoicemailContract.Status.NOTIFICATION_CHANNEL_STATE_MESSAGE_WAITING;
import static android.provider.VoicemailContract.Status.NOTIFICATION_CHANNEL_STATE_NO_CONNECTION;
import static android.provider.VoicemailContract.Status.NOTIFICATION_CHANNEL_STATE_OK;
import com.android.contacts.R;
import com.android.contacts.voicemail.VoicemailStatusHelper.StatusMessage;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.provider.VoicemailContract.Status;
import android.test.AndroidTestCase;
import java.util.List;
/**
* Unit tests for {@link VoicemailStatusHelperImpl}.
*/
public class VoicemailStatusHelperImplTest extends AndroidTestCase {
private static final String[] TEST_PACKAGES = new String[] {
"com.test.package1",
"com.test.package2"
};
private static final Uri TEST_SETTINGS_URI = Uri.parse("http://www.visual.voicemail.setup");
private static final Uri TEST_VOICEMAIL_URI = Uri.parse("tel:901");
private static final int ACTION_MSG_CALL_VOICEMAIL =
R.string.voicemail_status_action_call_server;
private static final int ACTION_MSG_CONFIGURE = R.string.voicemail_status_action_configure;
private static final int STATUS_MSG_NONE = -1;
private static final int STATUS_MSG_VOICEMAIL_NOT_AVAILABLE =
R.string.voicemail_status_voicemail_not_available;
private static final int STATUS_MSG_AUDIO_NOT_AVAIALABLE =
R.string.voicemail_status_audio_not_available;
private static final int STATUS_MSG_MESSAGE_WAITING = R.string.voicemail_status_messages_waiting;
private static final int STATUS_MSG_INVITE_FOR_CONFIGURATION =
R.string.voicemail_status_configure_voicemail;
// Object under test.
private VoicemailStatusHelper mStatusHelper;
@Override
protected void setUp() throws Exception {
super.setUp();
mStatusHelper = new VoicemailStatusHelperImpl();
}
@Override
protected void tearDown() throws Exception {
for (String sourcePackage : TEST_PACKAGES) {
deleteEntryForPackage(sourcePackage);
}
// Set member variables to null so that they are garbage collected across different runs
// of the tests.
mStatusHelper = null;
super.tearDown();
}
public void testNoStatusEntries() {
assertEquals(0, getStatusMessages().size());
}
public void testAllOK() {
insertEntryForPackage(TEST_PACKAGES[0], getAllOkStatusValues());
insertEntryForPackage(TEST_PACKAGES[1], getAllOkStatusValues());
assertEquals(0, getStatusMessages().size());
}
public void testNotAllOKForOnePackage() {
insertEntryForPackage(TEST_PACKAGES[0], getAllOkStatusValues());
insertEntryForPackage(TEST_PACKAGES[1], getAllOkStatusValues());
ContentValues values = new ContentValues();
// Good data channel + no notification
// action: call voicemail
// msg: voicemail not available in call log page & none in call details page.
values.put(NOTIFICATION_CHANNEL_STATE, NOTIFICATION_CHANNEL_STATE_NO_CONNECTION);
values.put(DATA_CHANNEL_STATE, DATA_CHANNEL_STATE_OK);
updateEntryForPackage(TEST_PACKAGES[1], values);
checkExpectedMessage(TEST_PACKAGES[1], values, STATUS_MSG_VOICEMAIL_NOT_AVAILABLE,
STATUS_MSG_NONE, ACTION_MSG_CALL_VOICEMAIL);
// Message waiting + good data channel - no action.
values.put(NOTIFICATION_CHANNEL_STATE, NOTIFICATION_CHANNEL_STATE_MESSAGE_WAITING);
values.put(DATA_CHANNEL_STATE, DATA_CHANNEL_STATE_OK);
updateEntryForPackage(TEST_PACKAGES[1], values);
checkNoMessages(TEST_PACKAGES[1], values);
// No data channel + no notification
// action: call voicemail
// msg: voicemail not available in call log page & audio not available in call details page.
values.put(NOTIFICATION_CHANNEL_STATE, NOTIFICATION_CHANNEL_STATE_OK);
values.put(DATA_CHANNEL_STATE, DATA_CHANNEL_STATE_NO_CONNECTION);
updateEntryForPackage(TEST_PACKAGES[1], values);
checkExpectedMessage(TEST_PACKAGES[1], values, STATUS_MSG_VOICEMAIL_NOT_AVAILABLE,
STATUS_MSG_AUDIO_NOT_AVAIALABLE, ACTION_MSG_CALL_VOICEMAIL);
// No data channel + Notification OK
// action: call voicemail
// msg: voicemail not available in call log page & audio not available in call details page.
values.put(NOTIFICATION_CHANNEL_STATE, NOTIFICATION_CHANNEL_STATE_NO_CONNECTION);
values.put(DATA_CHANNEL_STATE, DATA_CHANNEL_STATE_NO_CONNECTION);
updateEntryForPackage(TEST_PACKAGES[1], values);
checkExpectedMessage(TEST_PACKAGES[1], values, STATUS_MSG_VOICEMAIL_NOT_AVAILABLE,
STATUS_MSG_AUDIO_NOT_AVAIALABLE, ACTION_MSG_CALL_VOICEMAIL);
// No data channel + Notification OK
// action: call voicemail
// msg: message waiting in call log page & audio not available in call details page.
values.put(NOTIFICATION_CHANNEL_STATE, NOTIFICATION_CHANNEL_STATE_MESSAGE_WAITING);
values.put(DATA_CHANNEL_STATE, DATA_CHANNEL_STATE_NO_CONNECTION);
updateEntryForPackage(TEST_PACKAGES[1], values);
checkExpectedMessage(TEST_PACKAGES[1], values, STATUS_MSG_MESSAGE_WAITING,
STATUS_MSG_AUDIO_NOT_AVAIALABLE, ACTION_MSG_CALL_VOICEMAIL);
// Not configured. No user action, so no message.
values.put(CONFIGURATION_STATE, CONFIGURATION_STATE_NOT_CONFIGURED);
updateEntryForPackage(TEST_PACKAGES[1], values);
checkNoMessages(TEST_PACKAGES[1], values);
// Can be configured - invite user for configure voicemail.
values.put(CONFIGURATION_STATE, CONFIGURATION_STATE_CAN_BE_CONFIGURED);
updateEntryForPackage(TEST_PACKAGES[1], values);
checkExpectedMessage(TEST_PACKAGES[1], values, STATUS_MSG_INVITE_FOR_CONFIGURATION,
STATUS_MSG_NONE, ACTION_MSG_CONFIGURE, TEST_SETTINGS_URI);
}
// Test that priority of messages are handled well.
public void testMessageOrdering() {
insertEntryForPackage(TEST_PACKAGES[0], getAllOkStatusValues());
insertEntryForPackage(TEST_PACKAGES[1], getAllOkStatusValues());
final ContentValues valuesNoNotificationGoodDataChannel = new ContentValues();
valuesNoNotificationGoodDataChannel.put(NOTIFICATION_CHANNEL_STATE,
NOTIFICATION_CHANNEL_STATE_NO_CONNECTION);
valuesNoNotificationGoodDataChannel.put(DATA_CHANNEL_STATE, DATA_CHANNEL_STATE_OK);
final ContentValues valuesNoNotificationNoDataChannel = new ContentValues();
valuesNoNotificationNoDataChannel.put(NOTIFICATION_CHANNEL_STATE,
NOTIFICATION_CHANNEL_STATE_NO_CONNECTION);
valuesNoNotificationNoDataChannel.put(DATA_CHANNEL_STATE, DATA_CHANNEL_STATE_NO_CONNECTION);
// Package1 with valuesNoNotificationGoodDataChannel and
// package2 with valuesNoNotificationNoDataChannel. Package2 should be above.
updateEntryForPackage(TEST_PACKAGES[0], valuesNoNotificationGoodDataChannel);
updateEntryForPackage(TEST_PACKAGES[1], valuesNoNotificationNoDataChannel);
List<StatusMessage> messages = getStatusMessages();
assertEquals(2, messages.size());
assertEquals(TEST_PACKAGES[0], messages.get(1).sourcePackage);
assertEquals(TEST_PACKAGES[1], messages.get(0).sourcePackage);
// Now reverse the values - ordering should be reversed as well.
updateEntryForPackage(TEST_PACKAGES[0], valuesNoNotificationNoDataChannel);
updateEntryForPackage(TEST_PACKAGES[1], valuesNoNotificationGoodDataChannel);
messages = getStatusMessages();
assertEquals(2, messages.size());
assertEquals(TEST_PACKAGES[0], messages.get(0).sourcePackage);
assertEquals(TEST_PACKAGES[1], messages.get(1).sourcePackage);
}
/** Checks that the expected source status message is returned by VoicemailStatusHelper. */
private void checkExpectedMessage(String sourcePackage, ContentValues values,
int expectedCallLogMsg, int expectedCallDetailsMsg, int expectedActionMsg,
Uri expectedUri) {
List<StatusMessage> messages = getStatusMessages();
assertEquals(1, messages.size());
checkMessageMatches(messages.get(0), sourcePackage, expectedCallLogMsg,
expectedCallDetailsMsg, expectedActionMsg, expectedUri);
}
private void checkExpectedMessage(String sourcePackage, ContentValues values,
int expectedCallLogMsg, int expectedCallDetailsMessage, int expectedActionMsg) {
checkExpectedMessage(sourcePackage, values, expectedCallLogMsg, expectedCallDetailsMessage,
expectedActionMsg, TEST_VOICEMAIL_URI);
}
private void checkMessageMatches(StatusMessage message, String expectedSourcePackage,
int expectedCallLogMsg, int expectedCallDetailsMsg, int expectedActionMsg,
Uri expectedUri) {
assertEquals(expectedSourcePackage, message.sourcePackage);
assertEquals(expectedCallLogMsg, message.callLogMessageId);
assertEquals(expectedCallDetailsMsg, message.callDetailsMessageId);
assertEquals(expectedActionMsg, message.actionMessageId);
if (expectedUri == null) {
assertNull(message.actionUri);
} else {
assertEquals(expectedUri, message.actionUri);
}
}
private void checkNoMessages(String sourcePackage, ContentValues values) {
assertEquals(1, updateEntryForPackage(sourcePackage, values));
List<StatusMessage> messages = getStatusMessages();
assertEquals(0, messages.size());
}
private ContentValues getAllOkStatusValues() {
ContentValues values = new ContentValues();
values.put(Status.SETTINGS_URI, TEST_SETTINGS_URI.toString());
values.put(Status.VOICEMAIL_ACCESS_URI, TEST_VOICEMAIL_URI.toString());
values.put(Status.CONFIGURATION_STATE, Status.CONFIGURATION_STATE_OK);
values.put(Status.DATA_CHANNEL_STATE, Status.DATA_CHANNEL_STATE_OK);
values.put(Status.NOTIFICATION_CHANNEL_STATE, Status.NOTIFICATION_CHANNEL_STATE_OK);
return values;
}
private void insertEntryForPackage(String sourcePackage, ContentValues values) {
// If insertion fails then try update as the record might already exist.
if (getContentResolver().insert(Status.buildSourceUri(sourcePackage), values) == null) {
updateEntryForPackage(sourcePackage, values);
}
}
private void deleteEntryForPackage(String sourcePackage) {
getContentResolver().delete(Status.buildSourceUri(sourcePackage), null, null);
}
private int updateEntryForPackage(String sourcePackage, ContentValues values) {
return getContentResolver().update(
Status.buildSourceUri(sourcePackage), values, null, null);
}
private List<StatusMessage> getStatusMessages() {
// Restrict the cursor to only the the test packages to eliminate any side effects if there
// are other status messages already stored on the device.
Cursor cursor = getContentResolver().query(Status.CONTENT_URI,
VoicemailStatusHelperImpl.PROJECTION, getTestPackageSelection(), null, null);
return mStatusHelper.getStatusMessages(cursor);
}
private String getTestPackageSelection() {
StringBuilder sb = new StringBuilder();
for (String sourcePackage : TEST_PACKAGES) {
if (sb.length() > 0) {
sb.append(" OR ");
}
sb.append(String.format("(source_package='%s')", sourcePackage));
}
return sb.toString();
}
private ContentResolver getContentResolver() {
return getContext().getContentResolver();
}
}
| gpl-2.0 |
nickfun/newlifeblogger | profile.php | 3859 | <?PHP
/*
-----------------------------------------
NewLife Blogging System Version 3
-----------------------------------------
Nick F <nick@sevengraff.com>
www.sevengraff.com
-----------------------------------------
This product is distributed under the GNU
GPL liscense. A copy of that liscense
should be packaged with this product.
-----------------------------------------
*/
require_once 'config.php'; // require_once this before others!
require_once 'system/functions.php';
require_once 'system/ets_sql.php';
require_once 'system/sqldb2.class.php';
require_once 'system/nlb_blog.class.php';
require_once 'system/nlb_user.class.php';
require_once 'system/nlb_config.class.php';
require_once 'system/text.class.php';
require_once 'ets.php';
$path = fetch_url_data();
$db = new sqldb2( $DB_CONFIG );
$blog = new nlb_blog( $db );
$config = new nlb_config( $db );
include $config->langfile();
$user = new nlb_user( $db );
$user->checkLogin();
if( !isset($path['user']) ) {
jsRedirect( script_path . 'index.php'); // need a user id!!
} else {
$USERID = $path['user'];
if( !is_numeric($USERID) ) {
jsRedirect( script_path . 'index.php' );
}
// get info on user
$info = $db->getArray('
SELECT username, email, blog_count, birthday, gender, registered, bio
FROM ' . db_users . '
WHERE user_id="' . $USERID . '"
LIMIT 1;');
if( empty( $info ) ) {
jsRedirect( script_path . 'index.php'); // not valid userid
}
// comment count
$tmp = $db->getArray('SELECT COUNT(comment_id) AS count FROM ' . db_comments . ' WHERE author_id="' . $USERID . '";');
$info['comment_count'] = $tmp['count'];
// friends count
$tmp = $db->getArray('SELECT COUNT(*) AS count FROM ' . db_friends . ' WHERE owner_id="' . $USERID . '";');
$info['num_friends'] = $tmp['count'];
// as friend count
$tmp = $db->getArray('SELECT COUNT(*) AS count FROM ' . db_friends . ' WHERE friend_id = ' . $USERID . ' ;');
$info['num_as_friend'] = $tmp['count'];
// little cleanup before parsing
if( empty($info['birthday']) ) {
$info['birthday'] = $l['na'];
} else {
$info['birthday'] = date('dS of F Y', $info['birthday']);
}
$info['registered'] = date('M jS, Y g:i a', $info['registered']);
if( $info['gender'] == 1 ) {
$info['gender'] = $l['gender-male'];
} else if( $info['gender'] == 2 ) {
$info['gender'] = $l['gender-female'];
} else {
$info['gender'] = $l['na'];
}
if( !$user->isLogedIn ) {
$e = $info['email'];
$e = str_replace('@', ' at ', $e);
$e = str_replace('.', ' dot ', $e);
$info['email'] = $e;
}
// loop through the array and assign template tags
foreach( $info as $key => $val ) {
$ets->$key = $val;
}
// setup other template tags
$ets->username = $info['username'];
$ets->url_home = build_link('blog.php', array('user'=>$USERID));
$ets->url_profile = build_link('profile.php', array('user'=>$USERID));
$ets->url_friends = build_link('friends.php', array('user'=>$USERID));
// check for avatar
$avatar = $db->getArray('SELECT file, isCustom FROM ' . db_avatars . ' WHERE owner_id=' . $USERID . ' AND type=1;');
if( !empty( $avatar ) ) {
if( $avatar['isCustom'] == 1 ) {
$file = 'avatars/';
} else {
$file = 'avatars/default/';
}
$file .= $avatar['file'];
$ets->avatar_url = script_path . $file;
$ets->avatar = '<img src="' . script_path . $file . '" />';
}
// rss bit
$ets->rss_url = build_link('rss.php', array('id'=>$USERID));
$ets->rss_img = '<a href="' . $ets->rss_url . '"><img border="0" src="' . script_path . 'xml.gif" /></a>';
$ets->USER_TEMPLATE = serialize( array( 'type' => 'profile', 'user_id' => $USERID ) );
$OUTTER = serialize( array( 'type' => 'outter' ) );
printt( $ets, $OUTTER );
}
?> | gpl-2.0 |
ber5ien/autoValeBid | vendor/composer/autoload_real.php | 1585 | <?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInitcbcf025fd8fb702eeb8c1b0beb6f6e65
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInitcbcf025fd8fb702eeb8c1b0beb6f6e65', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInitcbcf025fd8fb702eeb8c1b0beb6f6e65', 'loadClassLoader'));
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
$loader->register(true);
$includeFiles = require __DIR__ . '/autoload_files.php';
foreach ($includeFiles as $file) {
composerRequirecbcf025fd8fb702eeb8c1b0beb6f6e65($file);
}
return $loader;
}
}
function composerRequirecbcf025fd8fb702eeb8c1b0beb6f6e65($file)
{
require $file;
}
| gpl-2.0 |
intelie/esper | esper/src/main/java/com/espertech/esper/epl/spec/OnTriggerWindowUpdateDesc.java | 1655 | /**************************************************************************************
* Copyright (C) 2008 EsperTech, Inc. All rights reserved. *
* http://esper.codehaus.org *
* http://www.espertech.com *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the GPL license *
* a copy of which has been included with this distribution in the license.txt file. *
**************************************************************************************/
package com.espertech.esper.epl.spec;
import java.util.List;
/**
* Specification for the on-select and on-delete (no split-stream) statement.
*/
public class OnTriggerWindowUpdateDesc extends OnTriggerWindowDesc
{
private static final long serialVersionUID = 3796573624109335943L;
private List<OnTriggerSetAssignment> assignments;
/**
* Ctor.
* @param windowName the window name
* @param optionalAsName the optional name
* @param assignments set-assignments
*/
public OnTriggerWindowUpdateDesc(String windowName, String optionalAsName, List<OnTriggerSetAssignment> assignments) {
super(windowName, optionalAsName, OnTriggerType.ON_UPDATE);
this.assignments = assignments;
}
/**
* Returns assignments.
* @return assignments
*/
public List<OnTriggerSetAssignment> getAssignments() {
return assignments;
}
} | gpl-2.0 |
dzandrey/portal | components/com_mtree/templates/kinabalu/sub_listingDetailsStyle2.tpl.php | 6832 | <div id="listing">
<h2><?php
$link_name = $this->fields->getFieldById(1);
$this->plugin( 'ahreflisting', $this->link, $link_name->getOutput(1), '', array("delete"=>true, "link"=>false) )
?></h2>
<?php
if ( !empty($this->mambotAfterDisplayTitle) ) {
echo trim( implode( "\n", $this->mambotAfterDisplayTitle ) );
}
if ( !empty($this->mambotBeforeDisplayContent) && $this->mambotBeforeDisplayContent[0] <> '' ) {
echo trim( implode( "\n", $this->mambotBeforeDisplayContent ) );
}
echo '<div class="column first">';
if ($this->config->getTemParam('skipFirstImage','0') == 1) {
array_shift($this->images);
}
if (!empty($this->images)) include $this->loadTemplate( 'sub_images.tpl.php' );
echo '<div class="listing-desc">';
if(!is_null($this->fields->getFieldById(2))) {
$link_desc = $this->fields->getFieldById(2);
echo $link_desc->getOutput(1);
}
echo '</div>';
if ( !empty($this->mambotAfterDisplayContent) ) { echo trim( implode( "\n", $this->mambotAfterDisplayContent ) ); }
if( $this->config->get('show_favourite') == 1 || $this->config->get('show_rating') == 1 )
{
echo '<div class="rating-fav">';
if($this->config->get('show_rating')) {
echo '<div class="rating">';
$this->plugin( 'ratableRating', $this->link, $this->link->link_rating, $this->link->link_votes);
echo '<div id="total-votes">';
if( $this->link->link_votes <= 1 ) {
echo $this->link->link_votes . " " . strtolower(JText::_( 'COM_MTREE_VOTE' ));
} elseif ($this->link->link_votes > 1 ) {
echo $this->link->link_votes . " " . strtolower(JText::_( 'COM_MTREE_VOTES' ));
}
echo '</div>';
echo '</div>';
}
if($this->config->get('show_favourite')) {
?>
<div class="favourite">
<span class="fav-caption"><?php echo JText::_( 'COM_MTREE_FAVOURED' ) ?>:</span>
<div id="fav-count"><?php echo number_format($this->total_favourites,0,'.',',') ?></div><?php
if($this->my->id > 0){
if($this->is_user_favourite) {
?><div id="fav-msg"><a href="javascript:fav(<?php echo $this->link->link_id ?>,-1);"><?php echo JText::_( 'COM_MTREE_REMOVE_FAVOURITE' ) ?></a></div><?php
} else {
?><div id="fav-msg"><a href="javascript:fav(<?php echo $this->link->link_id ?>,1);"><?php echo JText::_( 'COM_MTREE_ADD_AS_FAVOURITE' ) ?></a></div><?php
}
} ?>
</div><?php
}
echo '</div>';
}
echo '</div>';
echo '<div class="column second">';
echo '<h3>';
echo JText::_('COM_MTREE_LISTING_DETAILS');
echo '</h3>';
// Address
$address = '';
if( $this->config->getTemParam('displayAddressInOneRow','1') ) {
$address_parts = array();
$address_displayed = false;
foreach( array( 4,5,6,7,8 ) AS $address_field_id )
{
$field = $this->fields->getFieldById($address_field_id);
if( isset($field) && $output = $field->getOutput(1) )
{
$address_parts[] = $output;
}
}
if( !empty($address_parts) ) { $address = implode(', ',$address_parts); }
}
// Other custom fields
echo '<div class="fields">';
$number_of_columns = $this->config->getTemParam('numOfColumnsInDetailsView','1');
$field_count = 0;
$need_div_closure = false;
$this->fields->resetPointer();
while( $this->fields->hasNext() ) {
$field = $this->fields->getField();
$value = $field->getValue();
$hasValue = $field->hasValue();
if(
(
(
(!$field->hasInputField() && !$field->isCore() && empty($value))
||
(!empty($value) || $value == '0')
)
&&
// This condition ensure that fields listed in array() are skipped
!in_array($field->getName(),array('link_name','link_desc'))
&&
(
(
$this->config->getTemParam('displayAddressInOneRow','1') == 1
&&
!in_array($field->getId(),array(5,6,7,8))
)
||
$this->config->getTemParam('displayAddressInOneRow','1') == 0
)
&&
$hasValue
)
||
// Fields in array() are always displayed regardless of its value.
in_array($field->getName(),array('link_featured'))
) {
if( $field_count % $number_of_columns == 0 ) {
echo '<div class="row0">';
$need_div_closure = true;
}
echo '<div class="fieldRow'.(($field_count % $number_of_columns == ($number_of_columns -1))?' lastFieldRow':'').'" style="width:'.floor(98/intval($number_of_columns)).'%">';
if($this->config->getTemParam('displayAddressInOneRow','1') && in_array($field->getId(),array(4,5,6,7,8)) && $address_field = $this->fields->getFieldById(4)) {
if( $address_displayed == false ) {
echo '<div class="caption">';
if($address_field->hasCaption()) {
echo $address_field->getCaption();
}
echo '</div>';
echo '<div class="output">';
echo $address_field->getDisplayPrefixText();
echo $address;
echo $address_field->getDisplaySuffixText();
echo '</div>';
$address_displayed = true;
}
} else {
echo '<div class="caption">';
// echo $field->getId();
if($field->hasCaption()) {
echo $field->getCaption();
}
echo '</div>';
echo '<div class="output">';
switch($field->getFieldType()) {
case 'mfile':
echo $field->getDisplayPrefixText();
echo '<p>';
echo $field->getOutput(1);
echo '<p>';
echo $field->getDisplaySuffixText();
break;
case ( $field->getFieldType() == 'coreprice' && $field->getValue() == 0 ):
echo $field->getOutput(1);
break;
default:
echo $field->getDisplayPrefixText();
echo $field->getOutput(1);
echo $field->getDisplaySuffixText();
}
echo '</div>';
}
echo '</div>';
if( ($field_count % $number_of_columns) == ($number_of_columns-1) ) {
echo '</div>';
$need_div_closure = false;
}
$field_count++;
}
$this->fields->next();
}
if( $need_div_closure ) {
echo '</div>';
$need_div_closure = false;
}
echo '</div>';
echo '</div>';
if( $this->show_actions_rating_fav ) {
?>
<div class="actions-rating-fav">
<?php if( $this->show_actions ) { ?>
<div class="actions">
<?php
$this->plugin( 'ahrefreview', $this->link, array("rel"=>"nofollow") );
$this->plugin( 'ahrefrecommend', $this->link, array("rel"=>"nofollow") );
$this->plugin( 'ahrefprint', $this->link, array("rel"=>"nofollow") );
$this->plugin( 'ahrefcontact', $this->link, array("rel"=>"nofollow") );
$this->plugin( 'ahrefvisit', $this->link, '', 1, array("rel"=>"nofollow") );
$this->plugin( 'ahrefreport', $this->link, array("rel"=>"nofollow") );
$this->plugin( 'ahrefclaim', $this->link, array("rel"=>"nofollow") );
$this->plugin( 'ahrefownerlisting', $this->link );
$this->plugin( 'ahrefmap', $this->link, array("rel"=>"nofollow") );
?></div><?php
}
?></div><?php
}
// Load User Profile
if( $this->config->get('show_user_profile_in_listing_details') )
{
include $this->loadTemplate( 'sub_userProfile.tpl.php' );
}
// Load Contact Owner Form
if( $this->config->get('contact_form_location') == 2 )
{
include $this->loadTemplate( 'sub_contactOwnerForm.tpl.php' );
}
?>
</div> | gpl-2.0 |
dhavalmanjaria/dma-student-information-system | university_credits/tests.py | 1616 | from django.test import TestCase
from .models import UniversityCredit, SubjectCredit
from .management.commands import initcredits
from user_management.management.commands import createumuser, initgroups
from curriculum.management.commands import initcurriculum
from curriculum.models import Semester
import logging
LOG = logging.getLogger('app')
class UniversityCreditTestCase(TestCase):
"""
Note: This testcase does not contain tests to check if credits are created
when a new student is approved. Those tests are included in
user_management.tests.test_authentication
"""
@classmethod
def setUpTestData(self):
cmd = initgroups.Command()
cmd.handle()
cmd = createumuser.Command()
cmd.handle()
cmd = initcurriculum.Command()
cmd.handle()
cmd = initcredits.Command()
cmd.handle()
def setUp(self):
global semester
semester = Semester.objects.get(
course__short_name="BCA", semester_number=2)
def test_max_credits(self):
global semester
self.client.login(username='um0', password='dhaval27')
credit = SubjectCredit.objects.filter(
subject__semester=semester).first()
LOG.debug(str(credit.pk))
data = {
'crd_pk': credit.pk,
'max_credits': 12
}
resp = self.client.post(
'/actions/university-credits/edit-credits-for-semester/' + str(
semester.pk), data)
new_max = SubjectCredit.objects.get(pk=credit.pk).max_credits
self.assertEqual(new_max, 12)
| gpl-2.0 |
iquesters/ams | gen/com/iq/ams/action/community/CommunityDeleteSA.java | 791 | /**
* Copyright (c) 2013, iquesters - All Rights Reserved.
*/
package com.iq.ams.action.community;
import org.iq.action.Action;
import org.iq.action.SubmitAction;
/**
* @author Nilotpal
*
*/
@Action(id = "CommunityDeleteSA")
public class CommunityDeleteSA extends SubmitAction {
/**
*
*/
private static final long serialVersionUID = -1439120016220952463L;
/**
*
*/
public static final String COMMUNITY_DELETE_SUCCESS_ACTION_KEY = "CommunityDetailsLA";
// public static final String SEARCH_FAILURE_ACTION_KEY = "SearchFailure";
// public static final String SEARCH_VERIFY_ACTION_KEY = "SearchVerify";
/**
*
*/
public CommunityDeleteSA() {
super();
setName("CommunityDeleteSA");
setServiceName("DeleteCommunity");
}
} | gpl-2.0 |
karianna/jdk8_tl | jdk/test/sun/util/calendar/zi/Rule.java | 6202 | /*
* Copyright (c) 2000, 2004, 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.
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;
/**
* Rule manipulates Rule records.
*
* @since 1.4
*/
class Rule {
private List<RuleRec> list;
private String name;
/**
* Constructs a Rule which consists of a Rule record list. The
* specified name is given to this Rule.
* @param name the Rule name
*/
Rule(String name) {
this.name = name;
list = new ArrayList<RuleRec>();
}
/**
* Added a RuleRec to the Rule record list.
*/
void add(RuleRec rec) {
list.add(rec);
}
/**
* @return the Rule name
*/
String getName() {
return name;
}
/**
* Gets all rule records that cover the given year.
*
* @param year the year number for which the rule is applicable.
* @return rules in List that are collated in time. If no rule is found, an empty
* List is returned.
*/
List<RuleRec> getRules(int year) {
List<RuleRec> rules = new ArrayList<RuleRec>(3);
for (RuleRec rec : list) {
if (year >= rec.getFromYear() && year <= rec.getToYear()) {
if ((rec.isOdd() && year % 2 == 0) || (rec.isEven() && year % 2 == 1))
continue;
rules.add(rec);
}
}
int n = rules.size();
if (n <= 1) {
return rules;
}
if (n == 2) {
RuleRec rec1 = rules.get(0);
RuleRec rec2 = rules.get(1);
if (rec1.getMonthNum() > rec2.getMonthNum()) {
rules.set(0, rec2);
rules.set(1, rec1);
} else if (rec1.getMonthNum() == rec2.getMonthNum()) {
// TODO: it's not accurate to ignore time types (STD, WALL, UTC)
long t1 = Time.getLocalTime(year, rec1.getMonth(),
rec1.getDay(), rec1.getTime().getTime());
long t2 = Time.getLocalTime(year, rec2.getMonth(),
rec2.getDay(), rec2.getTime().getTime());
if (t1 > t2) {
rules.set(0, rec2);
rules.set(1, rec1);
}
}
return rules;
}
final int y = year;
RuleRec[] recs = new RuleRec[rules.size()];
rules.toArray(recs);
Arrays.sort(recs, new Comparator<RuleRec>() {
public int compare(RuleRec r1, RuleRec r2) {
int n = r1.getMonthNum() - r2.getMonthNum();
if (n != 0) {
return n;
}
// TODO: it's not accurate to ignore time types (STD, WALL, UTC)
long t1 = Time.getLocalTime(y, r1.getMonth(),
r1.getDay(), r1.getTime().getTime());
long t2 = Time.getLocalTime(y, r2.getMonth(),
r2.getDay(), r2.getTime().getTime());
return (int)(t1 - t2);
}
public boolean equals(Object o) {
return this == o;
}
});
rules.clear();
for (int i = 0; i < n; i++) {
rules.add(recs[i]);
}
return rules;
}
/**
* Gets rule records that have either "max" or cover the endYear
* value in its DST schedule.
*
* @return rules that contain last DST schedule. An empty
* ArrayList is returned if no last rules are found.
*/
List<RuleRec> getLastRules() {
RuleRec start = null;
RuleRec end = null;
for (int i = 0; i < list.size(); i++) {
RuleRec rec = list.get(i);
if (rec.isLastRule()) {
if (rec.getSave() > 0) {
start = rec;
} else {
end = rec;
}
}
}
if (start == null || end == null) {
int endYear = Zoneinfo.getEndYear();
for (int i = 0; i < list.size(); i++) {
RuleRec rec = list.get(i);
if (endYear >= rec.getFromYear() && endYear <= rec.getToYear()) {
if (start == null && rec.getSave() > 0) {
start = rec;
} else {
if (end == null && rec.getSave() == 0) {
end = rec;
}
}
}
}
}
List<RuleRec> r = new ArrayList<RuleRec>(2);
if (start == null || end == null) {
if (start != null || end != null) {
Main.warning("found last rules for "+name+" inconsistent.");
}
return r;
}
r.add(start);
r.add(end);
return r;
}
}
| gpl-2.0 |
smallslime/slime_app_creator | __APP__/__STD__/public/cli_publish.php | 336 | <?php
require __DIR__ . '/__init__.php';
main(
function ()
{
return \Slime\Framework\InitBean::factory()
->set_1_CFG(array('~PHP', DIR_CONFIG, 'publish'))
->set_2_CompConf('component_common;component_cli')
->set_2_Event('event_cli')
->set_2_Router('route_cli');
}
);
| gpl-2.0 |
r3dlex/teachalot | Lectures/LinguagemDeProgramacaoII/Code/Java/Mensagem-Part.java | 135 | public class Mensagem {
private String _titulo;
private String _texto;
private String _autor;
private String _data;
//...
}
| gpl-2.0 |
arrivu/elearning-wordpress | wp-config.php | 3451 | <?php
/**
* The base configurations of the WordPress.
*
* This file has the following configurations: MySQL settings, Table Prefix,
* Secret Keys, WordPress Language, and ABSPATH. You can find more information
* by visiting {@link http://codex.wordpress.org/Editing_wp-config.php Editing
* wp-config.php} Codex page. You can get the MySQL settings from your web host.
*
* This file is used by the wp-config.php creation script during the
* installation. You don't have to use the web site, you can just copy this file
* to "wp-config.php" and fill in the values.
*
* @package WordPress
*/
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'codefixe_rails');
/** MySQL database username */
define('DB_USER', 'root');
/** MySQL database password */
define('DB_PASSWORD', 'root');
/** MySQL hostname */
define('DB_HOST', 'localhost');
/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');
/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');
/**#@+
* Authentication Unique Keys and Salts.
*
* Change these to different unique phrases!
* You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
* You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
*
* @since 2.6.0
*/
define('AUTH_KEY', '+S:uy76I/~7r|Z!<<59iZ`ghBm`Rn$Pj|-HjjoK+&t:w+J!Gunmv=>Y(}CF)P@!=');
define('SECURE_AUTH_KEY', 'Pv_//*p B3~$+:y|F[O`w5x5[cNc1%V!x+K<NNKRyLwgdO+goZD>p$$@k<`MZVjR');
define('LOGGED_IN_KEY', '<+60M`C!xBcES]Sy2}HF8K[_BXO4QVk (zR1.3-K(d<~N&@G;_Aj*;ByOVi-qOhg');
define('NONCE_KEY', '/S9 c`)ew!Zs&n6VQJ$@T{hhwZ+p6G%qB_|+BL22t3^-.:.`W0p2{Ltj e|4ew*l');
define('AUTH_SALT', 'a]Lu8$?*YU+PY:bZgtD?;18ipw=5vgXA4HL_9JwUROSuN+p@Q_W(GWT1(U`Rhf02');
define('SECURE_AUTH_SALT', 'U}>~!wl2;YHoi3]Hn*XeFc+`e|;ORb0a3-~$3X`/)*madbthMB4UM1P~qf<iQn-}');
define('LOGGED_IN_SALT', '%+Tz|lht= |8|;&o+~I]l, PxuRwfe0^JlY0nH2gLf5&mGlzVoBW@Dq|LTNa{/mz');
define('NONCE_SALT', 'BcJ*A!DUe^=uh!s4k+xjG.0;^meDczfB g:=apfY?r+a]F3gGB4Jr|m]JHeoJ|Bg');
/**#@-*/
/**
* WordPress Database Table prefix.
*
* You can have multiple installations in one database if you give each a unique
* prefix. Only numbers, letters, and underscores please!
*/
$table_prefix = 'wp_';
/**
* WordPress Localized Language, defaults to English.
*
* Change this to localize WordPress. A corresponding MO file for the chosen
* language must be installed to wp-content/languages. For example, install
* de_DE.mo to wp-content/languages and set WPLANG to 'de_DE' to enable German
* language support.
*/
define('WPLANG', '');
/**
* For developers: WordPress debugging mode.
*
* Change this to true to enable the display of notices during development.
* It is strongly recommended that plugin and theme developers use WP_DEBUG
* in their development environments.
*/
define('WP_DEBUG', false);
/* That's all, stop editing! Happy blogging. */
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
| gpl-2.0 |
Teplitsa/Leyka | inc/settings/renders/leyka-class-extension-settings-render.php | 13239 | <?php if( !defined('WPINC') ) die;
/**
* Leyka Options Render class.
*/
class Leyka_Extension_Settings_Render extends Leyka_Settings_Render {
protected static $_instance = null;
// protected $_params = [];
protected function _set_attributes() {
$this->_id = 'options';
}
/** The main content layout wrapper method. */
public function render_content() {
$extension = $this->_controller->extension;?>
<form id="leyka-options-form-<?php echo $this->_controller->id;?>" class="leyka-options-form <?php echo $this->_controller->id;?>" method="post" action="">
<div class="single-settings-header">
<div class="header-left">
<h2 class="wp-heading-inline"><?php echo $extension->title;?></h2>
<div class="meta-data">
<div class="item activation-status">
<span class="item-name"><?php _e('Status:', 'leyka');?></span>
<span class="item-value status-label <?php echo $extension->activation_status;?>">
<?php echo mb_strtolower($extension->activation_status_label);?>
</span>
</div>
<div class="item extension-version">
<span class="item-name"><?php _e('Extension version:', 'leyka');?></span>
<span class="item-value"><?php echo $extension->version;?></span>
</div>
<div class="item leyka-version">
<span class="item-name"><?php _e('Leyka version:', 'leyka');?></span>
<span class="item-value"><?php echo LEYKA_VERSION;?></span>
</div>
<div class="item author">
<span class="item-name"><?php _e('Author:', 'leyka');?></span>
<span class="item-value">
<?php if($extension->author_url) {?>
<a href="<?php echo $extension->author_url;?>" target="_blank" class="outer-link">
<?php echo $extension->author_name;?>
</a>
<?php } else {
echo __('Author:', 'leyka').' '.$extension->author_name;
}?>
</span>
</div>
</div>
<div class="extension-description"><?php echo $extension->settings_description;?></div>
<div class="common-errors <?php echo $this->_controller->has_common_errors() ? 'has-errors' : '';?>">
<?php $this->render_common_errors_area();?>
</div>
</div>
<div class="header-right">
<div class="module-logo-wrapper">
<div class="module-logo extension-logo">
<img src="<?php echo $extension->logo_url;?>" class="module-logo-pic extension-logo-pic" alt="">
</div>
</div>
<div class="extension-main-cta">
<?php $submit_data = $this->_controller->get_submit_data();?>
<input type="submit" class="button <?php echo $submit_data['activation_status'] === 'active' ? 'button-secondary' : 'button-primary';?> activation-button <?php echo $submit_data['activation_status'];?>" name="<?php echo $submit_data['activation_status'] === 'active' ? 'leyka_deactivate_'.$this->_controller->id : 'leyka_activate_'.$this->_controller->id;?>" value="<?php echo $submit_data['activation_button_label'];?>">
</div>
</div>
</div>
<div id="poststuff">
<div class="metabox-holder columns-2">
<div class="postbox-container column-main">
<div class="leyka-options main-area"><?php $this->render_main_area();?></div>
</div>
<div class="postbox-container column-sidebar">
<?php if($extension->screenshots) {?>
<div class="lightbox">
<?php foreach($extension->screenshots as $thumbnail_url => $full_url) {?>
<a href="<?php echo esc_url($full_url);?>" target="_blank">
<img src="<?php echo esc_url($thumbnail_url);?>" alt="">
</a>
<?php }?>
</div>
<?php }?>
<?php if($extension->setup_description) {?>
<div class="setup-description"><?php echo $extension->setup_description;?></div>
<?php }
if($extension->docs_url) {?>
<div class="setup-user-manual-link">
<a class="outer-link" href="<?php echo $extension->docs_url;?>" target="_blank">
<?php _e('Detailed manual', 'leyka');?>
</a>
</div>
<?php }?>
</div>
</div>
</div>
<?php $this->render_footer();?>
</form>
<?php }
public function render_common_errors_area() {
foreach($this->_controller->get_common_errors() as $error) { /** @var WP_Error $error */?>
<span><?php echo $error->get_error_message();?></span>
<?php }
}
public function render_js_data() {
// wp_localize_script('leyka-settings', 'metabox_areas', [])
}
public function render_main_area() {
$this->render_js_data();
$this->_add_sections_metaboxes();?>
<div class="options-form-content">
<?php $metaboxes_area_id = $this->_controller->id.'-options_main_area';?>
<input type="hidden" class="leyka-support-metabox-area" value="<?php echo $metaboxes_area_id;?>">
<?php do_meta_boxes($metaboxes_area_id, 'normal', null);?>
</div>
<?php $this->render_hidden_fields();
}
public function render_footer() {
$this->render_submit_area();
}
public function render_hidden_fields() {?>
<input type="hidden" value="<?php echo $this->_controller->extension->id;?>" id="leyka_extension_id">
<?php }
public function render_submit_area() {
$submit_data = $this->_controller->get_submit_data();?>
<div class="options-form-submits">
<div class="delete-extension-error error" style="display: none;"></div>
<span class="buttons">
<?php if($this->_controller->extension->get_options_data()) { // Show "Save" submit only if there are options ?>
<input type="submit" class="button button-primary button-small save-settings" name="leyka_settings_submit_<?php echo $this->_controller->id;?>" value="<?php _e('Save', 'leyka');?>">
<?php }?>
<input type="submit" class="button <?php echo $submit_data['activation_status'] === 'active' ? 'button-secondary' : 'button-primary';?> activation-button <?php echo $submit_data['activation_status'];?>" name="<?php echo $submit_data['activation_status'] === 'active' ? 'leyka_deactivate_'.$this->_controller->id : 'leyka_activate_'.$this->_controller->id;?>" value="<?php echo $submit_data['activation_button_label'];?>">
</span>
</div>
<?php }
public function render_navigation_area() {
}
public function render_container_block(Leyka_Container_Block $block) {?>
<div id="<?php echo $block->id;?>" class="settings-block container-block <?php echo $block->classes ? (is_array($block->classes) ? implode(' ', $block->classes) : esc_attr($block->classes)) : '';?>">
<?php $entry_width = $block->entry_width ? (100.0*($block->entry_width - 0.06 * $block->entry_width)).'%' : false;
foreach($block->get_content() as $sub_block) { // $sub_block_index => $sub_block ?>
<div class="container-entry" <?php echo $entry_width ? 'style="flex-basis: '.$entry_width.';"' : '';?>>
<?php if(is_a($sub_block, 'Leyka_Text_Block')) { /** @var $sub_block Leyka_Text_Block */
$this->render_text_block($sub_block);
} else if(is_a($sub_block, 'Leyka_Custom_Setting_Block')) { /** @var $sub_block Leyka_Custom_Setting_Block */
$this->render_custom_setting_block($sub_block);
} else if(is_a($sub_block, 'Leyka_Option_Block')) { /** @var $sub_block Leyka_Option_Block */
$this->render_option_block($sub_block);
}?>
</div>
<?php }?>
</div>
<?php }
public function render_subtitle_block(Leyka_Subtitle_Block $block) {?>
<div id="<?php echo $block->id;?>" class="settings-block subtitle-block">
<h2><?php echo $block->get_content();?></h2>
</div>
<?php }
public function render_text_block(Leyka_Text_Block $block) {
$content = $block->get_content();?>
<div id="<?php echo $block->id;?>" class="settings-block text-block">
<?php echo $block->has_custom_templated() || preg_match('/<p>/', $content) ? $content : '<p>'.$content.'</p>';?>
</div>
<?php }
public function render_option_block(Leyka_Option_Block $block) {
$option_info = leyka_options()->get_info_of($block->get_content());?>
<div id="<?php echo $block->id;?>" class="settings-block option-block type-<?php echo $option_info['type']?> <?php echo $block->show_title ? '' : 'option-title-hidden';?> <?php echo $block->show_description ? '' : 'option-description-hidden';?> <?php echo $this->_controller->has_component_errors($block->id) ? 'has-errors' : '';?>" style="<?php echo $block->width < 1.0 ? 'width:'.(100.0*$block->width).'%;' : '';?>">
<?php do_action("leyka_render_{$option_info['type']}", $block->get_content(), $option_info);?>
<div class="field-errors <?php echo $this->_controller->has_component_errors($block->id) ? 'has-errors' : '';?>">
<?php foreach($this->_controller->get_component_errors($block->id) as $error) { /** @var $error WP_Error */?>
<span><?php echo $error->get_error_message();?></span>
<?php }?>
</div>
</div>
<?php }
public function render_custom_setting_block(Leyka_Custom_Setting_Block $block) {?>
<div id="<?php echo $block->id;?>" class="settings-block custom-block <?php echo $block->is_standard_field_type ? 'option-block' : '';?> <?php echo $this->_controller->has_component_errors($block->id) ? 'has-errors' : '';?> <?php echo $block->field_type;?>">
<?php echo $block->get_content();?>
<div class="field-errors <?php echo $this->_controller->has_component_errors($block->id) ? 'has-errors' : '';?>">
<?php foreach($this->_controller->get_component_errors($block->id) as $error) { /** @var $error WP_Error */?>
<span><?php echo $error->get_error_message();?></span>
<?php }?>
</div>
</div>
<?php }
public function render_section_metabox($post, $args) {
$section = $args['args']; /** @var $section Leyka_Settings_Section */
foreach($section->get_blocks() as $block) { /** @var $block Leyka_Settings_Block */
if(is_a($block, 'Leyka_Container_Block')) { /** @var $block Leyka_Container_Block */
$this->render_container_block($block);
} else if(is_a($block, 'Leyka_Text_Block')) { /** @var $block Leyka_Text_Block */
$this->render_text_block($block);
} else if(is_a($block, 'Leyka_Subtitle_Block')) { /** @var $block Leyka_Subtitle_Block */
$this->render_subtitle_block($block);
} else if(is_a($block, 'Leyka_Custom_Setting_Block')) { /** @var $block Leyka_Custom_Setting_Block */
$this->render_custom_setting_block($block);
} else if(is_a($block, 'Leyka_Option_Block')) { /** @var $block Leyka_Option_Block */
$this->render_option_block($block);
}
}
}
protected function _add_sections_metaboxes() {
foreach($this->_controller->get_current_stage()->get_sections() as $section) {
if($section->blocks) {
add_meta_box(
'leyka_'.$section->id,
$section->title,
[$this, 'render_section_metabox'],
$this->_controller->id.'-options_main_area',
'normal',
'default',
$section // We may pass several args to the metabox callback - just use an array here
);
}
}
}
} | gpl-2.0 |
beardeer/assistments_workbench | data_converters/data_converter.py | 633 |
class DataConverter(object):
def __init__(self, input_file_path, output_file_path, col_mapping):
self.input_file_path = input_file_path
self.output_file_path = output_file_path
self.col_mapping = col_mapping
self.csv_reader = None
self.csv_writer = None
def convert(self):
input_file = open(self.input_file_path, 'rb')
self.csv_reader = csv.reader(input_file)
output_file = open(self.output_file_path, 'wb')
self.csv_writer = csv.writer(output_file)
self.process_data(self.csv_reader, self.csv_writer)
input_file.close()
output_file.close()
def process_data(self, csv_reader, csv_writer):
pass
| gpl-2.0 |
martin26/NewNPCBots | src/server/game/Movement/MotionMaster.cpp | 24917 | /*
* Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.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, see <http://www.gnu.org/licenses/>.
*/
#include "MotionMaster.h"
#include "CreatureAISelector.h"
#include "Creature.h"
#include "ConfusedMovementGenerator.h"
#include "FleeingMovementGenerator.h"
#include "HomeMovementGenerator.h"
#include "IdleMovementGenerator.h"
#include "PointMovementGenerator.h"
#include "TargetedMovementGenerator.h"
#include "WaypointMovementGenerator.h"
#include "RandomMovementGenerator.h"
#include "MoveSpline.h"
#include "MoveSplineInit.h"
inline bool isStatic(MovementGenerator *mv)
{
return (mv == &si_idleMovement);
}
void MotionMaster::Initialize()
{
// clear ALL movement generators (including default)
while (!empty())
{
MovementGenerator *curr = top();
pop();
if (curr)
DirectDelete(curr);
}
InitDefault();
}
// set new default movement generator
void MotionMaster::InitDefault()
{
if (_owner->GetTypeId() == TYPEID_UNIT)
{
MovementGenerator* movement = FactorySelector::selectMovementGenerator(_owner->ToCreature());
Mutate(movement == NULL ? &si_idleMovement : movement, MOTION_SLOT_IDLE);
}
else
{
Mutate(&si_idleMovement, MOTION_SLOT_IDLE);
}
}
MotionMaster::~MotionMaster()
{
// clear ALL movement generators (including default)
while (!empty())
{
MovementGenerator *curr = top();
pop();
if (curr && !isStatic(curr))
delete curr; // Skip finalizing on delete, it might launch new movement
}
}
void MotionMaster::UpdateMotion(uint32 diff)
{
if (!_owner)
return;
if (_owner->HasUnitState(UNIT_STATE_ROOT | UNIT_STATE_STUNNED)) // what about UNIT_STATE_DISTRACTED? Why is this not included?
return;
ASSERT(!empty());
_cleanFlag |= MMCF_UPDATE;
if (!top()->Update(_owner, diff))
{
_cleanFlag &= ~MMCF_UPDATE;
MovementExpired();
}
else
_cleanFlag &= ~MMCF_UPDATE;
if (_expList)
{
for (size_t i = 0; i < _expList->size(); ++i)
{
MovementGenerator* mg = (*_expList)[i];
DirectDelete(mg);
}
delete _expList;
_expList = NULL;
if (empty())
Initialize();
else if (needInitTop())
InitTop();
else if (_cleanFlag & MMCF_RESET)
top()->Reset(_owner);
_cleanFlag &= ~MMCF_RESET;
}
// probably not the best place to pu this but im not really sure where else to put it.
_owner->UpdateUnderwaterState(_owner->GetMap(), _owner->GetPositionX(), _owner->GetPositionY(), _owner->GetPositionZ());
}
void MotionMaster::DirectClean(bool reset)
{
while (size() > 1)
{
MovementGenerator *curr = top();
pop();
if (curr) DirectDelete(curr);
}
if (empty())
return;
if (needInitTop())
InitTop();
else if (reset)
top()->Reset(_owner);
}
void MotionMaster::DelayedClean()
{
while (size() > 1)
{
MovementGenerator *curr = top();
pop();
if (curr)
DelayedDelete(curr);
}
}
void MotionMaster::DirectExpire(bool reset)
{
if (size() > 1)
{
MovementGenerator *curr = top();
pop();
DirectDelete(curr);
}
while (!empty() && !top())
--_top;
if (empty())
Initialize();
else if (needInitTop())
InitTop();
else if (reset)
top()->Reset(_owner);
}
void MotionMaster::DelayedExpire()
{
if (size() > 1)
{
MovementGenerator *curr = top();
pop();
DelayedDelete(curr);
}
while (!empty() && !top())
--_top;
}
void MotionMaster::MoveIdle()
{
//! Should be preceded by MovementExpired or Clear if there's an overlying movementgenerator active
if (empty() || !isStatic(top()))
Mutate(&si_idleMovement, MOTION_SLOT_IDLE);
}
void MotionMaster::MoveRandom(float spawndist)
{
if (_owner->GetTypeId() == TYPEID_UNIT)
{
TC_LOG_DEBUG("misc", "Creature (GUID: %u) started random movement.", _owner->GetGUID().GetCounter());
Mutate(new RandomMovementGenerator<Creature>(spawndist), MOTION_SLOT_IDLE);
}
}
void MotionMaster::MoveTargetedHome()
{
Clear(false);
if (_owner->GetTypeId() == TYPEID_UNIT && !_owner->ToCreature()->GetCharmerOrOwnerGUID())
{
TC_LOG_DEBUG("misc", "Creature (Entry: %u GUID: %u) targeted home.", _owner->GetEntry(), _owner->GetGUID().GetCounter());
Mutate(new HomeMovementGenerator<Creature>(), MOTION_SLOT_ACTIVE);
}
else if (_owner->GetTypeId() == TYPEID_UNIT && _owner->ToCreature()->GetCharmerOrOwnerGUID())
{
TC_LOG_DEBUG("misc", "Pet or controlled creature (Entry: %u GUID: %u) is targeting home.", _owner->GetEntry(), _owner->GetGUID().GetCounter());
Unit* target = _owner->ToCreature()->GetCharmerOrOwner();
if (target)
{
TC_LOG_DEBUG("misc", "Following %s (GUID: %u).", target->GetTypeId() == TYPEID_PLAYER ? "player" : "creature", target->GetTypeId() == TYPEID_PLAYER ? target->GetGUID().GetCounter() : ((Creature*)target)->GetSpawnId());
Mutate(new FollowMovementGenerator<Creature>(target, PET_FOLLOW_DIST, PET_FOLLOW_ANGLE), MOTION_SLOT_ACTIVE);
}
}
else
{
TC_LOG_ERROR("misc", "Player (GUID: %u) attempted to move towards target home.", _owner->GetGUID().GetCounter());
}
}
void MotionMaster::MoveConfused()
{
if (_owner->GetTypeId() == TYPEID_PLAYER)
{
TC_LOG_DEBUG("misc", "Player (GUID: %u) move confused", _owner->GetGUID().GetCounter());
Mutate(new ConfusedMovementGenerator<Player>(), MOTION_SLOT_CONTROLLED);
}
else
{
TC_LOG_DEBUG("misc", "Creature (Entry: %u GUID: %u) move confused",
_owner->GetEntry(), _owner->GetGUID().GetCounter());
Mutate(new ConfusedMovementGenerator<Creature>(), MOTION_SLOT_CONTROLLED);
}
}
void MotionMaster::MoveChase(Unit* target, float dist, float angle)
{
// ignore movement request if target not exist
if (!target || target == _owner)
return;
//_owner->ClearUnitState(UNIT_STATE_FOLLOW);
if (_owner->GetTypeId() == TYPEID_PLAYER)
{
TC_LOG_DEBUG("misc", "Player (GUID: %u) chase to %s (GUID: %u)",
_owner->GetGUID().GetCounter(),
target->GetTypeId() == TYPEID_PLAYER ? "player" : "creature",
target->GetTypeId() == TYPEID_PLAYER ? target->GetGUID().GetCounter() : target->ToCreature()->GetSpawnId());
Mutate(new ChaseMovementGenerator<Player>(target, dist, angle), MOTION_SLOT_ACTIVE);
}
else
{
TC_LOG_DEBUG("misc", "Creature (Entry: %u GUID: %u) chase to %s (GUID: %u)",
_owner->GetEntry(), _owner->GetGUID().GetCounter(),
target->GetTypeId() == TYPEID_PLAYER ? "player" : "creature",
target->GetTypeId() == TYPEID_PLAYER ? target->GetGUID().GetCounter() : target->ToCreature()->GetSpawnId());
Mutate(new ChaseMovementGenerator<Creature>(target, dist, angle), MOTION_SLOT_ACTIVE);
}
}
void MotionMaster::MoveFollow(Unit* target, float dist, float angle, MovementSlot slot)
{
// ignore movement request if target not exist
if (!target || target == _owner)
return;
//_owner->AddUnitState(UNIT_STATE_FOLLOW);
if (_owner->GetTypeId() == TYPEID_PLAYER)
{
TC_LOG_DEBUG("misc", "Player (GUID: %u) follows %s (GUID: %u).", _owner->GetGUID().GetCounter(),
target->GetTypeId() == TYPEID_PLAYER ? "player" : "creature",
target->GetTypeId() == TYPEID_PLAYER ? target->GetGUID().GetCounter() : target->ToCreature()->GetSpawnId());
Mutate(new FollowMovementGenerator<Player>(target, dist, angle), slot);
}
else
{
TC_LOG_DEBUG("misc", "Creature (Entry: %u GUID: %u) follows %s (GUID: %u).",
_owner->GetEntry(), _owner->GetGUID().GetCounter(),
target->GetTypeId() == TYPEID_PLAYER ? "player" : "creature",
target->GetTypeId() == TYPEID_PLAYER ? target->GetGUID().GetCounter() : target->ToCreature()->GetSpawnId());
Mutate(new FollowMovementGenerator<Creature>(target, dist, angle), slot);
}
}
void MotionMaster::MovePoint(uint32 id, float x, float y, float z, bool generatePath)
{
if (_owner->GetTypeId() == TYPEID_PLAYER)
{
TC_LOG_DEBUG("misc", "Player (GUID: %u) targeted point (Id: %u X: %f Y: %f Z: %f).", _owner->GetGUID().GetCounter(), id, x, y, z);
Mutate(new PointMovementGenerator<Player>(id, x, y, z, generatePath), MOTION_SLOT_ACTIVE);
}
else
{
TC_LOG_DEBUG("misc", "Creature (Entry: %u GUID: %u) targeted point (ID: %u X: %f Y: %f Z: %f).",
_owner->GetEntry(), _owner->GetGUID().GetCounter(), id, x, y, z);
Mutate(new PointMovementGenerator<Creature>(id, x, y, z, generatePath), MOTION_SLOT_ACTIVE);
}
}
void MotionMaster::MoveCloserAndStop(uint32 id, Unit* target, float distance)
{
float distanceToTravel = _owner->GetExactDist2d(target) - distance;
if (distanceToTravel > 0.0f)
{
float angle = _owner->GetAngle(target);
float destx = _owner->GetPositionX() + distanceToTravel * std::cos(angle);
float desty = _owner->GetPositionY() + distanceToTravel * std::sin(angle);
MovePoint(id, destx, desty, target->GetPositionZ());
}
else
{
// we are already close enough. We just need to turn toward the target without changing position.
Movement::MoveSplineInit init(_owner);
init.MoveTo(_owner->GetPositionX(), _owner->GetPositionY(), _owner->GetPositionZMinusOffset());
init.SetFacing(target);
init.Launch();
Mutate(new EffectMovementGenerator(id), MOTION_SLOT_ACTIVE);
}
}
void MotionMaster::MoveLand(uint32 id, Position const& pos)
{
float x, y, z;
pos.GetPosition(x, y, z);
TC_LOG_DEBUG("misc", "Creature (Entry: %u) landing point (ID: %u X: %f Y: %f Z: %f).", _owner->GetEntry(), id, x, y, z);
Movement::MoveSplineInit init(_owner);
init.MoveTo(x, y, z);
init.SetAnimation(Movement::ToGround);
init.Launch();
Mutate(new EffectMovementGenerator(id), MOTION_SLOT_ACTIVE);
}
void MotionMaster::MoveTakeoff(uint32 id, Position const& pos)
{
float x, y, z;
pos.GetPosition(x, y, z);
TC_LOG_DEBUG("misc", "Creature (Entry: %u) landing point (ID: %u X: %f Y: %f Z: %f).", _owner->GetEntry(), id, x, y, z);
Movement::MoveSplineInit init(_owner);
init.MoveTo(x, y, z);
init.SetAnimation(Movement::ToFly);
init.Launch();
Mutate(new EffectMovementGenerator(id), MOTION_SLOT_ACTIVE);
}
void MotionMaster::MoveKnockbackFrom(float srcX, float srcY, float speedXY, float speedZ)
{
//this function may make players fall below map
if (_owner->GetTypeId() == TYPEID_PLAYER)
return;
if (speedXY <= 0.1f)
return;
float x, y, z;
float moveTimeHalf = speedZ / Movement::gravity;
float dist = 2 * moveTimeHalf * speedXY;
float max_height = -Movement::computeFallElevation(moveTimeHalf, false, -speedZ);
_owner->GetNearPoint(_owner, x, y, z, _owner->GetObjectSize(), dist, _owner->GetAngle(srcX, srcY) + float(M_PI));
Movement::MoveSplineInit init(_owner);
init.MoveTo(x, y, z);
init.SetParabolic(max_height, 0);
init.SetOrientationFixed(true);
init.SetVelocity(speedXY);
init.Launch();
Mutate(new EffectMovementGenerator(0), MOTION_SLOT_CONTROLLED);
}
void MotionMaster::MoveJumpTo(float angle, float speedXY, float speedZ)
{
//this function may make players fall below map
if (_owner->GetTypeId() == TYPEID_PLAYER)
return;
float x, y, z;
//npcbot
if (_owner->GetTypeId() == TYPEID_UNIT && _owner->ToCreature()->IsNPCBot())
{
Movement::MoveSplineInit init(_owner);
init.MoveTo(x, y, z);
init.SetParabolic(speedZ/*max_height*/, 0);
init.SetOrientationFixed(true);
init.SetVelocity(speedXY);
init.Launch();
Mutate(new EffectMovementGenerator(0), MOTION_SLOT_CONTROLLED);
return;
}
//end npcbot
float moveTimeHalf = speedZ / Movement::gravity;
float dist = 2 * moveTimeHalf * speedXY;
_owner->GetClosePoint(x, y, z, _owner->GetObjectSize(), dist, angle);
MoveJump(x, y, z, 0.0f, speedXY, speedZ);
}
void MotionMaster::MoveJump(float x, float y, float z, float o, float speedXY, float speedZ, uint32 id, bool hasOrientation /* = false*/)
{
TC_LOG_DEBUG("misc", "Unit (GUID: %u) jumps to point (X: %f Y: %f Z: %f).", _owner->GetGUID().GetCounter(), x, y, z);
if (speedXY <= 0.1f)
return;
float moveTimeHalf = speedZ / Movement::gravity;
float max_height = -Movement::computeFallElevation(moveTimeHalf, false, -speedZ);
Movement::MoveSplineInit init(_owner);
init.MoveTo(x, y, z, false);
init.SetParabolic(max_height, 0);
init.SetVelocity(speedXY);
if (hasOrientation)
init.SetFacing(o);
init.Launch();
Mutate(new EffectMovementGenerator(id), MOTION_SLOT_CONTROLLED);
}
void MotionMaster::MoveCirclePath(float x, float y, float z, float radius, bool clockwise, uint8 stepCount)
{
float step = 2 * float(M_PI) / stepCount * (clockwise ? -1.0f : 1.0f);
Position const& pos = { x, y, z, 0.0f };
float angle = pos.GetAngle(_owner->GetPositionX(), _owner->GetPositionY());
Movement::MoveSplineInit init(_owner);
for (uint8 i = 0; i < stepCount; angle += step, ++i)
{
G3D::Vector3 point;
point.x = x + radius * cosf(angle);
point.y = y + radius * sinf(angle);
if (_owner->IsFlying())
point.z = z;
else
point.z = _owner->GetMap()->GetHeight(_owner->GetPhaseMask(), point.x, point.y, z);
init.Path().push_back(point);
}
if (_owner->IsFlying())
{
init.SetFly();
init.SetCyclic();
init.SetAnimation(Movement::ToFly);
}
else
{
init.SetWalk(true);
init.SetCyclic();
}
init.Launch();
}
void MotionMaster::MoveSmoothPath(uint32 pointId, G3D::Vector3 const* pathPoints, size_t pathSize, bool walk)
{
Movement::PointsArray path(pathPoints, pathPoints + pathSize);
Movement::MoveSplineInit init(_owner);
init.MovebyPath(path);
init.SetSmooth();
init.SetWalk(walk);
init.Launch();
// This code is not correct
// EffectMovementGenerator does not affect UNIT_STATE_ROAMING | UNIT_STATE_ROAMING_MOVE
// need to call PointMovementGenerator with various pointIds
Mutate(new EffectMovementGenerator(pointId), MOTION_SLOT_ACTIVE);
//Position pos(pathPoints[pathSize - 1].x, pathPoints[pathSize - 1].y, pathPoints[pathSize - 1].z);
//MovePoint(EVENT_CHARGE_PREPATH, pos, false);
}
void MotionMaster::MoveFall(uint32 id /*=0*/)
{
// use larger distance for vmap height search than in most other cases
float tz = _owner->GetMap()->GetHeight(_owner->GetPhaseMask(), _owner->GetPositionX(), _owner->GetPositionY(), _owner->GetPositionZ(), true, MAX_FALL_DISTANCE);
if (tz <= INVALID_HEIGHT)
{
TC_LOG_DEBUG("misc", "MotionMaster::MoveFall: unable to retrieve a proper height at map %u (x: %f, y: %f, z: %f).",
_owner->GetMap()->GetId(), _owner->GetPositionX(), _owner->GetPositionY(), _owner->GetPositionZ());
return;
}
// Abort too if the ground is very near
if (std::fabs(_owner->GetPositionZ() - tz) < 0.1f)
return;
_owner->AddUnitMovementFlag(MOVEMENTFLAG_FALLING);
_owner->m_movementInfo.SetFallTime(0);
// don't run spline movement for players
if (_owner->GetTypeId() == TYPEID_PLAYER)
return;
Movement::MoveSplineInit init(_owner);
init.MoveTo(_owner->GetPositionX(), _owner->GetPositionY(), tz, false);
init.SetFall();
init.Launch();
Mutate(new EffectMovementGenerator(id), MOTION_SLOT_CONTROLLED);
}
void MotionMaster::MoveCharge(float x, float y, float z, float speed /*= SPEED_CHARGE*/, uint32 id /*= EVENT_CHARGE*/, bool generatePath /*= false*/)
{
if (Impl[MOTION_SLOT_CONTROLLED] && Impl[MOTION_SLOT_CONTROLLED]->GetMovementGeneratorType() != DISTRACT_MOTION_TYPE)
return;
if (_owner->GetTypeId() == TYPEID_PLAYER)
{
TC_LOG_DEBUG("misc", "Player (GUID: %u) charged point (X: %f Y: %f Z: %f).", _owner->GetGUID().GetCounter(), x, y, z);
Mutate(new PointMovementGenerator<Player>(id, x, y, z, generatePath, speed), MOTION_SLOT_CONTROLLED);
}
else
{
TC_LOG_DEBUG("misc", "Creature (Entry: %u GUID: %u) charged point (X: %f Y: %f Z: %f).",
_owner->GetEntry(), _owner->GetGUID().GetCounter(), x, y, z);
Mutate(new PointMovementGenerator<Creature>(id, x, y, z, generatePath, speed), MOTION_SLOT_CONTROLLED);
}
}
void MotionMaster::MoveCharge(PathGenerator const& path, float speed /*= SPEED_CHARGE*/)
{
G3D::Vector3 dest = path.GetActualEndPosition();
MoveCharge(dest.x, dest.y, dest.z, speed, EVENT_CHARGE_PREPATH);
// Charge movement is not started when using EVENT_CHARGE_PREPATH
Movement::MoveSplineInit init(_owner);
init.MovebyPath(path.GetPath());
init.SetVelocity(speed);
init.Launch();
}
void MotionMaster::MoveSeekAssistance(float x, float y, float z)
{
if (_owner->GetTypeId() == TYPEID_PLAYER)
{
TC_LOG_ERROR("misc", "Player (GUID: %u) attempted to seek assistance.", _owner->GetGUID().GetCounter());
}
else
{
TC_LOG_DEBUG("misc", "Creature (Entry: %u GUID: %u) seek assistance (X: %f Y: %f Z: %f)",
_owner->GetEntry(), _owner->GetGUID().GetCounter(), x, y, z);
_owner->AttackStop();
_owner->CastStop();
_owner->ToCreature()->SetReactState(REACT_PASSIVE);
Mutate(new AssistanceMovementGenerator(x, y, z), MOTION_SLOT_ACTIVE);
}
}
void MotionMaster::MoveSeekAssistanceDistract(uint32 time)
{
if (_owner->GetTypeId() == TYPEID_PLAYER)
{
TC_LOG_ERROR("misc", "Player (GUID: %u) attempted to call distract assistance.", _owner->GetGUID().GetCounter());
}
else
{
TC_LOG_DEBUG("misc", "Creature (Entry: %u GUID: %u) is distracted after assistance call (Time: %u).",
_owner->GetEntry(), _owner->GetGUID().GetCounter(), time);
Mutate(new AssistanceDistractMovementGenerator(time), MOTION_SLOT_ACTIVE);
}
}
void MotionMaster::MoveFleeing(Unit* enemy, uint32 time)
{
if (!enemy)
return;
if (_owner->GetTypeId() == TYPEID_PLAYER)
{
TC_LOG_DEBUG("misc", "Player (GUID: %u) flees from %s (GUID: %u).", _owner->GetGUID().GetCounter(),
enemy->GetTypeId() == TYPEID_PLAYER ? "player" : "creature",
enemy->GetTypeId() == TYPEID_PLAYER ? enemy->GetGUID().GetCounter() : enemy->ToCreature()->GetSpawnId());
Mutate(new FleeingMovementGenerator<Player>(enemy->GetGUID()), MOTION_SLOT_CONTROLLED);
}
else
{
TC_LOG_DEBUG("misc", "Creature (Entry: %u GUID: %u) flees from %s (GUID: %u)%s.",
_owner->GetEntry(), _owner->GetGUID().GetCounter(),
enemy->GetTypeId() == TYPEID_PLAYER ? "player" : "creature",
enemy->GetTypeId() == TYPEID_PLAYER ? enemy->GetGUID().GetCounter() : enemy->ToCreature()->GetSpawnId(),
time ? " for a limited time" : "");
if (time)
Mutate(new TimedFleeingMovementGenerator(enemy->GetGUID(), time), MOTION_SLOT_CONTROLLED);
else
Mutate(new FleeingMovementGenerator<Creature>(enemy->GetGUID()), MOTION_SLOT_CONTROLLED);
}
}
void MotionMaster::MoveTaxiFlight(uint32 path, uint32 pathnode)
{
if (_owner->GetTypeId() == TYPEID_PLAYER)
{
if (path < sTaxiPathNodesByPath.size())
{
TC_LOG_DEBUG("misc", "%s taxi to (Path %u node %u).", _owner->GetName().c_str(), path, pathnode);
FlightPathMovementGenerator* mgen = new FlightPathMovementGenerator(pathnode);
mgen->LoadPath(_owner->ToPlayer());
Mutate(mgen, MOTION_SLOT_CONTROLLED);
}
else
{
TC_LOG_ERROR("misc", "%s attempted taxi to (non-existing Path %u node %u).",
_owner->GetName().c_str(), path, pathnode);
}
}
else
{
TC_LOG_ERROR("misc", "Creature (Entry: %u GUID: %u) attempted taxi to (Path %u node %u).",
_owner->GetEntry(), _owner->GetGUID().GetCounter(), path, pathnode);
}
}
void MotionMaster::MoveDistract(uint32 timer)
{
if (Impl[MOTION_SLOT_CONTROLLED])
return;
if (_owner->GetTypeId() == TYPEID_PLAYER)
{
TC_LOG_DEBUG("misc", "Player (GUID: %u) distracted (timer: %u).", _owner->GetGUID().GetCounter(), timer);
}
else
{
TC_LOG_DEBUG("misc", "Creature (Entry: %u GUID: %u) distracted (timer: %u)",
_owner->GetEntry(), _owner->GetGUID().GetCounter(), timer);
}
DistractMovementGenerator* mgen = new DistractMovementGenerator(timer);
Mutate(mgen, MOTION_SLOT_CONTROLLED);
}
void MotionMaster::Mutate(MovementGenerator *m, MovementSlot slot)
{
if (MovementGenerator *curr = Impl[slot])
{
Impl[slot] = NULL; // in case a new one is generated in this slot during directdelete
if (_top == slot && (_cleanFlag & MMCF_UPDATE))
DelayedDelete(curr);
else
DirectDelete(curr);
}
else if (_top < slot)
{
_top = slot;
}
Impl[slot] = m;
if (_top > slot)
_needInit[slot] = true;
else
{
_needInit[slot] = false;
m->Initialize(_owner);
}
}
void MotionMaster::MovePath(uint32 path_id, bool repeatable)
{
if (!path_id)
return;
//We set waypoint movement as new default movement generator
// clear ALL movement generators (including default)
/*while (!empty())
{
MovementGenerator *curr = top();
curr->Finalize(*_owner);
pop();
if (!isStatic(curr))
delete curr;
}*/
//_owner->GetTypeId() == TYPEID_PLAYER ?
//Mutate(new WaypointMovementGenerator<Player>(path_id, repeatable)):
Mutate(new WaypointMovementGenerator<Creature>(path_id, repeatable), MOTION_SLOT_IDLE);
TC_LOG_DEBUG("misc", "%s (GUID: %u) starts moving over path(Id:%u, repeatable: %s).",
_owner->GetTypeId() == TYPEID_PLAYER ? "Player" : "Creature",
_owner->GetGUID().GetCounter(), path_id, repeatable ? "YES" : "NO");
}
void MotionMaster::MoveRotate(uint32 time, RotateDirection direction)
{
if (!time)
return;
Mutate(new RotateMovementGenerator(time, direction), MOTION_SLOT_ACTIVE);
}
void MotionMaster::propagateSpeedChange()
{
/*Impl::container_type::iterator it = Impl::c.begin();
for (; it != end(); ++it)
{
(*it)->unitSpeedChanged();
}*/
for (int i = 0; i <= _top; ++i)
{
if (Impl[i])
Impl[i]->unitSpeedChanged();
}
}
MovementGeneratorType MotionMaster::GetCurrentMovementGeneratorType() const
{
if (empty())
return IDLE_MOTION_TYPE;
return top()->GetMovementGeneratorType();
}
MovementGeneratorType MotionMaster::GetMotionSlotType(int slot) const
{
if (!Impl[slot])
return NULL_MOTION_TYPE;
else
return Impl[slot]->GetMovementGeneratorType();
}
void MotionMaster::InitTop()
{
top()->Initialize(_owner);
_needInit[_top] = false;
}
void MotionMaster::DirectDelete(_Ty curr)
{
if (isStatic(curr))
return;
curr->Finalize(_owner);
delete curr;
}
void MotionMaster::DelayedDelete(_Ty curr)
{
TC_LOG_FATAL("misc", "Unit (Entry %u) is trying to delete its updating Movement Generator (Type %u)!", _owner->GetEntry(), curr->GetMovementGeneratorType());
if (isStatic(curr))
return;
if (!_expList)
_expList = new ExpireList();
_expList->push_back(curr);
}
bool MotionMaster::GetDestination(float &x, float &y, float &z)
{
if (_owner->movespline->Finalized())
return false;
G3D::Vector3 const& dest = _owner->movespline->FinalDestination();
x = dest.x;
y = dest.y;
z = dest.z;
return true;
}
| gpl-2.0 |
kivensolo/UiUsingListView | app/src/main/java/com/kingz/utils/ExecutorServiceHelper.java | 1555 | package com.kingz.utils;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* description:单例线程池,用于处理一些异步任务
*/
public class ExecutorServiceHelper {
private static ExecutorServiceHelper sExecutorServiceHelper;
private ExecutorService mSingleThreadExecutor;
public static ExecutorServiceHelper getInstance() {
if (sExecutorServiceHelper == null) {
synchronized (ExecutorServiceHelper.class) {
if (sExecutorServiceHelper == null){
sExecutorServiceHelper = new ExecutorServiceHelper();
}
}
}
return sExecutorServiceHelper;
}
public synchronized void execute(Runnable runnable) {
if (mSingleThreadExecutor == null) {
mSingleThreadExecutor = Executors.newCachedThreadPool();
}
mSingleThreadExecutor.execute(runnable);
}
public synchronized void execute(Callable callable) {
if (mSingleThreadExecutor == null) {
mSingleThreadExecutor = Executors.newCachedThreadPool();
}
Future mSubmit = mSingleThreadExecutor.submit(callable);
showResult(mSubmit);
}
private void showResult(Future<?> mSubmit) {
// try {
// ZLog.d("ExecutorServiceHelper", mSubmit.get());
// } catch (InterruptedException | ExecutionException e) {
// e.printStackTrace();
// }
}
}
| gpl-2.0 |
PhamPhi/birdy_task | src/com/frm/bdTask/VersionManager.java | 2184 | package com.frm.bdTask;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import com.frm.bdTask.controls.Properties;
/**
* @author: Larry Pham.
* @since: 3/24/2014.
* @version: 2014.03.24.
*/
public class VersionManager {
public static final String TAG = Properties.PREFIX + "VersionManager";
public static final String APP_ID = "com.frm.bdTask";
/**
* Determining the current App's version name. Reusing for checking the installation of this app or not.
* @param context The Application Context.
* @return String type.
*/
public static String getBirdyTaskVersion(Context context){
Log.d(TAG, "getBirdyTaskVersion");
String versionName = null;
try{
PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
versionName = info.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionName;
}
/**
* Determinging the Current App's Version Code. Reusing for checking the ability to update or upgrade this app.
* @param context The Application Context.
* @return String type.
*/
public static int getVersionCode(Context context){
Log.d(TAG, "getBirdyTaskVersionCode");
int versionCode = 0;
try{
PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
versionCode = info.versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionCode;
}
public static boolean isExistedBirdyApp(Context context){
Log.d(TAG, "isExistBirdyApp");
PackageManager pm = context.getPackageManager();
try{
if(pm != null) {
pm.getPackageInfo("com.frm.bdyTask", PackageManager.GET_ACTIVITIES);
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return false;
}
return true;
}
}
| gpl-2.0 |
bubble-07/MinecraftCircuitsMod | circuitsMod/src/main/java/com/circuits/circuitsmod/unbreakium/UnbreakiumBlock.java | 2211 | package com.circuits.circuitsmod.unbreakium;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class UnbreakiumBlock extends Block
{
public UnbreakiumBlock()
{
super(Material.ROCK);
this.setHardness(9999f);
this.setCreativeTab(CreativeTabs.BUILDING_BLOCKS);
this.setDefaultState(this.blockState.getBaseState().withProperty(FRAMEMIMIC, false));
}
public static final IProperty<Boolean> FRAMEMIMIC = PropertyBool.create("framemimic");
@SideOnly(Side.CLIENT)
public BlockRenderLayer getBlockLayer()
{
return BlockRenderLayer.TRANSLUCENT;
}
@Override
public boolean isOpaqueCube(IBlockState iBlockState) {
return false;
}
@Override
public boolean isFullCube(IBlockState iBlockState) {
return true;
}
@Override
protected BlockStateContainer createBlockState() {
return new BlockStateContainer(this, new IProperty[]{FRAMEMIMIC});
}
/**
* Convert the given metadata into a BlockState for this Block
*/
public IBlockState getStateFromMeta(int meta)
{
return this.getDefaultState().withProperty(FRAMEMIMIC, meta > 0);
}
/**
* Convert the BlockState into the correct metadata value
*/
public int getMetaFromState(IBlockState state)
{
return state.getValue(FRAMEMIMIC) ? 1 : 0;
}
@Override
public int damageDropped(IBlockState state) {
return getMetaFromState(state);
}
@Override
public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn) {
worldIn.scheduleUpdate(pos, this, 1);
}
@Override
public EnumBlockRenderType getRenderType(IBlockState iBlockState) {
return EnumBlockRenderType.MODEL;
}
}
| gpl-2.0 |
zakiya/Peoples-History | sites/all/modules/civicrm/CRM/Contact/Form/Task/Map.php | 7037 | <?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 1.8 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2007 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the Affero General Public License Version 1, |
| March 2002. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the Affero General Public |
| License along with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2007
* $Id$
*
*/
require_once 'CRM/Contact/Form/Task.php';
/**
* This class provides the functionality to map
* the address for group of
* contacts.
*/
class CRM_Contact_Form_Task_Map extends CRM_Contact_Form_Task {
/**
* Are we operating in "single mode", i.e. mapping address to one
* specific contact?
*
* @var boolean
*/
protected $_single = false;
/**
* build all the data structures needed to build the form
*
* @return void
* @access public
*/
function preProcess( ) {
$cid = CRM_Utils_Request::retrieve( 'cid', 'Positive',
$this, false );
$lid = CRM_Utils_Request::retrieve( 'lid', 'Positive',
$this, false );
$eid = CRM_Utils_Request::retrieve( 'eid', 'Positive',
$this, false );
$profileGID = CRM_Utils_Request::retrieve( 'profileGID', 'Boolean',
$this, false );
$this->assign( 'profileGID', $profileGID );
$type = 'Contact';
if ( $cid ) {
$ids = array( $cid );
$this->_single = true;
} else if ( $eid ) {
$ids = $eid;
$type = 'Event';
} else {
parent::preProcess( );
$ids = $this->_contactIds;
}
self::createMapXML( $ids, $lid, $this, true ,$type);
$this->assign( 'single', $this->_single );
}
/**
* Build the form
*
* @access public
* @return void
*/
public function buildQuickForm()
{
$this->addButtons( array(
array ( 'type' => 'done',
'name' => ts('Done'),
'isDefault' => true ),
)
);
}
/**
* process the form after the input has been submitted and validated
*
* @access public
* @return None
*/
public function postProcess() {
}//end of function
/**
* assign smarty variables to the template that will be used by google api to plot the contacts
*
* @param array $contactIds list of contact ids that we need to plot
* @param int $locationId location_id
*
* @return string the location of the file we have created
* @access protected
*/
static function createMapXML( $ids, $locationId, &$page, $addBreadCrumb, $type = 'Contact' ) {
$config =& CRM_Core_Config::singleton( );
CRM_Utils_System::setTitle( ts('Map Location(s)'));
$page->assign( 'query', 'CiviCRM Search Query' );
$page->assign( 'mapProvider', $config->mapProvider );
$page->assign( 'mapKey', $config->mapAPIKey );
if( $type == 'Contact' ) {
require_once 'CRM/Contact/BAO/Contact.php';
$locations =& CRM_Contact_BAO_Contact::getMapInfo( $ids , $locationId );
} else {
require_once 'CRM/Event/BAO/Event.php';
$locations =& CRM_Event_BAO_Event::getMapInfo( $ids );
}
if ( empty( $locations ) ) {
CRM_Core_Error::statusBounce(ts('This contact\'s primary address does not contain latitude/longitude information and can not be mapped.'));
}
if ( $addBreadCrumb ) {
$session =& CRM_Core_Session::singleton();
$redirect = $session->readUserContext();
if ( $type == 'Contact') {
$bcTitle = ts('Contact');
} else {
$bcTitle = ts('Event Info');
$session->pushUserContext( CRM_Utils_System::url('civicrm/event/info', 'reset=1&action=preview&id='. $ids ) );
}
CRM_Utils_System::appendBreadCrumb( $bcTitle, $redirect );
}
$page->assign_by_ref( 'locations', $locations );
// only issue a javascript warning if we know we will not
// mess the poor user with too many warnings
if ( count( $locations ) <= 3 ) {
$page->assign( 'geoCodeWarn', true );
} else {
$page->assign( 'geoCodeWarn', false );
}
$sumLat = $sumLng = 0;
$maxLat = $maxLng = -400;
$minLat = $minLng = +400;
foreach ( $locations as $location ) {
$sumLat += $location['lat'];
$sumLng += $location['lng'];
if ( $location['lat'] > $maxLat ) {
$maxLat = $location['lat'];
}
if ( $location['lat'] < $minLat ) {
$minLat = $location['lat'];
}
if ( $location['lng'] > $maxLng ) {
$maxLng = $location['lng'];
}
if ( $location['lng'] < $minLng ) {
$minLng = $location['lng'];
}
}
$center = array( 'lat' => (float ) $sumLat / count( $locations ),
'lng' => (float ) $sumLng / count( $locations ) );
$span = array( 'lat' => (float ) ( $maxLat - $minLat ),
'lng' => (float ) ( $maxLng - $minLng ) );
$page->assign_by_ref( 'center', $center );
$page->assign_by_ref( 'span' , $span );
}
}
?>
| gpl-2.0 |
lebauce/artub | builder/Installer/hooks/hook-xml.dom.py | 2243 | import string
attrs = [('Node', 0),
('INDEX_SIZE_ERR', 1),
('DOMSTRING_SIZE_ERR', 2),
('HIERARCHY_REQUEST_ERR', 3),
('WRONG_DOCUMENT_ERR', 4),
('INVALID_CHARACTER_ERR ', 5),
('NO_DATA_ALLOWED_ERR', 6),
('NO_MODIFICATION_ALLOWED_ERR', 7),
('NOT_FOUND_ERR', 8),
('NOT_SUPPORTED_ERR', 9),
('INUSE_ATTRIBUTE_ERR', 10),
('INVALID_STATE_ERR', 11),
('SYNTAX_ERR', 12),
('INVALID_MODIFICATION_ERR', 13),
('NAMESPACE_ERR', 14),
('INVALID_ACCESS_ERR', 15),
('DOMException', 0),
('IndexSizeErr', 0),
('DomstringSizeErr', 0),
('HierarchyRequestErr', 0),
('WrongDocumentErr', 0),
('InvalidCharacterErr', 0),
('NoDataAllowedErr', 0),
('NoModificationAllowedErr', 0),
('NotFoundErr', 0),
('NotSupportedErr', 0),
('InuseAttributeErr', 0),
('InvalidStateErr', 0),
('SyntaxErr', 0),
('InvalidModificationErr', 0),
('NamespaceErr', 0),
('InvalidAccessErr', 0),
('getDOMImplementation', 0),
('registerDOMImplementation', 0),
]
def hook(mod):
if string.find(mod.__file__, '_xmlplus') > -1:
mod.UNSPECIFIED_EVENT_TYPE_ERR = 0
mod.FT_EXCEPTION_BASE = 1000
mod.XML_PARSE_ERR = 1001
mod.BAD_BOUNDARYPOINTS_ERR = 1
mod.INVALID_NODE_TYPE_ERR = 2
mod.EventException = None
mod.RangeException = None
mod.FtException = None
if hasattr(mod, 'DomstringSizeErr'):
del mod.DomstringSizeErr
mod.DOMStringSizeErr = None
mod.UnspecifiedEventTypeErr = None
mod.XmlParseErr = None
mod.BadBoundaryPointsErr = None
mod.InvalidNodeTypeErr = None
mod.DOMImplementation = None
mod.implementation = None
mod.XML_NAMESPACE = None
mod.XMLNS_NAMESPACE = None
mod.XHTML_NAMESPACE = None
mod.DOMExceptionStrings = None
mod.EventExceptionStrings = None
mod.FtExceptionStrings = None
mod.RangeExceptionStrings = None
return mod
| gpl-2.0 |
Forage/Gramps | gramps/gen/filters/rules/person/_hasalternatename.py | 1841 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2010 Gramps
#
# 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
#
# gen.filters.rules/Person/_HasAlternateName.py
# $Id$
#
#-------------------------------------------------------------------------
#
# Standard Python modules
#
#-------------------------------------------------------------------------
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.get_translation().gettext
#-------------------------------------------------------------------------
#
# GRAMPS modules
#
#-------------------------------------------------------------------------
from .. import Rule
#-------------------------------------------------------------------------
#
# HasAlternateName
#
#-------------------------------------------------------------------------
class HasAlternateName(Rule):
"""Rule that checks an alternate name"""
name = _('People with an alternate name')
description = _("Matches people with an alternate name")
category = _('General filters')
def apply(self, db, person):
if person.get_alternate_names():
return True
else:
return False
| gpl-2.0 |
Sturnus-cineraceus/funen | view/funen_routes.py | 1965 | import bottle
from bottle import static_file,route,request,redirect, TEMPLATE_PATH, jinja2_template as template
from db.dbmod import passwordCheck,getUserData
import setting
@route('/login')
def lgin():
tmplobj = {}
tmplobj['title'] = setting.PAGE_MAIN_NAME + " :ログイン"
return template('tmpl/login.html',tmplobj = tmplobj)
@route('/logining',method="POST")
def logining():
lid = request.forms.get('login_id')
pw = request.forms.get('login_pw')
res = passwordCheck(lid,pw)
ac_obj = getUserData(lid)
if res:
session = bottle.request.environ.get('beaker.session')
session['login'] = True
session['userid'] = ac_obj.ac_id
session.save()
redirect("/" )
else:
redirect("/login")
@route('/logout',method="GET")
def logout():
session = bottle.request.environ.get('beaker.session')
session.delete()
redirect("/" )
@route('/')
def indx():
session = bottle.request.environ.get('beaker.session')
tmplobj = makeTmplObj(session)
print(session)
tmplobj['title'] = setting.PAGE_MAIN_NAME
if 'login' in session and session['login'] == True:
tmplobj['login'] = True
else:
tmplobj['login'] = False
return template('tmpl/index.html',tmplobj = tmplobj)
#static関連
@route('/js/<filename>')
def js_file(filename):
return static_file(filename,root=setting.ROOT_DIR+"/static/js")
@route('/js/page/<filename>')
def js_page_file(filename):
return static_file(filename,root=setting.ROOT_DIR+"/static/js/page")
@route('/css/<filename>')
def css_file(filename):
return static_file(filename,root=setting.ROOT_DIR+"/static/css")
# 便利機能 どこかに移動しようか
def makeTmplObj(session):
tmplobj = {}
tmplobj['userid'] = getSessionValue('userid',session)
print(tmplobj)
return tmplobj
def getSessionValue(key,session):
if key in session:
return session[key]
return None
| gpl-2.0 |
esseremmerik/Dashboard | wp-content/plugins/tina-mvc/sample_apps/sample_html_table_helper_page.php | 2964 | <?php
/**
* A sample page controller
*
* @package Tina-MVC
* @subpackage Tina-Sample-Apps
* @author Francis Crossen <francis@crossen.org>
*/
/**
* An example of the tina_mvc_html_table_helper in use
*
* @package Tina-MVC
* @subpackage Tina-Sample-Apps
* @author Francis Crossen <francis@crossen.org>
*/
class sample_html_table_helper_page extends tina_mvc_base_page_class {
function __construct( $request=array() ) {
parent::__construct( $request );
/**
* Automatic routing with the dispatcher method.
* @see dispatcher_example_page.php
*/
$this->use_dispatcher = TRUE;
}
/**
* Generate some data and use the tina_mvc_html_table_helper to generate HTML
* tables
*/
function index() {
/**
* Include the helper
*/
tina_mvc_include_helper('tina_mvc_table_helper');
/**
* Quick and dirty... the HTML we'll output
*
* No fancy view files here...
*/
$html_out = '';
/**
* The first table
*
* Generate an array of data to format
*/
$table_headings = array( 'column_one' , 'Column 2' , '<col-3>' );
$table_data = array();
for( $i=0; $i<5; $i++ ) {
foreach( $table_headings AS $j => $heading ) {
$table_data[$i][$heading] = rand();
}
}
$table = new tina_mvc_table_helper( 'first_table' );
$table->set_data( $table_data );
$html_out .= '<h2>The First Table</h2>';
$html_out .= $table->get_html();
/**
* All done
*/
unset( $table );
/**
* The second table
*
* Generate an object of data to format
*/
$table_headings = array( '<a href="#">column_one</a>' , 'Column 2(€)' , 'Now you see me -> <col-3> and now you don\'t -> <col-3>' );
$table_data = new stdClass;
for( $i=0; $i<12; $i++ ) {
foreach( $table_headings AS $j => $heading ) {
$table_data->$i->$heading = rand();
}
}
$table = new tina_mvc_table_helper( 'second_table' );
$table->set_data( $table_data );
/**
* Because we have proper HTML in the headers, we don't want to escape the
* table headings
*/
$table->do_not_esc_th( TRUE );
$html_out .= '<h2>The Second Table</h2>';
$html_out .= $table->get_html();
$this->set_post_title('My Beautiful Tables');
$this->set_post_content($html_out);
}
}
?>
| gpl-2.0 |
knightliao/common-utils | src/main/java/com/baidu/unbiz/common/logger/LoggerProvider.java | 235 | /**
*
*/
package com.baidu.unbiz.common.logger;
/**
* @author <a href="mailto:xuc@iphonele.com">saga67</a>
*
* @version create on 2013年8月13日 下午9:41:44
*/
public interface LoggerProvider {
Logger getLogger();
}
| gpl-2.0 |
registrodedalo/app | RegistroDedalo/RegistroDedalo.Zygote/Entities/Assenza.cs | 1359 | /*
Copyright (C) 2015 Dedalo
This file is part of Dedalo.
Dedalo 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.
Dedalo 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 Dedalo. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
namespace RegistroDedalo.Zygote.Entities
{
/// <summary>
/// Classe Assenza
/// </summary>
public class Assenza
{
private int id;
private DateTime data;
/// <summary>
/// ID univoco assenza
/// </summary>
public int ID
{
get { return id; }
set { id = value; }
}
/// <summary>
/// Data assenza
/// </summary>
public DateTime Data
{
get { return data; }
set { data = value; }
}
// IDStudente???
// IDGiustificazione???
}
}
| gpl-2.0 |
NeumimTo/NT-RPG | Plugin/src/main/java/cz/neumimto/rpg/Init.java | 1868 | package cz.neumimto.rpg;
import cz.neumimto.core.ioc.Inject;
import cz.neumimto.core.ioc.Singleton;
import cz.neumimto.rpg.effects.EffectService;
import cz.neumimto.rpg.exp.ExperienceService;
import cz.neumimto.rpg.gui.ParticleDecorator;
import cz.neumimto.rpg.gui.VanillaMessaging;
import cz.neumimto.rpg.inventory.CustomItemFactory;
import cz.neumimto.rpg.inventory.InventoryService;
import cz.neumimto.rpg.inventory.runewords.RWService;
import cz.neumimto.rpg.persistance.GroupDao;
import cz.neumimto.rpg.players.properties.PropertyService;
import cz.neumimto.rpg.scripting.JSLoader;
import cz.neumimto.rpg.skills.SkillService;
import cz.neumimto.rpg.utils.PseudoRandomDistribution;
/**
* Created by NeumimTo on 19.8.2018.
*/
@Singleton
public class Init {
@Inject PropertyService propertyService;
@Inject JSLoader jsLoader;
@Inject InventoryService inventoryService;
@Inject VanillaMessaging vanillaMessaging;
@Inject SkillService skillService;
@Inject EffectService effectService;
@Inject ParticleDecorator particleDecorator;
@Inject ExperienceService experienceService;
@Inject CustomItemFactory customItemFactory;
@Inject GroupService groupService;
@Inject GroupDao groupDao;
@Inject RWService rwService;
public void it() {
int a = 0;
PseudoRandomDistribution p = new PseudoRandomDistribution();
PseudoRandomDistribution.C = new double[101];
for (double i = 0.01; i <= 1; i += 0.01) {
PseudoRandomDistribution.C[a] = p.c(i);
a++;
}
experienceService.load();
inventoryService.init();
skillService.load();
propertyService.init();
jsLoader.initEngine();
groupService.registerPlaceholders();
rwService.load();
groupDao.loadGuilds();
groupDao.loadNClasses();
groupDao.loadRaces();
customItemFactory.initBuilder();
vanillaMessaging.load();
effectService.load();
particleDecorator.initModels();
}
}
| gpl-2.0 |
NickeyWoo/libsimplesvr | include/Timer.hpp | 12917 | /*++
*
* Simple Server Library
* Author: NickeyWoo
* Date: 2014-03-19
*
--*/
#ifndef __TIMER_HPP__
#define __TIMER_HPP__
#include <sys/time.h>
#include <utility>
#include <vector>
#include <list>
#include <map>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/unordered_map.hpp>
#include <boost/noncopyable.hpp>
#ifndef TIMER_DEFAULT_INTERVAL
// default check interval 10ms
#define TIMER_DEFAULT_INTERVAL 10
#endif
template<typename DataT, typename IdT, typename TimeValueT>
struct TimerItem
{
TimerItem<DataT, IdT, TimeValueT>* PrevItem;
TimerItem<DataT, IdT, TimeValueT>* NextItem;
TimerItem<DataT, IdT, TimeValueT>** Base;
IdT TimerId;
TimeValueT Timeval;
boost::function<void(DataT)> Callback;
DataT Data;
TimerItem() :
PrevItem(NULL),
NextItem(NULL),
Base(NULL),
TimerId(0),
Timeval(0)
{
}
inline void Invoke()
{
Callback(Data);
}
};
template<typename IdT, typename TimeValueT>
struct TimerItem<void, IdT, TimeValueT>
{
TimerItem<void, IdT, TimeValueT>* PrevItem;
TimerItem<void, IdT, TimeValueT>* NextItem;
TimerItem<void, IdT, TimeValueT>** Base;
IdT TimerId;
TimeValueT Timeval;
boost::function<void()> Callback;
TimerItem() :
PrevItem(NULL),
NextItem(NULL),
Base(NULL),
TimerId(0),
Timeval(0)
{
}
inline void Invoke()
{
Callback();
}
};
template<typename TimerBaseT, int32_t Interval>
class TimerStartup :
public boost::noncopyable
{
public:
TimerStartup()
{
if(Pool::Instance().IsStartup())
Startup();
else
Pool::Instance().RegisterStartupCallback(boost::bind(&TimerStartup<TimerBaseT, Interval>::Startup, this), true);
}
virtual ~TimerStartup()
{
}
bool Startup()
{
EventScheduler& scheduler = PoolObject<EventScheduler>::Instance();
int timeout = scheduler.GetIdleTimeout();
if(timeout == -1 || timeout > Interval)
scheduler.SetIdleTimeout(Interval);
scheduler.RegisterLoopCallback(boost::bind(&TimerBaseT::CheckTimer, reinterpret_cast<TimerBaseT*>(this)));
return true;
}
};
template<typename DataT, typename IdT, typename TimeValueT, int32_t Interval>
class TimerBase :
public TimerStartup<TimerBase<DataT, IdT, TimeValueT, Interval>, Interval>
{
protected:
IdT m_LastTimerId;
TimeValueT m_LastTimeval;
#define TVN_BITS 6
#define TVR_BITS 8
#define TVN_SIZE (1 << TVN_BITS)
#define TVR_SIZE (1 << TVR_BITS)
#define TVN_MASK (TVN_SIZE - 1)
#define TVR_MASK (TVR_SIZE - 1)
#define MAX_TVAL ((1ULL << (TVR_BITS + 4*TVN_BITS)) - 1)
TimerItem<DataT, IdT, TimeValueT>* m_Vector1[TVR_SIZE];
TimerItem<DataT, IdT, TimeValueT>* m_Vector2[TVN_SIZE];
TimerItem<DataT, IdT, TimeValueT>* m_Vector3[TVN_SIZE];
TimerItem<DataT, IdT, TimeValueT>* m_Vector4[TVN_SIZE];
TimerItem<DataT, IdT, TimeValueT>* m_Vector5[TVN_SIZE];
boost::unordered_map<IdT, TimerItem<DataT, IdT, TimeValueT>*> m_TimerDataMap;
TimeValueT GetTimeval()
{
timeval tv;
gettimeofday(&tv, NULL);
TimeValueT val = (tv.tv_sec * 1000 + tv.tv_usec / 1000) / Interval;
return val;
}
int InternalAddTimerItem(TimerItem<DataT, IdT, TimeValueT>* pItem)
{
TimeValueT idx = pItem->Timeval - m_LastTimeval;
TimerItem<DataT, IdT, TimeValueT>** ppVector = NULL;
if(pItem->Timeval < m_LastTimeval)
{
// already timeout item.
ppVector = &m_Vector1[m_LastTimeval & TVR_MASK];
}
else if(idx < TVR_SIZE)
{
ppVector = &m_Vector1[pItem->Timeval & TVR_MASK];
}
else if(idx < (1 << (TVR_BITS + TVN_BITS)))
{
ppVector = &m_Vector2[(pItem->Timeval >> TVR_BITS) & TVN_MASK];
}
else if(idx < (1 << (TVR_BITS + 2*TVN_BITS)))
{
ppVector = &m_Vector3[(pItem->Timeval >> (TVR_BITS + TVN_BITS)) & TVN_MASK];
}
else if(idx < (1 << (TVR_BITS + 3*TVN_BITS)))
{
ppVector = &m_Vector4[(pItem->Timeval >> (TVR_BITS + 2*TVN_BITS)) & TVN_MASK];
}
else
{
TimeValueT tv = pItem->Timeval;
if(idx > MAX_TVAL)
tv = MAX_TVAL + m_LastTimeval;
ppVector = &m_Vector5[(tv >> (TVR_BITS + 3*TVN_BITS)) & TVN_MASK];
}
pItem->Base = ppVector;
if(ppVector[0] == NULL)
ppVector[0] = pItem;
else
{
pItem->NextItem = ppVector[0];
ppVector[0]->PrevItem = pItem;
ppVector[0] = pItem;
}
return 0;
}
bool cascade(TimerItem<DataT, IdT, TimeValueT>** pVector, TimeValueT index)
{
TimerItem<DataT, IdT, TimeValueT>* pTimerItem = pVector[index];
pVector[index] = NULL;
while(pTimerItem)
{
TimerItem<DataT, IdT, TimeValueT>* pNextItem = pTimerItem->NextItem;
pTimerItem->PrevItem = NULL;
pTimerItem->NextItem = NULL;
pTimerItem->Base = NULL;
InternalAddTimerItem(pTimerItem);
pTimerItem = pNextItem;
}
return (index != 0);
}
void PrintVector(TimerItem<DataT, IdT, TimeValueT>** pVector, int size)
{
for(int i=0; i<size; ++i)
{
TimerItem<DataT, IdT, TimeValueT>* pItem = pVector[i];
printf(" %03d ", i);
if(pItem)
{
bool b = true;
while(pItem)
{
TimerItem<DataT, IdT, TimeValueT>* pNext = pItem->NextItem;
if(b)
{
printf("timeval: (0x%016lX)%lu\n", pItem->Timeval, pItem->Timeval);
b = false;
}
else
printf(" timeval: (0x%016lX)%lu\n", pItem->Timeval, pItem->Timeval);
pItem = pNext;
}
}
else
printf("timeval: NULL\n");
}
}
public:
TimerBase() :
m_LastTimerId(0)
{
m_LastTimeval = GetTimeval();
bzero(&m_Vector1, sizeof(TimerItem<DataT, IdT, TimeValueT>*)*TVR_SIZE);
bzero(&m_Vector2, sizeof(TimerItem<DataT, IdT, TimeValueT>*)*TVN_SIZE);
bzero(&m_Vector3, sizeof(TimerItem<DataT, IdT, TimeValueT>*)*TVN_SIZE);
bzero(&m_Vector4, sizeof(TimerItem<DataT, IdT, TimeValueT>*)*TVN_SIZE);
bzero(&m_Vector5, sizeof(TimerItem<DataT, IdT, TimeValueT>*)*TVN_SIZE);
}
void Update(IdT timerId, int timeout)
{
typename boost::unordered_map<IdT, TimerItem<DataT, IdT, TimeValueT>*>::iterator iter = m_TimerDataMap.find(timerId);
if(iter == m_TimerDataMap.end())
return;
TimerItem<DataT, IdT, TimeValueT>* pItem = iter->second;
if(pItem->NextItem)
pItem->NextItem->PrevItem = pItem->PrevItem;
if(pItem->PrevItem)
pItem->PrevItem->NextItem = pItem->NextItem;
else
pItem->Base[0] = pItem->NextItem;
pItem->PrevItem = NULL;
pItem->NextItem = NULL;
pItem->Base = NULL;
pItem->Timeval = GetTimeval() + (timeout / Interval);
if(InternalAddTimerItem(pItem) != 0)
{
delete pItem;
m_TimerDataMap.erase(iter);
return 0;
}
}
void Clear(IdT timerId)
{
typename boost::unordered_map<IdT, TimerItem<DataT, IdT, TimeValueT>*>::iterator iter = m_TimerDataMap.find(timerId);
if(iter == m_TimerDataMap.end())
{
return;
}
TimerItem<DataT, IdT, TimeValueT>* pItem = iter->second;
if(pItem->NextItem)
pItem->NextItem->PrevItem = pItem->PrevItem;
if(pItem->PrevItem)
pItem->PrevItem->NextItem = pItem->NextItem;
else
pItem->Base[0] = pItem->NextItem;
delete pItem;
m_TimerDataMap.erase(iter);
}
void CheckTimer()
{
TimeValueT now = GetTimeval();
while(m_LastTimeval < now)
{
TimeValueT index = m_LastTimeval & TVR_MASK;
if(!index &&
!cascade(m_Vector2, ((m_LastTimeval >> TVR_BITS) & TVN_MASK)) &&
!cascade(m_Vector3, ((m_LastTimeval >> (TVR_BITS + TVN_BITS)) & TVN_MASK)) &&
!cascade(m_Vector4, ((m_LastTimeval >> (TVR_BITS + 2*TVN_BITS)) & TVN_MASK)))
{
cascade(m_Vector5, ((m_LastTimeval >> (TVR_BITS + 3*TVN_BITS)) & TVN_MASK));
}
++m_LastTimeval;
TimerItem<DataT, IdT, TimeValueT>* pTimerItem = m_Vector1[index];
m_Vector1[index] = NULL;
while(pTimerItem)
{
typename boost::unordered_map<IdT, TimerItem<DataT, IdT, TimeValueT>*>::iterator iter = m_TimerDataMap.find(pTimerItem->TimerId);
if(iter != m_TimerDataMap.end())
m_TimerDataMap.erase(iter);
try
{
pTimerItem->Invoke();
}
catch(...)
{
// nothing
LOG("error: timer list catch exception, you need check your code to catch the exception.");
}
TimerItem<DataT, IdT, TimeValueT>* pItem = pTimerItem;
pTimerItem = pTimerItem->NextItem;
delete pItem;
}
}
}
void Dump()
{
printf("Base Timeval: (0x%016lX)%lu\n", m_LastTimeval, m_LastTimeval);
printf("////////////////////////////////////////////////////////////////////\n");
printf("vector1:\n");
PrintVector(m_Vector1, TVR_SIZE);
printf("\n");
printf("vector2:\n");
PrintVector(m_Vector2, TVN_SIZE);
printf("\n");
printf("vector3:\n");
PrintVector(m_Vector3, TVN_SIZE);
printf("\n");
printf("vector4:\n");
PrintVector(m_Vector4, TVN_SIZE);
printf("\n");
printf("vector5:\n");
PrintVector(m_Vector5, TVN_SIZE);
printf("\n");
}
};
template<typename DataT, int32_t Interval = TIMER_DEFAULT_INTERVAL>
class Timer :
public TimerBase<DataT, uint32_t, uint64_t, Interval>
{
public:
typedef uint32_t TimerID;
typedef uint64_t TimeValue;
TimerID SetTimeout(boost::function<void(DataT)> callback, int timeout, DataT data)
{
++this->m_LastTimerId;
TimerItem<DataT, TimerID, TimeValue>* pItem = new TimerItem<DataT, TimerID, TimeValue>();
pItem->TimerId = this->m_LastTimerId;
pItem->Timeval = this->GetTimeval() + (timeout / Interval);
pItem->Data = data;
pItem->Callback = callback;
if(this->InternalAddTimerItem(pItem) != 0)
{
delete pItem;
--this->m_LastTimerId;
return 0;
}
this->m_TimerDataMap.insert(std::make_pair<TimerID, TimerItem<DataT, TimerID, TimeValue>*>(pItem->TimerId, pItem));
return pItem->TimerId;
}
template<typename ServiceT>
inline TimerID SetTimeout(ServiceT* pService, int timeout, DataT data)
{
return SetTimeout(boost::bind(&ServiceT::OnTimeout, pService, _1), timeout, data);
}
inline DataT* GetTimer(TimerID timerId)
{
typename boost::unordered_map<TimerID, TimerItem<DataT, TimerID, TimeValue>*>::iterator iter = this->m_TimerDataMap.find(timerId);
if(iter == this->m_TimerDataMap.end())
return NULL;
else
return &iter->second->Data;
}
};
template<int32_t Interval>
class Timer<void, Interval> :
public TimerBase<void, uint32_t, uint64_t, Interval>
{
public:
typedef uint32_t TimerID;
typedef uint64_t TimeValue;
template<typename ServiceT>
inline TimerID SetTimeout(ServiceT* pService, int timeout)
{
return SetTimeout(boost::bind(&ServiceT::OnTimeout, pService), timeout);
}
TimerID SetTimeout(boost::function<void()> callback, int timeout)
{
++this->m_LastTimerId;
TimerItem<void, TimerID, TimeValue>* pItem = new TimerItem<void, TimerID, TimeValue>();
pItem->TimerId = this->m_LastTimerId;
pItem->Timeval = this->GetTimeval() + (timeout / Interval);
pItem->Callback = callback;
if(this->InternalAddTimerItem(pItem) != 0)
{
delete pItem;
--this->m_LastTimerId;
return 0;
}
this->m_TimerDataMap.insert(std::make_pair<TimerID, TimerItem<void, TimerID, TimeValue>*>(pItem->TimerId, pItem));
return pItem->TimerId;
}
};
#endif // define __TIMER_HPP__
| gpl-2.0 |
raphaelfeng/benerator | test/org/databene/benerator/wrapper/AlternativeGeneratorTest.java | 4529 | /*
* (c) Copyright 2006-2011 by Volker Bergmann. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, is permitted under the terms of the
* GNU General Public License.
*
* For redistributing this software or a derivative work under a license other
* than the GPL-compatible Free Software License as defined by the Free
* Software Foundation or approved by OSI, you must first obtain a commercial
* license to this software product from Volker Bergmann.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* WITHOUT A WARRANTY OF ANY KIND. ALL EXPRESS OR IMPLIED CONDITIONS,
* REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE
* HEREBY EXCLUDED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.databene.benerator.wrapper;
import org.databene.benerator.distribution.sequence.RandomIntegerGenerator;
import org.databene.benerator.sample.ConstantGenerator;
import org.databene.benerator.sample.SequenceGenerator;
import org.databene.benerator.test.GeneratorTest;
import org.databene.benerator.util.GeneratorUtil;
import org.databene.benerator.Generator;
import org.junit.Test;
import static junit.framework.Assert.*;
/**
* Tests the {@link AlternativeGenerator}.<br/>
* <br/>
* Created: 11.10.2006 23:10:34
* @since 0.1
* @author Volker Bergmann
*/
public class AlternativeGeneratorTest extends GeneratorTest {
@Test
@SuppressWarnings("unchecked")
public void testNonUnique() {
Generator<Integer> source1 = new RandomIntegerGenerator(-2, -1);
Generator<Integer> source2 = new RandomIntegerGenerator(1, 2);
AlternativeGenerator<Integer> generator = new AlternativeGenerator<Integer>(Integer.class, source1, source2);
generator.init(context);
for (int i = 0; i < 100; i++) {
int product = GeneratorUtil.generateNonNull(generator);
assertTrue((-2 <= product && product <= -1) || (1 <= product && product <= 2));
}
}
@Test
public void testUniqueOneShotAlternatives() {
expectUniquelyGeneratedSet(initialize(generator(0)), 0).withCeasedAvailability();
expectUniquelyGeneratedSet(initialize(generator(0, 1, 2)), 0, 1, 2).withCeasedAvailability();
}
@Test
@SuppressWarnings("unchecked")
public void testUniqueMultiAlternatives() {
Generator<Integer>[] gens = new Generator[2];
gens[0] = new NShotGeneratorProxy<Integer>(new ConstantGenerator<Integer>(2), 1);
gens[1] = generator(0, 1);
Generator<Integer> generator = new AlternativeGenerator<Integer>(Integer.class, gens);
generator.init(context);
expectUniquelyGeneratedSet(generator, 0, 1, 2).withCeasedAvailability();
}
@Test
@SuppressWarnings("unchecked")
public void testUniqueManyAlternatives() {
Generator<Integer>[] gens = new Generator[2];
gens[0] = new SequenceGenerator<Integer>(Integer.class, 0, 2, 4, 6, 8);
gens[1] = new SequenceGenerator<Integer>(Integer.class, 1, 3, 5, 7, 9);
Generator<Integer> generator = new AlternativeGenerator<Integer>(Integer.class, gens);
generator.init(context);
expectUniqueGenerations(generator, 10).withCeasedAvailability();
}
// helpers ---------------------------------------------------------------------------------------------------------
@SuppressWarnings("unchecked")
private Generator<Integer> generator(int ... values) {
Generator<Integer>[] gens = new Generator[values.length];
for (int i = 0; i < values.length; i++)
gens[i] = new NShotGeneratorProxy<Integer>(new ConstantGenerator<Integer>(values[i]), 1);
AlternativeGenerator<Integer> result = new AlternativeGenerator<Integer>(Integer.class, gens);
return result;
}
}
| gpl-2.0 |
TheTypoMaster/calligra | plugins/textshape/ReferencesToolFactory.cpp | 1539 | /* This file is part of the KDE project
* Copyright (C) 2008 Pierre Stirnweiss \pierre.stirnweiss_calligra@gadz.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "ReferencesToolFactory.h"
#include "ReferencesTool.h"
#include "TextShape.h"
#include <KoCanvasBase.h>
#include <KoIcon.h>
#include <klocalizedstring.h>
ReferencesToolFactory::ReferencesToolFactory()
: KoToolFactoryBase("ReferencesToolFactory_ID")
{
setToolTip(i18n("References"));
setToolType("calligrawords,calligraauthor");
setIconName(koIconNameCStr("tool_references"));
setPriority(20);
setActivationShapeId(TextShape_SHAPEID);
}
ReferencesToolFactory::~ReferencesToolFactory()
{
}
KoToolBase * ReferencesToolFactory::createTool(KoCanvasBase *canvas)
{
return new ReferencesTool(canvas);
}
| gpl-2.0 |
jmcvetta/slashcode | plugins/Ajax/htdocs/images/sd_autocomplete.js | 12317 | // _*_ Mode: JavaScript; tab-width: 8; indent-tabs-mode: true _*_
// $Id: sd_autocomplete.js,v 1.52 2008/03/28 20:53:43 pudge Exp $
YAHOO.namespace("slashdot");
YAHOO.slashdot.DS_JSArray = function(aData, oConfigs) {
if ( typeof oConfigs == "object" )
for ( var sConfig in oConfigs )
this[sConfig] = oConfigs[sConfig];
if ( !aData || (aData.constructor != Array) )
return
this.data = aData;
this._init();
}
YAHOO.slashdot.DS_JSArray.prototype = new YAHOO.widget.DataSource();
YAHOO.slashdot.DS_JSArray.prototype.data = null;
YAHOO.slashdot.DS_JSArray.prototype.doQuery = function(oCallbackFn, sQuery, oParent) {
var aData = this.data; // the array
var aResults = []; // container for results
var bMatchFound = false;
var bMatchContains = this.queryMatchContains;
if(sQuery && !this.queryMatchCase) {
sQuery = sQuery.toLowerCase();
}
// Loop through each element of the array...
// which can be a string or an array of strings
for(var i = aData.length-1; i >= 0; i--) {
var aDataset = [];
if(aData[i]) {
if(aData[i].constructor == String) {
aDataset[0] = aData[i];
}
else if(aData[i].constructor == Array) {
aDataset = aData[i];
}
}
if(aDataset[0] && (aDataset[0].constructor == String)) {
var sKeyIndex = 0;
if (sQuery) {
sKeyIndex = (this.queryMatchCase) ?
encodeURIComponent(aDataset[0]).indexOf(sQuery):
encodeURIComponent(aDataset[0]).toLowerCase().indexOf(sQuery);
}
// A STARTSWITH match is when the query is found at the beginning of the key string...
if((!bMatchContains && (sKeyIndex === 0)) ||
// A CONTAINS match is when the query is found anywhere within the key string...
(bMatchContains && (sKeyIndex > -1))) {
// Stash a match into aResults[].
aResults.unshift(aDataset);
}
}
}
this.getResultsEvent.fire(this, oParent, sQuery, aResults);
oCallbackFn(sQuery, aResults, oParent);
};
YAHOO.slashdot.gCompleterWidget = null;
YAHOO.slashdot.feedbackTags = ["dupe", "typo", "error"];
YAHOO.slashdot.actionTags = ["none", "quik", "hold", "back"];
YAHOO.slashdot.sectionTags = [ "apache",
"apple",
"askslashdot",
"awards",
"backslash",
"books",
"bsd",
"developers",
"entertainment",
"features",
"games",
"hardware",
"interviews",
"it",
"linux",
"mainpage",
"news",
"politics",
"polls",
"radio",
"science",
"search",
"tacohell",
"technology",
"vendors",
"vendor_amd",
"yro" ];
YAHOO.slashdot.topicTags = ["keyword",
"mainpage",
"apache",
"apple",
"askslashdot",
"awards",
"books",
"bsd",
"developers",
"features",
"games",
"interviews",
"polls",
"radio",
"science",
"search",
"tacohell",
"yro",
"be",
"caldera",
"comdex",
"debian",
"digital",
"gimp",
"encryption",
"gnustep",
"internet",
"links",
"movies",
"money",
"pilot",
"starwars",
"sun",
"usa",
"x",
"xmas",
"linux",
"java",
"microsoft",
"redhat",
"spam",
"quake",
"ie",
"netscape",
"enlightenment",
"cda",
"gnu",
"intel",
"eplus",
"aol",
"kde",
"doj",
"slashdot",
"wine",
"tech",
"bug",
"tv",
"unix",
"gnome",
"corel",
"humor",
"ibm",
"hardware",
"amiga",
"sgi",
"compaq",
"music",
"amd",
"suse",
"quickies",
"perl",
"ed",
"mandrake",
"media",
"va",
"linuxcare",
"graphics",
"censorship",
"mozilla",
"patents",
"programming",
"privacy",
"toys",
"space",
"transmeta",
"announce",
"linuxbiz",
"upgrades",
"turbolinux",
"editorial",
"slashback",
"anime",
"php",
"ximian",
"journal",
"security",
"hp",
"desktops",
"imac",
"media",
"networking",
"osnine",
"osx",
"portables",
"utilities",
"wireless",
"portables",
"software",
"ent",
"biz",
"media",
"gui",
"os",
"biotech",
"books",
"wireless",
"printers",
"displays",
"storage",
"lotr",
"matrix",
"windows",
"classic",
"emulation",
"fps",
"nes",
"pcgames",
"portablegames",
"puzzlegames",
"rpg",
"rts",
"xbox",
"ps2",
"gamecube",
"wii",
"scifi",
"communications",
"robotics",
"google",
"it",
"politics",
"military",
"worms",
"databases",
"hardhack",
"novell",
"republicans",
"democrats",
"mars",
"inputdev",
"math",
"moon",
"networking",
"supercomputing",
"power",
"sony",
"nintendo",
"e3",
"nasa",
"yahoo",
"vendors",
"vendor_amd",
"vendor_amd_64chip",
"vendor_amd_announce",
"vendor_amd_ask",
"vendor_amd_64fx",
"vendor_amd_laptops",
"vendor_amd_multicore",
"vendor_amd_ostg",
"backslash" ];
YAHOO.slashdot.fhitemOpts = [
"hold",
"back",
"quik",
"typo",
"dupe"
];
YAHOO.slashdot.storyOpts = [
"neverdisplay"
];
var feedbackDS = new YAHOO.slashdot.DS_JSArray(YAHOO.slashdot.feedbackTags);
var actionsDS = new YAHOO.slashdot.DS_JSArray(YAHOO.slashdot.actionTags);
var sectionsDS = new YAHOO.slashdot.DS_JSArray(YAHOO.slashdot.sectionTags);
var topicsDS = new YAHOO.slashdot.DS_JSArray(YAHOO.slashdot.topicTags);
var fhitemDS = new YAHOO.slashdot.DS_JSArray(YAHOO.slashdot.fhitemOpts);
var storyDS = new YAHOO.slashdot.DS_JSArray(YAHOO.slashdot.storyOpts);
var tagsDS = new YAHOO.widget.DS_XHR("./ajax.pl", ["\n", "\t"]);
// tagsDS.maxCacheEntries = 0; // turn off local cacheing, because Jamie says the query is fast
tagsDS.queryMatchSubset = false;
tagsDS.responseType = YAHOO.widget.DS_XHR.TYPE_FLAT;
tagsDS.scriptQueryParam = "prefix";
tagsDS.scriptQueryAppend = "op=tags_list_tagnames";
tagsDS.queryMethod = "POST";
var fhtabsDS = new YAHOO.widget.DS_XHR("./ajax.pl", ["\n", "\t"]);
fhtabsDS.queryMatchSubset = false;
fhtabsDS.responseType = YAHOO.widget.DS_XHR.TYPE_FLAT;
fhtabsDS.scriptQueryParam = "prefix";
fhtabsDS.scriptQueryAppend = "op=firehose_list_tabs";
fhtabsDS.queryMethod = "POST";
YAHOO.slashdot.dataSources = [tagsDS, actionsDS, sectionsDS, topicsDS, feedbackDS, storyDS, fhitemDS, fhtabsDS ];
YAHOO.slashdot.AutoCompleteWidget = function() {
this._widget = document.getElementById("ac-select-widget");
this._spareInput = document.getElementById("ac-select-input");
this._sourceEl = null;
this._denyNextAttachTo = null;
YAHOO.util.Event.addListener(document.body, "click", this._onSdClick, this, true);
// add body/window blur to detect changing windows?
}
YAHOO.slashdot.AutoCompleteWidget.prototype._textField = function() {
if ( this._sourceEl==null || this._sourceEl.type=='text' || this._sourceEl.type=='textarea' )
return this._sourceEl;
return this._spareInput;
}
YAHOO.slashdot.AutoCompleteWidget.prototype._needsSpareInput = function() {
// return this._textField() == this._spareInput;
return this._sourceEl && (this._sourceEl.type != "text") && (this._sourceEl.type != "textarea");
}
YAHOO.slashdot.AutoCompleteWidget.prototype._newCompleter = function( tagDomain ) {
var c = null;
if ( this._needsSpareInput() ) {
c = new YAHOO.widget.AutoComplete("ac-select-input", "ac-choices", YAHOO.slashdot.dataSources[tagDomain]);
c.minQueryLength = 0;
// hack? -- override YUI's private member function so that for top tags auto-complete, right arrow means select
c._jumpSelection = function() { if ( this._oCurItem ) this._selectItem(this._oCurItem); };
} else {
c = new YAHOO.widget.AutoComplete(this._sourceEl, "ac-choices", YAHOO.slashdot.dataSources[tagDomain]);
c.delimChar = " ";
c.minQueryLength = 3;
}
c.typeAhead = false;
c.forceSelection = false;
c.allowBrowserAutocomplete = false;
c.maxResultsDisplayed = 25;
c.animVert = false;
return c;
}
YAHOO.slashdot.AutoCompleteWidget.prototype._show = function( obj, callbackParams, tagDomain ) {
// onTextboxBlur should have already hidden the previous instance (if any), but if events
// come out of order, we must hide now to prevent broken listeners
if ( this._sourceEl )
this._hide();
this._sourceEl = obj;
if ( this._sourceEl ) {
this._callbackParams = callbackParams;
this._callbackParams._tagDomain = tagDomain;
this._completer = this._newCompleter(tagDomain);
if ( typeof callbackParams.yui == "object" )
for ( var field in callbackParams.yui )
this._completer[field] = callbackParams.yui[field];
if ( callbackParams.delayAutoHighlight )
this._completer.autoHighlight = false;
// widget must be visible to move
YAHOO.util.Dom.removeClass(this._widget, "hidden");
// move widget to be near the 'source'
var pos = YAHOO.util.Dom.getXY(this._sourceEl);
pos[1] += this._sourceEl.offsetHeight;
YAHOO.util.Dom.setXY(this._widget, pos);
YAHOO.util.Dom.addClass(this._sourceEl, "ac-source");
if ( this._needsSpareInput() ) {
YAHOO.util.Dom.removeClass(this._spareInput, "hidden");
this._spareInput.value = "";
this._spareInput.focus();
this._pending_hide = setTimeout(YAHOO.slashdot.gCompleterWidget._hide, 15000);
} else
YAHOO.util.Dom.addClass(this._spareInput, "hidden");
this._completer.itemSelectEvent.subscribe(this._onSdItemSelectEvent, this);
this._completer.unmatchedItemSelectEvent.subscribe(this._onSdItemSelectEvent, this);
this._completer.textboxBlurEvent.subscribe(this._onSdTextboxBlurEvent, this);
YAHOO.util.Event.addListener(this._textField(), "keydown", this._onSdTextboxKeyDown, this, true);
}
}
YAHOO.slashdot.AutoCompleteWidget.prototype._hide = function() {
if ( this._pending_hide ) {
clearTimeout(this._pending_hide);
this._pending_hide = null;
}
YAHOO.util.Dom.addClass(this._widget, "hidden");
YAHOO.util.Dom.addClass(this._spareInput, "hidden");
if ( this._sourceEl ) {
YAHOO.util.Dom.removeClass(this._sourceEl, "ac-source");
YAHOO.util.Event.removeListener(this._textField(), "keydown", this._onSdTextboxKeyDown, this, true);
this._completer.itemSelectEvent.unsubscribe(this._onSdItemSelectEvent, this);
this._completer.unmatchedItemSelectEvent.unsubscribe(this._onSdItemSelectEvent, this);
this._completer.textboxBlurEvent.unsubscribe(this._onSdTextboxBlurEvent, this);
this._sourceEl = null;
this._callbackParams = null;
this._completer = null;
}
this._denyNextAttachTo = null;
}
YAHOO.slashdot.AutoCompleteWidget.prototype.attach = function( obj, callbackParams, tagDomain ) {
var newSourceEl = obj;
if ( typeof obj == "string" )
newSourceEl = document.getElementById(obj);
// act like a menu: if we click on the same trigger while visible, hide
var denyThisAttach = this._denyNextAttachTo == newSourceEl;
this._denyNextAttachTo = null;
if ( denyThisAttach )
return;
if ( newSourceEl && newSourceEl !== this._sourceEl ) {
callbackParams._sourceEl = newSourceEl;
this._show(newSourceEl, callbackParams, tagDomain);
var q = callbackParams.queryOnAttach;
if ( q )
this._completer.sendQuery((typeof q == "string") ? q : "");
}
}
YAHOO.slashdot.AutoCompleteWidget.prototype._onSdClick = function( e, me ) {
// if the user re-clicked the item to which I'm attached, then they mean to hide me
// I'm going to hide automatically, because a click outside the text will blur, and that makes me go away
// but I need to remember _not_ to let the current click re-show me
var reclicked = me._sourceEl && YAHOO.util.Event.getTarget(e, true) == me._sourceEl;
me._denyNextAttachTo = reclicked ? me._sourceEl : null;
}
YAHOO.slashdot.AutoCompleteWidget.prototype._onSdItemSelectEvent = function( type, args, me ) {
var tagname = args[2];
if ( tagname !== undefined && tagname !== null ) {
if ( typeof tagname != 'string' )
tagname = tagname[0];
var p = me._callbackParams;
if ( p.action0 !== undefined )
p.action0(tagname, p);
me._hide();
if ( p.action1 !== undefined )
p.action1(tagname, p);
} else {
me._hide();
}
}
YAHOO.slashdot.AutoCompleteWidget.prototype._onSdTextboxBlurEvent = function( type, args, me ) {
var o = me._denyNextAttachTo;
me._hide();
me._denyNextAttachTo = o;
}
YAHOO.slashdot.AutoCompleteWidget.prototype._onSdTextboxKeyDown = function( e, me ) {
if ( me._callbackParams && me._callbackParams.delayAutoHighlight ) {
me._callbackParams.delayAutoHighlight = false;
me._completer.autoHighlight = true;
}
switch ( e.keyCode ) {
case 27: // esc
// any other keys?...
me._hide();
break;
case 13:
// I'm sorry to say we have to test first, something somehow somewhere can still
// leave this listener dangling; want to look deeper into this, as this would _still_
// leave the listener dangling
if ( me._completer )
me._completer.unmatchedItemSelectEvent.fire(me._completer, me, me._completer._sCurQuery);
break;
default:
if ( me._pending_hide )
clearTimeout(me._pending_hide);
if ( me._needsSpareInput() )
me._pending_hide = setTimeout(YAHOO.slashdot.gCompleterWidget._hide, 15000);
}
}
| gpl-2.0 |
abelmartin/pull-requester | app/helpers/application_helper.rb | 1358 | module ApplicationHelper
def circle_ci_badge(owner, repo, branch)
unknown_image_url = asset_path('status_unknown_2.png', type: :image)
base_url = "https://circleci.com/gh/#{owner}/"
full_url = "#{base_url}#{u(repo)}/tree/#{u(branch)}"
badge_url = "#{full_url}.png"
link_to(full_url, target: '_blank') do
image_tag(
badge_url,
onerror: "this.onerror=null;this.src='#{unknown_image_url}'"
)
end
end
def travis_ci_badge(owner, repo, branch=nil)
"https://travis-ci.org/#{owner}/#{repo}.png"
end
def render_markdown(md_text)
content = GitHub::Markdown.render_gfm(emojify_to_markdown(md_text))
# I'm not in love with this.
# I might go with <base target="_blank"> in head later
# And try to force <...target="_parent"...> later :-/
content.gsub(/(href=".*")/, '\1 target="_blank" ').html_safe
end
def emojify_to_markdown(md_text)
if md_text.present?
md_text.gsub(/:([a-z0-9\+\-_]+):/) do |match|
if Emoji.names.include?($1)
""
else
match
end
end
else
''
end
end
def user_or_repo_href(org)
if (current_user.github_login != org[:login])
"/repositories?org=#{org[:login]}"
else
"/repositories?user=#{org[:login]}"
end
end
end
| gpl-2.0 |
Krassmus/BombePlugin | BombePlugin.class.php | 4993 | <?php
require_once __DIR__."/models/Bombe.class.php";
class BombePlugin extends StudIPPlugin implements SystemPlugin {
public function __construct() {
parent::__construct();
PageLayout::addScript($this->getPluginURL()."/assets/bombe.js");
PageLayout::addBodyElements($this->getTemplate("bombs/bomb.php", null)->render());
if (UpdateInformation::isCollecting()) {
$bomben = Bombe::findBySQL("user_id = ? AND hit = '0' AND deactivated = '0' AND mkdate > UNIX_TIMESTAMP() - 2 * 60 ", array($GLOBALS['user']->id));
$data = array();
if (count($bomben)) {
if (!$this->userWasActive()) {
$bombtrack = $bomben[0]->toArray();
$bomben[0]['hit'] = 1;
$bomben[0]->store();
$bombtrack['from_user_name'] = get_fullname($bomben[0]['from_user']);
$data['bomb'] = $bombtrack;
} else {
$by = array();
foreach ($bomben as $bomb) {
$bomb['deactivated'] = 1;
$by[] = get_fullname($bomb['from_user']);
$bomb->store();
}
$data['deactivated'] = count($bomben);
$data['deactivated_by'] = implode(", ", $by);
}
}
if (count($data)) {
UpdateInformation::setInformation("Bombe.getHit", $data);
}
}
if (Navigation::hasItem("/profile")) {
$navigation = new Navigation(_("Bomben"), PluginEngine::getURL($this, array(), "manager/overview"));
Navigation::getItem("/profile")->addSubNavigation("bomben", $navigation);
}
PageLayout::addBodyElements('<audio style="display: none;" id="bombe_sound" preload="none">
<source type="audio/mpeg" src="'.$this->getPluginURL().'/assets/zangrutz_bomb-small.mp3"></source>
</audio>');
}
protected function getTemplate($template_file_name, $layout = "without_infobox") {
if (!$this->template_factory) {
$this->template_factory = new Flexi_TemplateFactory(dirname(__file__)."/views");
}
$template = $this->template_factory->open($template_file_name);
$template->set_attribute('plugin', $this);
if ($layout) {
if (method_exists($this, "getDisplayName")) {
PageLayout::setTitle($this->getDisplayName());
} else {
PageLayout::setTitle(get_class($this));
}
$template->set_layout($GLOBALS['template_factory']->open($layout === "without_infobox" ? 'layouts/base_without_infobox' : 'layouts/base'));
}
return $template;
}
protected function userWasActive() {
$tables = array();
$tables[] = array('table' => "user_info");
$tables[] = array('table' => "comments");
$tables[] = array('table' => "dokumente");
$tables[] = array('table' => "forum_entries");
$tables[] = array('table' => "news");
$tables[] = array('table' => "seminar_user");
$tables[] = array(
'table' => "blubber",
'where' => "context_type != 'private'"
);
$tables[] = array(
'table' => "kategorien",
'user_id_column' => "range_id"
);
$tables[] = array(
'table' => "message",
'user_id_column' => "autor_id"
);
$tables[] = array(
'table' => "vote",
'user_id_column' => "range_id"
);
$tables[] = array(
'table' => "voteanswers_user",
'date_column' => "votedate"
);
$tables[] = array(
'table' => "vote_user",
'date_column' => "votedate"
);
$tables[] = array(
'table' => "wiki",
'date_column' => "chdate"
);
foreach (PluginManager::getInstance()->getPlugins("ScorePlugin") as $plugin) {
foreach ((array) $plugin->getPluginActivityTables() as $table) {
if ($table['table']) {
$tables[] = $table;
}
}
}
$sql = "";
foreach ($tables as $key => $table) {
if ($key > 0) {
$sql .= "UNION ";
}
$sql .= "SELECT 1 "
. "FROM "
. $table['table']
. " WHERE "
. ($table['user_id_column'] ? : 'user_id')
. " = :user "
. ($table['where'] ? (' AND ' . $table['where']) : '')
. "AND ".($table['date_column'] ? : 'mkdate'). " > UNIX_TIMESTAMP() - 10 * 60 ";
}
$statement = DBManager::get()->prepare($sql);
$statement->execute(array('user' => $GLOBALS['user']->id));
return (bool) $statement->fetch(PDO::FETCH_COLUMN, 0);
}
} | gpl-2.0 |
MikeEstes/congenial-broccoli | wp-content/plugins/shopp/core/ui/reports/customers.php | 2723 | <?php
class CustomersReport extends ShoppReportFramework implements ShoppReport {
function setup () {
$this->setchart(array(
'series' => array(
'bars' => array(
'show' => true,
'lineWidth' => 0,
'fill' => true,
'barWidth' => 0.75
),
'points' => array('show' => false),
'lines' => array('show' => false)
),
'xaxis' => array('show' => false),
'yaxis' => array('tickFormatter' => 'asMoney')
));
}
function query () {
$this->options = array_merge(array( // Define default URL query parameters
'orderby' => 'orders',
'order' => 'desc'
), $this->options);
extract($this->options, EXTR_SKIP);
$where = array();
$where[] = "o.created BETWEEN '" . sDB::mkdatetime($starts) . "' AND '" . sDB::mkdatetime($ends) . "'";
$where = join(" AND ",$where);
if ( ! in_array( $order, array('asc', 'desc') ) ) $order = 'desc';
if ( ! in_array( $orderby, array('orders', 'sold', 'grossed') ) ) $orderby = 'orders';
$ordercols = "$orderby $order";
$id = 'c.id';
$purchase_table = ShoppDatabaseObject::tablename('purchase');
$purchased_table = ShoppDatabaseObject::tablename('purchased');
$customer_table = ShoppDatabaseObject::tablename('customer');
$query = "SELECT $id AS id,
CONCAT(c.firstname,' ',c.lastname) AS customer,
SUM( (SELECT SUM(p.quantity) FROM $purchased_table AS p WHERE o.id = p.purchase) ) AS sold,
COUNT(DISTINCT o.id) AS orders,
SUM(o.total) AS grossed
FROM $purchase_table as o
INNER JOIN $customer_table AS c ON c.id=o.customer
WHERE $where
GROUP BY $id ORDER BY $ordercols";
return $query;
}
function chartseries ( $label, array $options = array() ) {
if ( ! $this->Chart ) $this->initchart();
extract($options);
$this->Chart->series($record->customer, array( 'color' => '#1C63A8', 'data' => array( array($index, $record->grossed) ) ));
}
function filters () {
ShoppReportFramework::rangefilter();
ShoppReportFramework::filterbutton();
}
function columns () {
return array(
'customer' => __('Customer', 'Shopp'),
'orders' => __('Orders', 'Shopp'),
'sold' => __('Items', 'Shopp'),
'grossed' => __('Grossed', 'Shopp')
);
}
function sortcolumns () {
return array(
'orders' => 'orders',
'sold' => 'sold',
'grossed' => 'grossed'
);
}
static function customer ( $data ) { return trim($data->customer); }
static function orders ( $data ) { return intval($data->orders); }
static function sold ( $data ) { return intval($data->sold); }
static function grossed ( $data ) { return money($data->grossed); }
} | gpl-2.0 |
therandomfactory/nessi-control | doc/code/html/search/defines_66.js | 1081 | var searchData=
[
['fboxsizex',['FBOXSIZEX',['../guider_8h.html#a582797a36c8b66ef5ff8096a9a187dc2',1,'guider.h']]],
['fboxsizey',['FBOXSIZEY',['../guider_8h.html#a972629bffafeee9df017fc46bd147542',1,'guider.h']]],
['fibersperfop',['FIBERSPERFOP',['../guider_8h.html#a4c984fb1321084d74a25260f721d5708',1,'FIBERSPERFOP(): guider.h'],['../guider_8h.html#a4c984fb1321084d74a25260f721d5708',1,'FIBERSPERFOP(): guider.h']]],
['fopactive',['FOPACTIVE',['../guider_8h.html#a475aaae3304e238fdbf290ed365ad9be',1,'guider.h']]],
['fopautofocus',['FOPAUTOFOCUS',['../guider_8h.html#a3703780348ba795a305be702b753ecef',1,'guider.h']]],
['fopfocuscomplete',['FOPFOCUSCOMPLETE',['../guider_8h.html#af9bdbf30cbe6aa9b8945701a11a88259',1,'guider.h']]],
['fopguiderreset',['FOPGUIDERRESET',['../guider_8h.html#a911a57b909744287373db4d569db0c18',1,'guider.h']]],
['fopnottracking',['FOPNOTTRACKING',['../guider_8h.html#aef42c3fbe8fc6fbd8bcf914bbb53d280',1,'guider.h']]],
['foptracking',['FOPTRACKING',['../guider_8h.html#a68f6f7463cdf35f5755e82ee6a92ac51',1,'guider.h']]]
];
| gpl-2.0 |
marvindelarc/Refugiate | Proyecto Anterior/Refugiate/src/com/refujiate/extra/LazyList/ImageLoader.java | 3185 | package com.refujiate.extra.LazyList;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.widget.ImageView;
import com.refujiate.consumo.clsConexion;
import com.refujiate.ui.R;
public class ImageLoader {
MemoryCache memoryCache=new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
public ImageLoader(Context context){
fileCache=new FileCache(context);
executorService=Executors.newFixedThreadPool(5);
}
final int stub_id=R.drawable.libertador;
public void DisplayImage(String url, ImageView imageView)
{
imageViews.put(imageView, url);
Bitmap bitmap=memoryCache.get(url);
if(bitmap!=null)
imageView.setImageBitmap(bitmap);
else
{
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView)
{
PhotoToLoad p=new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
//Task for the queue
private class PhotoToLoad
{
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i){
url=u;
imageView=i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad){
this.photoToLoad=photoToLoad;
}
@Override
public void run() {
if(imageViewReused(photoToLoad))
return;
Bitmap bmp=clsConexion.getImage(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if(imageViewReused(photoToLoad))
return;
BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
Activity a=(Activity)photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
}
boolean imageViewReused(PhotoToLoad photoToLoad){
String tag=imageViews.get(photoToLoad.imageView);
if(tag==null || !tag.equals(photoToLoad.url))
return true;
return false;
}
//Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable
{
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
public void run()
{
if(imageViewReused(photoToLoad))
return;
if(bitmap!=null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
| gpl-2.0 |
nsnake/IRISCC | astercc/asterbilling/include/language/deleterate_en_US.php | 1492 | <?
$select_rate_table = "select_rate_table";
$select_table = "select_table";
$myrate = "myrate";
$callshoprate = "callshoprate";
$resellerrate = "resellerrate";
$delete_type = "Delete Type";
$all = "All";
$system = "System";
$reseller = "Reseller";
$group = "Group";
$object = "Object";
$search = "search";
$please_select_a_rate_table = "please select a rate table";
$are_you_sure_you_want_to_delete_this_rate = "are you sure you want to delete this rate";
$can_not_delete_this_rate = "can not delete this rate";
$delete_success = "Delete successfully";
$please_remember_to_restart_asterrc = "please remember to restart asterrc";
$page_rate_tips = "This rate has been deleted,please restart asterrc";
$restart_asterrc = "restart asterrc";
$delete_failed = "Delete failed";
$start_asterrc_failed = "start asterrc failed, asterrc is not running";
$asterrc_have_been_restart = "asterrc have been restart";
$asterrc_restart_failed = "asterrc restart failed";
$prefix = "Prefix";
$length = "Length";
$destination = "Destination";
$connect_charge = "Connect Charge";
$init_block = "Init Block";
$rate = "Rate";
$billing_block = "Billing Block";
$group = "Group";
$reseller = "Reseller";
$addtime = "Addtime";
$default = "Default";
$delete = "Delete";
$rate_amount_is = "Rate Amount is";
$default_show_20_data = "default show the first 20 data";
$are_you_sure_to = "Are you sure to";
$delete_failed_synchronization = "Delete failed,can not insert to history table by this rate";
$local = "Local";
?> | gpl-2.0 |
aag/dinoremix | cli/downloadComics.py | 3775 | """
Python script to download all of the comics from
the Dinosaur Comics web site.
Copyright 2008, 2009 Adam Goforth
Started on: 2008.07.31
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/>.
"""
from bs4 import BeautifulSoup
from datetime import datetime
from subprocess import call
import urllib.request
import re
import os
import sys
scriptDir = sys.path[0]
dataDir = os.path.join(scriptDir, "../data")
guestComicsPath = os.path.join(dataDir, "GuestComicsURLs.txt")
visitedPagesPath = os.path.join(dataDir, "AlreadyDownloaded.txt")
downloadDirPath = os.path.join(dataDir, "comics/")
def getImageOnArchivePage(url, downloadDir):
"""Accepts the url of a Dinosaur Comics archive page and saves the contained comic image to disk."""
comicPage = urllib.request.urlopen(url)
pageContents = comicPage.read()
comicSoup = BeautifulSoup(pageContents, 'html.parser')
comicImg = comicSoup.find('img', src=re.compile("comics\/comic2-.*\.[png|gif|jpg]"))
if comicImg == None:
comicImg = comicSoup.find('img', src=re.compile("comics\/.*\.[png|jpg|jpeg|gif]"))
print("\t*** NO MATCH *** Guess: " + comicImg['src'])
"""Add the page url to a list of guest comics"""
guestListFile = open(guestComicsPath, 'a')
guestListFile.write(url + "\n")
guestListFile.close()
else:
print("\tDownloading " + comicImg['src'])
filename = comicImg['src'].replace("comics/", "")
imageUrl = "http://www.qwantz.com/{}".format(comicImg['src'])
urllib.request.urlretrieve(imageUrl, os.path.join(downloadDir, filename))
"""Add the page url to a list of already downloaded comics"""
dlListFile = open(visitedPagesPath, 'a')
dlListFile.write(url + "\n")
dlListFile.close()
now = datetime.now()
dt_string = now.strftime("%Y-%m-%d %H:%M:%S")
print("\n\nStarting download at", dt_string)
""" Create missing directories."""
if not os.path.exists(dataDir):
os.makedirs(downloadDirPath)
""" Get a list of the archive pages we've already visited."""
visitedPages = []
if os.path.exists(visitedPagesPath):
dlListFile = open(visitedPagesPath, 'r')
fileContents = dlListFile.read()
dlListFile.close()
visitedPages = fileContents.split("\n")
guestPages = []
if os.path.exists(guestComicsPath):
guestComicsFile = open(guestComicsPath, 'r')
fileContents = guestComicsFile.read()
guestComicsFile.close()
guestPages = fileContents.split("\n")
excludePages = visitedPages + guestPages
print("Downloading comic archive list...\n")
archivePage = urllib.request.urlopen("http://www.qwantz.com/archive.php")
contents = archivePage.read()
print("Retrieving new comics...\n")
archiveSoup = BeautifulSoup(contents, 'html.parser')
allLinks = archiveSoup.findAll('a', href=re.compile("http:\/\/www.qwantz.com\/index\.php\?comic\=\d+"))
for link in allLinks:
url = link['href']
if url not in excludePages:
print(url)
getImageOnArchivePage(url, downloadDirPath)
""" Create panels """
import cutimages
cutimages.cutAllImages()
""" Create serialized file lists """
fileListsPath = os.path.join(scriptDir, "updateFileLists.php")
call(["php", fileListsPath])
| gpl-2.0 |
qsnake/mpqc | src/lib/chemistry/qc/oint3/i2312.cc | 27731 | #include <chemistry/qc/oint3/build.h>
int sc::BuildIntV3::i2312(){
/* the cost is 1507 */
double t1;
double t2;
double t3;
double t4;
double t5;
double t6;
double t7;
double t8;
double t9;
double t10;
double t11;
double t12;
double t13;
double t14;
double t15;
double t16;
double t17;
double t18;
double t19;
double t20;
double t21;
double t22;
double t23;
double t24;
double t25;
double t26;
double t27;
double t28;
double t29;
double t30;
double t31;
double t32;
double t33;
double t34;
double t35;
double t36;
double t37;
double t38;
double t39;
double t40;
double t41;
double t42;
double t43;
double t44;
double t45;
double t46;
double t47;
double t48;
double t49;
double t50;
double t51;
double t52;
double t53;
double t54;
double t55;
double t56;
double t57;
double t58;
double t59;
double t60;
double t61;
double t62;
double t63;
double t64;
double t65;
double t66;
double t67;
double t68;
double t69;
double t70;
double t71;
double t72;
double t73;
double t74;
double t75;
double t76;
double t77;
double t78;
double t79;
double t80;
double t81;
double t82;
double t83;
double t84;
double t85;
double t86;
double t87;
double t88;
double t89;
double t90;
double t91;
double t92;
double t93;
double t94;
double t95;
double t96;
double t97;
double t98;
double t99;
double t100;
double t101;
double t102;
double t103;
double t104;
double t105;
double t106;
double t107;
double t108;
double t109;
double t110;
double t111;
double t112;
double t113;
double t114;
double t115;
double t116;
double t117;
double t118;
double t119;
double t120;
double t121;
double t122;
double t123;
double t124;
double t125;
double t126;
double t127;
double t128;
double t129;
double t130;
double t131;
double t132;
double t133;
double t134;
double t135;
double t136;
double t137;
double t138;
double t139;
double t140;
double t141;
double t142;
double t143;
double t144;
double t145;
double t146;
double t147;
double t148;
double t149;
double t150;
double t151;
double t152;
double t153;
double t154;
double t155;
double t156;
double t157;
double t158;
double t159;
double t160;
double t161;
double t162;
double t163;
double t164;
double t165;
double t166;
t1=int_v_W0-int_v_p120;
double***restrictxx int_v_list0=int_v_list(0);
double**restrictxx int_v_list00=int_v_list0[0];
double*restrictxx int_v_list003=int_v_list00[3];
t2=t1*int_v_list003[0];
t3=int_v_p120-int_v_r10;
double*restrictxx int_v_list002=int_v_list00[2];
t4=t3*int_v_list002[0];
t5=t4+t2;
t2=0.5*int_v_ooze;
t4=t2*t5;
t6=int_v_W0-int_v_p340;
t7=t6*int_v_list003[0];
t8=int_v_p340-int_v_r30;
t9=t8*int_v_list002[0];
t10=t9+t7;
t7=int_v_zeta34*int_v_ooze;
t9=int_v_oo2zeta12*t7;
t7=(-1)*t9;
t9=t7*t10;
t11=t9+t4;
t12=t6*int_v_list002[0];
double*restrictxx int_v_list001=int_v_list00[1];
t13=t8*int_v_list001[0];
t14=t13+t12;
t12=int_v_oo2zeta12*t14;
t13=t12+t11;
t11=t2*int_v_list003[0];
double*restrictxx int_v_list004=int_v_list00[4];
t15=t6*int_v_list004[0];
t16=t8*int_v_list003[0];
t17=t16+t15;
t15=t1*t17;
t16=t15+t11;
t15=t3*t10;
t18=t15+t16;
t15=t1*t18;
t16=t15+t13;
t13=t2*int_v_list002[0];
t15=t1*t10;
t19=t15+t13;
t15=t3*t14;
t20=t15+t19;
t15=t3*t20;
t19=t15+t16;
t15=int_v_ooze*2;
t16=0.5*t15;
t21=t16*t19;
t22=t16*t10;
t23=int_v_zeta12*int_v_ooze;
t24=int_v_oo2zeta34*t23;
t23=t24*(-1);
t24=t23*int_v_list003[0];
t25=int_v_oo2zeta34*int_v_list002[0];
t26=t25+t24;
t24=t6*t17;
t25=t24+t26;
t24=t8*t10;
t27=t24+t25;
t24=t1*t27;
t25=t24+t22;
t22=t23*int_v_list002[0];
t24=int_v_oo2zeta34*int_v_list001[0];
t28=t24+t22;
t22=t6*t10;
t24=t22+t28;
t22=t8*t14;
t29=t22+t24;
t22=t3*t29;
t24=t22+t25;
t22=int_v_zeta34*t15;
t15=int_v_oo2zeta12*t22;
t22=(-1)*t15;
t15=t22*t24;
t25=t15+t21;
t15=t16*t14;
t21=t1*t29;
t30=t21+t15;
t15=t23*int_v_list001[0];
double*restrictxx int_v_list000=int_v_list00[0];
t21=int_v_oo2zeta34*int_v_list000[0];
t31=t21+t15;
t15=t6*t14;
t21=t15+t31;
t15=t6*int_v_list001[0];
t32=t8*int_v_list000[0];
t33=t32+t15;
t15=t8*t33;
t32=t15+t21;
t15=t3*t32;
t21=t15+t30;
t15=int_v_oo2zeta12*2;
t30=t15*t21;
t34=t30+t25;
t25=t16*t18;
t30=t7*t27;
t35=t30+t25;
t25=int_v_oo2zeta12*t29;
t36=t25+t35;
t35=t16*t17;
t37=t23*int_v_list004[0];
t23=int_v_oo2zeta34*int_v_list003[0];
t38=t23+t37;
double*restrictxx int_v_list005=int_v_list00[5];
t23=t6*int_v_list005[0];
t37=t8*int_v_list004[0];
t39=t37+t23;
t23=t6*t39;
t6=t23+t38;
t23=t8*t17;
t8=t23+t6;
t6=t1*t8;
t23=t6+t35;
t6=t3*t27;
t35=t6+t23;
t6=t1*t35;
t23=t6+t36;
t6=t3*t24;
t36=t6+t23;
t6=t1*t36;
t23=t6+t34;
t6=t16*t20;
t34=t7*t29;
t37=t34+t6;
t6=int_v_oo2zeta12*t32;
t40=t6+t37;
t37=t1*t24;
t41=t37+t40;
t37=t3*t21;
t40=t37+t41;
double***restrictxx int_v_list2=int_v_list(2);
double**restrictxx int_v_list22=int_v_list2[2];
double*restrictxx int_v_list220=int_v_list22[0];
int_v_list220[35]=t40;
t37=t3*t40;
t41=t37+t23;
double***restrictxx int_v_list3=int_v_list(3);
double**restrictxx int_v_list32=int_v_list3[2];
double*restrictxx int_v_list320=int_v_list32[0];
int_v_list320[59]=t41;
t23=int_v_W2-int_v_p342;
t37=t23*int_v_list003[0];
t42=int_v_p342-int_v_r32;
t43=t42*int_v_list002[0];
t44=t43+t37;
t37=t7*t44;
t43=t23*int_v_list002[0];
t45=t42*int_v_list001[0];
t46=t45+t43;
t43=int_v_oo2zeta12*t46;
t45=t43+t37;
t47=t23*int_v_list004[0];
t48=t42*int_v_list003[0];
t49=t48+t47;
t47=t1*t49;
t48=t3*t44;
t50=t48+t47;
t47=t1*t50;
t48=t47+t45;
t47=t1*t44;
t51=t3*t46;
t52=t51+t47;
t47=t3*t52;
t51=t47+t48;
t47=t2*t51;
t48=t23*t18;
t53=t42*t20;
t54=t53+t48;
t48=t22*t54;
t53=t48+t47;
t48=t23*t20;
t55=t2*int_v_list001[0];
t56=t1*t14;
t57=t56+t55;
t56=t3*t33;
t58=t56+t57;
t56=t42*t58;
t57=t56+t48;
t48=t15*t57;
t56=t48+t53;
t48=t2*t50;
t53=t23*t17;
t59=t42*t10;
t60=t59+t53;
t53=t7*t60;
t59=t53+t48;
t61=t23*t10;
t62=t42*t14;
t63=t62+t61;
t61=int_v_oo2zeta12*t63;
t62=t61+t59;
t59=t2*t49;
t64=t23*t39;
t65=t42*t17;
t66=t65+t64;
t64=t1*t66;
t65=t64+t59;
t64=t3*t60;
t67=t64+t65;
t64=t1*t67;
t65=t64+t62;
t62=t3*t54;
t64=t62+t65;
t62=t1*t64;
t65=t62+t56;
t56=t23*t19;
t62=t1*int_v_list002[0];
t68=t3*int_v_list001[0];
t69=t68+t62;
t62=t2*t69;
t68=t7*t14;
t70=t68+t62;
t71=int_v_oo2zeta12*t33;
t72=t71+t70;
t70=t1*t20;
t73=t70+t72;
t70=t3*t58;
t72=t70+t73;
double**restrictxx int_v_list21=int_v_list2[1];
double*restrictxx int_v_list210=int_v_list21[0];
int_v_list210[17]=t72;
t70=t42*t72;
t73=t70+t56;
int_v_list220[34]=t73;
t56=t3*t73;
t70=t56+t65;
int_v_list320[58]=t70;
t56=int_v_W1-int_v_p341;
t65=t56*int_v_list003[0];
t74=int_v_p341-int_v_r31;
t75=t74*int_v_list002[0];
t76=t75+t65;
t65=t7*t76;
t75=t56*int_v_list002[0];
t77=t74*int_v_list001[0];
t78=t77+t75;
t75=int_v_oo2zeta12*t78;
t77=t75+t65;
t79=t56*int_v_list004[0];
t80=t74*int_v_list003[0];
t81=t80+t79;
t79=t1*t81;
t80=t3*t76;
t82=t80+t79;
t79=t1*t82;
t80=t79+t77;
t79=t1*t76;
t83=t3*t78;
t84=t83+t79;
t79=t3*t84;
t83=t79+t80;
t79=t2*t83;
t80=t56*t18;
t85=t74*t20;
t86=t85+t80;
t80=t22*t86;
t85=t80+t79;
t80=t56*t20;
t87=t74*t58;
t88=t87+t80;
t80=t15*t88;
t87=t80+t85;
t80=t2*t82;
t85=t56*t17;
t89=t74*t10;
t90=t89+t85;
t85=t7*t90;
t89=t85+t80;
t91=t56*t10;
t92=t74*t14;
t93=t92+t91;
t91=int_v_oo2zeta12*t93;
t92=t91+t89;
t89=t2*t81;
t94=t56*t39;
t95=t74*t17;
t96=t95+t94;
t94=t1*t96;
t95=t94+t89;
t89=t3*t90;
t94=t89+t95;
t89=t1*t94;
t95=t89+t92;
t89=t3*t86;
t92=t89+t95;
t89=t1*t92;
t95=t89+t87;
t87=t56*t19;
t89=t74*t72;
t97=t89+t87;
int_v_list220[33]=t97;
t87=t3*t97;
t89=t87+t95;
int_v_list320[57]=t89;
t87=t23*t49;
t95=t26+t87;
t87=t42*t44;
t98=t87+t95;
t87=t1*t98;
t95=t23*t44;
t99=t28+t95;
t95=t42*t46;
t100=t95+t99;
t95=t3*t100;
t99=t95+t87;
t87=t22*t99;
t95=t1*t100;
t101=t23*t46;
t102=t31+t101;
t101=t23*int_v_list001[0];
t103=t42*int_v_list000[0];
t104=t103+t101;
t101=t42*t104;
t103=t101+t102;
t101=t3*t103;
t102=t101+t95;
t95=t15*t102;
t101=t95+t87;
t87=t7*t98;
t95=int_v_oo2zeta12*t100;
t105=t95+t87;
t106=t23*int_v_list005[0];
t107=t42*int_v_list004[0];
t108=t107+t106;
t106=t23*t108;
t107=t38+t106;
t106=t42*t49;
t108=t106+t107;
t106=t1*t108;
t107=t3*t98;
t109=t107+t106;
t106=t1*t109;
t107=t106+t105;
t106=t3*t99;
t110=t106+t107;
t106=t1*t110;
t107=t106+t101;
t101=t7*t100;
t106=int_v_oo2zeta12*t103;
t111=t106+t101;
t112=t1*t99;
t113=t112+t111;
t112=t3*t102;
t114=t112+t113;
int_v_list220[32]=t114;
t112=t3*t114;
t113=t112+t107;
int_v_list320[56]=t113;
t107=t23*t81;
t112=t42*t76;
t115=t112+t107;
t107=t1*t115;
t112=t23*t76;
t116=t42*t78;
t117=t116+t112;
t112=t3*t117;
t116=t112+t107;
t107=t22*t116;
t112=t23*t84;
t118=t1*t78;
t119=t56*int_v_list001[0];
t120=t74*int_v_list000[0];
t121=t120+t119;
t119=t3*t121;
t120=t119+t118;
t118=t42*t120;
t119=t118+t112;
t112=t15*t119;
t118=t112+t107;
t107=t7*t115;
t112=int_v_oo2zeta12*t117;
t117=t112+t107;
t122=t56*int_v_list005[0];
t123=t74*int_v_list004[0];
t124=t123+t122;
t122=t23*t124;
t123=t42*t81;
t125=t123+t122;
t122=t1*t125;
t123=t3*t115;
t126=t123+t122;
t122=t1*t126;
t123=t122+t117;
t117=t3*t116;
t122=t117+t123;
t117=t1*t122;
t123=t117+t118;
t117=t23*t83;
t118=t7*t78;
t127=int_v_oo2zeta12*t121;
t128=t127+t118;
t129=t1*t84;
t130=t129+t128;
t129=t3*t120;
t131=t129+t130;
int_v_list210[15]=t131;
t129=t42*t131;
t130=t129+t117;
int_v_list220[31]=t130;
t117=t3*t130;
t129=t117+t123;
int_v_list320[55]=t129;
t117=t56*t81;
t123=t26+t117;
t26=t74*t76;
t117=t26+t123;
t26=t1*t117;
t123=t56*t76;
t132=t28+t123;
t28=t74*t78;
t123=t28+t132;
t28=t3*t123;
t132=t28+t26;
t26=t22*t132;
t28=t1*t123;
t133=t56*t78;
t134=t31+t133;
t31=t74*t121;
t133=t31+t134;
t31=t3*t133;
t134=t31+t28;
t28=t15*t134;
t31=t28+t26;
t26=t7*t117;
t28=int_v_oo2zeta12*t123;
t135=t28+t26;
t136=t56*t124;
t137=t38+t136;
t38=t74*t81;
t136=t38+t137;
t38=t1*t136;
t137=t3*t117;
t138=t137+t38;
t38=t1*t138;
t137=t38+t135;
t38=t3*t132;
t139=t38+t137;
t38=t1*t139;
t137=t38+t31;
t31=t7*t123;
t38=int_v_oo2zeta12*t133;
t140=t38+t31;
t141=t1*t132;
t142=t141+t140;
t141=t3*t134;
t143=t141+t142;
int_v_list220[30]=t143;
t141=t3*t143;
t142=t141+t137;
int_v_list320[54]=t142;
t137=int_v_W2-int_v_p122;
t141=t137*t36;
t144=int_v_p122-int_v_r12;
t145=t144*t40;
t146=t145+t141;
int_v_list320[53]=t146;
t141=t2*t19;
t145=t137*t64;
t147=t145+t141;
t145=t144*t73;
t148=t145+t147;
int_v_list320[52]=t148;
t145=t137*t92;
t147=t144*t97;
t149=t147+t145;
int_v_list320[51]=t149;
t145=t16*t51;
t147=t137*t110;
t150=t147+t145;
t145=t144*t114;
t147=t145+t150;
int_v_list320[50]=t147;
t145=t137*t122;
t150=t79+t145;
t79=t144*t130;
t145=t79+t150;
int_v_list320[49]=t145;
t79=t137*t139;
t150=t144*t143;
t151=t150+t79;
int_v_list320[48]=t151;
t79=int_v_W1-int_v_p121;
t150=t36*t79;
t36=int_v_p121-int_v_r11;
t152=t36*t40;
t40=t152+t150;
int_v_list320[47]=t40;
t150=t79*t64;
t64=t36*t73;
t73=t64+t150;
int_v_list320[46]=t73;
t64=t79*t92;
t92=t141+t64;
t64=t36*t97;
t97=t64+t92;
int_v_list320[45]=t97;
t64=t79*t110;
t92=t36*t114;
t110=t92+t64;
int_v_list320[44]=t110;
t64=t79*t122;
t92=t47+t64;
t47=t36*t130;
t64=t47+t92;
int_v_list320[43]=t64;
t47=t16*t83;
t92=t79*t139;
t114=t92+t47;
t47=t36*t143;
t92=t47+t114;
int_v_list320[42]=t92;
t47=t7*t24;
t114=int_v_oo2zeta12*t21;
t122=t114+t47;
t47=t137*t35;
t114=t144*t24;
t130=t114+t47;
t47=t137*t130;
t114=t47+t122;
t47=t137*t24;
t130=t144*t21;
t139=t130+t47;
int_v_list220[29]=t139;
t47=t144*t139;
t130=t47+t114;
int_v_list320[41]=t130;
t47=t137*t18;
t114=t144*t20;
t139=t114+t47;
t47=t2*t139;
t114=t7*t54;
t141=t114+t47;
t47=int_v_oo2zeta12*t57;
t143=t47+t141;
t141=t2*t18;
t150=t137*t67;
t152=t150+t141;
t150=t144*t54;
t153=t150+t152;
t150=t137*t153;
t152=t150+t143;
t143=t2*t20;
t150=t137*t54;
t153=t150+t143;
t150=t144*t57;
t154=t150+t153;
int_v_list220[28]=t154;
t150=t144*t154;
t153=t150+t152;
int_v_list320[40]=t153;
t150=t7*t86;
t152=int_v_oo2zeta12*t88;
t154=t152+t150;
t155=t137*t94;
t156=t144*t86;
t157=t156+t155;
t155=t137*t157;
t156=t155+t154;
t154=t137*t86;
t155=t144*t88;
t157=t155+t154;
int_v_list220[27]=t157;
t154=t144*t157;
t155=t154+t156;
int_v_list320[39]=t155;
t154=t137*t50;
t156=t4+t154;
t154=t144*t52;
t157=t154+t156;
t154=t16*t157;
t156=t7*t99;
t158=t156+t154;
t154=int_v_oo2zeta12*t102;
t159=t154+t158;
t158=t16*t50;
t160=t137*t109;
t161=t160+t158;
t158=t144*t99;
t160=t158+t161;
t158=t137*t160;
t160=t158+t159;
t158=t16*t52;
t159=t137*t99;
t161=t159+t158;
t158=t144*t102;
t159=t158+t161;
int_v_list220[26]=t159;
t158=t144*t159;
t159=t158+t160;
int_v_list320[38]=t159;
t158=t137*t82;
t160=t144*t84;
t161=t160+t158;
t158=t2*t161;
t160=t7*t116;
t162=t160+t158;
t158=int_v_oo2zeta12*t119;
t163=t158+t162;
t162=t137*t126;
t164=t80+t162;
t80=t144*t116;
t162=t80+t164;
t80=t137*t162;
t162=t80+t163;
t80=t137*t116;
t163=t2*t84;
t164=t163+t80;
t80=t144*t119;
t119=t80+t164;
int_v_list220[25]=t119;
t80=t144*t119;
t119=t80+t162;
int_v_list320[37]=t119;
t80=t7*t132;
t162=int_v_oo2zeta12*t134;
t163=t162+t80;
t164=t137*t138;
t165=t144*t132;
t166=t165+t164;
t164=t137*t166;
t165=t164+t163;
t163=t137*t132;
t164=t144*t134;
t166=t164+t163;
int_v_list220[24]=t166;
t163=t144*t166;
t164=t163+t165;
int_v_list320[36]=t164;
t163=t79*t35;
t35=t36*t24;
t165=t35+t163;
t35=t137*t165;
t163=t79*t24;
t24=t36*t21;
t21=t24+t163;
int_v_list220[23]=t21;
t24=t144*t21;
t163=t24+t35;
int_v_list320[35]=t163;
t24=t79*t18;
t18=t36*t20;
t35=t18+t24;
t18=t2*t35;
t24=t79*t67;
t67=t36*t54;
t166=t67+t24;
t24=t137*t166;
t67=t24+t18;
t24=t79*t54;
t54=t36*t57;
t57=t54+t24;
int_v_list220[22]=t57;
t24=t144*t57;
t54=t24+t67;
int_v_list320[34]=t54;
t24=t79*t94;
t67=t141+t24;
t24=t36*t86;
t94=t24+t67;
t24=t137*t94;
t67=t79*t86;
t86=t143+t67;
t67=t36*t88;
t88=t67+t86;
int_v_list220[21]=t88;
t67=t144*t88;
t86=t67+t24;
int_v_list320[33]=t86;
t24=t79*t50;
t50=t36*t52;
t67=t50+t24;
t24=t16*t67;
t50=t79*t109;
t109=t36*t99;
t141=t109+t50;
t50=t137*t141;
t109=t50+t24;
t24=t79*t99;
t50=t36*t102;
t99=t50+t24;
int_v_list220[20]=t99;
t24=t144*t99;
t50=t24+t109;
int_v_list320[32]=t50;
t24=t79*t82;
t102=t4+t24;
t4=t36*t84;
t24=t4+t102;
t4=t2*t24;
t102=t79*t126;
t109=t48+t102;
t48=t36*t116;
t102=t48+t109;
t48=t137*t102;
t109=t48+t4;
t4=t23*t24;
t48=t79*t84;
t116=t62+t48;
t48=t36*t120;
t126=t48+t116;
int_v_list210[9]=t126;
t48=t42*t126;
t116=t48+t4;
int_v_list220[19]=t116;
t4=t144*t116;
t48=t4+t109;
int_v_list320[31]=t48;
t4=t16*t82;
t82=t79*t138;
t109=t82+t4;
t4=t36*t132;
t82=t4+t109;
t4=t137*t82;
t109=t16*t84;
t138=t79*t132;
t132=t138+t109;
t109=t36*t134;
t134=t109+t132;
int_v_list220[18]=t134;
t109=t144*t134;
t132=t109+t4;
int_v_list320[30]=t132;
t4=t79*t165;
t109=t122+t4;
t4=t36*t21;
t21=t4+t109;
int_v_list320[29]=t21;
t4=t47+t114;
t47=t79*t166;
t109=t47+t4;
t4=t36*t57;
t47=t4+t109;
int_v_list320[28]=t47;
t4=t150+t18;
t18=t152+t4;
t4=t79*t94;
t57=t4+t18;
t4=t36*t88;
t18=t4+t57;
int_v_list320[27]=t18;
t4=t154+t156;
t57=t79*t141;
t88=t57+t4;
t4=t36*t99;
t57=t4+t88;
int_v_list320[26]=t57;
t4=t2*t67;
t88=t160+t4;
t4=t158+t88;
t88=t79*t102;
t94=t88+t4;
t4=t36*t116;
t88=t4+t94;
int_v_list320[25]=t88;
t4=t16*t24;
t94=t80+t4;
t4=t162+t94;
t80=t79*t82;
t82=t80+t4;
t4=t36*t134;
t80=t4+t82;
int_v_list320[24]=t80;
t4=t137*t27;
t82=t144*t29;
t94=t82+t4;
t4=t22*t94;
t82=t137*t29;
t99=t144*t32;
t102=t99+t82;
t82=t15*t102;
t99=t82+t4;
t4=t25+t30;
t25=t137*t8;
t30=t144*t27;
t82=t30+t25;
t25=t137*t82;
t30=t25+t4;
t25=t144*t94;
t82=t25+t30;
t25=t137*t82;
t30=t25+t99;
t25=t6+t34;
t6=t137*t94;
t34=t6+t25;
t6=t144*t102;
t82=t6+t34;
int_v_list220[17]=t82;
t6=t144*t82;
t34=t6+t30;
int_v_list320[23]=t34;
t6=t12+t9;
t9=t137*t17;
t12=t144*t10;
t30=t12+t9;
t9=t137*t30;
t12=t9+t6;
t9=t137*t10;
t82=t144*t14;
t94=t82+t9;
t9=t144*t94;
t82=t9+t12;
t9=3*int_v_ooze;
t12=t9*0.5;
t9=t12*t82;
t99=t22*t30;
t102=t15*t94;
t109=t102+t99;
t99=t7*t17;
t102=int_v_oo2zeta12*t10;
t114=t102+t99;
t99=t137*t39;
t39=t144*t17;
t102=t39+t99;
t39=t137*t102;
t99=t39+t114;
t39=t144*t30;
t30=t39+t99;
t39=t137*t30;
t30=t39+t109;
t39=t144*t82;
t99=t39+t30;
t30=t23*t99;
t39=t30+t9;
t9=t22*t94;
t30=t137*t14;
t102=t144*t33;
t109=t102+t30;
t30=t15*t109;
t102=t30+t9;
t9=t137*t82;
t30=t9+t102;
t9=t71+t68;
t68=t137*t94;
t71=t68+t9;
t68=t144*t109;
t102=t68+t71;
int_v_list210[8]=t102;
t68=t144*t102;
t71=t68+t30;
double**restrictxx int_v_list31=int_v_list3[1];
double*restrictxx int_v_list310=int_v_list31[0];
int_v_list310[11]=t71;
t30=t42*t71;
t68=t30+t39;
int_v_list320[22]=t68;
t30=t56*t99;
t39=t74*t71;
t71=t39+t30;
int_v_list320[21]=t71;
t30=t137*int_v_list003[0];
t39=t144*int_v_list002[0];
t99=t39+t30;
t30=t2*t99;
t39=t37+t30;
t30=t43+t39;
t37=t137*t49;
t39=t11+t37;
t37=t144*t44;
t43=t37+t39;
t37=t137*t43;
t39=t37+t30;
t30=t137*t44;
t37=t13+t30;
t30=t144*t46;
t109=t30+t37;
t30=t144*t109;
t37=t30+t39;
t30=t16*t37;
t39=t16*t44;
t114=t137*t98;
t116=t114+t39;
t39=t144*t100;
t114=t39+t116;
t39=t22*t114;
t116=t39+t30;
t30=t16*t46;
t39=t137*t100;
t122=t39+t30;
t30=t144*t103;
t39=t30+t122;
t30=t15*t39;
t122=t30+t116;
t30=t16*t43;
t43=t87+t30;
t30=t95+t43;
t43=t16*t49;
t87=t137*t108;
t95=t87+t43;
t43=t144*t98;
t87=t43+t95;
t43=t137*t87;
t87=t43+t30;
t30=t144*t114;
t43=t30+t87;
t30=t137*t43;
t43=t30+t122;
t30=t16*t109;
t87=t101+t30;
t30=t106+t87;
t87=t137*t114;
t95=t87+t30;
t30=t144*t39;
t39=t30+t95;
int_v_list220[14]=t39;
t30=t144*t39;
t39=t30+t43;
int_v_list320[20]=t39;
t30=t137*t81;
t43=t144*t76;
t87=t43+t30;
t30=t137*t87;
t43=t77+t30;
t30=t137*t76;
t77=t144*t78;
t95=t77+t30;
t30=t144*t95;
t77=t30+t43;
t30=t12*t77;
t12=t22*t87;
t43=t15*t95;
t101=t43+t12;
t12=t137*t124;
t43=t144*t81;
t106=t43+t12;
t12=t137*t106;
t43=t7*t81;
t106=int_v_oo2zeta12*t76;
t114=t106+t43;
t43=t114+t12;
t12=t144*t87;
t87=t12+t43;
t12=t137*t87;
t43=t12+t101;
t12=t144*t77;
t87=t12+t43;
t12=t23*t87;
t43=t12+t30;
t12=t22*t95;
t30=t137*t78;
t87=t144*t121;
t101=t87+t30;
t30=t15*t101;
t87=t30+t12;
t12=t137*t77;
t30=t12+t87;
t12=t137*t95;
t87=t128+t12;
t12=t144*t101;
t101=t12+t87;
int_v_list210[6]=t101;
t12=t144*t101;
t87=t12+t30;
int_v_list310[9]=t87;
t12=t42*t87;
t30=t12+t43;
int_v_list320[19]=t30;
t12=t137*t117;
t43=t144*t123;
t87=t43+t12;
t12=t22*t87;
t43=t137*t123;
t106=t144*t133;
t114=t106+t43;
t43=t15*t114;
t106=t43+t12;
t12=t137*t136;
t43=t144*t117;
t116=t43+t12;
t12=t137*t116;
t43=t135+t12;
t12=t144*t87;
t116=t12+t43;
t12=t137*t116;
t43=t12+t106;
t12=t137*t87;
t87=t140+t12;
t12=t144*t114;
t106=t12+t87;
int_v_list220[12]=t106;
t12=t144*t106;
t87=t12+t43;
int_v_list320[18]=t87;
t12=t79*t27;
t43=t36*t29;
t106=t43+t12;
t12=t7*t106;
t43=t79*t29;
t29=t36*t32;
t32=t29+t43;
t29=int_v_oo2zeta12*t32;
t43=t29+t12;
t12=t79*t8;
t8=t36*t27;
t27=t8+t12;
t8=t137*t27;
t12=t144*t106;
t29=t12+t8;
t8=t137*t29;
t12=t8+t43;
t8=t137*t106;
t29=t144*t32;
t43=t29+t8;
int_v_list220[11]=t43;
t8=t144*t43;
t29=t8+t12;
int_v_list320[17]=t29;
t8=t79*t60;
t12=t36*t63;
t43=t12+t8;
t8=t7*t43;
t12=t79*t17;
t63=t36*t10;
t114=t63+t12;
t12=t137*t114;
t63=t79*t10;
t116=t36*t14;
t122=t116+t63;
t63=t144*t122;
t116=t63+t12;
t12=t2*t116;
t63=t12+t8;
t8=t23*t122;
t12=t79*t14;
t124=t36*t33;
t33=t124+t12;
t12=t42*t33;
t124=t12+t8;
t8=int_v_oo2zeta12*t124;
t12=t8+t63;
t8=t79*t66;
t63=t36*t60;
t60=t63+t8;
t8=t137*t60;
t63=t2*t114;
t66=t63+t8;
t8=t144*t43;
t128=t8+t66;
t8=t137*t128;
t66=t8+t12;
t8=t137*t43;
t12=t2*t122;
t128=t12+t8;
t8=t144*t124;
t12=t8+t128;
int_v_list220[10]=t12;
t8=t144*t12;
t12=t8+t66;
int_v_list320[16]=t12;
t8=t79*t90;
t66=t2*t10;
t10=t66+t8;
t8=t36*t93;
t66=t8+t10;
t8=t7*t66;
t10=t56*t122;
t93=t2*t14;
t14=t93+t10;
t10=t74*t33;
t93=t10+t14;
t10=int_v_oo2zeta12*t93;
t14=t10+t8;
t8=t79*t96;
t10=t2*t17;
t17=t10+t8;
t8=t36*t90;
t10=t8+t17;
t8=t137*t10;
t17=t144*t66;
t90=t17+t8;
t8=t137*t90;
t17=t8+t14;
t8=t137*t66;
t14=t144*t93;
t90=t14+t8;
int_v_list220[9]=t90;
t8=t144*t90;
t14=t8+t17;
int_v_list320[15]=t14;
t8=t79*t49;
t17=t36*t44;
t49=t17+t8;
t8=t137*t49;
t17=t79*int_v_list003[0];
t90=t36*int_v_list002[0];
t96=t90+t17;
t17=t2*t96;
t90=t17+t8;
t8=t79*t44;
t44=t36*t46;
t128=t44+t8;
t8=t144*t128;
t44=t8+t90;
t8=t16*t44;
t90=t79*t98;
t134=t36*t100;
t135=t134+t90;
t90=t7*t135;
t134=t90+t8;
t8=t79*t100;
t90=t36*t103;
t100=t90+t8;
t8=int_v_oo2zeta12*t100;
t90=t8+t134;
t8=t16*t49;
t103=t79*t108;
t108=t36*t98;
t98=t108+t103;
t103=t137*t98;
t108=t103+t8;
t8=t144*t135;
t103=t8+t108;
t8=t137*t103;
t103=t8+t90;
t8=t16*t128;
t90=t137*t135;
t108=t90+t8;
t8=t144*t100;
t90=t8+t108;
int_v_list220[8]=t90;
t8=t144*t90;
t90=t8+t103;
int_v_list320[14]=t90;
t8=t79*t81;
t103=t11+t8;
t8=t36*t76;
t11=t8+t103;
t8=t137*t11;
t103=t79*t76;
t108=t13+t103;
t13=t36*t78;
t103=t13+t108;
t13=t144*t103;
t108=t13+t8;
t8=t2*t108;
t13=t23*t11;
t134=t42*t103;
t138=t134+t13;
t13=t7*t138;
t134=t13+t8;
t8=t23*t103;
t13=t79*t78;
t140=t55+t13;
t13=t36*t121;
t121=t13+t140;
t13=t42*t121;
t140=t13+t8;
t8=int_v_oo2zeta12*t140;
t13=t8+t134;
t8=t2*t11;
t134=t79*t125;
t125=t59+t134;
t59=t36*t115;
t115=t59+t125;
t59=t137*t115;
t125=t59+t8;
t8=t144*t138;
t59=t8+t125;
t8=t137*t59;
t59=t8+t13;
t8=t2*t103;
t13=t137*t138;
t125=t13+t8;
t8=t144*t140;
t13=t8+t125;
int_v_list220[7]=t13;
t8=t144*t13;
t13=t8+t59;
int_v_list320[13]=t13;
t8=t16*t76;
t59=t79*t117;
t76=t59+t8;
t8=t36*t123;
t59=t8+t76;
t8=t7*t59;
t76=t16*t78;
t78=t79*t123;
t123=t78+t76;
t76=t36*t133;
t78=t76+t123;
t76=int_v_oo2zeta12*t78;
t123=t76+t8;
t8=t16*t81;
t76=t79*t136;
t81=t76+t8;
t8=t36*t117;
t76=t8+t81;
t8=t137*t76;
t81=t144*t59;
t117=t81+t8;
t8=t137*t117;
t81=t8+t123;
t8=t137*t59;
t117=t144*t78;
t123=t117+t8;
int_v_list220[6]=t123;
t8=t144*t123;
t117=t8+t81;
int_v_list320[12]=t117;
t8=t79*t27;
t27=t4+t8;
t4=t36*t106;
t8=t4+t27;
t4=t137*t8;
t27=t79*t106;
t81=t25+t27;
t25=t36*t32;
t27=t25+t81;
int_v_list220[5]=t27;
t25=t144*t27;
t81=t25+t4;
int_v_list320[11]=t81;
t4=t61+t53;
t25=t79*t60;
t53=t25+t4;
t4=t36*t43;
t25=t4+t53;
t4=t137*t25;
t53=t79*t114;
t60=t6+t53;
t6=t36*t122;
t53=t6+t60;
t6=t2*t53;
t60=t6+t4;
t4=t23*t53;
t61=t79*t122;
t114=t9+t61;
t9=t36*t33;
t61=t9+t114;
int_v_list210[2]=t61;
t9=t42*t61;
t114=t9+t4;
int_v_list220[4]=t114;
t4=t144*t114;
t9=t4+t60;
int_v_list320[10]=t9;
t4=t85+t63;
t60=t91+t4;
t4=t79*t10;
t10=t4+t60;
t4=t36*t66;
t60=t4+t10;
t4=t137*t60;
t10=t16*t122;
t63=t56*t53;
t85=t63+t10;
t10=t74*t61;
t63=t10+t85;
int_v_list220[3]=t63;
t10=t144*t63;
t85=t10+t4;
int_v_list320[9]=t85;
t4=t79*t49;
t10=t45+t4;
t4=t36*t128;
t45=t4+t10;
t4=t16*t45;
t10=t79*t98;
t91=t105+t10;
t10=t36*t135;
t98=t10+t91;
t10=t137*t98;
t91=t10+t4;
t4=t79*t135;
t10=t111+t4;
t4=t36*t100;
t105=t4+t10;
int_v_list220[2]=t105;
t4=t144*t105;
t10=t4+t91;
int_v_list320[8]=t10;
t4=t65+t17;
t17=t75+t4;
t4=t79*t11;
t65=t4+t17;
t4=t36*t103;
t17=t4+t65;
t4=t2*t17;
t65=t2*t49;
t49=t107+t65;
t65=t112+t49;
t49=t79*t115;
t75=t49+t65;
t49=t36*t138;
t65=t49+t75;
t49=t137*t65;
t75=t49+t4;
t4=t23*t17;
t49=t36*int_v_list001[0];
t91=t79*int_v_list002[0];
t107=t91+t49;
t49=t2*t107;
t91=t118+t49;
t111=t127+t91;
t91=t79*t103;
t112=t91+t111;
t91=t36*t121;
t111=t91+t112;
int_v_list210[0]=t111;
t91=t42*t111;
t112=t91+t4;
int_v_list220[1]=t112;
t4=t144*t112;
t91=t4+t75;
int_v_list320[7]=t91;
t4=t16*t11;
t11=t26+t4;
t4=t28+t11;
t11=t79*t76;
t26=t11+t4;
t4=t36*t59;
t11=t4+t26;
t4=t137*t11;
t26=t16*t103;
t28=t31+t26;
t26=t38+t28;
t28=t79*t59;
t31=t28+t26;
t26=t36*t78;
t28=t26+t31;
int_v_list220[0]=t28;
t26=t144*t28;
t31=t26+t4;
int_v_list320[6]=t31;
t4=t22*t106;
t26=t15*t32;
t32=t26+t4;
t4=t79*t8;
t8=t4+t32;
t4=t36*t27;
t26=t4+t8;
int_v_list320[5]=t26;
t4=t22*t43;
t8=t15*t124;
t27=t8+t4;
t4=t79*t25;
t8=t4+t27;
t4=t36*t114;
t25=t4+t8;
int_v_list320[4]=t25;
t4=t22*t66;
t8=t6+t4;
t4=t15*t93;
t6=t4+t8;
t4=t79*t60;
t8=t4+t6;
t4=t36*t63;
t6=t4+t8;
int_v_list320[3]=t6;
t4=t22*t135;
t8=t15*t100;
t27=t8+t4;
t4=t79*t98;
t8=t4+t27;
t4=t36*t105;
t27=t4+t8;
int_v_list320[2]=t27;
t4=t22*t138;
t8=t2*t45;
t32=t8+t4;
t4=t15*t140;
t8=t4+t32;
t4=t79*t65;
t32=t4+t8;
t4=t36*t112;
t8=t4+t32;
int_v_list320[1]=t8;
t4=t16*t17;
t32=t22*t59;
t38=t32+t4;
t4=t15*t78;
t32=t4+t38;
t4=t79*t11;
t11=t4+t32;
t4=t36*t28;
t28=t4+t11;
int_v_list320[0]=t28;
t4=t7*int_v_list002[0];
t11=int_v_oo2zeta12*int_v_list001[0];
t32=t11+t4;
t4=t1*t5;
t11=t4+t32;
t4=t3*t69;
t38=t4+t11;
t4=t2*t38;
t11=t22*t20;
t38=t11+t4;
t11=t15*t58;
t43=t11+t38;
t11=t1*t19;
t38=t11+t43;
t11=t3*t72;
t43=t11+t38;
int_v_list310[29]=t43;
t11=t22*t52;
t38=t1*t46;
t59=t3*t104;
t60=t59+t38;
t38=t15*t60;
t59=t38+t11;
t11=t1*t51;
t38=t11+t59;
t11=t7*t46;
t59=int_v_oo2zeta12*t104;
t63=t59+t11;
t65=t1*t52;
t66=t65+t63;
t65=t3*t60;
t75=t65+t66;
int_v_list210[16]=t75;
t65=t3*t75;
t66=t65+t38;
int_v_list310[28]=t66;
t38=t22*t84;
t65=t15*t120;
t76=t65+t38;
t38=t1*t83;
t1=t38+t76;
t38=t3*t131;
t3=t38+t1;
int_v_list310[27]=t3;
t1=t137*t19;
t38=t144*t72;
t65=t38+t1;
int_v_list310[26]=t65;
t1=t137*t51;
t38=t4+t1;
t1=t144*t75;
t76=t1+t38;
int_v_list310[25]=t76;
t1=t137*t83;
t38=t144*t131;
t78=t38+t1;
int_v_list310[24]=t78;
t1=t79*t19;
t19=t36*t72;
t38=t19+t1;
int_v_list310[23]=t38;
t1=t79*t51;
t19=t36*t75;
t51=t19+t1;
int_v_list310[22]=t51;
t1=t79*t83;
t19=t4+t1;
t1=t36*t131;
t4=t1+t19;
int_v_list310[21]=t4;
t1=t7*t20;
t19=int_v_oo2zeta12*t58;
t72=t19+t1;
t1=t137*t139;
t19=t1+t72;
t1=t137*t20;
t75=t144*t58;
t83=t75+t1;
int_v_list210[14]=t83;
t1=t144*t83;
t75=t1+t19;
int_v_list310[20]=t75;
t1=t137*t5;
t19=t144*t69;
t83=t19+t1;
t1=t2*t83;
t19=t7*t52;
t83=t19+t1;
t1=int_v_oo2zeta12*t60;
t93=t1+t83;
t83=t137*t157;
t98=t83+t93;
t83=t137*t52;
t93=t62+t83;
t62=t144*t60;
t83=t62+t93;
int_v_list210[13]=t83;
t62=t144*t83;
t83=t62+t98;
int_v_list310[19]=t83;
t62=t7*t84;
t93=int_v_oo2zeta12*t120;
t98=t93+t62;
t100=t137*t161;
t105=t100+t98;
t98=t137*t84;
t84=t144*t120;
t100=t84+t98;
int_v_list210[12]=t100;
t84=t144*t100;
t98=t84+t105;
int_v_list310[18]=t98;
t84=t137*t35;
t100=t79*t20;
t20=t36*t58;
t58=t20+t100;
int_v_list210[11]=t58;
t20=t144*t58;
t100=t20+t84;
int_v_list310[17]=t100;
t20=t79*t5;
t5=t36*t69;
t69=t5+t20;
t5=t2*t69;
t20=t137*t67;
t69=t20+t5;
t20=t79*t52;
t52=t36*t60;
t60=t52+t20;
int_v_list210[10]=t60;
t20=t144*t60;
t52=t20+t69;
int_v_list310[16]=t52;
t20=t137*t24;
t69=t144*t126;
t84=t69+t20;
int_v_list310[15]=t84;
t20=t79*t35;
t35=t72+t20;
t20=t36*t58;
t58=t20+t35;
int_v_list310[14]=t58;
t20=t1+t19;
t1=t79*t67;
t19=t1+t20;
t1=t36*t60;
t20=t1+t19;
int_v_list310[13]=t20;
t1=t62+t5;
t5=t93+t1;
t1=t79*t24;
t19=t1+t5;
t1=t36*t126;
t5=t1+t19;
int_v_list310[12]=t5;
t1=t22*t109;
t19=t137*t99;
t24=t32+t19;
t19=t137*int_v_list002[0];
t35=t144*int_v_list001[0];
t60=t35+t19;
t19=t144*t60;
t35=t19+t24;
t19=t2*t35;
t24=t19+t1;
t1=t137*t46;
t19=t55+t1;
t1=t144*t104;
t35=t1+t19;
t1=t15*t35;
t19=t1+t24;
t1=t137*t37;
t24=t1+t19;
t1=t2*t60;
t19=t11+t1;
t1=t59+t19;
t11=t137*t109;
t19=t11+t1;
t1=t144*t35;
t11=t1+t19;
int_v_list210[7]=t11;
t1=t144*t11;
t11=t1+t24;
int_v_list310[10]=t11;
t1=t7*t122;
t19=int_v_oo2zeta12*t33;
t24=t19+t1;
t1=t137*t116;
t19=t1+t24;
t1=t137*t122;
t24=t144*t33;
t35=t24+t1;
int_v_list210[5]=t35;
t1=t144*t35;
t24=t1+t19;
int_v_list310[8]=t24;
t1=t7*t128;
t19=t137*t96;
t35=t144*t107;
t37=t35+t19;
t19=t2*t37;
t35=t19+t1;
t1=t79*t46;
t19=t36*t104;
t37=t19+t1;
t1=int_v_oo2zeta12*t37;
t19=t1+t35;
t1=t137*t44;
t35=t1+t19;
t1=t137*t128;
t19=t49+t1;
t1=t144*t37;
t44=t1+t19;
int_v_list210[4]=t44;
t1=t144*t44;
t19=t1+t35;
int_v_list310[7]=t19;
t1=t7*t103;
t7=int_v_oo2zeta12*t121;
t35=t7+t1;
t1=t137*t108;
t7=t1+t35;
t1=t137*t103;
t35=t144*t121;
t44=t35+t1;
int_v_list210[3]=t44;
t1=t144*t44;
t35=t1+t7;
int_v_list310[6]=t35;
t1=t137*t53;
t7=t144*t61;
t44=t7+t1;
int_v_list310[5]=t44;
t1=t137*t45;
t7=t79*t96;
t46=t32+t7;
t7=t36*t107;
t32=t7+t46;
t7=t2*t32;
t2=t7+t1;
t1=t79*t128;
t32=t63+t1;
t1=t36*t37;
t46=t1+t32;
int_v_list210[1]=t46;
t1=t144*t46;
t32=t1+t2;
int_v_list310[4]=t32;
t1=t137*t17;
t2=t144*t111;
t49=t2+t1;
int_v_list310[3]=t49;
t1=t22*t122;
t2=t15*t33;
t33=t2+t1;
t1=t79*t53;
t2=t1+t33;
t1=t36*t61;
t33=t1+t2;
int_v_list310[2]=t33;
t1=t22*t128;
t2=t15*t37;
t37=t2+t1;
t1=t79*t45;
t2=t1+t37;
t1=t36*t46;
t37=t1+t2;
int_v_list310[1]=t37;
t1=t22*t103;
t2=t7+t1;
t1=t15*t121;
t7=t1+t2;
t1=t79*t17;
t2=t1+t7;
t1=t36*t111;
t7=t1+t2;
int_v_list310[0]=t7;
t1=t16*t94;
t2=t23*t82;
t15=t2+t1;
t1=t42*t102;
t2=t1+t15;
int_v_list220[16]=t2;
t1=t56*t82;
t15=t74*t102;
t17=t15+t1;
int_v_list220[15]=t17;
t1=t16*t95;
t15=t23*t77;
t16=t15+t1;
t1=t42*t101;
t15=t1+t16;
int_v_list220[13]=t15;
return 1;}
| gpl-2.0 |
kxgames/kingdoms-of-life | demos/texture.py | 4535 | #!/usr/bin/env python
# For now, only make a simplified flat map with three types: Land,
# Water, and Mountain.
class Map:
def __init__(self):
self.size = (0,0)
self.tile_width = 64
self.tiles = None
def setup(self, n_cols, n_rows):
self.size = (n_cols, n_rows)
self.generate_simple()
#self.generate_wander()
def generate_simple(self):
n_cols, n_rows = self.size
self.tiles = [[ Tile() for x in range(n_cols)] for y in range(n_rows)]
for x in range(n_cols):
for y in range(n_rows//2):
if x < n_cols//2:
self.tiles[y][x].land_type = 'Water'
else:
self.tiles[y+n_rows//2+n_rows%2][x].land_type = 'Mountain'
def get_type(self, col, row):
return self.tiles[row][col].land_type
class Tile:
def __init__(self):
self.land_type = 'Land'
if __name__ == '__main__':
import ctypes
import pyglet
import pyglet.gl as gl
bin = pyglet.image.atlas.TextureBin()
def path_to_array(path):
from matplotlib.pyplot import imread
buffer = 255 * imread(path)
buffer = buffer.astype('uint8')
return buffer
def array_to_texture(buffer):
width, height = buffer.shape[0:2]
data, stride = buffer.tostring(), -buffer.strides[0]
image = pyglet.image.ImageData(width, height, 'RGBA', data, stride)
return bin.add(image)
def load_image(path):
buffer = path_to_array(path)
return array_to_texture(buffer)
# Run tests
map = Map()
map.setup(25,25)
batch = pyglet.graphics.Batch()
#grass_img = pyglet.image.load('images/map/grass-64-res.png')
#grass_img = pyglet.image.load('images/map/grass-64-res.png').get_data('ub', 64)
#texture_id = gl.glGenTextures(1, ctypes.byref(gl.GLuint()))
#gl.glBindTexture(gl.GL_TEXTURE_2D, texture_id)
#gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR)
#gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR)
#gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, 64, 64, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, grass_img)
#
#grass_tex = grass_img.get_texture()
size = map.size
width = map.tile_width
offset = width / 2.0
icon = load_image('grass-64-res.png')
tile_sprites = []
grass = pyglet.resource.image('grass-64-res.png')
grass = pyglet.resource.image('grass-64-res.png')
tileset = pyglet.image.load('outdoor-tileset.png')
tiles = pyglet.image.ImageGrid(explosion, 6, 16)
grass = tiles[4, 1] # Also (4,10) (4,11) (5,10) (5,11)
water = tiles[3, 3]
for tile_x in range(size[0]):
for tile_y in range(size[1]):
dx,dy = -offset, -offset
x = tile_x * width + dx
y = tile_y * width + dy
tile_sprites.append(pyglet.sprite.Sprite(
icon,
x=x, y=y,
batch=batch))
#vertex_count = 4 * size[0] * size[1]
#gl.glEnable(grass_tex.target)
#gl.glBindTexture(grass_tex.target, grass_tex.id)
#vlist = batch.add(4, gl.GL_QUADS, None, 'v2f', 't2f')
#
#vlist.vertices[0:8] = [0,0, 320,0, 320,320, 0,320]
#vlist.tex_coords[0:8] = [0,0, 1,0, 1,1, 0,1]
#
##self.vertex_list = batch.add(vertex_count, GL_QUADS, layer, 'v2f', 't2f')
##for tile_x in range(size[0]):
## for tile_y in range(size[1]):
## # i initially is the first position of the tile in the
## # 2D vertex list. The corner for loop increments i by 2
## # because each coordinate takes two spots in the vertex
## # list.
## i = 2 * (4 * (y * size[0] + x) + corner)
## tile_type = self.map.get_type(tile_x, tile_y)
## pyglet.gl.glBindTexture(grass_tex.target, grass_tex.id)
## for corner in (-1,-1), (1,-1), (1,1), (-1,1):
## dx,dy = corner
## x = tile_x + dx * tile_half_width
## y = tile_y + dy * tile_half_width
## vlist.vertices[i:i+2] = [x, y]
## tx, ty = corner
## tx = (tx + 1) / 2.0
## ty = (ty + 1) / 2.0
## vlist.tex_coords[i:i+2] = [tx,ty]
## i += 2;
#pyglet.gl.glDisable(grass_tex.target)
window = pyglet.window.Window(320,320)
@window.event
def on_draw():
batch.draw()
pyglet.app.run()
| gpl-2.0 |
exic/last.fm-dbus | src/libMoose/LastFmSettings.cpp | 17287 | /***************************************************************************
* Copyright (C) 2005 - 2007 by *
* Last.fm Ltd <client@last.fm> *
* *
* 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 Steet, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
#include "LastFmSettings.h"
#include "UnicornCommon.h" // md5Digest
#include "MooseCommon.h"
#include "Settings.h"
#include "Station.h"
#include "logger.h"
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#ifdef Q_WS_MAC
#include <ApplicationServices/ApplicationServices.h>
#endif
/******************************************************************************
* LastFmUserSettings
******************************************************************************/
MooseEnums::UserIconColour
LastFmUserSettings::icon() const
{
MyQSettings s( this );
// This will return eRed if there is no entry. Don't want that.
if (s.contains( "Icon" ))
return (MooseEnums::UserIconColour) s.value( "Icon" ).toInt();
else
return MooseEnums::eNone;
}
void
LastFmUserSettings::setIcon( MooseEnums::UserIconColour colour )
{
MyQSettings( this ).setValue( "Icon", static_cast<int>(colour) );
emit userChanged( username() );
}
/// Written as int for backwards compatibility with the MFC Audioscrobbler
bool
LastFmUserSettings::isLogToProfile() const
{
return static_cast<bool>(MyQSettings( this ).value( "LogToProfile", 1 ).toInt());
}
/// Written as int for backwards compatibility with the MFC Audioscrobbler
void
LastFmUserSettings::setLogToProfile( bool state )
{
MyQSettings( this ).setValue( "LogToProfile", static_cast<int>(state) );
emit userChanged( username() );
}
bool
LastFmUserSettings::isDiscovery() const
{
return MyQSettings( this ).value( "DiscoveryEnabled", false ).toBool();
}
void
LastFmUserSettings::setDiscovery( bool state )
{
MyQSettings( this ).setValue( "DiscoveryEnabled", state );
emit userChanged( username() );
}
bool
LastFmUserSettings::sidebarEnabled() const
{
return MyQSettings( this ).value( "SidebarEnabled", false ).toBool();
}
void
LastFmUserSettings::setSidebarEnabled( bool state )
{
MyQSettings( this ).setValue( "SidebarEnabled", state );
emit userChanged( username() );
}
void
LastFmUserSettings::setResumePlayback( bool enabled )
{
MyQSettings( this ).setValue( "resumeplayback", enabled ? "1" : "0" );
emit userChanged( username() );
}
void
LastFmUserSettings::setResumeStation( StationUrl station )
{
MyQSettings( this ).setValue( "resumestation", station );
emit userChanged( username() );
}
void
LastFmUserSettings::addRecentStation( const Station& station )
{
MyQSettings s( this );
QList<Station> stations = recentStations();
// remove duplicates
for ( int i = 0; i < stations.count(); ++i )
if ( stations[i].url() == station.url() )
stations.removeAt( i-- );
stations.prepend( station );
s.remove( "RecentStations" );
s.beginGroup( "RecentStations" );
int j = stations.count();
while (j--)
s.setValue( QString::number( j ), stations[j].url() );
s.endGroup();
s.setValue( "StationNames/" + station.url(), station.name() );
s.sync();
emit userChanged( username() );
emit historyChanged();
}
void
LastFmUserSettings::removeRecentStation( int n )
{
MyQSettings s( this );
QString const N = QString::number( n );
s.beginGroup( "RecentStations" );
QString const url = s.value( N ).toString();
s.remove( N );
// now renumber in correct order (maps are auto-sorted by key)
QMap<int, QString> urls;
foreach (QString key, s.childKeys())
urls[key.toInt()] = s.value( key ).toString();
s.remove( "" ); //current group
int i = 0;
foreach (QString url, urls)
s.setValue( QString::number( i++ ), url );
s.endGroup();
s.remove( "StationNames/" + url );
s.sync();
emit userChanged( username() );
emit historyChanged();
}
void
LastFmUserSettings::clearRecentStations( bool emitting )
{
MyQSettings( this ).remove( "RecentStations" );
//TODO needed still?
if ( emitting )
emit historyChanged();
}
QList<Station>
LastFmUserSettings::recentStations()
{
MyQSettings s( this );
s.beginGroup( "RecentStations" );
QStringList const keys = s.childKeys();
s.endGroup();
QMap<int, Station> stations;
foreach (QString key, keys) {
Station station;
station.setUrl( s.value( "RecentStations/" + key ).toString() );
station.setName( s.value( "StationNames/" + station.url() ).toString() );
stations[key.toInt()] = station;
}
return stations.values();
}
void
LastFmUserSettings::setExcludedDirs( QStringList dirs )
{
#ifdef WIN32
QMutableStringListIterator i( dirs );
while (i.hasNext()) {
QString& s = i.next();
s = s.toLower();
}
#endif
MyQSettings( this ).setValue( "ExclusionDirs", dirs );
emit userChanged( username() );
}
QStringList
LastFmUserSettings::excludedDirs() const
{
QStringList paths = MyQSettings( this ).value( "ExclusionDirs" ).toStringList();
paths.removeAll( "" );
return paths;
}
void
LastFmUserSettings::setIncludedDirs( QStringList dirs )
{
MyQSettings( this ).setValue( "InclusionDirs", dirs );
emit userChanged( username() );
}
QString
LastFmUserSettings::bootStrapPluginId() const
{
return MyQSettings( this ).value( "BootStrapPluginId" ).toString();
}
void
LastFmUserSettings::setBootStrapPluginId( QString id )
{
MyQSettings( this ).setValue( "BootStrapPluginId", id );
emit userChanged( username() );
}
QStringList
LastFmUserSettings::includedDirs() const
{
return MyQSettings( this ).value( "InclusionDirs" ).toStringList();
}
void
LastFmUserSettings::setMetaDataEnabled( bool enabled )
{
MyQSettings( this ).setValue( "DownloadMetadata", enabled );
emit userChanged( username() );
}
bool
LastFmUserSettings::isMetaDataEnabled()
{
return MyQSettings( this ).value( "DownloadMetadata", true ).toBool();
}
void
LastFmUserSettings::setCrashReportingEnabled( bool enabled )
{
MyQSettings( this ).setValue( "ReportCrashes", enabled );
emit userChanged( username() );
}
bool
LastFmUserSettings::crashReportingEnabled()
{
return MyQSettings( this ).value( "ReportCrashes", true ).toBool();
}
void
LastFmUserSettings::setScrobblePoint( int scrobblePoint )
{
MyQSettings( this ).setValue( "ScrobblePoint", scrobblePoint );
emit userChanged( username() );
}
int
LastFmUserSettings::scrobblePoint()
{
return MyQSettings( this ).value( "ScrobblePoint", MooseDefaults::kScrobblePoint ).toInt();
}
void
LastFmUserSettings::setFingerprintingEnabled( bool enabled )
{
MyQSettings( this ).setValue( "Fingerprint", enabled );
emit userChanged( username() );
}
bool
LastFmUserSettings::fingerprintingEnabled()
{
return MyQSettings( this ).value( "Fingerprint", true ).toBool();
}
void
LastFmUserSettings::setTrackFrameClockMode( bool trackTimeEnabled )
{
MyQSettings( this ).setValue( "TrackFrameShowsTrackTime", trackTimeEnabled );
emit userChanged( username() );
}
bool
LastFmUserSettings::trackFrameClockMode()
{
return MyQSettings( this ).value( "TrackFrameShowsTrackTime", true ).toBool();
}
void
LastFmUserSettings::setAlwaysConfirmIPodScrobbles( bool b )
{
MyQSettings( this ).setValue( "alwaysConfirmIPodScrobbles", b );
}
bool
LastFmUserSettings::isAlwaysConfirmIPodScrobbles() const
{
//TODO false after 1.5 beta
return MyQSettings( this ).value( "alwaysConfirmIPodScrobbles", false ).toBool();
}
/******************************************************************************
* Settings
******************************************************************************/
LastFmSettings::LastFmSettings( QObject* parent ) :
AppSettings<QSettings>( parent ),
m_nullUser( "" )
{
#ifndef WIN32
QSettings new_config;
if (!QFile( new_config.fileName() ).exists())
{
//attempt to upgrade settings object from old and broken location
foreach (QString const name, QStringList() << "Client" << "Users" << "Plugins" << "MediaDevices")
{
QSettings old_config( QSettings::IniFormat, QSettings::UserScope, "Last.fm", name );
old_config.setFallbacksEnabled( false );
if (!QFile::exists( old_config.fileName() ))
continue;
foreach (QString const key, old_config.allKeys()) {
if (name != "Client")
//Client now becomes [General] group as this makes most sense
new_config.beginGroup( name );
new_config.setValue( key, old_config.value( key ) );
#ifndef QT_NO_DEBUG
if (name != "Client") // otherwise qWarning and aborts
#endif
new_config.endGroup();
}
new_config.sync();
QFile f( old_config.fileName() );
f.remove();
QFileInfo( f ).dir().rmdir( "." ); //safe as won't remove a non empty dir
}
}
#endif
s_instance = this;
}
LastFmUserSettings&
LastFmSettings::user( QString username ) const
{
Q_ASSERT( username != "" );
LastFmUserSettings *user = findChild<LastFmUserSettings*>( username );
if (!user) {
user = new LastFmUserSettings( username );
user->setParent( const_cast<LastFmSettings*>(this) );
user->setObjectName( username );
connect( user, SIGNAL(userChanged( QString )), SLOT(userChanged( QString )) );
}
return *user;
}
LastFmUserSettings&
LastFmSettings::currentUser()
{
return currentUsername() == ""
? m_nullUser
: user( currentUsername() );
}
void
LastFmSettings::setCurrentUsername( QString username )
{
UsersSettings<QSettings>().setValue( CURRENT_USER_KEY, username );
emit userSettingsChanged( currentUser() );
emit userSwitched( currentUser() );
}
bool
LastFmSettings::deleteUser( QString username )
{
if (isExistingUser( username ))
{
delete &user( username );
UsersSettings<QSettings>().remove( username );
return true;
}
else
return false;
}
// Don't rename registry key. Used by player plugins!
void
LastFmSettings::setLaunchWithMediaPlayer( bool en )
{
QSettings( this ).setValue( "LaunchWithMediaPlayer", en );
// emit userChanged( username() );
}
bool
LastFmSettings::launchWithMediaPlayer()
{
return QSettings( this ).value( "LaunchWithMediaPlayer", true ).toBool();
}
int
LastFmSettings::externalSoundSystem()
{
int externalSystem = -1;
#ifdef WIN32
externalSystem = 1;
#endif
#ifdef Q_WS_X11
externalSystem = 2;
#endif
#ifdef Q_WS_MAC
externalSystem = 1;
#endif
return externalSystem;
}
void
LastFmSettings::setDontAsk( const QString op, bool value )
{
QSettings().setValue( op + "DontAsk", value );
}
bool
LastFmSettings::isDontAsk( const QString op ) const
{
return QSettings().value( op + "DontAsk" ).toBool();
}
void
LastFmSettings::setShowTrayIcon( bool en )
{
QSettings().setValue( "ShowTrayIcon", en );
emit appearanceSettingsChanged();
}
bool
LastFmSettings::isFirstRun() const
{
// We fallback on HKLM here as versions of the client prior to 1.3.2
// stored the value there
QSettings s;
if ( s.contains( "FirstRun" ) )
return s.value( "FirstRun", "1" ).toBool();
else
return HklmSettings().value( "FirstRun", "1" ).toBool();
}
void
LastFmSettings::setFirstRunDone()
{
QSettings().setValue( "FirstRun", "0" );
}
QStringList
LastFmSettings::allPlugins( bool withVersions )
{
// These valued are written by the plugin installers and hence live in
// PluginsSettings, i.e. HKLM.
PluginsSettings s;
QStringList plugins;
foreach (QString group, s.childGroups()) {
s.beginGroup( group );
QString name = s.value( "Name" ).toString();
//If the plugin has been added but not installed name.size() == 0
if ( name.size() != 0 )
{
if ( withVersions )
{
QString version = s.value( "Version" ).toString();
plugins += name + ' ' + tr("plugin, version") + ' ' + version;
}
else
{
plugins += name;
}
}
s.endGroup();
}
return plugins;
}
QString
LastFmSettings::pluginVersion( QString id )
{
Q_ASSERT( !id.isEmpty() );
// These valued are written by the plugin installers and hence live in
// PluginsSettings, i.e. HKLM.
return PluginsSettings().value( id + "/Version" ).toString();
}
QString
LastFmSettings::pluginPlayerPath( QString id )
{
Q_ASSERT( !id.isEmpty() );
QString key = "Plugins/" + id + "/PlayerPath";
// We fallback on HKLM here as versions of the client prior to 1.3.2
// stored the value there
QSettings s;
if ( s.contains( key ) )
return s.value( key, "" ).toString();
else
return HklmSettings().value( key, "" ).toString();
}
void
LastFmSettings::setPluginPlayerPath( QString id,
QString path )
{
Q_ASSERT( !id.isEmpty() );
// Does not go in PluginsSettings since that's in HKLM (written by the installer),
// and a standard user does not have write access to that.
QSettings().setValue( "Plugins/" + id + "/PlayerPath", path );
}
void
LastFmSettings::setIPodScrobblingEnabled( bool en )
{
QSettings().setValue( "iPodScrobblingEnabled", en );
}
bool
LastFmSettings::isIPodScrobblingEnabled() const
{
return QSettings().value( "iPodScrobblingEnabled", true ).toBool();
}
QStringList
LastFmSettings::allMediaDevices()
{
MediaDeviceSettings s;
QStringList uids;
foreach (QString group, s.childGroups())
{
s.beginGroup( group );
foreach (QString childgroup, s.childGroups())
uids += group + '/' + childgroup;
s.endGroup();
}
return uids;
}
QString
LastFmSettings::usernameForDeviceId( const QString& uid ) const
{
MediaDeviceSettings s;
s.beginGroup( uid );
return s.value( "user" ).toString();
}
QStringList
LastFmSettings::iPodIdsForUsername( const QString& username ) const
{
MediaDeviceSettings s;
QStringList uids;
foreach (QString type, s.childGroups())
{
s.beginGroup( type );
foreach (QString uid, s.childGroups())
if (s.value( uid + "/user" ) == username)
uids += type + '/' + uid;
s.endGroup();
}
return uids;
}
void
LastFmSettings::addMediaDevice( QString uid, QString username )
{
MediaDeviceSettings s;
s.beginGroup( uid );
s.setValue( "user", username );
s.sync();
}
void
LastFmSettings::removeMediaDevice( QString uid )
{
MediaDeviceSettings s;
s.beginGroup( uid );
s.remove( "user" );
s.sync();
}
MooseEnums::UserIconColour
LastFmSettings::getFreeColour()
{
UsersSettings<QSettings> s;
QList<int> unused;
// Fill it with all colours
for (int i = 0; i < 5; ++i)
{
unused.push_back(i);
}
// Remove the ones in use
foreach (QString username, s.childGroups())
{
MooseEnums::UserIconColour col = LastFmUserSettings( username ).icon();
if (col != MooseEnums::eNone)
unused.removeAll( int(col) );
if (unused.isEmpty()) {
LOG( 2, "We ran out of colours, returning random\n" );
return static_cast<MooseEnums::UserIconColour>(rand() % 5);
}
}
return static_cast<MooseEnums::UserIconColour>(unused.front());
}
void
LastFmSettings::userChanged( QString username )
{
if ( username == currentUsername() )
emit userSettingsChanged( currentUser() );
}
| gpl-2.0 |
orrche/wokjab | plugins/normal/JabberConnection/XML_Output.cc | 4062 | /***************************************************************************
* Copyright (C) 2003-2007 Kent Gustavsson <nedo80@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 Library 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.
/* This is one of the sader classes in this library
* Horribule horribule code will follow here after
*/
#include "XML_Output.h"
#include <iostream>
#ifdef __WIN32
#include <winsock.h>
typedef unsigned int uint;
#else
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>
#endif
#include <errno.h>
#include <unistd.h> // close
#include <sstream>
XML_Output::XML_Output(WLSignal *wls, std::string session): WLSignalInstance(wls),
session(session)
{
EXP_SIGHOOK("Jabber Connection Disconnect '" + XMLisize(session) + "'", &XML_Output::SignalDisconnect, 1000);
transmitting = false;
this->socket_nr = 0;
ssl = NULL;
}
XML_Output::~XML_Output()
{
}
void
XML_Output::set_socket(int socket_nr)
{
this->socket_nr = socket_nr;
}
int
XML_Output::SignalDisconnect(WokXMLTag *tag)
{
sendxml("<stream::stream/>");
}
int
XML_Output::sendxml(std::string data)
{
if(!socket_nr)
{
WokXMLTag sigtag(NULL, "message");
sigtag.AddTag("body").AddText("Session not connected");
wls->SendSignal("Display Error", sigtag);
WokXMLTag msg(NULL, "message");
msg.AddAttr("session", session);
wls->SendSignal("Jabber Connection Lost", &msg);
return(-1);
}
buffer += data;
if ( !transmitting )
{
transmitting = true;
std::stringstream sstr_socket;
std::string str_socket;
sstr_socket << socket_nr;
str_socket = sstr_socket.str();
WokXMLTag sigtag(NULL, "socket");
sigtag.AddAttr("socket", str_socket);
wls->SendSignal("Woklib Socket Out Add", sigtag);
signal_out = sigtag.GetAttr("signal");
EXP_SIGHOOK(signal_out, &XML_Output::SocketAvailibule, 1000);
}
}
int
XML_Output::SocketAvailibule(WokXMLTag *tag)
{
int bcount;
int br;
char *str;
WokXMLTag activetag (NULL, "active");
activetag.AddAttr("session", session);
wls->SendSignal("Jabber Session IO Active", activetag);
wls->SendSignal("Jabber Session IO Active " + session, activetag);
#ifdef DEBUG
{
WokXMLTag sigtag(NULL, "message");
sigtag.AddAttr("type", "out");
sigtag.AddTag("body").AddText(buffer);
sigtag.AddAttr("session", session);
wls->SendSignal("Display Socket", sigtag);
}
#endif // DEBUG
bcount = br = 0;
str =(char *) buffer.c_str();
if ( ssl )
{
// No idea at all why this is nessesary
if ( buffer.size() > 5000 )
br = SSL_write(ssl, str, 5000);
else
br = SSL_write(ssl, str, buffer.size());
}
else
br = send(socket_nr, str, buffer.size() , 0);
if (br > 0)
{
buffer = buffer.substr(br);
}
else if (br < 0)
{
#ifdef __WIN32
#else
char buf[50];
strerror_r(br, buf, 50);
WokXMLTag sigtag(NULL, "message");
sigtag.AddTag("body").AddText(std::string("Error Socket Send: ") + buf);
wls->SendSignal("Display Error", sigtag);
#endif
socket_nr = 0;
}
if ( buffer.size() == 0 )
{
EXP_SIGUNHOOK(signal_out, &XML_Output::SocketAvailibule, 1000);
transmitting = false;
tag->AddAttr("stop","no more data");
}
return(1);
}
int
XML_Output::sendxml(const char *data)
{
std::string xml_data;
int ret;
xml_data = data;
ret = sendxml(xml_data);
return(ret);
}
void
XML_Output::SetSSL(SSL * s)
{
ssl = s;
}
| gpl-2.0 |
paulopinda/eventex | eventex/core/migrations/0004_auto_20160125_0337.py | 1101 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-01-25 03:37
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0003_contact'),
]
operations = [
migrations.AlterModelOptions(
name='contact',
options={'verbose_name': 'contato', 'verbose_name_plural': 'contatos'},
),
migrations.AlterField(
model_name='contact',
name='kind',
field=models.CharField(choices=[('E', 'Email'), ('P', 'Telefone')], max_length=1, verbose_name='tipo'),
),
migrations.AlterField(
model_name='contact',
name='speaker',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.Speaker', verbose_name='palestrante'),
),
migrations.AlterField(
model_name='contact',
name='value',
field=models.CharField(max_length=255, verbose_name='valor'),
),
]
| gpl-2.0 |
Infernosaint/WPSetupTest2 | wp-content/themes/flexfunding/functions.php | 13910 | <?php
/** WECODE EDITS **/
add_action( 'wp_ajax_send_email', 'send_email_callback' );
add_action( 'wp_ajax_nopriv_send_email', 'send_email_callback' );
function send_email_callback(){
//MAIL 1
//$mailTo = 'simonetta.soerensen@flexfunding.com, info@flexfunding.com';
$mailTo = 'johan.peen@flexfunding.com';
$mailFrom = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$headers = 'From: Låneansøgning <'.$mailFrom.'>;';
wp_mail($mailTo, $subject, $message, $headers);
//MAIL 2
//$mailTo = $_POST['email'];
add_filter('wp_mail_content_type',create_function('', 'return "text/html"; '));
$mailTo = 'johan.peen@flexfunding.com';
$mailFrom = $_POST['email_from'];
$headers = 'From: Simonetta Sørensen - Flex Funding A/S <'.$mailFrom.'>;';
$subject = 'Tak for din ansøgning!';
$message = 'Kære '.$_POST['name']. '<br/><br/>Endnu engang velkommen hos Flex Funding.
<br/><br/>Som lovet får du her mine kontaktoplysninger. Hvis du har spørgsmål til ansøgningsprocessen, eller tilføjelser til din ansøgning, så er du altid velkommen til at kontakte mig.<br/><br/>
I hverdage kan du forvente svar på din ansøgning inden for 24 timer.<br/><br/>
Hvis du ikke allerede har været inde og læse mere om ansøgningsprocessen, så kan du gøre det her:<br/> https://www.flexfunding.com/da/lantager/<br/><br/>
Du kan desuden hurtigt, og gratis, oprette dig som kunde gå på opdagelse i crowdlending universet her:<br/> https://app.flexfunding.com/RegistrationProcess/Registration/Register<br/><br/>
Bedste hilsner,<br/><br/>
<strong>Simonetta Sørensen</strong><br/>
<img width="100" src="https://www.flexfunding.com/wp-content/uploads/2016/02/signature.png" /><br/>
+45 7060 5200<br/>
simonetta.soerensen@flexfunding.com
';
wp_mail($mailTo, $subject, $message, $headers);
echo $mailFrom;
wp_die();
}
function submit_loan_function ($args){
$adminurl = admin_url('admin-ajax.php');
$search_form = "<div class='white_form'>
<form id='ansoeg_form' method='post'>
<h3 class='ansoeg_header'>ANSØG PÅ 30 SEKUNDER</h3>
<input type='text' id='laanebeloeb' placeholder='Skriv lånebeløb her...' />
<br/>
<ul>
<li>Lån fra 200.000 - 5 mio. kr.</li>
<li>Løbetid op til 10 år</li>
<li>Fast rente</li>
<li>Ingen genforhandling</li>
</ul>
<br/>
<input class='sf-button medium blue sf-icon-stroke ansoeg_button' type='submit' value='".$args['button_text']."'/>
<span class='button_sub_text'>Gratis. Ingen binding.</span>
</form>
<form id='details_form' method='post' style='display:none;'>
<small>Her er alt, hvad vi behøver fra dig for at kunne vende tilbage:</small>
<input class='input_details_form' type='text' id='name' name='name' placeholder='Dit navn' />
<input class='input_details_form' type='text' id='company_name' name='company_name' placeholder='Virksomhedens navn' />
<input class='input_details_form' type='text' id='cvr' name='cvr' placeholder='CVR nr.' />
<input class='input_details_form' type='text' id='email' name='email' placeholder='E-mail' />
<select class='input_details_form' name='use' id='loan_use' value='Hvad skal lånet bruges til?'>
<option value='' disabled selected>Hvad skal lånet bruges til?</option>
<option value='driftsfinansiering'>Driftsfinansiering</option>
<option value='ekspansion'>Ekspansion(nye markeder, nye produkter o.l.)
</option>
<option value='Finansiering af anlæg og faciliteter'>Finansiering af anlæg og faciliteter</option>
<option value='Engangsudgifter'>Engangsudgifter</option>
<option value='Overtagelse af eksisterende lån'>Overtagelse af eksisterende lån</option>
<option value='Mellem finansiering (ordrefinansiering, factoring o.l.)'>Mellem finansiering (ordrefinansiering, factoring o.l.)</option>
<option value='Finansiering af produktionsudstyr/driftsudstyr'>Finansiering af produktionsudstyr/driftsudstyr</option>
<option value='Overtagelse af eksisterende lån'>Overtagelse af eksisterende lån</option>
<option value='Generationsskifte'>Generationsskifte</option>
<option value='Ejendomsfinansiering'>Ejendomsfinansiering</option>
</select>
<select class='input_details_form' name='loebetid' id='loan_run_time' value='Vælg lånets løbetid'>
<option value='' disabled selected>Vælg lånets løbetid</option>
<option value='6'>6</option>
<option value='12'>12</option>
<option value='24'>24</option>
<option value='36'>36</option>
<option value='48'>48</option>
<option value='60'>60</option>
<option value='120'>120</option>
</select>
<input type='hidden' value='' id='laanebeloeb_details' />
<input class='sf-button medium blue sf-icon-stroke ansoeg_button input_details_form' type='submit' value='Send ansøgning'/>
</form>
<div id='thanks' style='display:none;'>
<h3>Tak for din ansøgning!</h3>
<span>Kære <span id='name_thanks'></span></span><br/><br/>
<small id='thanks_text'>
Velkommen hos Flex Funding!
<br/><br/>
Mit navn er Simonetta Sørensen og jeg har fået fornøjelsen af at være din personlige rådgiver.
<br/><br/>
Vi er allerede i fuld gang med at behandle din låneansøgning. I hverdage vender vi tilbage med svar på din ansøgning inden for 24 timer.
<br/><br/>
Jeg har sendt dig en mail med mine kontaktinformationer. Du er altid velkommen til at kontakte mig med spørgsmål.
<br/><br/>
I mellemtiden kan du læse mere om ansøgningsprocessen her: <a href='https://www.flexfunding.com/da/lantager/'>https://www.flexfunding.com/da/lantager/</a>
<br/><br/>
Alle oplysninger behandles dybt fortroligt.
</small>
<br/>
<img width='100' src='https://www.flexfunding.com/wp-content/uploads/2015/04/Simonetta_full_magic.jpg' alt='Simonette Sørensen' />
<span class='signature'>Bedste hilsner, <br/>Simonette Sørensen<br/>Flex Funding A/S</span>
</div>
</div>
<script>
jQuery(document).ready(function($){
$('#ansoeg_form').on('submit', function(event) {
var laanebeloeb = $('#laanebeloeb').val();
$('#laanebeloeb_details').val(laanebeloeb);
event.preventDefault();
$('#ansoeg_form').hide();
$('#details_form').css('display','block');
});
$('#details_form').on('submit', function(event) {
var name = $('#name').val();
var company_name = $('#company_name').val();
var cvr = $('#cvr').val();
var email = $('#email').val();
var loan_use = $('#loan_use').val();
var loan_run_time = $('#loan_run_time').val();
var loan_size = $('#laanebeloeb_details').val();
var email_from = 'simonetta.soerensen@flexfunding.com';
var subject = 'Lånansøgning';
event.preventDefault();
$('#details_form').hide();
$('#name_thanks').text(name);
$('#thanks').css('display','block');
$('.white_form').addClass('no_bottom');
var data = {
'action': 'send_email',
'name': name,
'cvr': company_name,
'email': email,
'loan_use': loan_use,
'loan_run_time': loan_run_time,
'loan_size': loan_size,
'email_from': email_from,
'subject': subject,
'message': 'Låneansøg fra ' + company_name + ' med CVR ' + cvr + '. Deres email er ' + email + '. De ønsker et lån på: ' + loan_size + ' til ' + loan_use + ' over ' + loan_run_time + ' måneder.'
};
jQuery.post('".$adminurl."', data, function(response) {
console.log('Email was sent from: ' + response);
});
});
});
</script>
";
return $search_form;
}
add_shortcode( 'submit_loan', 'submit_loan_function' );
/*
*
* Atelier Functions - Child Theme
* ------------------------------------------------
* These functions will override the parent theme
* functions. We have provided some examples below.
*
*
*/
/* LOAD PARENT THEME STYLES
================================================== */
function atelier_child_enqueue_styles() {
wp_enqueue_style( 'atelier-parent-style', get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'jquery-ui-style', get_stylesheet_directory_uri() . '/assets/css/jquery-ui.min.css' );
wp_enqueue_style( 'calculator-style', get_stylesheet_directory_uri() . '/assets/css/calculator.css' );
wp_enqueue_style( 'pages-style', get_stylesheet_directory_uri() . '/assets/css/pages.css' );
}
add_action( 'wp_enqueue_scripts', 'atelier_child_enqueue_styles' );
function atelier_child_enqueue_responsive_styles() {
wp_enqueue_style( 'responsive-style', get_stylesheet_directory_uri() . '/assets/css/responsive.css' );
}
add_action( 'wp_enqueue_scripts', 'atelier_child_enqueue_responsive_styles', 100 );
function atelier_child_enqueue_scripts() {
wp_enqueue_script( 'jquery-ui-core');
wp_enqueue_script( 'jquery-ui-slider');
wp_enqueue_script( 'calculator-js', get_stylesheet_directory_uri() . '/assets/js/flex_calc.calculator.js', array('jquery'), NULL, TRUE );
}
add_action( 'wp_enqueue_scripts', 'atelier_child_enqueue_scripts' );
/* LOAD THEME LANGUAGE
================================================== */
/*
* You can uncomment the line below to include your own translations
* into your child theme, simply create a "language" folder and add your po/mo files
*/
// load_theme_textdomain('swiftframework', get_stylesheet_directory().'/language');
/* REMOVE PAGE BUILDER ASSETS
================================================== */
/*
* You can uncomment the line below to remove selected assets from the page builder
*/
// function spb_remove_assets( $pb_assets ) {
// unset($pb_assets['parallax']);
// return $pb_assets;
// }
// add_filter( 'spb_assets_filter', 'spb_remove_assets' );
/* ADD/EDIT PAGE BUILDER TEMPLATES
================================================== */
function custom_prebuilt_templates($prebuilt_templates) {
/*
* You can uncomment the lines below to add custom templates
*/
// $prebuilt_templates["custom"] = array(
// 'id' => "custom",
// 'name' => 'Custom',
// 'code' => 'your-code-here'
// );
/*
* You can uncomment the lines below to remove default templates
*/
// unset($prebuilt_templates['home-1']);
// unset($prebuilt_templates['home-2']);
// return templates array
return $prebuilt_templates;
}
//add_filter( 'spb_prebuilt_templates', 'custom_prebuilt_templates' );
// function custom_post_thumb_image($thumb_img_url) {
//
// if ($thumb_img_url == "") {
// global $post;
// ob_start();
// ob_end_clean();
// $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
// if (!empty($matches) && isset($matches[1][0])) {
// $thumb_img_url = $matches[1][0];
// }
// }
//
// return $thumb_img_url;
// }
// add_filter( 'sf_post_thumb_image_url', 'custom_post_thumb_image' );
// function dynamic_section( $sections ) {
// //$sections = array();
// $sections[] = array(
// 'title' => __( 'Section via hook', 'redux-framework-demo' ),
// 'desc' => __( '<p class="description">This is a section created by adding a filter to the sections array. Can be used by child themes to add/remove sections from the options.</p>', 'redux-framework-demo' ),
// 'icon' => 'el-icon-paper-clip',
// // Leave this as a blank section, no options just some intro text set above.
// 'fields' => array()
// );
// return $sections;
// }
//
// function custom_style_sheet() {
// echo '<link rel="stylesheet" href="'.get_stylesheet_directory_uri() . '/test.css'.'" type="text/css" media="all" />';
// }
// add_action('wp_head', 'custom_style_sheet', 100);
// function custom_wishlist_icon() {
// return '<i class="fa-heart"></i>';
// }
// add_filter('sf_wishlist_icon', 'custom_wishlist_icon', 100);
// add_filter('sf_add_to_wishlist_icon', 'custom_wishlist_icon', 100);
// add_filter('sf_wishlist_menu_icon', 'custom_wishlist_icon', 100);
/* Add telephone to header */
add_filter( 'wp_nav_menu_items', 'ff_menu_language_selector', 10, 2 );
function ff_menu_language_selector ( $items, $args ) {
if (in_array($args->theme_location, array('top_bar_menu', 'mobile_menu'))) {
ob_start();
//do_action('wpml_add_language_selector');
do_action('icl_language_selector');
$switcher = ob_get_clean();
$items = '<li class="language-switcher">' . $switcher . '</li>' . $items;
}
return $items;
}
function icl_language_switcher(){
$languages = icl_get_languages('skip_missing=1');
if(1 < count($languages)){
foreach($languages as $l){
if(!$l['active']) $langs[] = '<a href="'.$l['url'].'">'.$l['translated_name'].'</a>';
}
echo join(', ', $langs);
}
}
add_filter( 'the_content_more_link', 'modify_read_more_link' );
function modify_read_more_link() {
return '... <a class="more-link" href="' . get_permalink() . '">' . __('Read more', 'swiftframework') . '</a>';
}
add_action( 'customize_preview_init', 'twentytwelve_customize_preview_js' );
add_action( 'wp_head', 'wpml_custom_redirect' );
function wpml_custom_redirect() {
global $sitepress;
if( $sitepress->get_default_language() == ICL_LANGUAGE_CODE ) {
$uri = $_SERVER['REQUEST_URI'];
if( ! preg_match( '#/' . ICL_LANGUAGE_CODE . '/#', $uri ) ) {
wp_redirect( site_url( $sitepress->get_default_language() . '/' ) );
}
}
}
| gpl-2.0 |
swilson96/sudoku-web-solver | Sudoku/Areas/HelpPage/XmlDocumentationProvider.cs | 4654 | using System;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using System.Xml.XPath;
namespace Sudoku.Areas.HelpPage
{
/// <summary>
/// A custom <see cref="IDocumentationProvider"/> that reads the API documentation from an XML documentation file.
/// </summary>
public class XmlDocumentationProvider : IDocumentationProvider
{
private XPathNavigator _documentNavigator;
private const string MethodExpression = "/doc/members/member[@name='M:{0}']";
private const string ParameterExpression = "param[@name='{0}']";
/// <summary>
/// Initializes a new instance of the <see cref="XmlDocumentationProvider"/> class.
/// </summary>
/// <param name="documentPath">The physical path to XML document.</param>
public XmlDocumentationProvider(string documentPath)
{
if (documentPath == null)
{
throw new ArgumentNullException("documentPath");
}
XPathDocument xpath = new XPathDocument(documentPath);
_documentNavigator = xpath.CreateNavigator();
}
public virtual string GetDocumentation(HttpActionDescriptor actionDescriptor)
{
XPathNavigator methodNode = GetMethodNode(actionDescriptor);
if (methodNode != null)
{
XPathNavigator summaryNode = methodNode.SelectSingleNode("summary");
if (summaryNode != null)
{
return summaryNode.Value.Trim();
}
}
return null;
}
public virtual string GetDocumentation(HttpParameterDescriptor parameterDescriptor)
{
ReflectedHttpParameterDescriptor reflectedParameterDescriptor = parameterDescriptor as ReflectedHttpParameterDescriptor;
if (reflectedParameterDescriptor != null)
{
XPathNavigator methodNode = GetMethodNode(reflectedParameterDescriptor.ActionDescriptor);
if (methodNode != null)
{
string parameterName = reflectedParameterDescriptor.ParameterInfo.Name;
XPathNavigator parameterNode = methodNode.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, ParameterExpression, parameterName));
if (parameterNode != null)
{
return parameterNode.Value.Trim();
}
}
}
return null;
}
private XPathNavigator GetMethodNode(HttpActionDescriptor actionDescriptor)
{
ReflectedHttpActionDescriptor reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor;
if (reflectedActionDescriptor != null)
{
string selectExpression = String.Format(CultureInfo.InvariantCulture, MethodExpression, GetMemberName(reflectedActionDescriptor.MethodInfo));
return _documentNavigator.SelectSingleNode(selectExpression);
}
return null;
}
private static string GetMemberName(MethodInfo method)
{
string name = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", method.DeclaringType.FullName, method.Name);
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length != 0)
{
string[] parameterTypeNames = parameters.Select(param => GetTypeName(param.ParameterType)).ToArray();
name += String.Format(CultureInfo.InvariantCulture, "({0})", String.Join(",", parameterTypeNames));
}
return name;
}
private static string GetTypeName(Type type)
{
if (type.IsGenericType)
{
// Format the generic type name to something like: Generic{System.Int32,System.String}
Type genericType = type.GetGenericTypeDefinition();
Type[] genericArguments = type.GetGenericArguments();
string typeName = genericType.FullName;
// Trim the generic parameter counts from the name
typeName = typeName.Substring(0, typeName.IndexOf('`'));
string[] argumentTypeNames = genericArguments.Select(t => GetTypeName(t)).ToArray();
return String.Format(CultureInfo.InvariantCulture, "{0}{{{1}}}", typeName, String.Join(",", argumentTypeNames));
}
return type.FullName;
}
}
}
| gpl-2.0 |
gureedo/eMule-IS-Mod | srchybrid/QueueListCtrl.cpp | 25127 | //this file is part of eMule
//Copyright (C)2002-2008 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.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, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#include "stdafx.h"
#include "TempIconLoader.h"
#include "emule.h"
#include "QueueListCtrl.h"
#include "OtherFunctions.h"
#include "MenuCmds.h"
#include "ClientDetailDialog.h"
#include "Exceptions.h"
#include "KademliaWnd.h"
#include "emuledlg.h"
#include "FriendList.h"
#include "UploadQueue.h"
#include "UpDownClient.h"
#include "TransferDlg.h"
#include "MemDC.h"
#include "SharedFileList.h"
#include "ClientCredits.h"
#include "PartFile.h"
#include "ChatWnd.h"
#include "Kademlia/Kademlia/Kademlia.h"
#include "Kademlia/Kademlia/Prefs.h"
#include "kademlia/net/KademliaUDPListener.h"
#include "Log.h"
// ismod
#include "sharedfileswnd.h" // for goto file
#include "Friend.h" // for friend slot
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
IMPLEMENT_DYNAMIC(CQueueListCtrl, CMuleListCtrl)
BEGIN_MESSAGE_MAP(CQueueListCtrl, CMuleListCtrl)
ON_NOTIFY_REFLECT(LVN_COLUMNCLICK, OnLvnColumnClick)
ON_NOTIFY_REFLECT(LVN_GETDISPINFO, OnLvnGetDispInfo)
ON_NOTIFY_REFLECT(NM_DBLCLK, OnNmDblClk)
ON_WM_CONTEXTMENU()
ON_WM_SYSCOLORCHANGE()
END_MESSAGE_MAP()
CQueueListCtrl::CQueueListCtrl()
: CListCtrlItemWalk(this)
{
SetGeneralPurposeFind(true);
SetSkinKey(L"QueuedLv");
// Barry - Refresh the queue every 10 secs
VERIFY( (m_hTimer = ::SetTimer(NULL, NULL, 10000, QueueUpdateTimer)) != NULL );
if (thePrefs.GetVerbose() && !m_hTimer)
AddDebugLogLine(true,_T("Failed to create 'queue list control' timer - %s"),GetErrorMessage(GetLastError()));
}
CQueueListCtrl::~CQueueListCtrl()
{
if (m_hTimer)
VERIFY( ::KillTimer(NULL, m_hTimer) );
}
void CQueueListCtrl::Init()
{
SetPrefsKey(_T("QueueListCtrl"));
SetExtendedStyle(LVS_EX_FULLROWSELECT | LVS_EX_INFOTIP);
// ismod
UINT i = 0;
InsertColumn(i++, GetResString(IDS_QL_USERNAME), LVCFMT_LEFT, DFLT_CLIENTNAME_COL_WIDTH);
InsertColumn(i++, GetResString(IDS_FILE), LVCFMT_LEFT, DFLT_FILENAME_COL_WIDTH);
InsertColumn(i++, GetResString(IDS_FILEPRIO), LVCFMT_LEFT, DFLT_PRIORITY_COL_WIDTH);
InsertColumn(i++, GetResString(IDS_QL_RATING), LVCFMT_LEFT, 60);
InsertColumn(i++, GetResString(IDS_SCORE), LVCFMT_LEFT, 60);
InsertColumn(i++, GetResString(IDS_ASKED), LVCFMT_LEFT, 60);
InsertColumn(i++, GetResString(IDS_LASTSEEN), LVCFMT_LEFT, 110);
InsertColumn(i++, GetResString(IDS_ENTERQUEUE), LVCFMT_LEFT, 110);
InsertColumn(i++, GetResString(IDS_BANNED), LVCFMT_LEFT, 60);
InsertColumn(i++, GetResString(IDS_UPSTATUS), LVCFMT_LEFT, DFLT_PARTSTATUS_COL_WIDTH);
SetAllIcons();
Localize();
LoadSettings();
SetSortArrow();
SortItems(SortProc, GetSortItem() + (GetSortAscending() ? 0 : 100));
}
void CQueueListCtrl::Localize()
{
CHeaderCtrl *pHeaderCtrl = GetHeaderCtrl();
HDITEM hdi;
// ismod
UINT i = 0;
hdi.mask = HDI_TEXT;
CString strRes;
strRes = GetResString(IDS_QL_USERNAME);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(i++, &hdi);
strRes = GetResString(IDS_FILE);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(i++, &hdi);
strRes = GetResString(IDS_FILEPRIO);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(i++, &hdi);
strRes = GetResString(IDS_QL_RATING);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(i++, &hdi);
strRes = GetResString(IDS_SCORE);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(i++, &hdi);
strRes = GetResString(IDS_ASKED);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(i++, &hdi);
strRes = GetResString(IDS_LASTSEEN);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(i++, &hdi);
strRes = GetResString(IDS_ENTERQUEUE);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(i++, &hdi);
strRes = GetResString(IDS_BANNED);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(i++, &hdi);
strRes = GetResString(IDS_UPSTATUS);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(i++, &hdi);
}
void CQueueListCtrl::OnSysColorChange()
{
CMuleListCtrl::OnSysColorChange();
SetAllIcons();
}
void CQueueListCtrl::SetAllIcons()
{
ApplyImageList(NULL);
m_ImageList.DeleteImageList();
m_ImageList.Create(16, 16, ILC_COLOR32 | ILC_MASK, 0, 1);
m_ImageList.Add(CTempIconLoader(_T("ClientEDonkey")));
m_ImageList.Add(CTempIconLoader(_T("ClientCompatible")));
m_ImageList.Add(CTempIconLoader(_T("ClientEDonkeyPlus")));
m_ImageList.Add(CTempIconLoader(_T("ClientCompatiblePlus")));
m_ImageList.Add(CTempIconLoader(_T("Friend")));
m_ImageList.Add(CTempIconLoader(_T("ClientMLDonkey")));
m_ImageList.Add(CTempIconLoader(_T("ClientMLDonkeyPlus")));
m_ImageList.Add(CTempIconLoader(_T("ClientEDonkeyHybrid")));
m_ImageList.Add(CTempIconLoader(_T("ClientEDonkeyHybridPlus")));
m_ImageList.Add(CTempIconLoader(_T("ClientShareaza")));
m_ImageList.Add(CTempIconLoader(_T("ClientShareazaPlus")));
m_ImageList.Add(CTempIconLoader(_T("ClientAMule")));
m_ImageList.Add(CTempIconLoader(_T("ClientAMulePlus")));
m_ImageList.Add(CTempIconLoader(_T("ClientLPhant")));
m_ImageList.Add(CTempIconLoader(_T("ClientLPhantPlus")));
m_ImageList.SetOverlayImage(m_ImageList.Add(CTempIconLoader(_T("ClientSecureOvl"))), 1);
m_ImageList.SetOverlayImage(m_ImageList.Add(CTempIconLoader(_T("OverlayObfu"))), 2);
m_ImageList.SetOverlayImage(m_ImageList.Add(CTempIconLoader(_T("OverlaySecureObfu"))), 3);
// Apply the image list also to the listview control, even if we use our own 'DrawItem'.
// This is needed to give the listview control a chance to initialize the row height.
ASSERT( (GetStyle() & LVS_SHAREIMAGELISTS) != 0 );
VERIFY( ApplyImageList(m_ImageList) == NULL );
}
void CQueueListCtrl::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
if (!theApp.IsRunning())
return;
if (!lpDrawItemStruct->itemData)
return;
CMemDC dc(CDC::FromHandle(lpDrawItemStruct->hDC), &lpDrawItemStruct->rcItem);
BOOL bCtrlFocused;
InitItemMemDC(dc, lpDrawItemStruct, bCtrlFocused);
CRect cur_rec(lpDrawItemStruct->rcItem);
CRect rcClient;
GetClientRect(&rcClient);
const CUpDownClient *client = (CUpDownClient *)lpDrawItemStruct->itemData;
// ismod
dc->SetTextColor(client->GetClientColor());
CHeaderCtrl *pHeaderCtrl = GetHeaderCtrl();
int iCount = pHeaderCtrl->GetItemCount();
cur_rec.right = cur_rec.left - sm_iLabelOffset;
cur_rec.left += sm_iIconOffset;
for (int iCurrent = 0; iCurrent < iCount; iCurrent++)
{
int iColumn = pHeaderCtrl->OrderToIndex(iCurrent);
if (!IsColumnHidden(iColumn))
{
UINT uDrawTextAlignment;
int iColumnWidth = GetColumnWidth(iColumn, uDrawTextAlignment);
cur_rec.right += iColumnWidth;
if (cur_rec.left < cur_rec.right && HaveIntersection(rcClient, cur_rec))
{
TCHAR szItem[1024];
GetItemDisplayText(client, iColumn, szItem, _countof(szItem));
switch (iColumn)
{
case 0:{
int iImage;
if (client->IsFriend())
iImage = 4;
else if (client->GetClientSoft() == SO_EDONKEYHYBRID) {
if (client->credits->GetScoreRatio(client->GetIP()) > 1)
iImage = 8;
else
iImage = 7;
}
else if (client->GetClientSoft() == SO_MLDONKEY) {
if (client->credits->GetScoreRatio(client->GetIP()) > 1)
iImage = 6;
else
iImage = 5;
}
else if (client->GetClientSoft() == SO_SHAREAZA) {
if (client->credits->GetScoreRatio(client->GetIP()) > 1)
iImage = 10;
else
iImage = 9;
}
else if (client->GetClientSoft() == SO_AMULE) {
if (client->credits->GetScoreRatio(client->GetIP()) > 1)
iImage = 12;
else
iImage = 11;
}
else if (client->GetClientSoft() == SO_LPHANT) {
if (client->credits->GetScoreRatio(client->GetIP()) > 1)
iImage = 14;
else
iImage = 13;
}
else if (client->ExtProtocolAvailable()) {
if (client->credits->GetScoreRatio(client->GetIP()) > 1)
iImage = 3;
else
iImage = 1;
}
else {
if (client->credits->GetScoreRatio(client->GetIP()) > 1)
iImage = 2;
else
iImage = 0;
}
UINT nOverlayImage = 0;
if ((client->Credits() && client->Credits()->GetCurrentIdentState(client->GetIP()) == IS_IDENTIFIED))
nOverlayImage |= 1;
if (client->IsObfuscatedConnectionEstablished())
nOverlayImage |= 2;
int iIconPosY = (cur_rec.Height() > 16) ? ((cur_rec.Height() - 16) / 2) : 1;
POINT point = { cur_rec.left, cur_rec.top + iIconPosY };
m_ImageList.Draw(dc, iImage, point, ILD_NORMAL | INDEXTOOVERLAYMASK(nOverlayImage));
cur_rec.left += 16 + sm_iLabelOffset;
dc.DrawText(szItem, -1, &cur_rec, MLC_DT_TEXT | uDrawTextAlignment);
cur_rec.left -= 16;
cur_rec.right -= sm_iSubItemInset;
break;
}
case 10:
if (client->GetUpPartCount()) {
cur_rec.bottom--;
cur_rec.top++;
client->DrawUpStatusBar(dc, &cur_rec, false, thePrefs.UseFlatBar());
cur_rec.bottom++;
cur_rec.top--;
}
break;
default:
dc.DrawText(szItem, -1, &cur_rec, MLC_DT_TEXT | uDrawTextAlignment);
break;
}
}
cur_rec.left += iColumnWidth;
}
}
DrawFocusRect(dc, lpDrawItemStruct->rcItem, lpDrawItemStruct->itemState & ODS_FOCUS, bCtrlFocused, lpDrawItemStruct->itemState & ODS_SELECTED);
}
void CQueueListCtrl::GetItemDisplayText(const CUpDownClient *client, int iSubItem, LPTSTR pszText, int cchTextMax)
{
if (pszText == NULL || cchTextMax <= 0) {
ASSERT(0);
return;
}
pszText[0] = _T('\0');
switch (iSubItem)
{
case 0:
if (client->GetUserName() == NULL)
_sntprintf(pszText, cchTextMax, _T("(%s)"), GetResString(IDS_UNKNOWN));
else
_tcsncpy(pszText, client->GetUserName(), cchTextMax);
break;
case 1: {
const CKnownFile *file = theApp.sharedfiles->GetFileByID(client->GetUploadFileID());
_tcsncpy(pszText, file != NULL ? file->GetFileName() : _T(""), cchTextMax);
break;
}
case 2: {
const CKnownFile *file = theApp.sharedfiles->GetFileByID(client->GetUploadFileID());
if (file)
{
switch (file->GetUpPriority())
{
case PR_VERYLOW:
_tcsncpy(pszText, GetResString(IDS_PRIOVERYLOW), cchTextMax);
break;
case PR_LOW:
if (file->IsAutoUpPriority())
_tcsncpy(pszText, GetResString(IDS_PRIOAUTOLOW), cchTextMax);
else
_tcsncpy(pszText, GetResString(IDS_PRIOLOW), cchTextMax);
break;
case PR_NORMAL:
if (file->IsAutoUpPriority())
_tcsncpy(pszText, GetResString(IDS_PRIOAUTONORMAL), cchTextMax);
else
_tcsncpy(pszText, GetResString(IDS_PRIONORMAL), cchTextMax);
break;
case PR_HIGH:
if (file->IsAutoUpPriority())
_tcsncpy(pszText, GetResString(IDS_PRIOAUTOHIGH), cchTextMax);
else
_tcsncpy(pszText, GetResString(IDS_PRIOHIGH), cchTextMax);
break;
case PR_VERYHIGH:
_tcsncpy(pszText, GetResString(IDS_PRIORELEASE), cchTextMax);
break;
}
}
break;
}
case 3:
_sntprintf(pszText, cchTextMax, _T("%i"), client->GetScore(false, false, true));
break;
case 4:
if (client->HasLowID()) {
if (client->m_bAddNextConnect)
_sntprintf(pszText, cchTextMax, _T("%i ****"),client->GetScore(false));
else
_sntprintf(pszText, cchTextMax, _T("%i (%s)"),client->GetScore(false), GetResString(IDS_IDLOW));
}
else
_sntprintf(pszText, cchTextMax, _T("%i"), client->GetScore(false));
break;
case 5:
_sntprintf(pszText, cchTextMax, _T("%i"), client->GetAskedCount());
break;
case 6:
_tcsncpy(pszText, CastSecondsToHM((GetTickCount() - client->GetLastUpRequest()) / 1000), cchTextMax);
break;
case 7:
_tcsncpy(pszText, CastSecondsToHM((GetTickCount() - client->GetWaitStartTime()) / 1000), cchTextMax);
break;
case 8:
_tcsncpy(pszText, GetResString(client->IsBanned() ? IDS_YES : IDS_NO), cchTextMax);
break;
case 9:
_tcsncpy(pszText, GetResString(IDS_UPSTATUS), cchTextMax);
break;
}
pszText[cchTextMax - 1] = _T('\0');
}
void CQueueListCtrl::OnLvnGetDispInfo(NMHDR *pNMHDR, LRESULT *pResult)
{
if (theApp.IsRunning()) {
// Although we have an owner drawn listview control we store the text for the primary item in the listview, to be
// capable of quick searching those items via the keyboard. Because our listview items may change their contents,
// we do this via a text callback function. The listview control will send us the LVN_DISPINFO notification if
// it needs to know the contents of the primary item.
//
// But, the listview control sends this notification all the time, even if we do not search for an item. At least
// this notification is only sent for the visible items and not for all items in the list. Though, because this
// function is invoked *very* often, do *NOT* put any time consuming code in here.
//
// Vista: That callback is used to get the strings for the label tips for the sub(!) items.
//
NMLVDISPINFO *pDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR);
if (pDispInfo->item.mask & LVIF_TEXT) {
const CUpDownClient* pClient = reinterpret_cast<CUpDownClient*>(pDispInfo->item.lParam);
if (pClient != NULL)
GetItemDisplayText(pClient, pDispInfo->item.iSubItem, pDispInfo->item.pszText, pDispInfo->item.cchTextMax);
}
}
*pResult = 0;
}
void CQueueListCtrl::OnLvnColumnClick(NMHDR *pNMHDR, LRESULT *pResult)
{
NMLISTVIEW *pNMListView = (NMLISTVIEW *)pNMHDR;
bool sortAscending;
if (GetSortItem() != pNMListView->iSubItem)
{
switch (pNMListView->iSubItem)
{
case 2: // Up Priority
case 3: // Rating
case 4: // Score
case 5: // Ask Count
case 8: // Banned
case 9: // Part Count
sortAscending = false;
break;
default:
sortAscending = true;
break;
}
}
else
sortAscending = !GetSortAscending();
// Sort table
UpdateSortHistory(pNMListView->iSubItem + (sortAscending ? 0 : 100));
SetSortArrow(pNMListView->iSubItem, sortAscending);
SortItems(SortProc, pNMListView->iSubItem + (sortAscending ? 0 : 100));
*pResult = 0;
}
int CQueueListCtrl::SortProc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
{
const CUpDownClient *item1 = (CUpDownClient *)lParam1;
const CUpDownClient *item2 = (CUpDownClient *)lParam2;
int iColumn = (lParamSort >= 100) ? lParamSort - 100 : lParamSort;
int iResult = 0;
switch (iColumn)
{
case 0:
if (item1->GetUserName() && item2->GetUserName())
iResult = CompareLocaleStringNoCase(item1->GetUserName(), item2->GetUserName());
else if (item1->GetUserName() == NULL)
iResult = 1; // place clients with no usernames at bottom
else if (item2->GetUserName() == NULL)
iResult = -1; // place clients with no usernames at bottom
break;
case 1: {
const CKnownFile *file1 = theApp.sharedfiles->GetFileByID(item1->GetUploadFileID());
const CKnownFile *file2 = theApp.sharedfiles->GetFileByID(item2->GetUploadFileID());
if (file1 != NULL && file2 != NULL)
iResult = CompareLocaleStringNoCase(file1->GetFileName(), file2->GetFileName());
else if (file1 == NULL)
iResult = 1;
else
iResult = -1;
break;
}
case 2: {
const CKnownFile *file1 = theApp.sharedfiles->GetFileByID(item1->GetUploadFileID());
const CKnownFile *file2 = theApp.sharedfiles->GetFileByID(item2->GetUploadFileID());
if (file1 != NULL && file2 != NULL)
iResult = (file1->GetUpPriority() == PR_VERYLOW ? -1 : file1->GetUpPriority()) - (file2->GetUpPriority() == PR_VERYLOW ? -1 : file2->GetUpPriority());
else if (file1 == NULL)
iResult = 1;
else
iResult = -1;
break;
}
case 3:
iResult = CompareUnsigned(item1->GetScore(false, false, true), item2->GetScore(false, false, true));
break;
case 4:
iResult = CompareUnsigned(item1->GetScore(false), item2->GetScore(false));
break;
case 5:
iResult = CompareUnsigned(item1->GetAskedCount(), item2->GetAskedCount());
break;
case 6:
iResult = CompareUnsigned64(item1->GetLastUpRequest(), item2->GetLastUpRequest());
break;
case 7:
iResult = CompareUnsigned64(item1->GetWaitStartTime(), item2->GetWaitStartTime());
break;
case 8:
iResult = item1->IsBanned() - item2->IsBanned();
break;
case 9:
iResult = CompareUnsigned(item1->GetUpPartCount(), item2->GetUpPartCount());
break;
}
if (lParamSort >= 100)
iResult = -iResult;
//call secondary sortorder, if this one results in equal
int dwNextSort;
if (iResult == 0 && (dwNextSort = theApp.emuledlg->transferwnd->GetQueueList()->GetNextSortOrder(lParamSort)) != -1)
iResult = SortProc(lParam1, lParam2, dwNextSort);
return iResult;
}
void CQueueListCtrl::OnNmDblClk(NMHDR* /*pNMHDR*/, LRESULT *pResult)
{
int iSel = GetNextItem(-1, LVIS_SELECTED | LVIS_FOCUSED);
if (iSel != -1) {
CUpDownClient* client = (CUpDownClient*)GetItemData(iSel);
if (client){
CClientDetailDialog dialog(client, this);
dialog.DoModal();
}
}
*pResult = 0;
}
void CQueueListCtrl::OnContextMenu(CWnd* /*pWnd*/, CPoint point)
{
int iSel = GetNextItem(-1, LVIS_SELECTED | LVIS_FOCUSED);
const CUpDownClient* client = (iSel != -1) ? (CUpDownClient*)GetItemData(iSel) : NULL;
CTitleMenu ClientMenu;
ClientMenu.CreatePopupMenu();
ClientMenu.AddMenuTitle(GetResString(IDS_CLIENTS), true);
ClientMenu.AppendMenu(MF_STRING | (client ? MF_ENABLED : MF_GRAYED), MP_DETAIL, GetResString(IDS_SHOWDETAILS), _T("CLIENTDETAILS"));
ClientMenu.SetDefaultItem(MP_DETAIL);
/* ismod: friend slot [start]
ClientMenu.AppendMenu(MF_STRING | ((client && client->IsEd2kClient() && !client->IsFriend()) ? MF_ENABLED : MF_GRAYED), MP_ADDFRIEND, GetResString(IDS_ADDFRIEND), _T("ADDFRIEND"));
*/
if ( client )
{
if ( !client->IsFriend() && client->IsEd2kClient() )
ClientMenu.AppendMenu(MF_STRING | MF_ENABLED, MP_ADDFRIEND, GetResString(IDS_ADDFRIEND), _T("ADDFRIEND"));
else
{
ClientMenu.AppendMenu(MF_STRING | MF_ENABLED, MP_FRIENDSLOT, GetResString(IDS_FRIENDSLOT), _T("FRIENDSLOT"));
ClientMenu.CheckMenuItem(MP_FRIENDSLOT, client->GetFriendSlot() ? MF_CHECKED : MF_UNCHECKED);
}
}
// ismod [end]
ClientMenu.AppendMenu(MF_STRING | ((client && client->IsEd2kClient()) ? MF_ENABLED : MF_GRAYED), MP_MESSAGE, GetResString(IDS_SEND_MSG), _T("SENDMESSAGE"));
ClientMenu.AppendMenu(MF_STRING | ((client && client->IsEd2kClient() && client->GetViewSharedFilesSupport()) ? MF_ENABLED : MF_GRAYED), MP_SHOWLIST, GetResString(IDS_VIEWFILES), _T("VIEWFILES"));
if (thePrefs.IsExtControlsEnabled())
ClientMenu.AppendMenu(MF_STRING | ((client && client->IsEd2kClient() && client->IsBanned()) ? MF_ENABLED : MF_GRAYED), MP_UNBAN, GetResString(IDS_UNBAN));
if (Kademlia::CKademlia::IsRunning() && !Kademlia::CKademlia::IsConnected())
ClientMenu.AppendMenu(MF_STRING | ((client && client->IsEd2kClient() && client->GetKadPort()!=0) ? MF_ENABLED : MF_GRAYED), MP_BOOT, GetResString(IDS_BOOTSTRAP));
ClientMenu.AppendMenu(MF_STRING | (GetItemCount() > 0 ? MF_ENABLED : MF_GRAYED), MP_FIND, GetResString(IDS_FIND), _T("Search"));
// ismod: goto file
ClientMenu.AppendMenu(MF_STRING | ((client && (theApp.sharedfiles->GetFileByID(client->GetUploadFileID())!=NULL)) ? MF_ENABLED : MF_GRAYED), MP_GOTOFILE, GetResString(IDS_MOD_GOTOFILE), _T("SEARCHFILETYPE_ANY"));
GetPopupMenuPos(*this, point);
ClientMenu.TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, this);
}
BOOL CQueueListCtrl::OnCommand(WPARAM wParam, LPARAM /*lParam*/)
{
wParam = LOWORD(wParam);
switch (wParam)
{
case MP_FIND:
OnFindStart();
return TRUE;
}
int iSel = GetNextItem(-1, LVIS_SELECTED | LVIS_FOCUSED);
if (iSel != -1){
CUpDownClient* client = (CUpDownClient*)GetItemData(iSel);
switch (wParam){
case MP_SHOWLIST:
client->RequestSharedFileList();
break;
// ismod: goto file [start]
case MP_GOTOFILE:
if ( client ) {
const CKnownFile* temp = theApp.sharedfiles->GetFileByID(client->GetUploadFileID());
if ( temp ) {
if ( temp->IsPartFile() ) {
theApp.emuledlg->transferwnd->GetDownloadList()->GotoFile((CPartFile *)temp);
} else {
theApp.emuledlg->sharedfileswnd->GotoFile(temp);
theApp.emuledlg->SetActiveDialog(theApp.emuledlg->sharedfileswnd);
}
}
}
break;
// ismod
case MP_MESSAGE:
theApp.emuledlg->chatwnd->StartSession(client);
break;
case MP_ADDFRIEND:
if (theApp.friendlist->AddFriend(client))
Update(iSel);
break;
case MP_UNBAN:
if (client->IsBanned()){
client->UnBan();
Update(iSel);
}
break;
case MP_DETAIL:
case MPG_ALTENTER:
case IDA_ENTER:
{
CClientDetailDialog dialog(client, this);
dialog.DoModal();
break;
}
case MP_BOOT:
if (client->GetKadPort())
Kademlia::CKademlia::Bootstrap(ntohl(client->GetIP()), client->GetKadPort(), (client->GetKadVersion() > 1));
break;
// ismod: friend slot [start]
case MP_FRIENDSLOT:
{
CFriend *cur_friend = theApp.friendlist->SearchFriend(client->GetUserHash(),client->GetIP(),client->GetUserPort());
if ( cur_friend )
{
if( cur_friend->GetFriendSlot() )
cur_friend->SetFriendSlot(false);
else
{
theApp.friendlist->RemoveAllFriendSlots();
cur_friend->SetFriendSlot(true);
}
}
break;
}
// ismod [end]
}
}
return true;
}
void CQueueListCtrl::AddClient(/*const*/ CUpDownClient *client, bool resetclient)
{
if (resetclient && client){
client->SetWaitStartTime();
client->SetAskedCount(1);
}
if (!theApp.IsRunning())
return;
if (thePrefs.IsQueueListDisabled())
return;
int iItemCount = GetItemCount();
int iItem = InsertItem(LVIF_TEXT | LVIF_PARAM, iItemCount, LPSTR_TEXTCALLBACK, 0, 0, 0, (LPARAM)client);
Update(iItem);
theApp.emuledlg->transferwnd->UpdateListCount(CTransferDlg::wnd2OnQueue, iItemCount + 1);
}
void CQueueListCtrl::RemoveClient(const CUpDownClient *client)
{
if (!theApp.IsRunning())
return;
LVFINDINFO find;
find.flags = LVFI_PARAM;
find.lParam = (LPARAM)client;
int result = FindItem(&find);
if (result != -1) {
DeleteItem(result);
theApp.emuledlg->transferwnd->UpdateListCount(CTransferDlg::wnd2OnQueue);
}
}
void CQueueListCtrl::RefreshClient(const CUpDownClient *client)
{
if (!theApp.IsRunning())
return;
if (theApp.emuledlg->activewnd != theApp.emuledlg->transferwnd || !theApp.emuledlg->transferwnd->GetQueueList()->IsWindowVisible())
return;
LVFINDINFO find;
find.flags = LVFI_PARAM;
find.lParam = (LPARAM)client;
int result = FindItem(&find);
if (result != -1)
Update(result);
}
void CQueueListCtrl::ShowSelectedUserDetails()
{
POINT point;
::GetCursorPos(&point);
CPoint p = point;
ScreenToClient(&p);
int it = HitTest(p);
if (it == -1)
return;
SetItemState(-1, 0, LVIS_SELECTED);
SetItemState(it, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
SetSelectionMark(it); // display selection mark correctly!
CUpDownClient* client = (CUpDownClient*)GetItemData(GetSelectionMark());
if (client){
CClientDetailDialog dialog(client, this);
dialog.DoModal();
}
}
void CQueueListCtrl::ShowQueueClients()
{
DeleteAllItems();
CUpDownClient *update = theApp.uploadqueue->GetNextClient(NULL);
while( update )
{
AddClient(update, false);
update = theApp.uploadqueue->GetNextClient(update);
}
}
// Barry - Refresh the queue every 10 secs
void CALLBACK CQueueListCtrl::QueueUpdateTimer(HWND /*hwnd*/, UINT /*uiMsg*/, UINT_PTR /*idEvent*/, DWORD /*dwTime*/)
{
// NOTE: Always handle all type of MFC exceptions in TimerProcs - otherwise we'll get mem leaks
try
{
if ( !theApp.IsRunning() // Don't do anything if the app is shutting down - can cause unhandled exceptions
|| !thePrefs.GetUpdateQueueList()
|| theApp.emuledlg->activewnd != theApp.emuledlg->transferwnd
|| !theApp.emuledlg->transferwnd->GetQueueList()->IsWindowVisible() )
return;
const CUpDownClient* update = theApp.uploadqueue->GetNextClient(NULL);
while( update )
{
theApp.emuledlg->transferwnd->GetQueueList()->RefreshClient(update);
update = theApp.uploadqueue->GetNextClient(update);
}
}
CATCH_DFLT_EXCEPTIONS(_T("CQueueListCtrl::QueueUpdateTimer"))
} | gpl-2.0 |
googaloo/Sunshine-Pest-Control | wp-content/themes/3clicks/template-parts/g1_about_author.php | 1208 | <?php
/**
* The Template Part for displaying "About Author" box.
*
* For the full license information, please view the Licensing folder
* that was distributed with this source code.
*
* @package G1_Framework
* @subpackage G1_Theme03
* @since G1_Theme03 1.0.0
*/
// Prevent direct script access
if ( !defined('ABSPATH') )
die ( 'No direct script access allowed' );
?>
<?php if ( post_type_supports( get_post_type(), 'author' ) && get_the_author_meta( 'description' ) ): ?>
<section itemscope itemtype="http://schema.org/Person" class="author-info">
<header class="author-title g1-hgroup">
<h6 class="g1-regular"><?php echo __( 'About the Author', 'g1_theme' ); ?></h6>
<h3 class="g1-important">
<a href="<?php echo esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ); ?>">
<span itemprop="name"><?php echo get_the_author(); ?></span>
</a>
</h3>
</header>
<figure class="author-avatar">
<?php echo get_avatar( get_the_author_meta('email'), 60 ); ?>
</figure>
<p itemprop="description" class="author-description">
<?php the_author_meta( 'description' ) ?>
</p>
</section>
<?php endif; ?> | gpl-2.0 |
mailwl/citra | src/citra_qt/multiplayer/direct_connect.cpp | 4865 | // Copyright 2017 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include <QComboBox>
#include <QFuture>
#include <QIntValidator>
#include <QRegExpValidator>
#include <QString>
#include <QtConcurrent/QtConcurrentRun>
#include "citra_qt/main.h"
#include "citra_qt/multiplayer/client_room.h"
#include "citra_qt/multiplayer/direct_connect.h"
#include "citra_qt/multiplayer/message.h"
#include "citra_qt/multiplayer/state.h"
#include "citra_qt/multiplayer/validation.h"
#include "citra_qt/ui_settings.h"
#include "core/hle/service/cfg/cfg.h"
#include "core/settings.h"
#include "network/network.h"
#include "ui_direct_connect.h"
enum class ConnectionType : u8 { TraversalServer, IP };
DirectConnectWindow::DirectConnectWindow(QWidget* parent)
: QDialog(parent, Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint),
ui(std::make_unique<Ui::DirectConnect>()) {
ui->setupUi(this);
// setup the watcher for background connections
watcher = new QFutureWatcher<void>;
connect(watcher, &QFutureWatcher<void>::finished, this, &DirectConnectWindow::OnConnection);
ui->nickname->setValidator(validation.GetNickname());
ui->nickname->setText(UISettings::values.nickname);
if (ui->nickname->text().isEmpty() && !Settings::values.citra_username.empty()) {
// Use Citra Web Service user name as nickname by default
ui->nickname->setText(QString::fromStdString(Settings::values.citra_username));
}
ui->ip->setValidator(validation.GetIP());
ui->ip->setText(UISettings::values.ip);
ui->port->setValidator(validation.GetPort());
ui->port->setText(UISettings::values.port);
// TODO(jroweboy): Show or hide the connection options based on the current value of the combo
// box. Add this back in when the traversal server support is added.
connect(ui->connect, &QPushButton::clicked, this, &DirectConnectWindow::Connect);
}
DirectConnectWindow::~DirectConnectWindow() = default;
void DirectConnectWindow::RetranslateUi() {
ui->retranslateUi(this);
}
void DirectConnectWindow::Connect() {
if (!ui->nickname->hasAcceptableInput()) {
NetworkMessage::ShowError(NetworkMessage::USERNAME_NOT_VALID);
return;
}
if (const auto member = Network::GetRoomMember().lock()) {
// Prevent the user from trying to join a room while they are already joining.
if (member->GetState() == Network::RoomMember::State::Joining) {
return;
} else if (member->IsConnected()) {
// And ask if they want to leave the room if they are already in one.
if (!NetworkMessage::WarnDisconnect()) {
return;
}
}
}
switch (static_cast<ConnectionType>(ui->connection_type->currentIndex())) {
case ConnectionType::TraversalServer:
break;
case ConnectionType::IP:
if (!ui->ip->hasAcceptableInput()) {
NetworkMessage::ShowError(NetworkMessage::IP_ADDRESS_NOT_VALID);
return;
}
if (!ui->port->hasAcceptableInput()) {
NetworkMessage::ShowError(NetworkMessage::PORT_NOT_VALID);
return;
}
break;
}
// Store settings
UISettings::values.nickname = ui->nickname->text();
UISettings::values.ip = ui->ip->text();
UISettings::values.port = (ui->port->isModified() && !ui->port->text().isEmpty())
? ui->port->text()
: UISettings::values.port;
Settings::Apply();
// attempt to connect in a different thread
QFuture<void> f = QtConcurrent::run([&] {
if (auto room_member = Network::GetRoomMember().lock()) {
auto port = UISettings::values.port.toUInt();
room_member->Join(ui->nickname->text().toStdString(),
Service::CFG::GetConsoleIdHash(Core::System::GetInstance()),
ui->ip->text().toStdString().c_str(), port, 0,
Network::NoPreferredMac, ui->password->text().toStdString().c_str());
}
});
watcher->setFuture(f);
// and disable widgets and display a connecting while we wait
BeginConnecting();
}
void DirectConnectWindow::BeginConnecting() {
ui->connect->setEnabled(false);
ui->connect->setText(tr("Connecting"));
}
void DirectConnectWindow::EndConnecting() {
ui->connect->setEnabled(true);
ui->connect->setText(tr("Connect"));
}
void DirectConnectWindow::OnConnection() {
EndConnecting();
if (auto room_member = Network::GetRoomMember().lock()) {
if (room_member->GetState() == Network::RoomMember::State::Joined ||
room_member->GetState() == Network::RoomMember::State::Moderator) {
close();
}
}
}
| gpl-2.0 |
Victov/NClass | src/Core/Members/Event.cs | 1779 | // NClass - Free class diagram editor
// Copyright (C) 2006-2009 Balazs Tihanyi
//
// 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, write to the Free Software Foundation, Inc.,
// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
namespace NClass.Core
{
public abstract class Event : Operation
{
/// <exception cref="BadSyntaxException">
/// The <paramref name="name" /> does not fit to the syntax.
/// </exception>
/// <exception cref="ArgumentException">
/// The language of <paramref name="parent" /> does not equal.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="parent" /> is null.
/// </exception>
protected Event( string name, CompositeType parent ) : base( name, parent ) {}
public sealed override MemberType MemberType
{
get { return MemberType.Event; }
}
public sealed override string GetUmlDescription( bool getType, bool getParameters, bool getParameterNames, bool getInitValue )
{
if ( getType )
return Name + " : " + Type;
return Name;
}
}
} | gpl-2.0 |
RedHenLab/Audio | GSoC2015/BroadcastSegmentor/src/be/panako/strategy/nfft/package-info.java | 2791 | /***************************************************************************
* *
* Panako - acoustic fingerprinting *
* Copyright (C) 2014 - Joren Six / IPEM *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero 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 Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/> *
* *
****************************************************************************
* ______ ________ ___ __ ________ ___ ___ ______ *
* /_____/\ /_______/\ /__/\ /__/\ /_______/\ /___/\/__/\ /_____/\ *
* \:::_ \ \\::: _ \ \\::\_\\ \ \\::: _ \ \\::.\ \\ \ \\:::_ \ \ *
* \:(_) \ \\::(_) \ \\:. `-\ \ \\::(_) \ \\:: \/_) \ \\:\ \ \ \ *
* \: ___\/ \:: __ \ \\:. _ \ \\:: __ \ \\:. __ ( ( \:\ \ \ \ *
* \ \ \ \:.\ \ \ \\. \`-\ \ \\:.\ \ \ \\: \ ) \ \ \:\_\ \ \ *
* \_\/ \__\/\__\/ \__\/ \__\/ \__\/\__\/ \__\/\__\/ \_____\/ *
* *
****************************************************************************
* *
* Panako *
* Acoustic Fingerprinting *
* *
****************************************************************************/
/**
* A cleaner implementation of the FFT event point extractor and matcher.
* It uses a streaming minimum/maximum filter to find peaks. The N in NFFT stands for New.
*/
package be.panako.strategy.nfft;
| gpl-2.0 |
FauxFaux/jdk9-jdk | src/java.desktop/share/classes/javax/swing/JComponent.java | 214809 | /*
* Copyright (c) 1997, 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. 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 javax.swing;
import java.beans.*;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Vector;
import java.util.EventListener;
import java.util.Set;
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.io.ObjectInputValidation;
import java.io.InvalidObjectException;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.plaf.*;
import static javax.swing.ClientPropertyKey.*;
import javax.accessibility.*;
import sun.awt.AWTAccessor;
import sun.awt.SunToolkit;
import sun.swing.SwingUtilities2;
/**
* The base class for all Swing components except top-level containers.
* To use a component that inherits from <code>JComponent</code>,
* you must place the component in a containment hierarchy
* whose root is a top-level Swing container.
* Top-level Swing containers --
* such as <code>JFrame</code>, <code>JDialog</code>,
* and <code>JApplet</code> --
* are specialized components
* that provide a place for other Swing components to paint themselves.
* For an explanation of containment hierarchies, see
* <a
href="http://docs.oracle.com/javase/tutorial/uiswing/components/toplevel.html">Swing Components and the Containment Hierarchy</a>,
* a section in <em>The Java Tutorial</em>.
*
* <p>
* The <code>JComponent</code> class provides:
* <ul>
* <li>The base class for both standard and custom components
* that use the Swing architecture.
* <li>A "pluggable look and feel" (L&F) that can be specified by the
* programmer or (optionally) selected by the user at runtime.
* The look and feel for each component is provided by a
* <em>UI delegate</em> -- an object that descends from
* {@link javax.swing.plaf.ComponentUI}.
* See <a
* href="http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html">How
* to Set the Look and Feel</a>
* in <em>The Java Tutorial</em>
* for more information.
* <li>Comprehensive keystroke handling.
* See the document <a
* href="http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html">How to Use Key Bindings</a>,
* an article in <em>The Java Tutorial</em>,
* for more information.
* <li>Support for tool tips --
* short descriptions that pop up when the cursor lingers
* over a component.
* See <a
* href="http://docs.oracle.com/javase/tutorial/uiswing/components/tooltip.html">How
* to Use Tool Tips</a>
* in <em>The Java Tutorial</em>
* for more information.
* <li>Support for accessibility.
* <code>JComponent</code> contains all of the methods in the
* <code>Accessible</code> interface,
* but it doesn't actually implement the interface. That is the
* responsibility of the individual classes
* that extend <code>JComponent</code>.
* <li>Support for component-specific properties.
* With the {@link #putClientProperty}
* and {@link #getClientProperty} methods,
* you can associate name-object pairs
* with any object that descends from <code>JComponent</code>.
* <li>An infrastructure for painting
* that includes double buffering and support for borders.
* For more information see <a
* href="http://www.oracle.com/technetwork/java/painting-140037.html#swing">Painting</a> and
* <a href="http://docs.oracle.com/javase/tutorial/uiswing/components/border.html">How
* to Use Borders</a>,
* both of which are sections in <em>The Java Tutorial</em>.
* </ul>
* For more information on these subjects, see the
* <a href="package-summary.html#package_description">Swing package description</a>
* and <em>The Java Tutorial</em> section
* <a href="http://docs.oracle.com/javase/tutorial/uiswing/components/jcomponent.html">The JComponent Class</a>.
* <p>
* <code>JComponent</code> and its subclasses document default values
* for certain properties. For example, <code>JTable</code> documents the
* default row height as 16. Each <code>JComponent</code> subclass
* that has a <code>ComponentUI</code> will create the
* <code>ComponentUI</code> as part of its constructor. In order
* to provide a particular look and feel each
* <code>ComponentUI</code> may set properties back on the
* <code>JComponent</code> that created it. For example, a custom
* look and feel may require <code>JTable</code>s to have a row
* height of 24. The documented defaults are the value of a property
* BEFORE the <code>ComponentUI</code> has been installed. If you
* need a specific value for a particular property you should
* explicitly set it.
* <p>
* In release 1.4, the focus subsystem was rearchitected.
* For more information, see
* <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>.
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans™
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @see KeyStroke
* @see Action
* @see #setBorder
* @see #registerKeyboardAction
* @see JOptionPane
* @see #setDebugGraphicsOptions
* @see #setToolTipText
* @see #setAutoscrolls
*
* @author Hans Muller
* @author Arnaud Weber
* @since 1.2
*/
@JavaBean(defaultProperty = "UIClassID")
@SuppressWarnings("serial") // Same-version serialization only
public abstract class JComponent extends Container implements Serializable,
TransferHandler.HasGetTransferHandler
{
/**
* @see #getUIClassID
* @see #writeObject
*/
private static final String uiClassID = "ComponentUI";
/**
* @see #readObject
*/
private static final Hashtable<ObjectInputStream, ReadObjectCallback> readObjectCallbacks =
new Hashtable<ObjectInputStream, ReadObjectCallback>(1);
/**
* Keys to use for forward focus traversal when the JComponent is
* managing focus.
*/
private static Set<KeyStroke> managingFocusForwardTraversalKeys;
/**
* Keys to use for backward focus traversal when the JComponent is
* managing focus.
*/
private static Set<KeyStroke> managingFocusBackwardTraversalKeys;
// Following are the possible return values from getObscuredState.
private static final int NOT_OBSCURED = 0;
private static final int PARTIALLY_OBSCURED = 1;
private static final int COMPLETELY_OBSCURED = 2;
/**
* Set to true when DebugGraphics has been loaded.
*/
static boolean DEBUG_GRAPHICS_LOADED;
/**
* Key used to look up a value from the AppContext to determine the
* JComponent the InputVerifier is running for. That is, if
* AppContext.get(INPUT_VERIFIER_SOURCE_KEY) returns non-null, it
* indicates the EDT is calling into the InputVerifier from the
* returned component.
*/
private static final Object INPUT_VERIFIER_SOURCE_KEY =
new StringBuilder("InputVerifierSourceKey");
/* The following fields support set methods for the corresponding
* java.awt.Component properties.
*/
private boolean isAlignmentXSet;
private float alignmentX;
private boolean isAlignmentYSet;
private float alignmentY;
/**
* Backing store for JComponent properties and listeners
*/
/** The look and feel delegate for this component. */
protected transient ComponentUI ui;
/** A list of event listeners for this component. */
protected EventListenerList listenerList = new EventListenerList();
private transient ArrayTable clientProperties;
private VetoableChangeSupport vetoableChangeSupport;
/**
* Whether or not autoscroll has been enabled.
*/
private boolean autoscrolls;
private Border border;
private int flags;
/* Input verifier for this component */
private InputVerifier inputVerifier = null;
private boolean verifyInputWhenFocusTarget = true;
/**
* Set in <code>_paintImmediately</code>.
* Will indicate the child that initiated the painting operation.
* If <code>paintingChild</code> is opaque, no need to paint
* any child components after <code>paintingChild</code>.
* Test used in <code>paintChildren</code>.
*/
transient Component paintingChild;
/**
* Constant used for <code>registerKeyboardAction</code> that
* means that the command should be invoked when
* the component has the focus.
*/
public static final int WHEN_FOCUSED = 0;
/**
* Constant used for <code>registerKeyboardAction</code> that
* means that the command should be invoked when the receiving
* component is an ancestor of the focused component or is
* itself the focused component.
*/
public static final int WHEN_ANCESTOR_OF_FOCUSED_COMPONENT = 1;
/**
* Constant used for <code>registerKeyboardAction</code> that
* means that the command should be invoked when
* the receiving component is in the window that has the focus
* or is itself the focused component.
*/
public static final int WHEN_IN_FOCUSED_WINDOW = 2;
/**
* Constant used by some of the APIs to mean that no condition is defined.
*/
public static final int UNDEFINED_CONDITION = -1;
/**
* The key used by <code>JComponent</code> to access keyboard bindings.
*/
private static final String KEYBOARD_BINDINGS_KEY = "_KeyboardBindings";
/**
* An array of <code>KeyStroke</code>s used for
* <code>WHEN_IN_FOCUSED_WINDOW</code> are stashed
* in the client properties under this string.
*/
private static final String WHEN_IN_FOCUSED_WINDOW_BINDINGS = "_WhenInFocusedWindow";
/**
* The comment to display when the cursor is over the component,
* also known as a "value tip", "flyover help", or "flyover label".
*/
public static final String TOOL_TIP_TEXT_KEY = "ToolTipText";
private static final String NEXT_FOCUS = "nextFocus";
/**
* <code>JPopupMenu</code> assigned to this component
* and all of its children
*/
private JPopupMenu popupMenu;
/** Private flags **/
private static final int IS_DOUBLE_BUFFERED = 0;
private static final int ANCESTOR_USING_BUFFER = 1;
private static final int IS_PAINTING_TILE = 2;
private static final int IS_OPAQUE = 3;
private static final int KEY_EVENTS_ENABLED = 4;
private static final int FOCUS_INPUTMAP_CREATED = 5;
private static final int ANCESTOR_INPUTMAP_CREATED = 6;
private static final int WIF_INPUTMAP_CREATED = 7;
private static final int ACTIONMAP_CREATED = 8;
private static final int CREATED_DOUBLE_BUFFER = 9;
// bit 10 is free
private static final int IS_PRINTING = 11;
private static final int IS_PRINTING_ALL = 12;
private static final int IS_REPAINTING = 13;
/** Bits 14-21 are used to handle nested writeObject calls. **/
private static final int WRITE_OBJ_COUNTER_FIRST = 14;
private static final int RESERVED_1 = 15;
private static final int RESERVED_2 = 16;
private static final int RESERVED_3 = 17;
private static final int RESERVED_4 = 18;
private static final int RESERVED_5 = 19;
private static final int RESERVED_6 = 20;
private static final int WRITE_OBJ_COUNTER_LAST = 21;
private static final int REQUEST_FOCUS_DISABLED = 22;
private static final int INHERITS_POPUP_MENU = 23;
private static final int OPAQUE_SET = 24;
private static final int AUTOSCROLLS_SET = 25;
private static final int FOCUS_TRAVERSAL_KEYS_FORWARD_SET = 26;
private static final int FOCUS_TRAVERSAL_KEYS_BACKWARD_SET = 27;
private transient AtomicBoolean revalidateRunnableScheduled = new AtomicBoolean(false);
/**
* Temporary rectangles.
*/
private static java.util.List<Rectangle> tempRectangles = new java.util.ArrayList<Rectangle>(11);
/** Used for <code>WHEN_FOCUSED</code> bindings. */
private InputMap focusInputMap;
/** Used for <code>WHEN_ANCESTOR_OF_FOCUSED_COMPONENT</code> bindings. */
private InputMap ancestorInputMap;
/** Used for <code>WHEN_IN_FOCUSED_KEY</code> bindings. */
private ComponentInputMap windowInputMap;
/** ActionMap. */
private ActionMap actionMap;
/** Key used to store the default locale in an AppContext **/
private static final String defaultLocale = "JComponent.defaultLocale";
private static Component componentObtainingGraphicsFrom;
private static Object componentObtainingGraphicsFromLock = new
StringBuilder("componentObtainingGraphicsFrom");
/**
* AA text hints.
*/
private transient Object aaHint;
private transient Object lcdRenderingHint;
static Graphics safelyGetGraphics(Component c) {
return safelyGetGraphics(c, SwingUtilities.getRoot(c));
}
static Graphics safelyGetGraphics(Component c, Component root) {
synchronized(componentObtainingGraphicsFromLock) {
componentObtainingGraphicsFrom = root;
Graphics g = c.getGraphics();
componentObtainingGraphicsFrom = null;
return g;
}
}
static void getGraphicsInvoked(Component root) {
if (!JComponent.isComponentObtainingGraphicsFrom(root)) {
JRootPane rootPane = ((RootPaneContainer)root).getRootPane();
if (rootPane != null) {
rootPane.disableTrueDoubleBuffering();
}
}
}
/**
* Returns true if {@code c} is the component the graphics is being
* requested of. This is intended for use when getGraphics is invoked.
*/
private static boolean isComponentObtainingGraphicsFrom(Component c) {
synchronized(componentObtainingGraphicsFromLock) {
return (componentObtainingGraphicsFrom == c);
}
}
/**
* Returns the Set of <code>KeyStroke</code>s to use if the component
* is managing focus for forward focus traversal.
*/
static Set<KeyStroke> getManagingFocusForwardTraversalKeys() {
synchronized(JComponent.class) {
if (managingFocusForwardTraversalKeys == null) {
managingFocusForwardTraversalKeys = new HashSet<KeyStroke>(1);
managingFocusForwardTraversalKeys.add(
KeyStroke.getKeyStroke(KeyEvent.VK_TAB,
InputEvent.CTRL_MASK));
}
}
return managingFocusForwardTraversalKeys;
}
/**
* Returns the Set of <code>KeyStroke</code>s to use if the component
* is managing focus for backward focus traversal.
*/
static Set<KeyStroke> getManagingFocusBackwardTraversalKeys() {
synchronized(JComponent.class) {
if (managingFocusBackwardTraversalKeys == null) {
managingFocusBackwardTraversalKeys = new HashSet<KeyStroke>(1);
managingFocusBackwardTraversalKeys.add(
KeyStroke.getKeyStroke(KeyEvent.VK_TAB,
InputEvent.SHIFT_MASK |
InputEvent.CTRL_MASK));
}
}
return managingFocusBackwardTraversalKeys;
}
private static Rectangle fetchRectangle() {
synchronized(tempRectangles) {
Rectangle rect;
int size = tempRectangles.size();
if (size > 0) {
rect = tempRectangles.remove(size - 1);
}
else {
rect = new Rectangle(0, 0, 0, 0);
}
return rect;
}
}
private static void recycleRectangle(Rectangle rect) {
synchronized(tempRectangles) {
tempRectangles.add(rect);
}
}
/**
* Sets whether or not <code>getComponentPopupMenu</code> should delegate
* to the parent if this component does not have a <code>JPopupMenu</code>
* assigned to it.
* <p>
* The default value for this is false, but some <code>JComponent</code>
* subclasses that are implemented as a number of <code>JComponent</code>s
* may set this to true.
* <p>
* This is a bound property.
*
* @param value whether or not the JPopupMenu is inherited
* @see #setComponentPopupMenu
* @since 1.5
*/
@BeanProperty(description
= "Whether or not the JPopupMenu is inherited")
public void setInheritsPopupMenu(boolean value) {
boolean oldValue = getFlag(INHERITS_POPUP_MENU);
setFlag(INHERITS_POPUP_MENU, value);
firePropertyChange("inheritsPopupMenu", oldValue, value);
}
/**
* Returns true if the JPopupMenu should be inherited from the parent.
*
* @return true if the JPopupMenu should be inherited from the parent
* @see #setComponentPopupMenu
* @since 1.5
*/
public boolean getInheritsPopupMenu() {
return getFlag(INHERITS_POPUP_MENU);
}
/**
* Sets the <code>JPopupMenu</code> for this <code>JComponent</code>.
* The UI is responsible for registering bindings and adding the necessary
* listeners such that the <code>JPopupMenu</code> will be shown at
* the appropriate time. When the <code>JPopupMenu</code> is shown
* depends upon the look and feel: some may show it on a mouse event,
* some may enable a key binding.
* <p>
* If <code>popup</code> is null, and <code>getInheritsPopupMenu</code>
* returns true, then <code>getComponentPopupMenu</code> will be delegated
* to the parent. This provides for a way to make all child components
* inherit the popupmenu of the parent.
* <p>
* This is a bound property.
*
* @param popup - the popup that will be assigned to this component
* may be null
* @see #getComponentPopupMenu
* @since 1.5
*/
@BeanProperty(preferred = true, description
= "Popup to show")
public void setComponentPopupMenu(JPopupMenu popup) {
if(popup != null) {
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
}
JPopupMenu oldPopup = this.popupMenu;
this.popupMenu = popup;
firePropertyChange("componentPopupMenu", oldPopup, popup);
}
/**
* Returns <code>JPopupMenu</code> that assigned for this component.
* If this component does not have a <code>JPopupMenu</code> assigned
* to it and <code>getInheritsPopupMenu</code> is true, this
* will return <code>getParent().getComponentPopupMenu()</code> (assuming
* the parent is valid.)
*
* @return <code>JPopupMenu</code> assigned for this component
* or <code>null</code> if no popup assigned
* @see #setComponentPopupMenu
* @since 1.5
*/
public JPopupMenu getComponentPopupMenu() {
if(!getInheritsPopupMenu()) {
return popupMenu;
}
if(popupMenu == null) {
// Search parents for its popup
Container parent = getParent();
while (parent != null) {
if(parent instanceof JComponent) {
return ((JComponent)parent).getComponentPopupMenu();
}
if(parent instanceof Window ||
parent instanceof Applet) {
// Reached toplevel, break and return null
break;
}
parent = parent.getParent();
}
return null;
}
return popupMenu;
}
/**
* Default <code>JComponent</code> constructor. This constructor does
* very little initialization beyond calling the <code>Container</code>
* constructor. For example, the initial layout manager is
* <code>null</code>. It does, however, set the component's locale
* property to the value returned by
* <code>JComponent.getDefaultLocale</code>.
*
* @see #getDefaultLocale
*/
public JComponent() {
super();
// We enable key events on all JComponents so that accessibility
// bindings will work everywhere. This is a partial fix to BugID
// 4282211.
enableEvents(AWTEvent.KEY_EVENT_MASK);
if (isManagingFocus()) {
LookAndFeel.installProperty(this,
"focusTraversalKeysForward",
getManagingFocusForwardTraversalKeys());
LookAndFeel.installProperty(this,
"focusTraversalKeysBackward",
getManagingFocusBackwardTraversalKeys());
}
super.setLocale( JComponent.getDefaultLocale() );
}
/**
* Resets the UI property to a value from the current look and feel.
* <code>JComponent</code> subclasses must override this method
* like this:
* <pre>
* public void updateUI() {
* setUI((SliderUI)UIManager.getUI(this);
* }
* </pre>
*
* @see #setUI
* @see UIManager#getLookAndFeel
* @see UIManager#getUI
*/
public void updateUI() {}
/**
* Returns the look and feel delegate that renders this component.
*
* @return the {@code ComponentUI} object that renders this component
* @since 9
*/
@Transient
public ComponentUI getUI() {
return ui;
}
/**
* Sets the look and feel delegate for this component.
* <code>JComponent</code> subclasses generally override this method
* to narrow the argument type. For example, in <code>JSlider</code>:
* <pre>
* public void setUI(SliderUI newUI) {
* super.setUI(newUI);
* }
* </pre>
* <p>
* Additionally <code>JComponent</code> subclasses must provide a
* <code>getUI</code> method that returns the correct type. For example:
* <pre>
* public SliderUI getUI() {
* return (SliderUI)ui;
* }
* </pre>
*
* @param newUI the new UI delegate
* @see #updateUI
* @see UIManager#getLookAndFeel
* @see UIManager#getUI
*/
@BeanProperty(hidden = true, visualUpdate = true, description
= "The component's look and feel delegate.")
protected void setUI(ComponentUI newUI) {
/* We do not check that the UI instance is different
* before allowing the switch in order to enable the
* same UI instance *with different default settings*
* to be installed.
*/
uninstallUIAndProperties();
// aaText shouldn't persist between look and feels, reset it.
aaHint = UIManager.getDefaults().get(
RenderingHints.KEY_TEXT_ANTIALIASING);
lcdRenderingHint = UIManager.getDefaults().get(
RenderingHints.KEY_TEXT_LCD_CONTRAST);
ComponentUI oldUI = ui;
ui = newUI;
if (ui != null) {
ui.installUI(this);
}
firePropertyChange("UI", oldUI, newUI);
revalidate();
repaint();
}
/**
* Uninstalls the UI, if any, and any client properties designated
* as being specific to the installed UI - instances of
* {@code UIClientPropertyKey}.
*/
private void uninstallUIAndProperties() {
if (ui != null) {
ui.uninstallUI(this);
//clean UIClientPropertyKeys from client properties
if (clientProperties != null) {
synchronized(clientProperties) {
Object[] clientPropertyKeys =
clientProperties.getKeys(null);
if (clientPropertyKeys != null) {
for (Object key : clientPropertyKeys) {
if (key instanceof UIClientPropertyKey) {
putClientProperty(key, null);
}
}
}
}
}
}
}
/**
* Returns the <code>UIDefaults</code> key used to
* look up the name of the <code>swing.plaf.ComponentUI</code>
* class that defines the look and feel
* for this component. Most applications will never need to
* call this method. Subclasses of <code>JComponent</code> that support
* pluggable look and feel should override this method to
* return a <code>UIDefaults</code> key that maps to the
* <code>ComponentUI</code> subclass that defines their look and feel.
*
* @return the <code>UIDefaults</code> key for a
* <code>ComponentUI</code> subclass
* @see UIDefaults#getUI
*/
@BeanProperty(bound = false, expert = true, description
= "UIClassID")
public String getUIClassID() {
return uiClassID;
}
/**
* Returns the graphics object used to paint this component.
* If <code>DebugGraphics</code> is turned on we create a new
* <code>DebugGraphics</code> object if necessary.
* Otherwise we just configure the
* specified graphics object's foreground and font.
*
* @param g the original <code>Graphics</code> object
* @return a <code>Graphics</code> object configured for this component
*/
protected Graphics getComponentGraphics(Graphics g) {
Graphics componentGraphics = g;
if (ui != null && DEBUG_GRAPHICS_LOADED) {
if ((DebugGraphics.debugComponentCount() != 0) &&
(shouldDebugGraphics() != 0) &&
!(g instanceof DebugGraphics)) {
componentGraphics = new DebugGraphics(g,this);
}
}
componentGraphics.setColor(getForeground());
componentGraphics.setFont(getFont());
return componentGraphics;
}
/**
* Calls the UI delegate's paint method, if the UI delegate
* is non-<code>null</code>. We pass the delegate a copy of the
* <code>Graphics</code> object to protect the rest of the
* paint code from irrevocable changes
* (for example, <code>Graphics.translate</code>).
* <p>
* If you override this in a subclass you should not make permanent
* changes to the passed in <code>Graphics</code>. For example, you
* should not alter the clip <code>Rectangle</code> or modify the
* transform. If you need to do these operations you may find it
* easier to create a new <code>Graphics</code> from the passed in
* <code>Graphics</code> and manipulate it. Further, if you do not
* invoker super's implementation you must honor the opaque property,
* that is
* if this component is opaque, you must completely fill in the background
* in a non-opaque color. If you do not honor the opaque property you
* will likely see visual artifacts.
* <p>
* The passed in <code>Graphics</code> object might
* have a transform other than the identify transform
* installed on it. In this case, you might get
* unexpected results if you cumulatively apply
* another transform.
*
* @param g the <code>Graphics</code> object to protect
* @see #paint
* @see ComponentUI
*/
protected void paintComponent(Graphics g) {
if (ui != null) {
Graphics scratchGraphics = (g == null) ? null : g.create();
try {
ui.update(scratchGraphics, this);
}
finally {
scratchGraphics.dispose();
}
}
}
/**
* Paints this component's children.
* If <code>shouldUseBuffer</code> is true,
* no component ancestor has a buffer and
* the component children can use a buffer if they have one.
* Otherwise, one ancestor has a buffer currently in use and children
* should not use a buffer to paint.
* @param g the <code>Graphics</code> context in which to paint
* @see #paint
* @see java.awt.Container#paint
*/
protected void paintChildren(Graphics g) {
Graphics sg = g;
synchronized(getTreeLock()) {
int i = getComponentCount() - 1;
if (i < 0) {
return;
}
// If we are only to paint to a specific child, determine
// its index.
if (paintingChild != null &&
(paintingChild instanceof JComponent) &&
paintingChild.isOpaque()) {
for (; i >= 0; i--) {
if (getComponent(i) == paintingChild){
break;
}
}
}
Rectangle tmpRect = fetchRectangle();
boolean checkSiblings = (!isOptimizedDrawingEnabled() &&
checkIfChildObscuredBySibling());
Rectangle clipBounds = null;
if (checkSiblings) {
clipBounds = sg.getClipBounds();
if (clipBounds == null) {
clipBounds = new Rectangle(0, 0, getWidth(),
getHeight());
}
}
boolean printing = getFlag(IS_PRINTING);
final Window window = SwingUtilities.getWindowAncestor(this);
final boolean isWindowOpaque = window == null || window.isOpaque();
for (; i >= 0 ; i--) {
Component comp = getComponent(i);
if (comp == null) {
continue;
}
final boolean isJComponent = comp instanceof JComponent;
// Enable painting of heavyweights in non-opaque windows.
// See 6884960
if ((!isWindowOpaque || isJComponent ||
isLightweightComponent(comp)) && comp.isVisible())
{
Rectangle cr;
cr = comp.getBounds(tmpRect);
Shape clip = g.getClip();
boolean hitClip = (clip != null)
? clip.intersects(cr.x, cr.y, cr.width, cr.height)
: true;
if (hitClip) {
if (checkSiblings && i > 0) {
int x = cr.x;
int y = cr.y;
int width = cr.width;
int height = cr.height;
SwingUtilities.computeIntersection
(clipBounds.x, clipBounds.y,
clipBounds.width, clipBounds.height, cr);
if(getObscuredState(i, cr.x, cr.y, cr.width,
cr.height) == COMPLETELY_OBSCURED) {
continue;
}
cr.x = x;
cr.y = y;
cr.width = width;
cr.height = height;
}
Graphics cg = sg.create(cr.x, cr.y, cr.width,
cr.height);
cg.setColor(comp.getForeground());
cg.setFont(comp.getFont());
boolean shouldSetFlagBack = false;
try {
if(isJComponent) {
if(getFlag(ANCESTOR_USING_BUFFER)) {
((JComponent)comp).setFlag(
ANCESTOR_USING_BUFFER,true);
shouldSetFlagBack = true;
}
if(getFlag(IS_PAINTING_TILE)) {
((JComponent)comp).setFlag(
IS_PAINTING_TILE,true);
shouldSetFlagBack = true;
}
if(!printing) {
comp.paint(cg);
}
else {
if (!getFlag(IS_PRINTING_ALL)) {
comp.print(cg);
}
else {
comp.printAll(cg);
}
}
} else {
// The component is either lightweight, or
// heavyweight in a non-opaque window
if (!printing) {
comp.paint(cg);
}
else {
if (!getFlag(IS_PRINTING_ALL)) {
comp.print(cg);
}
else {
comp.printAll(cg);
}
}
}
} finally {
cg.dispose();
if(shouldSetFlagBack) {
((JComponent)comp).setFlag(
ANCESTOR_USING_BUFFER,false);
((JComponent)comp).setFlag(
IS_PAINTING_TILE,false);
}
}
}
}
}
recycleRectangle(tmpRect);
}
}
/**
* Paints the component's border.
* <p>
* If you override this in a subclass you should not make permanent
* changes to the passed in <code>Graphics</code>. For example, you
* should not alter the clip <code>Rectangle</code> or modify the
* transform. If you need to do these operations you may find it
* easier to create a new <code>Graphics</code> from the passed in
* <code>Graphics</code> and manipulate it.
*
* @param g the <code>Graphics</code> context in which to paint
*
* @see #paint
* @see #setBorder
*/
protected void paintBorder(Graphics g) {
Border border = getBorder();
if (border != null) {
border.paintBorder(this, g, 0, 0, getWidth(), getHeight());
}
}
/**
* Calls <code>paint</code>. Doesn't clear the background but see
* <code>ComponentUI.update</code>, which is called by
* <code>paintComponent</code>.
*
* @param g the <code>Graphics</code> context in which to paint
* @see #paint
* @see #paintComponent
* @see javax.swing.plaf.ComponentUI
*/
public void update(Graphics g) {
paint(g);
}
/**
* Invoked by Swing to draw components.
* Applications should not invoke <code>paint</code> directly,
* but should instead use the <code>repaint</code> method to
* schedule the component for redrawing.
* <p>
* This method actually delegates the work of painting to three
* protected methods: <code>paintComponent</code>,
* <code>paintBorder</code>,
* and <code>paintChildren</code>. They're called in the order
* listed to ensure that children appear on top of component itself.
* Generally speaking, the component and its children should not
* paint in the insets area allocated to the border. Subclasses can
* just override this method, as always. A subclass that just
* wants to specialize the UI (look and feel) delegate's
* <code>paint</code> method should just override
* <code>paintComponent</code>.
*
* @param g the <code>Graphics</code> context in which to paint
* @see #paintComponent
* @see #paintBorder
* @see #paintChildren
* @see #getComponentGraphics
* @see #repaint
*/
public void paint(Graphics g) {
boolean shouldClearPaintFlags = false;
if ((getWidth() <= 0) || (getHeight() <= 0)) {
return;
}
Graphics componentGraphics = getComponentGraphics(g);
Graphics co = componentGraphics.create();
try {
RepaintManager repaintManager = RepaintManager.currentManager(this);
Rectangle clipRect = co.getClipBounds();
int clipX;
int clipY;
int clipW;
int clipH;
if (clipRect == null) {
clipX = clipY = 0;
clipW = getWidth();
clipH = getHeight();
}
else {
clipX = clipRect.x;
clipY = clipRect.y;
clipW = clipRect.width;
clipH = clipRect.height;
}
if(clipW > getWidth()) {
clipW = getWidth();
}
if(clipH > getHeight()) {
clipH = getHeight();
}
if(getParent() != null && !(getParent() instanceof JComponent)) {
adjustPaintFlags();
shouldClearPaintFlags = true;
}
int bw,bh;
boolean printing = getFlag(IS_PRINTING);
if (!printing && repaintManager.isDoubleBufferingEnabled() &&
!getFlag(ANCESTOR_USING_BUFFER) && isDoubleBuffered() &&
(getFlag(IS_REPAINTING) || repaintManager.isPainting()))
{
repaintManager.beginPaint();
try {
repaintManager.paint(this, this, co, clipX, clipY, clipW,
clipH);
} finally {
repaintManager.endPaint();
}
}
else {
// Will ocassionaly happen in 1.2, especially when printing.
if (clipRect == null) {
co.setClip(clipX, clipY, clipW, clipH);
}
if (!rectangleIsObscured(clipX,clipY,clipW,clipH)) {
if (!printing) {
paintComponent(co);
paintBorder(co);
}
else {
printComponent(co);
printBorder(co);
}
}
if (!printing) {
paintChildren(co);
}
else {
printChildren(co);
}
}
} finally {
co.dispose();
if(shouldClearPaintFlags) {
setFlag(ANCESTOR_USING_BUFFER,false);
setFlag(IS_PAINTING_TILE,false);
setFlag(IS_PRINTING,false);
setFlag(IS_PRINTING_ALL,false);
}
}
}
// paint forcing use of the double buffer. This is used for historical
// reasons: JViewport, when scrolling, previously directly invoked paint
// while turning off double buffering at the RepaintManager level, this
// codes simulates that.
void paintForceDoubleBuffered(Graphics g) {
RepaintManager rm = RepaintManager.currentManager(this);
Rectangle clip = g.getClipBounds();
rm.beginPaint();
setFlag(IS_REPAINTING, true);
try {
rm.paint(this, this, g, clip.x, clip.y, clip.width, clip.height);
} finally {
rm.endPaint();
setFlag(IS_REPAINTING, false);
}
}
/**
* Returns true if this component, or any of its ancestors, are in
* the processing of painting.
*/
boolean isPainting() {
Container component = this;
while (component != null) {
if (component instanceof JComponent &&
((JComponent)component).getFlag(ANCESTOR_USING_BUFFER)) {
return true;
}
component = component.getParent();
}
return false;
}
private void adjustPaintFlags() {
JComponent jparent;
Container parent;
for(parent = getParent() ; parent != null ; parent =
parent.getParent()) {
if(parent instanceof JComponent) {
jparent = (JComponent) parent;
if(jparent.getFlag(ANCESTOR_USING_BUFFER))
setFlag(ANCESTOR_USING_BUFFER, true);
if(jparent.getFlag(IS_PAINTING_TILE))
setFlag(IS_PAINTING_TILE, true);
if(jparent.getFlag(IS_PRINTING))
setFlag(IS_PRINTING, true);
if(jparent.getFlag(IS_PRINTING_ALL))
setFlag(IS_PRINTING_ALL, true);
break;
}
}
}
/**
* Invoke this method to print the component. This method invokes
* <code>print</code> on the component.
*
* @param g the <code>Graphics</code> context in which to paint
* @see #print
* @see #printComponent
* @see #printBorder
* @see #printChildren
*/
public void printAll(Graphics g) {
setFlag(IS_PRINTING_ALL, true);
try {
print(g);
}
finally {
setFlag(IS_PRINTING_ALL, false);
}
}
/**
* Invoke this method to print the component to the specified
* <code>Graphics</code>. This method will result in invocations
* of <code>printComponent</code>, <code>printBorder</code> and
* <code>printChildren</code>. It is recommended that you override
* one of the previously mentioned methods rather than this one if
* your intention is to customize the way printing looks. However,
* it can be useful to override this method should you want to prepare
* state before invoking the superclass behavior. As an example,
* if you wanted to change the component's background color before
* printing, you could do the following:
* <pre>
* public void print(Graphics g) {
* Color orig = getBackground();
* setBackground(Color.WHITE);
*
* // wrap in try/finally so that we always restore the state
* try {
* super.print(g);
* } finally {
* setBackground(orig);
* }
* }
* </pre>
* <p>
* Alternatively, or for components that delegate painting to other objects,
* you can query during painting whether or not the component is in the
* midst of a print operation. The <code>isPaintingForPrint</code> method provides
* this ability and its return value will be changed by this method: to
* <code>true</code> immediately before rendering and to <code>false</code>
* immediately after. With each change a property change event is fired on
* this component with the name <code>"paintingForPrint"</code>.
* <p>
* This method sets the component's state such that the double buffer
* will not be used: painting will be done directly on the passed in
* <code>Graphics</code>.
*
* @param g the <code>Graphics</code> context in which to paint
* @see #printComponent
* @see #printBorder
* @see #printChildren
* @see #isPaintingForPrint
*/
public void print(Graphics g) {
setFlag(IS_PRINTING, true);
firePropertyChange("paintingForPrint", false, true);
try {
paint(g);
}
finally {
setFlag(IS_PRINTING, false);
firePropertyChange("paintingForPrint", true, false);
}
}
/**
* This is invoked during a printing operation. This is implemented to
* invoke <code>paintComponent</code> on the component. Override this
* if you wish to add special painting behavior when printing.
*
* @param g the <code>Graphics</code> context in which to paint
* @see #print
* @since 1.3
*/
protected void printComponent(Graphics g) {
paintComponent(g);
}
/**
* Prints this component's children. This is implemented to invoke
* <code>paintChildren</code> on the component. Override this if you
* wish to print the children differently than painting.
*
* @param g the <code>Graphics</code> context in which to paint
* @see #print
* @since 1.3
*/
protected void printChildren(Graphics g) {
paintChildren(g);
}
/**
* Prints the component's border. This is implemented to invoke
* <code>paintBorder</code> on the component. Override this if you
* wish to print the border differently that it is painted.
*
* @param g the <code>Graphics</code> context in which to paint
* @see #print
* @since 1.3
*/
protected void printBorder(Graphics g) {
paintBorder(g);
}
/**
* Returns true if the component is currently painting a tile.
* If this method returns true, paint will be called again for another
* tile. This method returns false if you are not painting a tile or
* if the last tile is painted.
* Use this method to keep some state you might need between tiles.
*
* @return true if the component is currently painting a tile,
* false otherwise
*/
@BeanProperty(bound = false)
public boolean isPaintingTile() {
return getFlag(IS_PAINTING_TILE);
}
/**
* Returns <code>true</code> if the current painting operation on this
* component is part of a <code>print</code> operation. This method is
* useful when you want to customize what you print versus what you show
* on the screen.
* <p>
* You can detect changes in the value of this property by listening for
* property change events on this component with name
* <code>"paintingForPrint"</code>.
* <p>
* Note: This method provides complimentary functionality to that provided
* by other high level Swing printing APIs. However, it deals strictly with
* painting and should not be confused as providing information on higher
* level print processes. For example, a {@link javax.swing.JTable#print()}
* operation doesn't necessarily result in a continuous rendering of the
* full component, and the return value of this method can change multiple
* times during that operation. It is even possible for the component to be
* painted to the screen while the printing process is ongoing. In such a
* case, the return value of this method is <code>true</code> when, and only
* when, the table is being painted as part of the printing process.
*
* @return true if the current painting operation on this component
* is part of a print operation
* @see #print
* @since 1.6
*/
@BeanProperty(bound = false)
public final boolean isPaintingForPrint() {
return getFlag(IS_PRINTING);
}
/**
* In release 1.4, the focus subsystem was rearchitected.
* For more information, see
* <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>.
* <p>
* Changes this <code>JComponent</code>'s focus traversal keys to
* CTRL+TAB and CTRL+SHIFT+TAB. Also prevents
* <code>SortingFocusTraversalPolicy</code> from considering descendants
* of this JComponent when computing a focus traversal cycle.
*
* @return false
* @see java.awt.Component#setFocusTraversalKeys
* @see SortingFocusTraversalPolicy
* @deprecated As of 1.4, replaced by
* <code>Component.setFocusTraversalKeys(int, Set)</code> and
* <code>Container.setFocusCycleRoot(boolean)</code>.
*/
@Deprecated
@BeanProperty(bound = false)
public boolean isManagingFocus() {
return false;
}
private void registerNextFocusableComponent() {
registerNextFocusableComponent(getNextFocusableComponent());
}
private void registerNextFocusableComponent(Component
nextFocusableComponent) {
if (nextFocusableComponent == null) {
return;
}
Container nearestRoot =
(isFocusCycleRoot()) ? this : getFocusCycleRootAncestor();
FocusTraversalPolicy policy = nearestRoot.getFocusTraversalPolicy();
if (!(policy instanceof LegacyGlueFocusTraversalPolicy)) {
policy = new LegacyGlueFocusTraversalPolicy(policy);
nearestRoot.setFocusTraversalPolicy(policy);
}
((LegacyGlueFocusTraversalPolicy)policy).
setNextFocusableComponent(this, nextFocusableComponent);
}
private void deregisterNextFocusableComponent() {
Component nextFocusableComponent = getNextFocusableComponent();
if (nextFocusableComponent == null) {
return;
}
Container nearestRoot =
(isFocusCycleRoot()) ? this : getFocusCycleRootAncestor();
if (nearestRoot == null) {
return;
}
FocusTraversalPolicy policy = nearestRoot.getFocusTraversalPolicy();
if (policy instanceof LegacyGlueFocusTraversalPolicy) {
((LegacyGlueFocusTraversalPolicy)policy).
unsetNextFocusableComponent(this, nextFocusableComponent);
}
}
/**
* In release 1.4, the focus subsystem was rearchitected.
* For more information, see
* <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>.
* <p>
* Overrides the default <code>FocusTraversalPolicy</code> for this
* <code>JComponent</code>'s focus traversal cycle by unconditionally
* setting the specified <code>Component</code> as the next
* <code>Component</code> in the cycle, and this <code>JComponent</code>
* as the specified <code>Component</code>'s previous
* <code>Component</code> in the cycle.
*
* @param aComponent the <code>Component</code> that should follow this
* <code>JComponent</code> in the focus traversal cycle
*
* @see #getNextFocusableComponent
* @see java.awt.FocusTraversalPolicy
* @deprecated As of 1.4, replaced by <code>FocusTraversalPolicy</code>
*/
@Deprecated
public void setNextFocusableComponent(Component aComponent) {
boolean displayable = isDisplayable();
if (displayable) {
deregisterNextFocusableComponent();
}
putClientProperty(NEXT_FOCUS, aComponent);
if (displayable) {
registerNextFocusableComponent(aComponent);
}
}
/**
* In release 1.4, the focus subsystem was rearchitected.
* For more information, see
* <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>.
* <p>
* Returns the <code>Component</code> set by a prior call to
* <code>setNextFocusableComponent(Component)</code> on this
* <code>JComponent</code>.
*
* @return the <code>Component</code> that will follow this
* <code>JComponent</code> in the focus traversal cycle, or
* <code>null</code> if none has been explicitly specified
*
* @see #setNextFocusableComponent
* @deprecated As of 1.4, replaced by <code>FocusTraversalPolicy</code>.
*/
@Deprecated
public Component getNextFocusableComponent() {
return (Component)getClientProperty(NEXT_FOCUS);
}
/**
* Provides a hint as to whether or not this <code>JComponent</code>
* should get focus. This is only a hint, and it is up to consumers that
* are requesting focus to honor this property. This is typically honored
* for mouse operations, but not keyboard operations. For example, look
* and feels could verify this property is true before requesting focus
* during a mouse operation. This would often times be used if you did
* not want a mouse press on a <code>JComponent</code> to steal focus,
* but did want the <code>JComponent</code> to be traversable via the
* keyboard. If you do not want this <code>JComponent</code> focusable at
* all, use the <code>setFocusable</code> method instead.
* <p>
* Please see
* <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>,
* for more information.
*
* @param requestFocusEnabled indicates whether you want this
* <code>JComponent</code> to be focusable or not
* @see <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
* @see java.awt.Component#setFocusable
*/
public void setRequestFocusEnabled(boolean requestFocusEnabled) {
setFlag(REQUEST_FOCUS_DISABLED, !requestFocusEnabled);
}
/**
* Returns <code>true</code> if this <code>JComponent</code> should
* get focus; otherwise returns <code>false</code>.
* <p>
* Please see
* <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>,
* for more information.
*
* @return <code>true</code> if this component should get focus,
* otherwise returns <code>false</code>
* @see #setRequestFocusEnabled
* @see <a href="../../java/awt/doc-files/FocusSpec.html">Focus
* Specification</a>
* @see java.awt.Component#isFocusable
*/
public boolean isRequestFocusEnabled() {
return !getFlag(REQUEST_FOCUS_DISABLED);
}
/**
* Requests that this <code>Component</code> gets the input focus.
* Refer to {@link java.awt.Component#requestFocus()
* Component.requestFocus()} for a complete description of
* this method.
* <p>
* Note that the use of this method is discouraged because
* its behavior is platform dependent. Instead we recommend the
* use of {@link #requestFocusInWindow() requestFocusInWindow()}.
* If you would like more information on focus, see
* <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>.
*
* @see java.awt.Component#requestFocusInWindow()
* @see java.awt.Component#requestFocusInWindow(boolean)
* @since 1.4
*/
public void requestFocus() {
super.requestFocus();
}
/**
* Requests that this <code>Component</code> gets the input focus.
* Refer to {@link java.awt.Component#requestFocus(boolean)
* Component.requestFocus(boolean)} for a complete description of
* this method.
* <p>
* Note that the use of this method is discouraged because
* its behavior is platform dependent. Instead we recommend the
* use of {@link #requestFocusInWindow(boolean)
* requestFocusInWindow(boolean)}.
* If you would like more information on focus, see
* <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>.
*
* @param temporary boolean indicating if the focus change is temporary
* @return <code>false</code> if the focus change request is guaranteed to
* fail; <code>true</code> if it is likely to succeed
* @see java.awt.Component#requestFocusInWindow()
* @see java.awt.Component#requestFocusInWindow(boolean)
* @since 1.4
*/
public boolean requestFocus(boolean temporary) {
return super.requestFocus(temporary);
}
/**
* Requests that this <code>Component</code> gets the input focus.
* Refer to {@link java.awt.Component#requestFocusInWindow()
* Component.requestFocusInWindow()} for a complete description of
* this method.
* <p>
* If you would like more information on focus, see
* <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>.
*
* @return <code>false</code> if the focus change request is guaranteed to
* fail; <code>true</code> if it is likely to succeed
* @see java.awt.Component#requestFocusInWindow()
* @see java.awt.Component#requestFocusInWindow(boolean)
* @since 1.4
*/
public boolean requestFocusInWindow() {
return super.requestFocusInWindow();
}
/**
* Requests that this <code>Component</code> gets the input focus.
* Refer to {@link java.awt.Component#requestFocusInWindow(boolean)
* Component.requestFocusInWindow(boolean)} for a complete description of
* this method.
* <p>
* If you would like more information on focus, see
* <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>.
*
* @param temporary boolean indicating if the focus change is temporary
* @return <code>false</code> if the focus change request is guaranteed to
* fail; <code>true</code> if it is likely to succeed
* @see java.awt.Component#requestFocusInWindow()
* @see java.awt.Component#requestFocusInWindow(boolean)
* @since 1.4
*/
protected boolean requestFocusInWindow(boolean temporary) {
return super.requestFocusInWindow(temporary);
}
/**
* Requests that this Component get the input focus, and that this
* Component's top-level ancestor become the focused Window. This component
* must be displayable, visible, and focusable for the request to be
* granted.
* <p>
* This method is intended for use by focus implementations. Client code
* should not use this method; instead, it should use
* <code>requestFocusInWindow()</code>.
*
* @see #requestFocusInWindow()
*/
public void grabFocus() {
requestFocus();
}
/**
* Sets the value to indicate whether input verifier for the
* current focus owner will be called before this component requests
* focus. The default is true. Set to false on components such as a
* Cancel button or a scrollbar, which should activate even if the
* input in the current focus owner is not "passed" by the input
* verifier for that component.
*
* @param verifyInputWhenFocusTarget value for the
* <code>verifyInputWhenFocusTarget</code> property
* @see InputVerifier
* @see #setInputVerifier
* @see #getInputVerifier
* @see #getVerifyInputWhenFocusTarget
*
* @since 1.3
*/
@BeanProperty(description
= "Whether the Component verifies input before accepting focus.")
public void setVerifyInputWhenFocusTarget(boolean
verifyInputWhenFocusTarget) {
boolean oldVerifyInputWhenFocusTarget =
this.verifyInputWhenFocusTarget;
this.verifyInputWhenFocusTarget = verifyInputWhenFocusTarget;
firePropertyChange("verifyInputWhenFocusTarget",
oldVerifyInputWhenFocusTarget,
verifyInputWhenFocusTarget);
}
/**
* Returns the value that indicates whether the input verifier for the
* current focus owner will be called before this component requests
* focus.
*
* @return value of the <code>verifyInputWhenFocusTarget</code> property
*
* @see InputVerifier
* @see #setInputVerifier
* @see #getInputVerifier
* @see #setVerifyInputWhenFocusTarget
*
* @since 1.3
*/
public boolean getVerifyInputWhenFocusTarget() {
return verifyInputWhenFocusTarget;
}
/**
* Gets the <code>FontMetrics</code> for the specified <code>Font</code>.
*
* @param font the font for which font metrics is to be
* obtained
* @return the font metrics for <code>font</code>
* @throws NullPointerException if <code>font</code> is null
* @since 1.5
*/
public FontMetrics getFontMetrics(Font font) {
return SwingUtilities2.getFontMetrics(this, font);
}
/**
* Sets the preferred size of this component.
* If <code>preferredSize</code> is <code>null</code>, the UI will
* be asked for the preferred size.
*/
@BeanProperty(preferred = true, description
= "The preferred size of the component.")
public void setPreferredSize(Dimension preferredSize) {
super.setPreferredSize(preferredSize);
}
/**
* If the <code>preferredSize</code> has been set to a
* non-<code>null</code> value just returns it.
* If the UI delegate's <code>getPreferredSize</code>
* method returns a non <code>null</code> value then return that;
* otherwise defer to the component's layout manager.
*
* @return the value of the <code>preferredSize</code> property
* @see #setPreferredSize
* @see ComponentUI
*/
@Transient
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
Dimension size = null;
if (ui != null) {
size = ui.getPreferredSize(this);
}
return (size != null) ? size : super.getPreferredSize();
}
/**
* Sets the maximum size of this component to a constant
* value. Subsequent calls to <code>getMaximumSize</code> will always
* return this value; the component's UI will not be asked
* to compute it. Setting the maximum size to <code>null</code>
* restores the default behavior.
*
* @param maximumSize a <code>Dimension</code> containing the
* desired maximum allowable size
* @see #getMaximumSize
*/
@BeanProperty(description
= "The maximum size of the component.")
public void setMaximumSize(Dimension maximumSize) {
super.setMaximumSize(maximumSize);
}
/**
* If the maximum size has been set to a non-<code>null</code> value
* just returns it. If the UI delegate's <code>getMaximumSize</code>
* method returns a non-<code>null</code> value then return that;
* otherwise defer to the component's layout manager.
*
* @return the value of the <code>maximumSize</code> property
* @see #setMaximumSize
* @see ComponentUI
*/
@Transient
public Dimension getMaximumSize() {
if (isMaximumSizeSet()) {
return super.getMaximumSize();
}
Dimension size = null;
if (ui != null) {
size = ui.getMaximumSize(this);
}
return (size != null) ? size : super.getMaximumSize();
}
/**
* Sets the minimum size of this component to a constant
* value. Subsequent calls to <code>getMinimumSize</code> will always
* return this value; the component's UI will not be asked
* to compute it. Setting the minimum size to <code>null</code>
* restores the default behavior.
*
* @param minimumSize the new minimum size of this component
* @see #getMinimumSize
*/
@BeanProperty(description
= "The minimum size of the component.")
public void setMinimumSize(Dimension minimumSize) {
super.setMinimumSize(minimumSize);
}
/**
* If the minimum size has been set to a non-<code>null</code> value
* just returns it. If the UI delegate's <code>getMinimumSize</code>
* method returns a non-<code>null</code> value then return that; otherwise
* defer to the component's layout manager.
*
* @return the value of the <code>minimumSize</code> property
* @see #setMinimumSize
* @see ComponentUI
*/
@Transient
public Dimension getMinimumSize() {
if (isMinimumSizeSet()) {
return super.getMinimumSize();
}
Dimension size = null;
if (ui != null) {
size = ui.getMinimumSize(this);
}
return (size != null) ? size : super.getMinimumSize();
}
/**
* Gives the UI delegate an opportunity to define the precise
* shape of this component for the sake of mouse processing.
*
* @return true if this component logically contains x,y
* @see java.awt.Component#contains(int, int)
* @see ComponentUI
*/
public boolean contains(int x, int y) {
return (ui != null) ? ui.contains(this, x, y) : super.contains(x, y);
}
/**
* Sets the border of this component. The <code>Border</code> object is
* responsible for defining the insets for the component
* (overriding any insets set directly on the component) and
* for optionally rendering any border decorations within the
* bounds of those insets. Borders should be used (rather
* than insets) for creating both decorative and non-decorative
* (such as margins and padding) regions for a swing component.
* Compound borders can be used to nest multiple borders within a
* single component.
* <p>
* Although technically you can set the border on any object
* that inherits from <code>JComponent</code>, the look and
* feel implementation of many standard Swing components
* doesn't work well with user-set borders. In general,
* when you want to set a border on a standard Swing
* component other than <code>JPanel</code> or <code>JLabel</code>,
* we recommend that you put the component in a <code>JPanel</code>
* and set the border on the <code>JPanel</code>.
* <p>
* This is a bound property.
*
* @param border the border to be rendered for this component
* @see Border
* @see CompoundBorder
*/
@BeanProperty(preferred = true, visualUpdate = true, description
= "The component's border.")
public void setBorder(Border border) {
Border oldBorder = this.border;
this.border = border;
firePropertyChange("border", oldBorder, border);
if (border != oldBorder) {
if (border == null || oldBorder == null ||
!(border.getBorderInsets(this).equals(oldBorder.getBorderInsets(this)))) {
revalidate();
}
repaint();
}
}
/**
* Returns the border of this component or <code>null</code> if no
* border is currently set.
*
* @return the border object for this component
* @see #setBorder
*/
public Border getBorder() {
return border;
}
/**
* If a border has been set on this component, returns the
* border's insets; otherwise calls <code>super.getInsets</code>.
*
* @return the value of the insets property
* @see #setBorder
*/
@BeanProperty(expert = true)
public Insets getInsets() {
if (border != null) {
return border.getBorderInsets(this);
}
return super.getInsets();
}
/**
* Returns an <code>Insets</code> object containing this component's inset
* values. The passed-in <code>Insets</code> object will be reused
* if possible.
* Calling methods cannot assume that the same object will be returned,
* however. All existing values within this object are overwritten.
* If <code>insets</code> is null, this will allocate a new one.
*
* @param insets the <code>Insets</code> object, which can be reused
* @return the <code>Insets</code> object
* @see #getInsets
*/
public Insets getInsets(Insets insets) {
if (insets == null) {
insets = new Insets(0, 0, 0, 0);
}
if (border != null) {
if (border instanceof AbstractBorder) {
return ((AbstractBorder)border).getBorderInsets(this, insets);
} else {
// Can't reuse border insets because the Border interface
// can't be enhanced.
return border.getBorderInsets(this);
}
} else {
// super.getInsets() always returns an Insets object with
// all of its value zeroed. No need for a new object here.
insets.left = insets.top = insets.right = insets.bottom = 0;
return insets;
}
}
/**
* Overrides <code>Container.getAlignmentY</code> to return
* the vertical alignment.
*
* @return the value of the <code>alignmentY</code> property
* @see #setAlignmentY
* @see java.awt.Component#getAlignmentY
*/
public float getAlignmentY() {
if (isAlignmentYSet) {
return alignmentY;
}
return super.getAlignmentY();
}
/**
* Sets the vertical alignment.
*
* @param alignmentY the new vertical alignment
* @see #getAlignmentY
*/
@BeanProperty(description
= "The preferred vertical alignment of the component.")
public void setAlignmentY(float alignmentY) {
this.alignmentY = validateAlignment(alignmentY);
isAlignmentYSet = true;
}
/**
* Overrides <code>Container.getAlignmentX</code> to return
* the horizontal alignment.
*
* @return the value of the <code>alignmentX</code> property
* @see #setAlignmentX
* @see java.awt.Component#getAlignmentX
*/
public float getAlignmentX() {
if (isAlignmentXSet) {
return alignmentX;
}
return super.getAlignmentX();
}
/**
* Sets the horizontal alignment.
*
* @param alignmentX the new horizontal alignment
* @see #getAlignmentX
*/
@BeanProperty(description
= "The preferred horizontal alignment of the component.")
public void setAlignmentX(float alignmentX) {
this.alignmentX = validateAlignment(alignmentX);
isAlignmentXSet = true;
}
private float validateAlignment(float alignment) {
return alignment > 1.0f ? 1.0f : alignment < 0.0f ? 0.0f : alignment;
}
/**
* Sets the input verifier for this component.
*
* @param inputVerifier the new input verifier
* @since 1.3
* @see InputVerifier
*/
@BeanProperty(description
= "The component's input verifier.")
public void setInputVerifier(InputVerifier inputVerifier) {
InputVerifier oldInputVerifier = (InputVerifier)getClientProperty(
JComponent_INPUT_VERIFIER);
putClientProperty(JComponent_INPUT_VERIFIER, inputVerifier);
firePropertyChange("inputVerifier", oldInputVerifier, inputVerifier);
}
/**
* Returns the input verifier for this component.
*
* @return the <code>inputVerifier</code> property
* @since 1.3
* @see InputVerifier
*/
public InputVerifier getInputVerifier() {
return (InputVerifier)getClientProperty(JComponent_INPUT_VERIFIER);
}
/**
* Returns this component's graphics context, which lets you draw
* on a component. Use this method to get a <code>Graphics</code> object and
* then invoke operations on that object to draw on the component.
* @return this components graphics context
*/
@BeanProperty(bound = false)
public Graphics getGraphics() {
if (DEBUG_GRAPHICS_LOADED && shouldDebugGraphics() != 0) {
DebugGraphics graphics = new DebugGraphics(super.getGraphics(),
this);
return graphics;
}
return super.getGraphics();
}
/** Enables or disables diagnostic information about every graphics
* operation performed within the component or one of its children.
*
* @param debugOptions determines how the component should display
* the information; one of the following options:
* <ul>
* <li>DebugGraphics.LOG_OPTION - causes a text message to be printed.
* <li>DebugGraphics.FLASH_OPTION - causes the drawing to flash several
* times.
* <li>DebugGraphics.BUFFERED_OPTION - creates an
* <code>ExternalWindow</code> that displays the operations
* performed on the View's offscreen buffer.
* <li>DebugGraphics.NONE_OPTION disables debugging.
* <li>A value of 0 causes no changes to the debugging options.
* </ul>
* <code>debugOptions</code> is bitwise OR'd into the current value
*/
@BeanProperty(bound = false, preferred = true, enumerationValues = {
"DebugGraphics.NONE_OPTION",
"DebugGraphics.LOG_OPTION",
"DebugGraphics.FLASH_OPTION",
"DebugGraphics.BUFFERED_OPTION"}, description
= "Diagnostic options for graphics operations.")
public void setDebugGraphicsOptions(int debugOptions) {
DebugGraphics.setDebugOptions(this, debugOptions);
}
/** Returns the state of graphics debugging.
*
* @return a bitwise OR'd flag of zero or more of the following options:
* <ul>
* <li>DebugGraphics.LOG_OPTION - causes a text message to be printed.
* <li>DebugGraphics.FLASH_OPTION - causes the drawing to flash several
* times.
* <li>DebugGraphics.BUFFERED_OPTION - creates an
* <code>ExternalWindow</code> that displays the operations
* performed on the View's offscreen buffer.
* <li>DebugGraphics.NONE_OPTION disables debugging.
* <li>A value of 0 causes no changes to the debugging options.
* </ul>
* @see #setDebugGraphicsOptions
*/
public int getDebugGraphicsOptions() {
return DebugGraphics.getDebugOptions(this);
}
/**
* Returns true if debug information is enabled for this
* <code>JComponent</code> or one of its parents.
*/
int shouldDebugGraphics() {
return DebugGraphics.shouldComponentDebug(this);
}
/**
* This method is now obsolete, please use a combination of
* <code>getActionMap()</code> and <code>getInputMap()</code> for
* similar behavior. For example, to bind the <code>KeyStroke</code>
* <code>aKeyStroke</code> to the <code>Action</code> <code>anAction</code>
* now use:
* <pre>
* component.getInputMap().put(aKeyStroke, aCommand);
* component.getActionMap().put(aCommmand, anAction);
* </pre>
* The above assumes you want the binding to be applicable for
* <code>WHEN_FOCUSED</code>. To register bindings for other focus
* states use the <code>getInputMap</code> method that takes an integer.
* <p>
* Register a new keyboard action.
* <code>anAction</code> will be invoked if a key event matching
* <code>aKeyStroke</code> occurs and <code>aCondition</code> is verified.
* The <code>KeyStroke</code> object defines a
* particular combination of a keyboard key and one or more modifiers
* (alt, shift, ctrl, meta).
* <p>
* The <code>aCommand</code> will be set in the delivered event if
* specified.
* <p>
* The <code>aCondition</code> can be one of:
* <blockquote>
* <DL>
* <DT>WHEN_FOCUSED
* <DD>The action will be invoked only when the keystroke occurs
* while the component has the focus.
* <DT>WHEN_IN_FOCUSED_WINDOW
* <DD>The action will be invoked when the keystroke occurs while
* the component has the focus or if the component is in the
* window that has the focus. Note that the component need not
* be an immediate descendent of the window -- it can be
* anywhere in the window's containment hierarchy. In other
* words, whenever <em>any</em> component in the window has the focus,
* the action registered with this component is invoked.
* <DT>WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
* <DD>The action will be invoked when the keystroke occurs while the
* component has the focus or if the component is an ancestor of
* the component that has the focus.
* </DL>
* </blockquote>
* <p>
* The combination of keystrokes and conditions lets you define high
* level (semantic) action events for a specified keystroke+modifier
* combination (using the KeyStroke class) and direct to a parent or
* child of a component that has the focus, or to the component itself.
* In other words, in any hierarchical structure of components, an
* arbitrary key-combination can be immediately directed to the
* appropriate component in the hierarchy, and cause a specific method
* to be invoked (usually by way of adapter objects).
* <p>
* If an action has already been registered for the receiving
* container, with the same charCode and the same modifiers,
* <code>anAction</code> will replace the action.
*
* @param anAction the <code>Action</code> to be registered
* @param aCommand the command to be set in the delivered event
* @param aKeyStroke the <code>KeyStroke</code> to bind to the action
* @param aCondition the condition that needs to be met, see above
* @see KeyStroke
*/
public void registerKeyboardAction(ActionListener anAction,String aCommand,KeyStroke aKeyStroke,int aCondition) {
InputMap inputMap = getInputMap(aCondition, true);
if (inputMap != null) {
ActionMap actionMap = getActionMap(true);
ActionStandin action = new ActionStandin(anAction, aCommand);
inputMap.put(aKeyStroke, action);
if (actionMap != null) {
actionMap.put(action, action);
}
}
}
/**
* Registers any bound <code>WHEN_IN_FOCUSED_WINDOW</code> actions with
* the <code>KeyboardManager</code>. If <code>onlyIfNew</code>
* is true only actions that haven't been registered are pushed
* to the <code>KeyboardManager</code>;
* otherwise all actions are pushed to the <code>KeyboardManager</code>.
*
* @param onlyIfNew if true, only actions that haven't been registered
* are pushed to the <code>KeyboardManager</code>
*/
private void registerWithKeyboardManager(boolean onlyIfNew) {
InputMap inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW, false);
KeyStroke[] strokes;
@SuppressWarnings("unchecked")
Hashtable<KeyStroke, KeyStroke> registered =
(Hashtable<KeyStroke, KeyStroke>)getClientProperty
(WHEN_IN_FOCUSED_WINDOW_BINDINGS);
if (inputMap != null) {
// Push any new KeyStrokes to the KeyboardManager.
strokes = inputMap.allKeys();
if (strokes != null) {
for (int counter = strokes.length - 1; counter >= 0;
counter--) {
if (!onlyIfNew || registered == null ||
registered.get(strokes[counter]) == null) {
registerWithKeyboardManager(strokes[counter]);
}
if (registered != null) {
registered.remove(strokes[counter]);
}
}
}
}
else {
strokes = null;
}
// Remove any old ones.
if (registered != null && registered.size() > 0) {
Enumeration<KeyStroke> keys = registered.keys();
while (keys.hasMoreElements()) {
KeyStroke ks = keys.nextElement();
unregisterWithKeyboardManager(ks);
}
registered.clear();
}
// Updated the registered Hashtable.
if (strokes != null && strokes.length > 0) {
if (registered == null) {
registered = new Hashtable<KeyStroke, KeyStroke>(strokes.length);
putClientProperty(WHEN_IN_FOCUSED_WINDOW_BINDINGS, registered);
}
for (int counter = strokes.length - 1; counter >= 0; counter--) {
registered.put(strokes[counter], strokes[counter]);
}
}
else {
putClientProperty(WHEN_IN_FOCUSED_WINDOW_BINDINGS, null);
}
}
/**
* Unregisters all the previously registered
* <code>WHEN_IN_FOCUSED_WINDOW</code> <code>KeyStroke</code> bindings.
*/
private void unregisterWithKeyboardManager() {
@SuppressWarnings("unchecked")
Hashtable<KeyStroke, KeyStroke> registered =
(Hashtable<KeyStroke, KeyStroke>)getClientProperty
(WHEN_IN_FOCUSED_WINDOW_BINDINGS);
if (registered != null && registered.size() > 0) {
Enumeration<KeyStroke> keys = registered.keys();
while (keys.hasMoreElements()) {
KeyStroke ks = keys.nextElement();
unregisterWithKeyboardManager(ks);
}
}
putClientProperty(WHEN_IN_FOCUSED_WINDOW_BINDINGS, null);
}
/**
* Invoked from <code>ComponentInputMap</code> when its bindings change.
* If <code>inputMap</code> is the current <code>windowInputMap</code>
* (or a parent of the window <code>InputMap</code>)
* the <code>KeyboardManager</code> is notified of the new bindings.
*
* @param inputMap the map containing the new bindings
*/
void componentInputMapChanged(ComponentInputMap inputMap) {
InputMap km = getInputMap(WHEN_IN_FOCUSED_WINDOW, false);
while (km != inputMap && km != null) {
km = km.getParent();
}
if (km != null) {
registerWithKeyboardManager(false);
}
}
private void registerWithKeyboardManager(KeyStroke aKeyStroke) {
KeyboardManager.getCurrentManager().registerKeyStroke(aKeyStroke,this);
}
private void unregisterWithKeyboardManager(KeyStroke aKeyStroke) {
KeyboardManager.getCurrentManager().unregisterKeyStroke(aKeyStroke,
this);
}
/**
* This method is now obsolete, please use a combination of
* <code>getActionMap()</code> and <code>getInputMap()</code> for
* similar behavior.
*
* @param anAction action to be registered to given keystroke and condition
* @param aKeyStroke a {@code KeyStroke}
* @param aCondition the condition to be associated with given keystroke
* and action
* @see #getActionMap
* @see #getInputMap(int)
*/
public void registerKeyboardAction(ActionListener anAction,KeyStroke aKeyStroke,int aCondition) {
registerKeyboardAction(anAction,null,aKeyStroke,aCondition);
}
/**
* This method is now obsolete. To unregister an existing binding
* you can either remove the binding from the
* <code>ActionMap/InputMap</code>, or place a dummy binding the
* <code>InputMap</code>. Removing the binding from the
* <code>InputMap</code> allows bindings in parent <code>InputMap</code>s
* to be active, whereas putting a dummy binding in the
* <code>InputMap</code> effectively disables
* the binding from ever happening.
* <p>
* Unregisters a keyboard action.
* This will remove the binding from the <code>ActionMap</code>
* (if it exists) as well as the <code>InputMap</code>s.
*
* @param aKeyStroke the keystroke for which to unregister its
* keyboard action
*/
public void unregisterKeyboardAction(KeyStroke aKeyStroke) {
ActionMap am = getActionMap(false);
for (int counter = 0; counter < 3; counter++) {
InputMap km = getInputMap(counter, false);
if (km != null) {
Object actionID = km.get(aKeyStroke);
if (am != null && actionID != null) {
am.remove(actionID);
}
km.remove(aKeyStroke);
}
}
}
/**
* Returns the <code>KeyStrokes</code> that will initiate
* registered actions.
*
* @return an array of <code>KeyStroke</code> objects
* @see #registerKeyboardAction
*/
@BeanProperty(bound = false)
public KeyStroke[] getRegisteredKeyStrokes() {
int[] counts = new int[3];
KeyStroke[][] strokes = new KeyStroke[3][];
for (int counter = 0; counter < 3; counter++) {
InputMap km = getInputMap(counter, false);
strokes[counter] = (km != null) ? km.allKeys() : null;
counts[counter] = (strokes[counter] != null) ?
strokes[counter].length : 0;
}
KeyStroke[] retValue = new KeyStroke[counts[0] + counts[1] +
counts[2]];
for (int counter = 0, last = 0; counter < 3; counter++) {
if (counts[counter] > 0) {
System.arraycopy(strokes[counter], 0, retValue, last,
counts[counter]);
last += counts[counter];
}
}
return retValue;
}
/**
* Returns the condition that determines whether a registered action
* occurs in response to the specified keystroke.
* <p>
* For Java 2 platform v1.3, a <code>KeyStroke</code> can be associated
* with more than one condition.
* For example, 'a' could be bound for the two
* conditions <code>WHEN_FOCUSED</code> and
* <code>WHEN_IN_FOCUSED_WINDOW</code> condition.
*
* @param aKeyStroke the keystroke for which to request an
* action-keystroke condition
* @return the action-keystroke condition
*/
public int getConditionForKeyStroke(KeyStroke aKeyStroke) {
for (int counter = 0; counter < 3; counter++) {
InputMap inputMap = getInputMap(counter, false);
if (inputMap != null && inputMap.get(aKeyStroke) != null) {
return counter;
}
}
return UNDEFINED_CONDITION;
}
/**
* Returns the object that will perform the action registered for a
* given keystroke.
*
* @param aKeyStroke the keystroke for which to return a listener
* @return the <code>ActionListener</code>
* object invoked when the keystroke occurs
*/
public ActionListener getActionForKeyStroke(KeyStroke aKeyStroke) {
ActionMap am = getActionMap(false);
if (am == null) {
return null;
}
for (int counter = 0; counter < 3; counter++) {
InputMap inputMap = getInputMap(counter, false);
if (inputMap != null) {
Object actionBinding = inputMap.get(aKeyStroke);
if (actionBinding != null) {
Action action = am.get(actionBinding);
if (action instanceof ActionStandin) {
return ((ActionStandin)action).actionListener;
}
return action;
}
}
}
return null;
}
/**
* Unregisters all the bindings in the first tier <code>InputMaps</code>
* and <code>ActionMap</code>. This has the effect of removing any
* local bindings, and allowing the bindings defined in parent
* <code>InputMap/ActionMaps</code>
* (the UI is usually defined in the second tier) to persist.
*/
public void resetKeyboardActions() {
// Keys
for (int counter = 0; counter < 3; counter++) {
InputMap inputMap = getInputMap(counter, false);
if (inputMap != null) {
inputMap.clear();
}
}
// Actions
ActionMap am = getActionMap(false);
if (am != null) {
am.clear();
}
}
/**
* Sets the <code>InputMap</code> to use under the condition
* <code>condition</code> to
* <code>map</code>. A <code>null</code> value implies you
* do not want any bindings to be used, even from the UI. This will
* not reinstall the UI <code>InputMap</code> (if there was one).
* <code>condition</code> has one of the following values:
* <ul>
* <li><code>WHEN_IN_FOCUSED_WINDOW</code>
* <li><code>WHEN_FOCUSED</code>
* <li><code>WHEN_ANCESTOR_OF_FOCUSED_COMPONENT</code>
* </ul>
* If <code>condition</code> is <code>WHEN_IN_FOCUSED_WINDOW</code>
* and <code>map</code> is not a <code>ComponentInputMap</code>, an
* <code>IllegalArgumentException</code> will be thrown.
* Similarly, if <code>condition</code> is not one of the values
* listed, an <code>IllegalArgumentException</code> will be thrown.
*
* @param condition one of the values listed above
* @param map the <code>InputMap</code> to use for the given condition
* @exception IllegalArgumentException if <code>condition</code> is
* <code>WHEN_IN_FOCUSED_WINDOW</code> and <code>map</code>
* is not an instance of <code>ComponentInputMap</code>; or
* if <code>condition</code> is not one of the legal values
* specified above
* @since 1.3
*/
public final void setInputMap(int condition, InputMap map) {
switch (condition) {
case WHEN_IN_FOCUSED_WINDOW:
if (map != null && !(map instanceof ComponentInputMap)) {
throw new IllegalArgumentException("WHEN_IN_FOCUSED_WINDOW InputMaps must be of type ComponentInputMap");
}
windowInputMap = (ComponentInputMap)map;
setFlag(WIF_INPUTMAP_CREATED, true);
registerWithKeyboardManager(false);
break;
case WHEN_ANCESTOR_OF_FOCUSED_COMPONENT:
ancestorInputMap = map;
setFlag(ANCESTOR_INPUTMAP_CREATED, true);
break;
case WHEN_FOCUSED:
focusInputMap = map;
setFlag(FOCUS_INPUTMAP_CREATED, true);
break;
default:
throw new IllegalArgumentException("condition must be one of JComponent.WHEN_IN_FOCUSED_WINDOW, JComponent.WHEN_FOCUSED or JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT");
}
}
/**
* Returns the <code>InputMap</code> that is used during
* <code>condition</code>.
*
* @param condition one of WHEN_IN_FOCUSED_WINDOW, WHEN_FOCUSED,
* WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
* @return the <code>InputMap</code> for the specified
* <code>condition</code>
* @since 1.3
*/
public final InputMap getInputMap(int condition) {
return getInputMap(condition, true);
}
/**
* Returns the <code>InputMap</code> that is used when the
* component has focus.
* This is convenience method for <code>getInputMap(WHEN_FOCUSED)</code>.
*
* @return the <code>InputMap</code> used when the component has focus
* @since 1.3
*/
public final InputMap getInputMap() {
return getInputMap(WHEN_FOCUSED, true);
}
/**
* Sets the <code>ActionMap</code> to <code>am</code>. This does not set
* the parent of the <code>am</code> to be the <code>ActionMap</code>
* from the UI (if there was one), it is up to the caller to have done this.
*
* @param am the new <code>ActionMap</code>
* @since 1.3
*/
public final void setActionMap(ActionMap am) {
actionMap = am;
setFlag(ACTIONMAP_CREATED, true);
}
/**
* Returns the <code>ActionMap</code> used to determine what
* <code>Action</code> to fire for particular <code>KeyStroke</code>
* binding. The returned <code>ActionMap</code>, unless otherwise
* set, will have the <code>ActionMap</code> from the UI set as the parent.
*
* @return the <code>ActionMap</code> containing the key/action bindings
* @since 1.3
*/
public final ActionMap getActionMap() {
return getActionMap(true);
}
/**
* Returns the <code>InputMap</code> to use for condition
* <code>condition</code>. If the <code>InputMap</code> hasn't
* been created, and <code>create</code> is
* true, it will be created.
*
* @param condition one of the following values:
* <ul>
* <li>JComponent.FOCUS_INPUTMAP_CREATED
* <li>JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
* <li>JComponent.WHEN_IN_FOCUSED_WINDOW
* </ul>
* @param create if true, create the <code>InputMap</code> if it
* is not already created
* @return the <code>InputMap</code> for the given <code>condition</code>;
* if <code>create</code> is false and the <code>InputMap</code>
* hasn't been created, returns <code>null</code>
* @exception IllegalArgumentException if <code>condition</code>
* is not one of the legal values listed above
*/
final InputMap getInputMap(int condition, boolean create) {
switch (condition) {
case WHEN_FOCUSED:
if (getFlag(FOCUS_INPUTMAP_CREATED)) {
return focusInputMap;
}
// Hasn't been created yet.
if (create) {
InputMap km = new InputMap();
setInputMap(condition, km);
return km;
}
break;
case WHEN_ANCESTOR_OF_FOCUSED_COMPONENT:
if (getFlag(ANCESTOR_INPUTMAP_CREATED)) {
return ancestorInputMap;
}
// Hasn't been created yet.
if (create) {
InputMap km = new InputMap();
setInputMap(condition, km);
return km;
}
break;
case WHEN_IN_FOCUSED_WINDOW:
if (getFlag(WIF_INPUTMAP_CREATED)) {
return windowInputMap;
}
// Hasn't been created yet.
if (create) {
ComponentInputMap km = new ComponentInputMap(this);
setInputMap(condition, km);
return km;
}
break;
default:
throw new IllegalArgumentException("condition must be one of JComponent.WHEN_IN_FOCUSED_WINDOW, JComponent.WHEN_FOCUSED or JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT");
}
return null;
}
/**
* Finds and returns the appropriate <code>ActionMap</code>.
*
* @param create if true, create the <code>ActionMap</code> if it
* is not already created
* @return the <code>ActionMap</code> for this component; if the
* <code>create</code> flag is false and there is no
* current <code>ActionMap</code>, returns <code>null</code>
*/
final ActionMap getActionMap(boolean create) {
if (getFlag(ACTIONMAP_CREATED)) {
return actionMap;
}
// Hasn't been created.
if (create) {
ActionMap am = new ActionMap();
setActionMap(am);
return am;
}
return null;
}
/**
* Returns the baseline. The baseline is measured from the top of
* the component. This method is primarily meant for
* <code>LayoutManager</code>s to align components along their
* baseline. A return value less than 0 indicates this component
* does not have a reasonable baseline and that
* <code>LayoutManager</code>s should not align this component on
* its baseline.
* <p>
* This method calls into the <code>ComponentUI</code> method of the
* same name. If this component does not have a <code>ComponentUI</code>
* -1 will be returned. If a value >= 0 is
* returned, then the component has a valid baseline for any
* size >= the minimum size and <code>getBaselineResizeBehavior</code>
* can be used to determine how the baseline changes with size.
*
* @throws IllegalArgumentException {@inheritDoc}
* @see #getBaselineResizeBehavior
* @see java.awt.FontMetrics
* @since 1.6
*/
public int getBaseline(int width, int height) {
// check size.
super.getBaseline(width, height);
if (ui != null) {
return ui.getBaseline(this, width, height);
}
return -1;
}
/**
* Returns an enum indicating how the baseline of the component
* changes as the size changes. This method is primarily meant for
* layout managers and GUI builders.
* <p>
* This method calls into the <code>ComponentUI</code> method of
* the same name. If this component does not have a
* <code>ComponentUI</code>
* <code>BaselineResizeBehavior.OTHER</code> will be
* returned. Subclasses should
* never return <code>null</code>; if the baseline can not be
* calculated return <code>BaselineResizeBehavior.OTHER</code>. Callers
* should first ask for the baseline using
* <code>getBaseline</code> and if a value >= 0 is returned use
* this method. It is acceptable for this method to return a
* value other than <code>BaselineResizeBehavior.OTHER</code> even if
* <code>getBaseline</code> returns a value less than 0.
*
* @see #getBaseline(int, int)
* @since 1.6
*/
@BeanProperty(bound = false)
public BaselineResizeBehavior getBaselineResizeBehavior() {
if (ui != null) {
return ui.getBaselineResizeBehavior(this);
}
return BaselineResizeBehavior.OTHER;
}
/**
* In release 1.4, the focus subsystem was rearchitected.
* For more information, see
* <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>.
* <p>
* Requests focus on this <code>JComponent</code>'s
* <code>FocusTraversalPolicy</code>'s default <code>Component</code>.
* If this <code>JComponent</code> is a focus cycle root, then its
* <code>FocusTraversalPolicy</code> is used. Otherwise, the
* <code>FocusTraversalPolicy</code> of this <code>JComponent</code>'s
* focus-cycle-root ancestor is used.
*
* @return true if this component can request to get the input focus,
* false if it can not
* @see java.awt.FocusTraversalPolicy#getDefaultComponent
* @deprecated As of 1.4, replaced by
* <code>FocusTraversalPolicy.getDefaultComponent(Container).requestFocus()</code>
*/
@Deprecated
public boolean requestDefaultFocus() {
Container nearestRoot =
(isFocusCycleRoot()) ? this : getFocusCycleRootAncestor();
if (nearestRoot == null) {
return false;
}
Component comp = nearestRoot.getFocusTraversalPolicy().
getDefaultComponent(nearestRoot);
if (comp != null) {
comp.requestFocus();
return true;
} else {
return false;
}
}
/**
* Makes the component visible or invisible.
* Overrides <code>Component.setVisible</code>.
*
* @param aFlag true to make the component visible; false to
* make it invisible
*/
@BeanProperty(hidden = true, visualUpdate = true)
public void setVisible(boolean aFlag) {
if (aFlag != isVisible()) {
super.setVisible(aFlag);
if (aFlag) {
Container parent = getParent();
if (parent != null) {
Rectangle r = getBounds();
parent.repaint(r.x, r.y, r.width, r.height);
}
revalidate();
}
}
}
/**
* Sets whether or not this component is enabled.
* A component that is enabled may respond to user input,
* while a component that is not enabled cannot respond to
* user input. Some components may alter their visual
* representation when they are disabled in order to
* provide feedback to the user that they cannot take input.
* <p>Note: Disabling a component does not disable its children.
*
* <p>Note: Disabling a lightweight component does not prevent it from
* receiving MouseEvents.
*
* @param enabled true if this component should be enabled, false otherwise
* @see java.awt.Component#isEnabled
* @see java.awt.Component#isLightweight
*/
@BeanProperty(expert = true, preferred = true, visualUpdate = true, description
= "The enabled state of the component.")
public void setEnabled(boolean enabled) {
boolean oldEnabled = isEnabled();
super.setEnabled(enabled);
firePropertyChange("enabled", oldEnabled, enabled);
if (enabled != oldEnabled) {
repaint();
}
}
/**
* Sets the foreground color of this component. It is up to the
* look and feel to honor this property, some may choose to ignore
* it.
*
* @param fg the desired foreground <code>Color</code>
* @see java.awt.Component#getForeground
*/
@BeanProperty(preferred = true, visualUpdate = true, description
= "The foreground color of the component.")
public void setForeground(Color fg) {
Color oldFg = getForeground();
super.setForeground(fg);
if ((oldFg != null) ? !oldFg.equals(fg) : ((fg != null) && !fg.equals(oldFg))) {
// foreground already bound in AWT1.2
repaint();
}
}
/**
* Sets the background color of this component. The background
* color is used only if the component is opaque, and only
* by subclasses of <code>JComponent</code> or
* <code>ComponentUI</code> implementations. Direct subclasses of
* <code>JComponent</code> must override
* <code>paintComponent</code> to honor this property.
* <p>
* It is up to the look and feel to honor this property, some may
* choose to ignore it.
*
* @param bg the desired background <code>Color</code>
* @see java.awt.Component#getBackground
* @see #setOpaque
*/
@BeanProperty(preferred = true, visualUpdate = true, description
= "The background color of the component.")
public void setBackground(Color bg) {
Color oldBg = getBackground();
super.setBackground(bg);
if ((oldBg != null) ? !oldBg.equals(bg) : ((bg != null) && !bg.equals(oldBg))) {
// background already bound in AWT1.2
repaint();
}
}
/**
* Sets the font for this component.
*
* @param font the desired <code>Font</code> for this component
* @see java.awt.Component#getFont
*/
@BeanProperty(preferred = true, visualUpdate = true, description
= "The font for the component.")
public void setFont(Font font) {
Font oldFont = getFont();
super.setFont(font);
// font already bound in AWT1.2
if (font != oldFont) {
revalidate();
repaint();
}
}
/**
* Returns the default locale used to initialize each JComponent's
* locale property upon creation.
*
* The default locale has "AppContext" scope so that applets (and
* potentially multiple lightweight applications running in a single VM)
* can have their own setting. An applet can safely alter its default
* locale because it will have no affect on other applets (or the browser).
*
* @return the default <code>Locale</code>.
* @see #setDefaultLocale
* @see java.awt.Component#getLocale
* @see #setLocale
* @since 1.4
*/
public static Locale getDefaultLocale() {
Locale l = (Locale) SwingUtilities.appContextGet(defaultLocale);
if( l == null ) {
//REMIND(bcb) choosing the default value is more complicated
//than this.
l = Locale.getDefault();
JComponent.setDefaultLocale( l );
}
return l;
}
/**
* Sets the default locale used to initialize each JComponent's locale
* property upon creation. The initial value is the VM's default locale.
*
* The default locale has "AppContext" scope so that applets (and
* potentially multiple lightweight applications running in a single VM)
* can have their own setting. An applet can safely alter its default
* locale because it will have no affect on other applets (or the browser).
*
* @param l the desired default <code>Locale</code> for new components.
* @see #getDefaultLocale
* @see java.awt.Component#getLocale
* @see #setLocale
* @since 1.4
*/
public static void setDefaultLocale( Locale l ) {
SwingUtilities.appContextPut(defaultLocale, l);
}
/**
* Processes any key events that the component itself
* recognizes. This is called after the focus
* manager and any interested listeners have been
* given a chance to steal away the event. This
* method is called only if the event has not
* yet been consumed. This method is called prior
* to the keyboard UI logic.
* <p>
* This method is implemented to do nothing. Subclasses would
* normally override this method if they process some
* key events themselves. If the event is processed,
* it should be consumed.
*
* @param e the event to be processed
*/
protected void processComponentKeyEvent(KeyEvent e) {
}
/** Overrides <code>processKeyEvent</code> to process events. **/
protected void processKeyEvent(KeyEvent e) {
boolean result;
boolean shouldProcessKey;
// This gives the key event listeners a crack at the event
super.processKeyEvent(e);
// give the component itself a crack at the event
if (! e.isConsumed()) {
processComponentKeyEvent(e);
}
shouldProcessKey = KeyboardState.shouldProcess(e);
if(e.isConsumed()) {
return;
}
if (shouldProcessKey && processKeyBindings(e, e.getID() ==
KeyEvent.KEY_PRESSED)) {
e.consume();
}
}
/**
* Invoked to process the key bindings for <code>ks</code> as the result
* of the <code>KeyEvent</code> <code>e</code>. This obtains
* the appropriate <code>InputMap</code>,
* gets the binding, gets the action from the <code>ActionMap</code>,
* and then (if the action is found and the component
* is enabled) invokes <code>notifyAction</code> to notify the action.
*
* @param ks the <code>KeyStroke</code> queried
* @param e the <code>KeyEvent</code>
* @param condition one of the following values:
* <ul>
* <li>JComponent.WHEN_FOCUSED
* <li>JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
* <li>JComponent.WHEN_IN_FOCUSED_WINDOW
* </ul>
* @param pressed true if the key is pressed
* @return true if there was a binding to an action, and the action
* was enabled
*
* @since 1.3
*/
protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,
int condition, boolean pressed) {
InputMap map = getInputMap(condition, false);
ActionMap am = getActionMap(false);
if(map != null && am != null && isEnabled()) {
Object binding = map.get(ks);
Action action = (binding == null) ? null : am.get(binding);
if (action != null) {
return SwingUtilities.notifyAction(action, ks, e, this,
e.getModifiers());
}
}
return false;
}
/**
* This is invoked as the result of a <code>KeyEvent</code>
* that was not consumed by the <code>FocusManager</code>,
* <code>KeyListeners</code>, or the component. It will first try
* <code>WHEN_FOCUSED</code> bindings,
* then <code>WHEN_ANCESTOR_OF_FOCUSED_COMPONENT</code> bindings,
* and finally <code>WHEN_IN_FOCUSED_WINDOW</code> bindings.
*
* @param e the unconsumed <code>KeyEvent</code>
* @param pressed true if the key is pressed
* @return true if there is a key binding for <code>e</code>
*/
boolean processKeyBindings(KeyEvent e, boolean pressed) {
if (!SwingUtilities.isValidKeyEventForKeyBindings(e)) {
return false;
}
// Get the KeyStroke
// There may be two keystrokes associated with a low-level key event;
// in this case a keystroke made of an extended key code has a priority.
KeyStroke ks;
KeyStroke ksE = null;
if (e.getID() == KeyEvent.KEY_TYPED) {
ks = KeyStroke.getKeyStroke(e.getKeyChar());
}
else {
ks = KeyStroke.getKeyStroke(e.getKeyCode(),e.getModifiers(),
(pressed ? false:true));
if (e.getKeyCode() != e.getExtendedKeyCode()) {
ksE = KeyStroke.getKeyStroke(e.getExtendedKeyCode(),e.getModifiers(),
(pressed ? false:true));
}
}
// Do we have a key binding for e?
// If we have a binding by an extended code, use it.
// If not, check for regular code binding.
if(ksE != null && processKeyBinding(ksE, e, WHEN_FOCUSED, pressed)) {
return true;
}
if(processKeyBinding(ks, e, WHEN_FOCUSED, pressed))
return true;
/* We have no key binding. Let's try the path from our parent to the
* window excluded. We store the path components so we can avoid
* asking the same component twice.
*/
Container parent = this;
while (parent != null && !(parent instanceof Window) &&
!(parent instanceof Applet)) {
if(parent instanceof JComponent) {
if(ksE != null && ((JComponent)parent).processKeyBinding(ksE, e,
WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, pressed))
return true;
if(((JComponent)parent).processKeyBinding(ks, e,
WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, pressed))
return true;
}
// This is done so that the children of a JInternalFrame are
// given precedence for WHEN_IN_FOCUSED_WINDOW bindings before
// other components WHEN_IN_FOCUSED_WINDOW bindings. This also gives
// more precedence to the WHEN_IN_FOCUSED_WINDOW bindings of the
// JInternalFrame's children vs the
// WHEN_ANCESTOR_OF_FOCUSED_COMPONENT bindings of the parents.
// maybe generalize from JInternalFrame (like isFocusCycleRoot).
if ((parent instanceof JInternalFrame) &&
JComponent.processKeyBindingsForAllComponents(e,parent,pressed)){
return true;
}
parent = parent.getParent();
}
/* No components between the focused component and the window is
* actually interested by the key event. Let's try the other
* JComponent in this window.
*/
if(parent != null) {
return JComponent.processKeyBindingsForAllComponents(e,parent,pressed);
}
return false;
}
static boolean processKeyBindingsForAllComponents(KeyEvent e,
Container container, boolean pressed) {
while (true) {
if (KeyboardManager.getCurrentManager().fireKeyboardAction(
e, pressed, container)) {
return true;
}
if (container instanceof Popup.HeavyWeightWindow) {
container = ((Window)container).getOwner();
}
else {
return false;
}
}
}
/**
* Registers the text to display in a tool tip.
* The text displays when the cursor lingers over the component.
* <p>
* See <a href="http://docs.oracle.com/javase/tutorial/uiswing/components/tooltip.html">How to Use Tool Tips</a>
* in <em>The Java Tutorial</em>
* for further documentation.
*
* @param text the string to display; if the text is <code>null</code>,
* the tool tip is turned off for this component
* @see #TOOL_TIP_TEXT_KEY
*/
@BeanProperty(bound = false, preferred = true, description
= "The text to display in a tool tip.")
public void setToolTipText(String text) {
String oldText = getToolTipText();
putClientProperty(TOOL_TIP_TEXT_KEY, text);
ToolTipManager toolTipManager = ToolTipManager.sharedInstance();
if (text != null) {
if (oldText == null) {
toolTipManager.registerComponent(this);
}
} else {
toolTipManager.unregisterComponent(this);
}
}
/**
* Returns the tooltip string that has been set with
* <code>setToolTipText</code>.
*
* @return the text of the tool tip
* @see #TOOL_TIP_TEXT_KEY
*/
public String getToolTipText() {
return (String)getClientProperty(TOOL_TIP_TEXT_KEY);
}
/**
* Returns the string to be used as the tooltip for <i>event</i>.
* By default this returns any string set using
* <code>setToolTipText</code>. If a component provides
* more extensive API to support differing tooltips at different locations,
* this method should be overridden.
*
* @param event the {@code MouseEvent} that initiated the
* {@code ToolTip} display
* @return a string containing the tooltip
*/
public String getToolTipText(MouseEvent event) {
return getToolTipText();
}
/**
* Returns the tooltip location in this component's coordinate system.
* If <code>null</code> is returned, Swing will choose a location.
* The default implementation returns <code>null</code>.
*
* @param event the <code>MouseEvent</code> that caused the
* <code>ToolTipManager</code> to show the tooltip
* @return always returns <code>null</code>
*/
public Point getToolTipLocation(MouseEvent event) {
return null;
}
/**
* Returns the preferred location to display the popup menu in this
* component's coordinate system. It is up to the look and feel to
* honor this property, some may choose to ignore it.
* If {@code null}, the look and feel will choose a suitable location.
*
* @param event the {@code MouseEvent} that triggered the popup to be
* shown, or {@code null} if the popup is not being shown as the
* result of a mouse event
* @return location to display the {@code JPopupMenu}, or {@code null}
* @since 1.5
*/
public Point getPopupLocation(MouseEvent event) {
return null;
}
/**
* Returns the instance of <code>JToolTip</code> that should be used
* to display the tooltip.
* Components typically would not override this method,
* but it can be used to
* cause different tooltips to be displayed differently.
*
* @return the <code>JToolTip</code> used to display this toolTip
*/
public JToolTip createToolTip() {
JToolTip tip = new JToolTip();
tip.setComponent(this);
return tip;
}
/**
* Forwards the <code>scrollRectToVisible()</code> message to the
* <code>JComponent</code>'s parent. Components that can service
* the request, such as <code>JViewport</code>,
* override this method and perform the scrolling.
*
* @param aRect the visible <code>Rectangle</code>
* @see JViewport
*/
public void scrollRectToVisible(Rectangle aRect) {
Container parent;
int dx = getX(), dy = getY();
for (parent = getParent();
!(parent == null) &&
!(parent instanceof JComponent) &&
!(parent instanceof CellRendererPane);
parent = parent.getParent()) {
Rectangle bounds = parent.getBounds();
dx += bounds.x;
dy += bounds.y;
}
if (!(parent == null) && !(parent instanceof CellRendererPane)) {
aRect.x += dx;
aRect.y += dy;
((JComponent)parent).scrollRectToVisible(aRect);
aRect.x -= dx;
aRect.y -= dy;
}
}
/**
* Sets the <code>autoscrolls</code> property.
* If <code>true</code> mouse dragged events will be
* synthetically generated when the mouse is dragged
* outside of the component's bounds and mouse motion
* has paused (while the button continues to be held
* down). The synthetic events make it appear that the
* drag gesture has resumed in the direction established when
* the component's boundary was crossed. Components that
* support autoscrolling must handle <code>mouseDragged</code>
* events by calling <code>scrollRectToVisible</code> with a
* rectangle that contains the mouse event's location. All of
* the Swing components that support item selection and are
* typically displayed in a <code>JScrollPane</code>
* (<code>JTable</code>, <code>JList</code>, <code>JTree</code>,
* <code>JTextArea</code>, and <code>JEditorPane</code>)
* already handle mouse dragged events in this way. To enable
* autoscrolling in any other component, add a mouse motion
* listener that calls <code>scrollRectToVisible</code>.
* For example, given a <code>JPanel</code>, <code>myPanel</code>:
* <pre>
* MouseMotionListener doScrollRectToVisible = new MouseMotionAdapter() {
* public void mouseDragged(MouseEvent e) {
* Rectangle r = new Rectangle(e.getX(), e.getY(), 1, 1);
* ((JPanel)e.getSource()).scrollRectToVisible(r);
* }
* };
* myPanel.addMouseMotionListener(doScrollRectToVisible);
* </pre>
* The default value of the <code>autoScrolls</code>
* property is <code>false</code>.
*
* @param autoscrolls if true, synthetic mouse dragged events
* are generated when the mouse is dragged outside of a component's
* bounds and the mouse button continues to be held down; otherwise
* false
* @see #getAutoscrolls
* @see JViewport
* @see JScrollPane
*/
@BeanProperty(bound = false, expert = true, description
= "Determines if this component automatically scrolls its contents when dragged.")
public void setAutoscrolls(boolean autoscrolls) {
setFlag(AUTOSCROLLS_SET, true);
if (this.autoscrolls != autoscrolls) {
this.autoscrolls = autoscrolls;
if (autoscrolls) {
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK);
}
else {
Autoscroller.stop(this);
}
}
}
/**
* Gets the <code>autoscrolls</code> property.
*
* @return the value of the <code>autoscrolls</code> property
* @see JViewport
* @see #setAutoscrolls
*/
public boolean getAutoscrolls() {
return autoscrolls;
}
/**
* Sets the {@code TransferHandler}, which provides support for transfer
* of data into and out of this component via cut/copy/paste and drag
* and drop. This may be {@code null} if the component does not support
* data transfer operations.
* <p>
* If the new {@code TransferHandler} is not {@code null}, this method
* also installs a <b>new</b> {@code DropTarget} on the component to
* activate drop handling through the {@code TransferHandler} and activate
* any built-in support (such as calculating and displaying potential drop
* locations). If you do not wish for this component to respond in any way
* to drops, you can disable drop support entirely either by removing the
* drop target ({@code setDropTarget(null)}) or by de-activating it
* ({@code getDropTaget().setActive(false)}).
* <p>
* If the new {@code TransferHandler} is {@code null}, this method removes
* the drop target.
* <p>
* Under two circumstances, this method does not modify the drop target:
* First, if the existing drop target on this component was explicitly
* set by the developer to a {@code non-null} value. Second, if the
* system property {@code suppressSwingDropSupport} is {@code true}. The
* default value for the system property is {@code false}.
* <p>
* Please see
* <a href="http://docs.oracle.com/javase/tutorial/uiswing/dnd/index.html">
* How to Use Drag and Drop and Data Transfer</a>,
* a section in <em>The Java Tutorial</em>, for more information.
*
* @param newHandler the new {@code TransferHandler}
*
* @see TransferHandler
* @see #getTransferHandler
* @since 1.4
*/
@BeanProperty(hidden = true, description
= "Mechanism for transfer of data to and from the component")
public void setTransferHandler(TransferHandler newHandler) {
TransferHandler oldHandler = (TransferHandler)getClientProperty(
JComponent_TRANSFER_HANDLER);
putClientProperty(JComponent_TRANSFER_HANDLER, newHandler);
SwingUtilities.installSwingDropTargetAsNecessary(this, newHandler);
firePropertyChange("transferHandler", oldHandler, newHandler);
}
/**
* Gets the <code>transferHandler</code> property.
*
* @return the value of the <code>transferHandler</code> property
*
* @see TransferHandler
* @see #setTransferHandler
* @since 1.4
*/
public TransferHandler getTransferHandler() {
return (TransferHandler)getClientProperty(JComponent_TRANSFER_HANDLER);
}
/**
* Calculates a custom drop location for this type of component,
* representing where a drop at the given point should insert data.
* <code>null</code> is returned if this component doesn't calculate
* custom drop locations. In this case, <code>TransferHandler</code>
* will provide a default <code>DropLocation</code> containing just
* the point.
*
* @param p the point to calculate a drop location for
* @return the drop location, or <code>null</code>
*/
TransferHandler.DropLocation dropLocationForPoint(Point p) {
return null;
}
/**
* Called to set or clear the drop location during a DnD operation.
* In some cases, the component may need to use its internal selection
* temporarily to indicate the drop location. To help facilitate this,
* this method returns and accepts as a parameter a state object.
* This state object can be used to store, and later restore, the selection
* state. Whatever this method returns will be passed back to it in
* future calls, as the state parameter. If it wants the DnD system to
* continue storing the same state, it must pass it back every time.
* Here's how this is used:
* <p>
* Let's say that on the first call to this method the component decides
* to save some state (because it is about to use the selection to show
* a drop index). It can return a state object to the caller encapsulating
* any saved selection state. On a second call, let's say the drop location
* is being changed to something else. The component doesn't need to
* restore anything yet, so it simply passes back the same state object
* to have the DnD system continue storing it. Finally, let's say this
* method is messaged with <code>null</code>. This means DnD
* is finished with this component for now, meaning it should restore
* state. At this point, it can use the state parameter to restore
* said state, and of course return <code>null</code> since there's
* no longer anything to store.
*
* @param location the drop location (as calculated by
* <code>dropLocationForPoint</code>) or <code>null</code>
* if there's no longer a valid drop location
* @param state the state object saved earlier for this component,
* or <code>null</code>
* @param forDrop whether or not the method is being called because an
* actual drop occurred
* @return any saved state for this component, or <code>null</code> if none
*/
Object setDropLocation(TransferHandler.DropLocation location,
Object state,
boolean forDrop) {
return null;
}
/**
* Called to indicate to this component that DnD is done.
* Needed by <code>JTree</code>.
*/
void dndDone() {
}
/**
* Processes mouse events occurring on this component by
* dispatching them to any registered
* <code>MouseListener</code> objects, refer to
* {@link java.awt.Component#processMouseEvent(MouseEvent)}
* for a complete description of this method.
*
* @param e the mouse event
* @see java.awt.Component#processMouseEvent
* @since 1.5
*/
protected void processMouseEvent(MouseEvent e) {
if (autoscrolls && e.getID() == MouseEvent.MOUSE_RELEASED) {
Autoscroller.stop(this);
}
super.processMouseEvent(e);
}
/**
* Processes mouse motion events, such as MouseEvent.MOUSE_DRAGGED.
*
* @param e the <code>MouseEvent</code>
* @see MouseEvent
*/
protected void processMouseMotionEvent(MouseEvent e) {
boolean dispatch = true;
if (autoscrolls && e.getID() == MouseEvent.MOUSE_DRAGGED) {
// We don't want to do the drags when the mouse moves if we're
// autoscrolling. It makes it feel spastic.
dispatch = !Autoscroller.isRunning(this);
Autoscroller.processMouseDragged(e);
}
if (dispatch) {
super.processMouseMotionEvent(e);
}
}
// Inner classes can't get at this method from a super class
void superProcessMouseMotionEvent(MouseEvent e) {
super.processMouseMotionEvent(e);
}
/**
* This is invoked by the <code>RepaintManager</code> if
* <code>createImage</code> is called on the component.
*
* @param newValue true if the double buffer image was created from this component
*/
void setCreatedDoubleBuffer(boolean newValue) {
setFlag(CREATED_DOUBLE_BUFFER, newValue);
}
/**
* Returns true if the <code>RepaintManager</code>
* created the double buffer image from the component.
*
* @return true if this component had a double buffer image, false otherwise
*/
boolean getCreatedDoubleBuffer() {
return getFlag(CREATED_DOUBLE_BUFFER);
}
/**
* <code>ActionStandin</code> is used as a standin for
* <code>ActionListeners</code> that are
* added via <code>registerKeyboardAction</code>.
*/
final class ActionStandin implements Action {
private final ActionListener actionListener;
private final String command;
// This will be non-null if actionListener is an Action.
private final Action action;
ActionStandin(ActionListener actionListener, String command) {
this.actionListener = actionListener;
if (actionListener instanceof Action) {
this.action = (Action)actionListener;
}
else {
this.action = null;
}
this.command = command;
}
public Object getValue(String key) {
if (key != null) {
if (key.equals(Action.ACTION_COMMAND_KEY)) {
return command;
}
if (action != null) {
return action.getValue(key);
}
if (key.equals(NAME)) {
return "ActionStandin";
}
}
return null;
}
public boolean isEnabled() {
if (actionListener == null) {
// This keeps the old semantics where
// registerKeyboardAction(null) would essentialy remove
// the binding. We don't remove the binding from the
// InputMap as that would still allow parent InputMaps
// bindings to be accessed.
return false;
}
if (action == null) {
return true;
}
return action.isEnabled();
}
public void actionPerformed(ActionEvent ae) {
if (actionListener != null) {
actionListener.actionPerformed(ae);
}
}
// We don't allow any values to be added.
public void putValue(String key, Object value) {}
// Does nothing, our enabledness is determiend from our asociated
// action.
public void setEnabled(boolean b) { }
public void addPropertyChangeListener
(PropertyChangeListener listener) {}
public void removePropertyChangeListener
(PropertyChangeListener listener) {}
}
// This class is used by the KeyboardState class to provide a single
// instance that can be stored in the AppContext.
static final class IntVector {
int array[] = null;
int count = 0;
int capacity = 0;
int size() {
return count;
}
int elementAt(int index) {
return array[index];
}
void addElement(int value) {
if (count == capacity) {
capacity = (capacity + 2) * 2;
int[] newarray = new int[capacity];
if (count > 0) {
System.arraycopy(array, 0, newarray, 0, count);
}
array = newarray;
}
array[count++] = value;
}
void setElementAt(int value, int index) {
array[index] = value;
}
}
@SuppressWarnings("serial")
static class KeyboardState implements Serializable {
private static final Object keyCodesKey =
JComponent.KeyboardState.class;
// Get the array of key codes from the AppContext.
static IntVector getKeyCodeArray() {
IntVector iv =
(IntVector)SwingUtilities.appContextGet(keyCodesKey);
if (iv == null) {
iv = new IntVector();
SwingUtilities.appContextPut(keyCodesKey, iv);
}
return iv;
}
static void registerKeyPressed(int keyCode) {
IntVector kca = getKeyCodeArray();
int count = kca.size();
int i;
for(i=0;i<count;i++) {
if(kca.elementAt(i) == -1){
kca.setElementAt(keyCode, i);
return;
}
}
kca.addElement(keyCode);
}
static void registerKeyReleased(int keyCode) {
IntVector kca = getKeyCodeArray();
int count = kca.size();
int i;
for(i=0;i<count;i++) {
if(kca.elementAt(i) == keyCode) {
kca.setElementAt(-1, i);
return;
}
}
}
static boolean keyIsPressed(int keyCode) {
IntVector kca = getKeyCodeArray();
int count = kca.size();
int i;
for(i=0;i<count;i++) {
if(kca.elementAt(i) == keyCode) {
return true;
}
}
return false;
}
/**
* Updates internal state of the KeyboardState and returns true
* if the event should be processed further.
*/
static boolean shouldProcess(KeyEvent e) {
switch (e.getID()) {
case KeyEvent.KEY_PRESSED:
if (!keyIsPressed(e.getKeyCode())) {
registerKeyPressed(e.getKeyCode());
}
return true;
case KeyEvent.KEY_RELEASED:
// We are forced to process VK_PRINTSCREEN separately because
// the Windows doesn't generate the key pressed event for
// printscreen and it block the processing of key release
// event for printscreen.
if (keyIsPressed(e.getKeyCode()) || e.getKeyCode()==KeyEvent.VK_PRINTSCREEN) {
registerKeyReleased(e.getKeyCode());
return true;
}
return false;
case KeyEvent.KEY_TYPED:
return true;
default:
// Not a known KeyEvent type, bail.
return false;
}
}
}
static final sun.awt.RequestFocusController focusController =
new sun.awt.RequestFocusController() {
public boolean acceptRequestFocus(Component from, Component to,
boolean temporary, boolean focusedWindowChangeAllowed,
FocusEvent.Cause cause)
{
if ((to == null) || !(to instanceof JComponent)) {
return true;
}
if ((from == null) || !(from instanceof JComponent)) {
return true;
}
JComponent target = (JComponent) to;
if (!target.getVerifyInputWhenFocusTarget()) {
return true;
}
JComponent jFocusOwner = (JComponent)from;
InputVerifier iv = jFocusOwner.getInputVerifier();
if (iv == null) {
return true;
} else {
Object currentSource = SwingUtilities.appContextGet(
INPUT_VERIFIER_SOURCE_KEY);
if (currentSource == jFocusOwner) {
// We're currently calling into the InputVerifier
// for this component, so allow the focus change.
return true;
}
SwingUtilities.appContextPut(INPUT_VERIFIER_SOURCE_KEY,
jFocusOwner);
try {
return iv.shouldYieldFocus(jFocusOwner, target);
} finally {
if (currentSource != null) {
// We're already in the InputVerifier for
// currentSource. By resetting the currentSource
// we ensure that if the InputVerifier for
// currentSource does a requestFocus, we don't
// try and run the InputVerifier again.
SwingUtilities.appContextPut(
INPUT_VERIFIER_SOURCE_KEY, currentSource);
} else {
SwingUtilities.appContextRemove(
INPUT_VERIFIER_SOURCE_KEY);
}
}
}
}
};
/*
* --- Accessibility Support ---
*/
/**
* @deprecated As of JDK version 1.1,
* replaced by <code>java.awt.Component.setEnabled(boolean)</code>.
*/
@Deprecated
public void enable() {
if (isEnabled() != true) {
super.enable();
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
null, AccessibleState.ENABLED);
}
}
}
/**
* @deprecated As of JDK version 1.1,
* replaced by <code>java.awt.Component.setEnabled(boolean)</code>.
*/
@Deprecated
public void disable() {
if (isEnabled() != false) {
super.disable();
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
AccessibleState.ENABLED, null);
}
}
}
/**
* Inner class of JComponent used to provide default support for
* accessibility. This class is not meant to be used directly by
* application developers, but is instead meant only to be
* subclassed by component developers.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans™
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*/
@SuppressWarnings("serial") // Same-version serialization only
public abstract class AccessibleJComponent extends AccessibleAWTContainer
implements AccessibleExtendedComponent
{
/**
* Though the class is abstract, this should be called by
* all sub-classes.
*/
protected AccessibleJComponent() {
super();
}
/**
* Number of PropertyChangeListener objects registered. It's used
* to add/remove ContainerListener and FocusListener to track
* target JComponent's state
*/
private transient volatile int propertyListenersCount = 0;
/**
* This field duplicates the function of the accessibleAWTFocusHandler field
* in java.awt.Component.AccessibleAWTComponent, so it has been deprecated.
*/
@Deprecated
protected FocusListener accessibleFocusHandler = null;
/**
* Fire PropertyChange listener, if one is registered,
* when children added/removed.
*/
protected class AccessibleContainerHandler
implements ContainerListener {
public void componentAdded(ContainerEvent e) {
Component c = e.getChild();
if (c != null && c instanceof Accessible) {
AccessibleJComponent.this.firePropertyChange(
AccessibleContext.ACCESSIBLE_CHILD_PROPERTY,
null, c.getAccessibleContext());
}
}
public void componentRemoved(ContainerEvent e) {
Component c = e.getChild();
if (c != null && c instanceof Accessible) {
AccessibleJComponent.this.firePropertyChange(
AccessibleContext.ACCESSIBLE_CHILD_PROPERTY,
c.getAccessibleContext(), null);
}
}
}
/**
* Fire PropertyChange listener, if one is registered,
* when focus events happen
* @since 1.3
*/
protected class AccessibleFocusHandler implements FocusListener {
public void focusGained(FocusEvent event) {
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
null, AccessibleState.FOCUSED);
}
}
public void focusLost(FocusEvent event) {
if (accessibleContext != null) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
AccessibleState.FOCUSED, null);
}
}
} // inner class AccessibleFocusHandler
/**
* Adds a PropertyChangeListener to the listener list.
*
* @param listener the PropertyChangeListener to be added
*/
public void addPropertyChangeListener(PropertyChangeListener listener) {
super.addPropertyChangeListener(listener);
}
/**
* Removes a PropertyChangeListener from the listener list.
* This removes a PropertyChangeListener that was registered
* for all properties.
*
* @param listener the PropertyChangeListener to be removed
*/
public void removePropertyChangeListener(PropertyChangeListener listener) {
super.removePropertyChangeListener(listener);
}
/**
* Recursively search through the border hierarchy (if it exists)
* for a TitledBorder with a non-null title. This does a depth
* first search on first the inside borders then the outside borders.
* The assumption is that titles make really pretty inside borders
* but not very pretty outside borders in compound border situations.
* It's rather arbitrary, but hopefully decent UI programmers will
* not create multiple titled borders for the same component.
*
* @param b the {@code Border} for which to retrieve its title
* @return the border's title as a {@code String}, null if it has
* no title
*/
protected String getBorderTitle(Border b) {
String s;
if (b instanceof TitledBorder) {
return ((TitledBorder) b).getTitle();
} else if (b instanceof CompoundBorder) {
s = getBorderTitle(((CompoundBorder) b).getInsideBorder());
if (s == null) {
s = getBorderTitle(((CompoundBorder) b).getOutsideBorder());
}
return s;
} else {
return null;
}
}
// AccessibleContext methods
//
/**
* Gets the accessible name of this object. This should almost never
* return java.awt.Component.getName(), as that generally isn't
* a localized name, and doesn't have meaning for the user. If the
* object is fundamentally a text object (such as a menu item), the
* accessible name should be the text of the object (for example,
* "save").
* If the object has a tooltip, the tooltip text may also be an
* appropriate String to return.
*
* @return the localized name of the object -- can be null if this
* object does not have a name
* @see AccessibleContext#setAccessibleName
*/
public String getAccessibleName() {
String name = accessibleName;
// fallback to the client name property
//
if (name == null) {
name = (String)getClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY);
}
// fallback to the titled border if it exists
//
if (name == null) {
name = getBorderTitle(getBorder());
}
// fallback to the label labeling us if it exists
//
if (name == null) {
Object o = getClientProperty(JLabel.LABELED_BY_PROPERTY);
if (o instanceof Accessible) {
AccessibleContext ac = ((Accessible) o).getAccessibleContext();
if (ac != null) {
name = ac.getAccessibleName();
}
}
}
return name;
}
/**
* Gets the accessible description of this object. This should be
* a concise, localized description of what this object is - what
* is its meaning to the user. If the object has a tooltip, the
* tooltip text may be an appropriate string to return, assuming
* it contains a concise description of the object (instead of just
* the name of the object - for example a "Save" icon on a toolbar that
* had "save" as the tooltip text shouldn't return the tooltip
* text as the description, but something like "Saves the current
* text document" instead).
*
* @return the localized description of the object -- can be null if
* this object does not have a description
* @see AccessibleContext#setAccessibleDescription
*/
public String getAccessibleDescription() {
String description = accessibleDescription;
// fallback to the client description property
//
if (description == null) {
description = (String)getClientProperty(AccessibleContext.ACCESSIBLE_DESCRIPTION_PROPERTY);
}
// fallback to the tool tip text if it exists
//
if (description == null) {
try {
description = getToolTipText();
} catch (Exception e) {
// Just in case the subclass overrode the
// getToolTipText method and actually
// requires a MouseEvent.
// [[[FIXME: WDW - we probably should require this
// method to take a MouseEvent and just pass it on
// to getToolTipText. The swing-feedback traffic
// leads me to believe getToolTipText might change,
// though, so I was hesitant to make this change at
// this time.]]]
}
}
// fallback to the label labeling us if it exists
//
if (description == null) {
Object o = getClientProperty(JLabel.LABELED_BY_PROPERTY);
if (o instanceof Accessible) {
AccessibleContext ac = ((Accessible) o).getAccessibleContext();
if (ac != null) {
description = ac.getAccessibleDescription();
}
}
}
return description;
}
/**
* Gets the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.SWING_COMPONENT;
}
/**
* Gets the state of this object.
*
* @return an instance of AccessibleStateSet containing the current
* state set of the object
* @see AccessibleState
*/
public AccessibleStateSet getAccessibleStateSet() {
AccessibleStateSet states = super.getAccessibleStateSet();
if (JComponent.this.isOpaque()) {
states.add(AccessibleState.OPAQUE);
}
return states;
}
/**
* Returns the number of accessible children in the object. If all
* of the children of this object implement Accessible, than this
* method should return the number of children of this object.
*
* @return the number of accessible children in the object.
*/
public int getAccessibleChildrenCount() {
return super.getAccessibleChildrenCount();
}
/**
* Returns the nth Accessible child of the object.
*
* @param i zero-based index of child
* @return the nth Accessible child of the object
*/
public Accessible getAccessibleChild(int i) {
return super.getAccessibleChild(i);
}
// ----- AccessibleExtendedComponent
/**
* Returns the AccessibleExtendedComponent
*
* @return the AccessibleExtendedComponent
*/
AccessibleExtendedComponent getAccessibleExtendedComponent() {
return this;
}
/**
* Returns the tool tip text
*
* @return the tool tip text, if supported, of the object;
* otherwise, null
* @since 1.4
*/
public String getToolTipText() {
return JComponent.this.getToolTipText();
}
/**
* Returns the titled border text
*
* @return the titled border text, if supported, of the object;
* otherwise, null
* @since 1.4
*/
public String getTitledBorderText() {
Border border = JComponent.this.getBorder();
if (border instanceof TitledBorder) {
return ((TitledBorder)border).getTitle();
} else {
return null;
}
}
/**
* Returns key bindings associated with this object
*
* @return the key bindings, if supported, of the object;
* otherwise, null
* @see AccessibleKeyBinding
* @since 1.4
*/
public AccessibleKeyBinding getAccessibleKeyBinding(){
// Try to get the linked label's mnemonic if it exists
Object o = getClientProperty(JLabel.LABELED_BY_PROPERTY);
if (o instanceof Accessible){
AccessibleContext ac = ((Accessible) o).getAccessibleContext();
if (ac != null){
AccessibleComponent comp = ac.getAccessibleComponent();
if (! (comp instanceof AccessibleExtendedComponent))
return null;
return ((AccessibleExtendedComponent)comp).getAccessibleKeyBinding();
}
}
return null;
}
} // inner class AccessibleJComponent
/**
* Returns an <code>ArrayTable</code> used for
* key/value "client properties" for this component. If the
* <code>clientProperties</code> table doesn't exist, an empty one
* will be created.
*
* @return an ArrayTable
* @see #putClientProperty
* @see #getClientProperty
*/
private ArrayTable getClientProperties() {
if (clientProperties == null) {
clientProperties = new ArrayTable();
}
return clientProperties;
}
/**
* Returns the value of the property with the specified key. Only
* properties added with <code>putClientProperty</code> will return
* a non-<code>null</code> value.
*
* @param key the being queried
* @return the value of this property or <code>null</code>
* @see #putClientProperty
*/
public final Object getClientProperty(Object key) {
if (key == RenderingHints.KEY_TEXT_ANTIALIASING) {
return aaHint;
} else if (key == RenderingHints.KEY_TEXT_LCD_CONTRAST) {
return lcdRenderingHint;
}
if(clientProperties == null) {
return null;
} else {
synchronized(clientProperties) {
return clientProperties.get(key);
}
}
}
/**
* Adds an arbitrary key/value "client property" to this component.
* <p>
* The <code>get/putClientProperty</code> methods provide access to
* a small per-instance hashtable. Callers can use get/putClientProperty
* to annotate components that were created by another module.
* For example, a
* layout manager might store per child constraints this way. For example:
* <pre>
* componentA.putClientProperty("to the left of", componentB);
* </pre>
* If value is <code>null</code> this method will remove the property.
* Changes to client properties are reported with
* <code>PropertyChange</code> events.
* The name of the property (for the sake of PropertyChange
* events) is <code>key.toString()</code>.
* <p>
* The <code>clientProperty</code> dictionary is not intended to
* support large
* scale extensions to JComponent nor should be it considered an
* alternative to subclassing when designing a new component.
*
* @param key the new client property key
* @param value the new client property value; if <code>null</code>
* this method will remove the property
* @see #getClientProperty
* @see #addPropertyChangeListener
*/
public final void putClientProperty(Object key, Object value) {
if (key == RenderingHints.KEY_TEXT_ANTIALIASING) {
aaHint = value;
return;
} else if (key == RenderingHints.KEY_TEXT_LCD_CONTRAST) {
lcdRenderingHint = value;
return;
}
if (value == null && clientProperties == null) {
// Both the value and ArrayTable are null, implying we don't
// have to do anything.
return;
}
ArrayTable clientProperties = getClientProperties();
Object oldValue;
synchronized(clientProperties) {
oldValue = clientProperties.get(key);
if (value != null) {
clientProperties.put(key, value);
} else if (oldValue != null) {
clientProperties.remove(key);
} else {
// old == new == null
return;
}
}
clientPropertyChanged(key, oldValue, value);
firePropertyChange(key.toString(), oldValue, value);
}
// Invoked from putClientProperty. This is provided for subclasses
// in Swing.
void clientPropertyChanged(Object key, Object oldValue,
Object newValue) {
}
/*
* Sets the property with the specified name to the specified value if
* the property has not already been set by the client program.
* This method is used primarily to set UI defaults for properties
* with primitive types, where the values cannot be marked with
* UIResource.
* @see LookAndFeel#installProperty
* @param propertyName String containing the name of the property
* @param value Object containing the property value
*/
void setUIProperty(String propertyName, Object value) {
if (propertyName == "opaque") {
if (!getFlag(OPAQUE_SET)) {
setOpaque(((Boolean)value).booleanValue());
setFlag(OPAQUE_SET, false);
}
} else if (propertyName == "autoscrolls") {
if (!getFlag(AUTOSCROLLS_SET)) {
setAutoscrolls(((Boolean)value).booleanValue());
setFlag(AUTOSCROLLS_SET, false);
}
} else if (propertyName == "focusTraversalKeysForward") {
@SuppressWarnings("unchecked")
Set<AWTKeyStroke> strokeSet = (Set<AWTKeyStroke>) value;
if (!getFlag(FOCUS_TRAVERSAL_KEYS_FORWARD_SET)) {
super.setFocusTraversalKeys(KeyboardFocusManager.
FORWARD_TRAVERSAL_KEYS,
strokeSet);
}
} else if (propertyName == "focusTraversalKeysBackward") {
@SuppressWarnings("unchecked")
Set<AWTKeyStroke> strokeSet = (Set<AWTKeyStroke>) value;
if (!getFlag(FOCUS_TRAVERSAL_KEYS_BACKWARD_SET)) {
super.setFocusTraversalKeys(KeyboardFocusManager.
BACKWARD_TRAVERSAL_KEYS,
strokeSet);
}
} else {
throw new IllegalArgumentException("property \""+
propertyName+ "\" cannot be set using this method");
}
}
/**
* Sets the focus traversal keys for a given traversal operation for this
* Component.
* Refer to
* {@link java.awt.Component#setFocusTraversalKeys}
* for a complete description of this method.
* <p>
* This method may throw a {@code ClassCastException} if any {@code Object}
* in {@code keystrokes} is not an {@code AWTKeyStroke}.
*
* @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
* KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
* KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
* @param keystrokes the Set of AWTKeyStroke for the specified operation
* @see java.awt.KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS
* @see java.awt.KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS
* @see java.awt.KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS
* @throws IllegalArgumentException if id is not one of
* KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
* KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
* KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or if keystrokes
* contains null, or if any keystroke represents a KEY_TYPED event,
* or if any keystroke already maps to another focus traversal
* operation for this Component
* @since 1.5
*/
public void
setFocusTraversalKeys(int id, Set<? extends AWTKeyStroke> keystrokes)
{
if (id == KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS) {
setFlag(FOCUS_TRAVERSAL_KEYS_FORWARD_SET,true);
} else if (id == KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS) {
setFlag(FOCUS_TRAVERSAL_KEYS_BACKWARD_SET,true);
}
super.setFocusTraversalKeys(id,keystrokes);
}
/* --- Transitional java.awt.Component Support ---
* The methods and fields in this section will migrate to
* java.awt.Component in the next JDK release.
*/
/**
* Returns true if this component is lightweight, that is, if it doesn't
* have a native window system peer.
*
* @param c the {@code Component} to be checked
* @return true if this component is lightweight
*/
public static boolean isLightweightComponent(Component c) {
// TODO we cannot call c.isLightweight() because it is incorrectly
// overriden in DelegateContainer on osx.
return AWTAccessor.getComponentAccessor().isLightweight(c);
}
/**
* @deprecated As of JDK 5,
* replaced by <code>Component.setBounds(int, int, int, int)</code>.
* <p>
* Moves and resizes this component.
*
* @param x the new horizontal location
* @param y the new vertical location
* @param w the new width
* @param h the new height
* @see java.awt.Component#setBounds
*/
@Deprecated
public void reshape(int x, int y, int w, int h) {
super.reshape(x, y, w, h);
}
/**
* Stores the bounds of this component into "return value"
* <code>rv</code> and returns <code>rv</code>.
* If <code>rv</code> is <code>null</code> a new <code>Rectangle</code>
* is allocated. This version of <code>getBounds</code> is useful
* if the caller wants to avoid allocating a new <code>Rectangle</code>
* object on the heap.
*
* @param rv the return value, modified to the component's bounds
* @return <code>rv</code>; if <code>rv</code> is <code>null</code>
* return a newly created <code>Rectangle</code> with this
* component's bounds
*/
public Rectangle getBounds(Rectangle rv) {
if (rv == null) {
return new Rectangle(getX(), getY(), getWidth(), getHeight());
}
else {
rv.setBounds(getX(), getY(), getWidth(), getHeight());
return rv;
}
}
/**
* Stores the width/height of this component into "return value"
* <code>rv</code> and returns <code>rv</code>.
* If <code>rv</code> is <code>null</code> a new <code>Dimension</code>
* object is allocated. This version of <code>getSize</code>
* is useful if the caller wants to avoid allocating a new
* <code>Dimension</code> object on the heap.
*
* @param rv the return value, modified to the component's size
* @return <code>rv</code>
*/
public Dimension getSize(Dimension rv) {
if (rv == null) {
return new Dimension(getWidth(), getHeight());
}
else {
rv.setSize(getWidth(), getHeight());
return rv;
}
}
/**
* Stores the x,y origin of this component into "return value"
* <code>rv</code> and returns <code>rv</code>.
* If <code>rv</code> is <code>null</code> a new <code>Point</code>
* is allocated. This version of <code>getLocation</code> is useful
* if the caller wants to avoid allocating a new <code>Point</code>
* object on the heap.
*
* @param rv the return value, modified to the component's location
* @return <code>rv</code>
*/
public Point getLocation(Point rv) {
if (rv == null) {
return new Point(getX(), getY());
}
else {
rv.setLocation(getX(), getY());
return rv;
}
}
/**
* Returns the current x coordinate of the component's origin.
* This method is preferable to writing
* <code>component.getBounds().x</code>, or
* <code>component.getLocation().x</code> because it doesn't cause any
* heap allocations.
*
* @return the current x coordinate of the component's origin
*/
@BeanProperty(bound = false)
public int getX() { return super.getX(); }
/**
* Returns the current y coordinate of the component's origin.
* This method is preferable to writing
* <code>component.getBounds().y</code>, or
* <code>component.getLocation().y</code> because it doesn't cause any
* heap allocations.
*
* @return the current y coordinate of the component's origin
*/
@BeanProperty(bound = false)
public int getY() { return super.getY(); }
/**
* Returns the current width of this component.
* This method is preferable to writing
* <code>component.getBounds().width</code>, or
* <code>component.getSize().width</code> because it doesn't cause any
* heap allocations.
*
* @return the current width of this component
*/
@BeanProperty(bound = false)
public int getWidth() { return super.getWidth(); }
/**
* Returns the current height of this component.
* This method is preferable to writing
* <code>component.getBounds().height</code>, or
* <code>component.getSize().height</code> because it doesn't cause any
* heap allocations.
*
* @return the current height of this component
*/
@BeanProperty(bound = false)
public int getHeight() { return super.getHeight(); }
/**
* Returns true if this component is completely opaque.
* <p>
* An opaque component paints every pixel within its
* rectangular bounds. A non-opaque component paints only a subset of
* its pixels or none at all, allowing the pixels underneath it to
* "show through". Therefore, a component that does not fully paint
* its pixels provides a degree of transparency.
* <p>
* Subclasses that guarantee to always completely paint their contents
* should override this method and return true.
*
* @return true if this component is completely opaque
* @see #setOpaque
*/
public boolean isOpaque() {
return getFlag(IS_OPAQUE);
}
/**
* If true the component paints every pixel within its bounds.
* Otherwise, the component may not paint some or all of its
* pixels, allowing the underlying pixels to show through.
* <p>
* The default value of this property is false for <code>JComponent</code>.
* However, the default value for this property on most standard
* <code>JComponent</code> subclasses (such as <code>JButton</code> and
* <code>JTree</code>) is look-and-feel dependent.
*
* @param isOpaque true if this component should be opaque
* @see #isOpaque
*/
@BeanProperty(expert = true, description
= "The component's opacity")
public void setOpaque(boolean isOpaque) {
boolean oldValue = getFlag(IS_OPAQUE);
setFlag(IS_OPAQUE, isOpaque);
setFlag(OPAQUE_SET, true);
firePropertyChange("opaque", oldValue, isOpaque);
}
/**
* If the specified rectangle is completely obscured by any of this
* component's opaque children then returns true. Only direct children
* are considered, more distant descendants are ignored. A
* <code>JComponent</code> is opaque if
* <code>JComponent.isOpaque()</code> returns true, other lightweight
* components are always considered transparent, and heavyweight components
* are always considered opaque.
*
* @param x x value of specified rectangle
* @param y y value of specified rectangle
* @param width width of specified rectangle
* @param height height of specified rectangle
* @return true if the specified rectangle is obscured by an opaque child
*/
boolean rectangleIsObscured(int x,int y,int width,int height)
{
int numChildren = getComponentCount();
for(int i = 0; i < numChildren; i++) {
Component child = getComponent(i);
int cx, cy, cw, ch;
cx = child.getX();
cy = child.getY();
cw = child.getWidth();
ch = child.getHeight();
if (x >= cx && (x + width) <= (cx + cw) &&
y >= cy && (y + height) <= (cy + ch) && child.isVisible()) {
if(child instanceof JComponent) {
// System.out.println("A) checking opaque: " + ((JComponent)child).isOpaque() + " " + child);
// System.out.print("B) ");
// Thread.dumpStack();
return child.isOpaque();
} else {
/** Sometimes a heavy weight can have a bound larger than its peer size
* so we should always draw under heavy weights
*/
return false;
}
}
}
return false;
}
/**
* Returns the <code>Component</code>'s "visible rect rectangle" - the
* intersection of the visible rectangles for the component <code>c</code>
* and all of its ancestors. The return value is stored in
* <code>visibleRect</code>.
*
* @param c the component
* @param visibleRect a <code>Rectangle</code> computed as the
* intersection of all visible rectangles for the component
* <code>c</code> and all of its ancestors -- this is the
* return value for this method
* @see #getVisibleRect
*/
static final void computeVisibleRect(Component c, Rectangle visibleRect) {
Container p = c.getParent();
Rectangle bounds = c.getBounds();
if (p == null || p instanceof Window || p instanceof Applet) {
visibleRect.setBounds(0, 0, bounds.width, bounds.height);
} else {
computeVisibleRect(p, visibleRect);
visibleRect.x -= bounds.x;
visibleRect.y -= bounds.y;
SwingUtilities.computeIntersection(0,0,bounds.width,bounds.height,visibleRect);
}
}
/**
* Returns the <code>Component</code>'s "visible rect rectangle" - the
* intersection of the visible rectangles for this component
* and all of its ancestors. The return value is stored in
* <code>visibleRect</code>.
*
* @param visibleRect a <code>Rectangle</code> computed as the
* intersection of all visible rectangles for this
* component and all of its ancestors -- this is the return
* value for this method
* @see #getVisibleRect
*/
public void computeVisibleRect(Rectangle visibleRect) {
computeVisibleRect(this, visibleRect);
}
/**
* Returns the <code>Component</code>'s "visible rectangle" - the
* intersection of this component's visible rectangle,
* <code>new Rectangle(0, 0, getWidth(), getHeight())</code>,
* and all of its ancestors' visible rectangles.
*
* @return the visible rectangle
*/
@BeanProperty(bound = false)
public Rectangle getVisibleRect() {
Rectangle visibleRect = new Rectangle();
computeVisibleRect(visibleRect);
return visibleRect;
}
/**
* Support for reporting bound property changes for boolean properties.
* This method can be called when a bound property has changed and it will
* send the appropriate PropertyChangeEvent to any registered
* PropertyChangeListeners.
*
* @param propertyName the property whose value has changed
* @param oldValue the property's previous value
* @param newValue the property's new value
*/
public void firePropertyChange(String propertyName,
boolean oldValue, boolean newValue) {
super.firePropertyChange(propertyName, oldValue, newValue);
}
/**
* Support for reporting bound property changes for integer properties.
* This method can be called when a bound property has changed and it will
* send the appropriate PropertyChangeEvent to any registered
* PropertyChangeListeners.
*
* @param propertyName the property whose value has changed
* @param oldValue the property's previous value
* @param newValue the property's new value
*/
public void firePropertyChange(String propertyName,
int oldValue, int newValue) {
super.firePropertyChange(propertyName, oldValue, newValue);
}
// XXX This method is implemented as a workaround to a JLS issue with ambiguous
// methods. This should be removed once 4758654 is resolved.
public void firePropertyChange(String propertyName, char oldValue, char newValue) {
super.firePropertyChange(propertyName, oldValue, newValue);
}
/**
* Supports reporting constrained property changes.
* This method can be called when a constrained property has changed
* and it will send the appropriate <code>PropertyChangeEvent</code>
* to any registered <code>VetoableChangeListeners</code>.
*
* @param propertyName the name of the property that was listened on
* @param oldValue the old value of the property
* @param newValue the new value of the property
* @exception java.beans.PropertyVetoException when the attempt to set the
* property is vetoed by the component
*/
protected void fireVetoableChange(String propertyName, Object oldValue, Object newValue)
throws java.beans.PropertyVetoException
{
if (vetoableChangeSupport == null) {
return;
}
vetoableChangeSupport.fireVetoableChange(propertyName, oldValue, newValue);
}
/**
* Adds a <code>VetoableChangeListener</code> to the listener list.
* The listener is registered for all properties.
*
* @param listener the <code>VetoableChangeListener</code> to be added
*/
public synchronized void addVetoableChangeListener(VetoableChangeListener listener) {
if (vetoableChangeSupport == null) {
vetoableChangeSupport = new java.beans.VetoableChangeSupport(this);
}
vetoableChangeSupport.addVetoableChangeListener(listener);
}
/**
* Removes a <code>VetoableChangeListener</code> from the listener list.
* This removes a <code>VetoableChangeListener</code> that was registered
* for all properties.
*
* @param listener the <code>VetoableChangeListener</code> to be removed
*/
public synchronized void removeVetoableChangeListener(VetoableChangeListener listener) {
if (vetoableChangeSupport == null) {
return;
}
vetoableChangeSupport.removeVetoableChangeListener(listener);
}
/**
* Returns an array of all the vetoable change listeners
* registered on this component.
*
* @return all of the component's <code>VetoableChangeListener</code>s
* or an empty
* array if no vetoable change listeners are currently registered
*
* @see #addVetoableChangeListener
* @see #removeVetoableChangeListener
*
* @since 1.4
*/
@BeanProperty(bound = false)
public synchronized VetoableChangeListener[] getVetoableChangeListeners() {
if (vetoableChangeSupport == null) {
return new VetoableChangeListener[0];
}
return vetoableChangeSupport.getVetoableChangeListeners();
}
/**
* Returns the top-level ancestor of this component (either the
* containing <code>Window</code> or <code>Applet</code>),
* or <code>null</code> if this component has not
* been added to any container.
*
* @return the top-level <code>Container</code> that this component is in,
* or <code>null</code> if not in any container
*/
@BeanProperty(bound = false)
public Container getTopLevelAncestor() {
for(Container p = this; p != null; p = p.getParent()) {
if(p instanceof Window || p instanceof Applet) {
return p;
}
}
return null;
}
private AncestorNotifier getAncestorNotifier() {
return (AncestorNotifier)
getClientProperty(JComponent_ANCESTOR_NOTIFIER);
}
/**
* Registers <code>listener</code> so that it will receive
* <code>AncestorEvents</code> when it or any of its ancestors
* move or are made visible or invisible.
* Events are also sent when the component or its ancestors are added
* or removed from the containment hierarchy.
*
* @param listener the <code>AncestorListener</code> to register
* @see AncestorEvent
*/
public void addAncestorListener(AncestorListener listener) {
AncestorNotifier ancestorNotifier = getAncestorNotifier();
if (ancestorNotifier == null) {
ancestorNotifier = new AncestorNotifier(this);
putClientProperty(JComponent_ANCESTOR_NOTIFIER,
ancestorNotifier);
}
ancestorNotifier.addAncestorListener(listener);
}
/**
* Unregisters <code>listener</code> so that it will no longer receive
* <code>AncestorEvents</code>.
*
* @param listener the <code>AncestorListener</code> to be removed
* @see #addAncestorListener
*/
public void removeAncestorListener(AncestorListener listener) {
AncestorNotifier ancestorNotifier = getAncestorNotifier();
if (ancestorNotifier == null) {
return;
}
ancestorNotifier.removeAncestorListener(listener);
if (ancestorNotifier.listenerList.getListenerList().length == 0) {
ancestorNotifier.removeAllListeners();
putClientProperty(JComponent_ANCESTOR_NOTIFIER, null);
}
}
/**
* Returns an array of all the ancestor listeners
* registered on this component.
*
* @return all of the component's <code>AncestorListener</code>s
* or an empty
* array if no ancestor listeners are currently registered
*
* @see #addAncestorListener
* @see #removeAncestorListener
*
* @since 1.4
*/
@BeanProperty(bound = false)
public AncestorListener[] getAncestorListeners() {
AncestorNotifier ancestorNotifier = getAncestorNotifier();
if (ancestorNotifier == null) {
return new AncestorListener[0];
}
return ancestorNotifier.getAncestorListeners();
}
/**
* Returns an array of all the objects currently registered
* as <code><em>Foo</em>Listener</code>s
* upon this <code>JComponent</code>.
* <code><em>Foo</em>Listener</code>s are registered using the
* <code>add<em>Foo</em>Listener</code> method.
*
* <p>
*
* You can specify the <code>listenerType</code> argument
* with a class literal,
* such as
* <code><em>Foo</em>Listener.class</code>.
* For example, you can query a
* <code>JComponent</code> <code>c</code>
* for its mouse listeners with the following code:
* <pre>MouseListener[] mls = (MouseListener[])(c.getListeners(MouseListener.class));</pre>
* If no such listeners exist, this method returns an empty array.
*
* @param listenerType the type of listeners requested; this parameter
* should specify an interface that descends from
* <code>java.util.EventListener</code>
* @return an array of all objects registered as
* <code><em>Foo</em>Listener</code>s on this component,
* or an empty array if no such
* listeners have been added
* @exception ClassCastException if <code>listenerType</code>
* doesn't specify a class or interface that implements
* <code>java.util.EventListener</code>
*
* @since 1.3
*
* @see #getVetoableChangeListeners
* @see #getAncestorListeners
*/
@SuppressWarnings("unchecked") // Casts to (T[])
public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
T[] result;
if (listenerType == AncestorListener.class) {
// AncestorListeners are handled by the AncestorNotifier
result = (T[])getAncestorListeners();
}
else if (listenerType == VetoableChangeListener.class) {
// VetoableChangeListeners are handled by VetoableChangeSupport
result = (T[])getVetoableChangeListeners();
}
else if (listenerType == PropertyChangeListener.class) {
// PropertyChangeListeners are handled by PropertyChangeSupport
result = (T[])getPropertyChangeListeners();
}
else {
result = listenerList.getListeners(listenerType);
}
if (result.length == 0) {
return super.getListeners(listenerType);
}
return result;
}
/**
* Notifies this component that it now has a parent component.
* When this method is invoked, the chain of parent components is
* set up with <code>KeyboardAction</code> event listeners.
* This method is called by the toolkit internally and should
* not be called directly by programs.
*
* @see #registerKeyboardAction
*/
public void addNotify() {
super.addNotify();
firePropertyChange("ancestor", null, getParent());
registerWithKeyboardManager(false);
registerNextFocusableComponent();
}
/**
* Notifies this component that it no longer has a parent component.
* When this method is invoked, any <code>KeyboardAction</code>s
* set up in the chain of parent components are removed.
* This method is called by the toolkit internally and should
* not be called directly by programs.
*
* @see #registerKeyboardAction
*/
public void removeNotify() {
super.removeNotify();
// This isn't strictly correct. The event shouldn't be
// fired until *after* the parent is set to null. But
// we only get notified before that happens
firePropertyChange("ancestor", getParent(), null);
unregisterWithKeyboardManager();
deregisterNextFocusableComponent();
if (getCreatedDoubleBuffer()) {
RepaintManager.currentManager(this).resetDoubleBuffer();
setCreatedDoubleBuffer(false);
}
if (autoscrolls) {
Autoscroller.stop(this);
}
}
/**
* Adds the specified region to the dirty region list if the component
* is showing. The component will be repainted after all of the
* currently pending events have been dispatched.
*
* @param tm this parameter is not used
* @param x the x value of the dirty region
* @param y the y value of the dirty region
* @param width the width of the dirty region
* @param height the height of the dirty region
* @see #isPaintingOrigin()
* @see java.awt.Component#isShowing
* @see RepaintManager#addDirtyRegion
*/
public void repaint(long tm, int x, int y, int width, int height) {
RepaintManager.currentManager(SunToolkit.targetToAppContext(this))
.addDirtyRegion(this, x, y, width, height);
}
/**
* Adds the specified region to the dirty region list if the component
* is showing. The component will be repainted after all of the
* currently pending events have been dispatched.
*
* @param r a <code>Rectangle</code> containing the dirty region
* @see #isPaintingOrigin()
* @see java.awt.Component#isShowing
* @see RepaintManager#addDirtyRegion
*/
public void repaint(Rectangle r) {
repaint(0,r.x,r.y,r.width,r.height);
}
/**
* Supports deferred automatic layout.
* <p>
* Calls <code>invalidate</code> and then adds this component's
* <code>validateRoot</code> to a list of components that need to be
* validated. Validation will occur after all currently pending
* events have been dispatched. In other words after this method
* is called, the first validateRoot (if any) found when walking
* up the containment hierarchy of this component will be validated.
* By default, <code>JRootPane</code>, <code>JScrollPane</code>,
* and <code>JTextField</code> return true
* from <code>isValidateRoot</code>.
* <p>
* This method will automatically be called on this component
* when a property value changes such that size, location, or
* internal layout of this component has been affected. This automatic
* updating differs from the AWT because programs generally no
* longer need to invoke <code>validate</code> to get the contents of the
* GUI to update.
*
* @see java.awt.Component#invalidate
* @see java.awt.Container#validate
* @see #isValidateRoot
* @see RepaintManager#addInvalidComponent
*/
public void revalidate() {
if (getParent() == null) {
// Note: We don't bother invalidating here as once added
// to a valid parent invalidate will be invoked (addImpl
// invokes addNotify which will invoke invalidate on the
// new Component). Also, if we do add a check to isValid
// here it can potentially be called before the constructor
// which was causing some people grief.
return;
}
if (SunToolkit.isDispatchThreadForAppContext(this)) {
invalidate();
RepaintManager.currentManager(this).addInvalidComponent(this);
}
else {
// To avoid a flood of Runnables when constructing GUIs off
// the EDT, a flag is maintained as to whether or not
// a Runnable has been scheduled.
if (revalidateRunnableScheduled.getAndSet(true)) {
return;
}
SunToolkit.executeOnEventHandlerThread(this, () -> {
revalidateRunnableScheduled.set(false);
revalidate();
});
}
}
/**
* If this method returns true, <code>revalidate</code> calls by
* descendants of this component will cause the entire tree
* beginning with this root to be validated.
* Returns false by default. <code>JScrollPane</code> overrides
* this method and returns true.
*
* @return always returns false
* @see #revalidate
* @see java.awt.Component#invalidate
* @see java.awt.Container#validate
* @see java.awt.Container#isValidateRoot
*/
@Override
public boolean isValidateRoot() {
return false;
}
/**
* Returns true if this component tiles its children -- that is, if
* it can guarantee that the children will not overlap. The
* repainting system is substantially more efficient in this
* common case. <code>JComponent</code> subclasses that can't make this
* guarantee, such as <code>JLayeredPane</code>,
* should override this method to return false.
*
* @return always returns true
*/
@BeanProperty(bound = false)
public boolean isOptimizedDrawingEnabled() {
return true;
}
/**
* Returns {@code true} if a paint triggered on a child component should cause
* painting to originate from this Component, or one of its ancestors.
* <p>
* Calling {@link #repaint} or {@link #paintImmediately(int, int, int, int)}
* on a Swing component will result in calling
* the {@link JComponent#paintImmediately(int, int, int, int)} method of
* the first ancestor which {@code isPaintingOrigin()} returns {@code true}, if there are any.
* <p>
* {@code JComponent} subclasses that need to be painted when any of their
* children are repainted should override this method to return {@code true}.
*
* @return always returns {@code false}
*
* @see #paintImmediately(int, int, int, int)
*/
protected boolean isPaintingOrigin() {
return false;
}
/**
* Paints the specified region in this component and all of its
* descendants that overlap the region, immediately.
* <p>
* It's rarely necessary to call this method. In most cases it's
* more efficient to call repaint, which defers the actual painting
* and can collapse redundant requests into a single paint call.
* This method is useful if one needs to update the display while
* the current event is being dispatched.
* <p>
* This method is to be overridden when the dirty region needs to be changed
* for components that are painting origins.
*
* @param x the x value of the region to be painted
* @param y the y value of the region to be painted
* @param w the width of the region to be painted
* @param h the height of the region to be painted
* @see #repaint
* @see #isPaintingOrigin()
*/
public void paintImmediately(int x,int y,int w, int h) {
Component c = this;
Component parent;
if(!isShowing()) {
return;
}
JComponent paintingOigin = SwingUtilities.getPaintingOrigin(this);
if (paintingOigin != null) {
Rectangle rectangle = SwingUtilities.convertRectangle(
c, new Rectangle(x, y, w, h), paintingOigin);
paintingOigin.paintImmediately(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
return;
}
while(!c.isOpaque()) {
parent = c.getParent();
if(parent != null) {
x += c.getX();
y += c.getY();
c = parent;
} else {
break;
}
if(!(c instanceof JComponent)) {
break;
}
}
if(c instanceof JComponent) {
((JComponent)c)._paintImmediately(x,y,w,h);
} else {
c.repaint(x,y,w,h);
}
}
/**
* Paints the specified region now.
*
* @param r a <code>Rectangle</code> containing the region to be painted
*/
public void paintImmediately(Rectangle r) {
paintImmediately(r.x,r.y,r.width,r.height);
}
/**
* Returns whether this component should be guaranteed to be on top.
* For example, it would make no sense for <code>Menu</code>s to pop up
* under another component, so they would always return true.
* Most components will want to return false, hence that is the default.
*
* @return always returns false
*/
// package private
boolean alwaysOnTop() {
return false;
}
void setPaintingChild(Component paintingChild) {
this.paintingChild = paintingChild;
}
void _paintImmediately(int x, int y, int w, int h) {
Graphics g;
Container c;
Rectangle b;
int tmpX, tmpY, tmpWidth, tmpHeight;
int offsetX=0,offsetY=0;
boolean hasBuffer = false;
JComponent bufferedComponent = null;
JComponent paintingComponent = this;
RepaintManager repaintManager = RepaintManager.currentManager(this);
// parent Container's up to Window or Applet. First container is
// the direct parent. Note that in testing it was faster to
// alloc a new Vector vs keeping a stack of them around, and gc
// seemed to have a minimal effect on this.
java.util.List<Component> path = new java.util.ArrayList<Component>(7);
int pIndex = -1;
int pCount = 0;
tmpX = tmpY = tmpWidth = tmpHeight = 0;
Rectangle paintImmediatelyClip = fetchRectangle();
paintImmediatelyClip.x = x;
paintImmediatelyClip.y = y;
paintImmediatelyClip.width = w;
paintImmediatelyClip.height = h;
// System.out.println("1) ************* in _paintImmediately for " + this);
boolean ontop = alwaysOnTop() && isOpaque();
if (ontop) {
SwingUtilities.computeIntersection(0, 0, getWidth(), getHeight(),
paintImmediatelyClip);
if (paintImmediatelyClip.width == 0) {
recycleRectangle(paintImmediatelyClip);
return;
}
}
Component child;
for (c = this, child = null;
c != null && !(c instanceof Window) && !(c instanceof Applet);
child = c, c = c.getParent()) {
JComponent jc = (c instanceof JComponent) ? (JComponent)c :
null;
path.add(c);
if(!ontop && jc != null && !jc.isOptimizedDrawingEnabled()) {
boolean resetPC;
// Children of c may overlap, three possible cases for the
// painting region:
// . Completely obscured by an opaque sibling, in which
// case there is no need to paint.
// . Partially obscured by a sibling: need to start
// painting from c.
// . Otherwise we aren't obscured and thus don't need to
// start painting from parent.
if (c != this) {
if (jc.isPaintingOrigin()) {
resetPC = true;
}
else {
Component[] children = c.getComponents();
int i = 0;
for (; i<children.length; i++) {
if (children[i] == child) break;
}
switch (jc.getObscuredState(i,
paintImmediatelyClip.x,
paintImmediatelyClip.y,
paintImmediatelyClip.width,
paintImmediatelyClip.height)) {
case NOT_OBSCURED:
resetPC = false;
break;
case COMPLETELY_OBSCURED:
recycleRectangle(paintImmediatelyClip);
return;
default:
resetPC = true;
break;
}
}
}
else {
resetPC = false;
}
if (resetPC) {
// Get rid of any buffer since we draw from here and
// we might draw something larger
paintingComponent = jc;
pIndex = pCount;
offsetX = offsetY = 0;
hasBuffer = false;
}
}
pCount++;
// look to see if the parent (and therefor this component)
// is double buffered
if(repaintManager.isDoubleBufferingEnabled() && jc != null &&
jc.isDoubleBuffered()) {
hasBuffer = true;
bufferedComponent = jc;
}
// if we aren't on top, include the parent's clip
if (!ontop) {
int bx = c.getX();
int by = c.getY();
tmpWidth = c.getWidth();
tmpHeight = c.getHeight();
SwingUtilities.computeIntersection(tmpX,tmpY,tmpWidth,tmpHeight,paintImmediatelyClip);
paintImmediatelyClip.x += bx;
paintImmediatelyClip.y += by;
offsetX += bx;
offsetY += by;
}
}
// If the clip width or height is negative, don't bother painting
if(c == null || !c.isDisplayable() ||
paintImmediatelyClip.width <= 0 ||
paintImmediatelyClip.height <= 0) {
recycleRectangle(paintImmediatelyClip);
return;
}
paintingComponent.setFlag(IS_REPAINTING, true);
paintImmediatelyClip.x -= offsetX;
paintImmediatelyClip.y -= offsetY;
// Notify the Components that are going to be painted of the
// child component to paint to.
if(paintingComponent != this) {
Component comp;
int i = pIndex;
for(; i > 0 ; i--) {
comp = path.get(i);
if(comp instanceof JComponent) {
((JComponent)comp).setPaintingChild(path.get(i-1));
}
}
}
try {
if ((g = safelyGetGraphics(paintingComponent, c)) != null) {
try {
if (hasBuffer) {
RepaintManager rm = RepaintManager.currentManager(
bufferedComponent);
rm.beginPaint();
try {
rm.paint(paintingComponent, bufferedComponent, g,
paintImmediatelyClip.x,
paintImmediatelyClip.y,
paintImmediatelyClip.width,
paintImmediatelyClip.height);
} finally {
rm.endPaint();
}
} else {
g.setClip(paintImmediatelyClip.x, paintImmediatelyClip.y,
paintImmediatelyClip.width, paintImmediatelyClip.height);
paintingComponent.paint(g);
}
} finally {
g.dispose();
}
}
}
finally {
// Reset the painting child for the parent components.
if(paintingComponent != this) {
Component comp;
int i = pIndex;
for(; i > 0 ; i--) {
comp = path.get(i);
if(comp instanceof JComponent) {
((JComponent)comp).setPaintingChild(null);
}
}
}
paintingComponent.setFlag(IS_REPAINTING, false);
}
recycleRectangle(paintImmediatelyClip);
}
/**
* Paints to the specified graphics. This does not set the clip and it
* does not adjust the Graphics in anyway, callers must do that first.
* This method is package-private for RepaintManager.PaintManager and
* its subclasses to call, it is NOT intended for general use outside
* of that.
*/
void paintToOffscreen(Graphics g, int x, int y, int w, int h, int maxX,
int maxY) {
try {
setFlag(ANCESTOR_USING_BUFFER, true);
if ((y + h) < maxY || (x + w) < maxX) {
setFlag(IS_PAINTING_TILE, true);
}
if (getFlag(IS_REPAINTING)) {
// Called from paintImmediately (RepaintManager) to fill
// repaint request
paint(g);
} else {
// Called from paint() (AWT) to repair damage
if(!rectangleIsObscured(x, y, w, h)) {
paintComponent(g);
paintBorder(g);
}
paintChildren(g);
}
} finally {
setFlag(ANCESTOR_USING_BUFFER, false);
setFlag(IS_PAINTING_TILE, false);
}
}
/**
* Returns whether or not the region of the specified component is
* obscured by a sibling.
*
* @return NOT_OBSCURED if non of the siblings above the Component obscure
* it, COMPLETELY_OBSCURED if one of the siblings completely
* obscures the Component or PARTIALLY_OBSCURED if the Component is
* only partially obscured.
*/
private int getObscuredState(int compIndex, int x, int y, int width,
int height) {
int retValue = NOT_OBSCURED;
Rectangle tmpRect = fetchRectangle();
for (int i = compIndex - 1 ; i >= 0 ; i--) {
Component sibling = getComponent(i);
if (!sibling.isVisible()) {
continue;
}
Rectangle siblingRect;
boolean opaque;
if (sibling instanceof JComponent) {
opaque = sibling.isOpaque();
if (!opaque) {
if (retValue == PARTIALLY_OBSCURED) {
continue;
}
}
}
else {
opaque = true;
}
siblingRect = sibling.getBounds(tmpRect);
if (opaque && x >= siblingRect.x && (x + width) <=
(siblingRect.x + siblingRect.width) &&
y >= siblingRect.y && (y + height) <=
(siblingRect.y + siblingRect.height)) {
recycleRectangle(tmpRect);
return COMPLETELY_OBSCURED;
}
else if (retValue == NOT_OBSCURED &&
!((x + width <= siblingRect.x) ||
(y + height <= siblingRect.y) ||
(x >= siblingRect.x + siblingRect.width) ||
(y >= siblingRect.y + siblingRect.height))) {
retValue = PARTIALLY_OBSCURED;
}
}
recycleRectangle(tmpRect);
return retValue;
}
/**
* Returns true, which implies that before checking if a child should
* be painted it is first check that the child is not obscured by another
* sibling. This is only checked if <code>isOptimizedDrawingEnabled</code>
* returns false.
*
* @return always returns true
*/
boolean checkIfChildObscuredBySibling() {
return true;
}
private void setFlag(int aFlag, boolean aValue) {
if(aValue) {
flags |= (1 << aFlag);
} else {
flags &= ~(1 << aFlag);
}
}
private boolean getFlag(int aFlag) {
int mask = (1 << aFlag);
return ((flags & mask) == mask);
}
// These functions must be static so that they can be called from
// subclasses inside the package, but whose inheritance hierarhcy includes
// classes outside of the package below JComponent (e.g., JTextArea).
static void setWriteObjCounter(JComponent comp, byte count) {
comp.flags = (comp.flags & ~(0xFF << WRITE_OBJ_COUNTER_FIRST)) |
(count << WRITE_OBJ_COUNTER_FIRST);
}
static byte getWriteObjCounter(JComponent comp) {
return (byte)((comp.flags >> WRITE_OBJ_COUNTER_FIRST) & 0xFF);
}
/** Buffering **/
/**
* Sets whether this component should use a buffer to paint.
* If set to true, all the drawing from this component will be done
* in an offscreen painting buffer. The offscreen painting buffer will
* the be copied onto the screen.
* If a <code>Component</code> is buffered and one of its ancestor
* is also buffered, the ancestor buffer will be used.
*
* @param aFlag if true, set this component to be double buffered
*/
public void setDoubleBuffered(boolean aFlag) {
setFlag(IS_DOUBLE_BUFFERED,aFlag);
}
/**
* Returns whether this component should use a buffer to paint.
*
* @return true if this component is double buffered, otherwise false
*/
public boolean isDoubleBuffered() {
return getFlag(IS_DOUBLE_BUFFERED);
}
/**
* Returns the <code>JRootPane</code> ancestor for this component.
*
* @return the <code>JRootPane</code> that contains this component,
* or <code>null</code> if no <code>JRootPane</code> is found
*/
@BeanProperty(bound = false)
public JRootPane getRootPane() {
return SwingUtilities.getRootPane(this);
}
/** Serialization **/
/**
* This is called from Component by way of reflection. Do NOT change
* the name unless you change the code in Component as well.
*/
void compWriteObjectNotify() {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, (byte)(count + 1));
if (count != 0) {
return;
}
uninstallUIAndProperties();
/* JTableHeader is in a separate package, which prevents it from
* being able to override this package-private method the way the
* other components can. We don't want to make this method protected
* because it would introduce public-api for a less-than-desirable
* serialization scheme, so we compromise with this 'instanceof' hack
* for now.
*/
if (getToolTipText() != null ||
this instanceof javax.swing.table.JTableHeader) {
ToolTipManager.sharedInstance().unregisterComponent(JComponent.this);
}
}
/**
* This object is the <code>ObjectInputStream</code> callback
* that's called after a complete graph of objects (including at least
* one <code>JComponent</code>) has been read.
* It sets the UI property of each Swing component
* that was read to the current default with <code>updateUI</code>.
* <p>
* As each component is read in we keep track of the current set of
* root components here, in the roots vector. Note that there's only one
* <code>ReadObjectCallback</code> per <code>ObjectInputStream</code>,
* they're stored in the static <code>readObjectCallbacks</code>
* hashtable.
*
* @see java.io.ObjectInputStream#registerValidation
* @see SwingUtilities#updateComponentTreeUI
*/
private class ReadObjectCallback implements ObjectInputValidation
{
private final Vector<JComponent> roots = new Vector<JComponent>(1);
private final ObjectInputStream inputStream;
ReadObjectCallback(ObjectInputStream s) throws Exception {
inputStream = s;
s.registerValidation(this, 0);
}
/**
* This is the method that's called after the entire graph
* of objects has been read in. It initializes
* the UI property of all of the copmonents with
* <code>SwingUtilities.updateComponentTreeUI</code>.
*/
public void validateObject() throws InvalidObjectException {
try {
for (JComponent root : roots) {
SwingUtilities.updateComponentTreeUI(root);
}
}
finally {
readObjectCallbacks.remove(inputStream);
}
}
/**
* If <code>c</code> isn't a descendant of a component we've already
* seen, then add it to the roots <code>Vector</code>.
*
* @param c the <code>JComponent</code> to add
*/
private void registerComponent(JComponent c)
{
/* If the Component c is a descendant of one of the
* existing roots (or it IS an existing root), we're done.
*/
for (JComponent root : roots) {
for(Component p = c; p != null; p = p.getParent()) {
if (p == root) {
return;
}
}
}
/* Otherwise: if Component c is an ancestor of any of the
* existing roots then remove them and add c (the "new root")
* to the roots vector.
*/
for(int i = 0; i < roots.size(); i++) {
JComponent root = roots.elementAt(i);
for(Component p = root.getParent(); p != null; p = p.getParent()) {
if (p == c) {
roots.removeElementAt(i--); // !!
break;
}
}
}
roots.addElement(c);
}
}
/**
* We use the <code>ObjectInputStream</code> "registerValidation"
* callback to update the UI for the entire tree of components
* after they've all been read in.
*
* @param s the <code>ObjectInputStream</code> from which to read
*/
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException
{
ObjectInputStream.GetField f = s.readFields();
isAlignmentXSet = f.get("isAlignmentXSet", false);
alignmentX = validateAlignment(f.get("alignmentX", 0f));
isAlignmentYSet = f.get("isAlignmentYSet", false);
alignmentY = validateAlignment(f.get("alignmentY", 0f));
listenerList = (EventListenerList) f.get("listenerList", null);
vetoableChangeSupport = (VetoableChangeSupport) f.get("vetoableChangeSupport", null);
autoscrolls = f.get("autoscrolls", false);
border = (Border) f.get("border", null);
flags = f.get("flags", 0);
inputVerifier = (InputVerifier) f.get("inputVerifier", null);
verifyInputWhenFocusTarget = f.get("verifyInputWhenFocusTarget", false);
popupMenu = (JPopupMenu) f.get("popupMenu", null);
focusInputMap = (InputMap) f.get("focusInputMap", null);
ancestorInputMap = (InputMap) f.get("ancestorInputMap", null);
windowInputMap = (ComponentInputMap) f.get("windowInputMap", null);
actionMap = (ActionMap) f.get("actionMap", null);
/* If there's no ReadObjectCallback for this stream yet, that is, if
* this is the first call to JComponent.readObject() for this
* graph of objects, then create a callback and stash it
* in the readObjectCallbacks table. Note that the ReadObjectCallback
* constructor takes care of calling s.registerValidation().
*/
ReadObjectCallback cb = readObjectCallbacks.get(s);
if (cb == null) {
try {
readObjectCallbacks.put(s, cb = new ReadObjectCallback(s));
}
catch (Exception e) {
throw new IOException(e.toString());
}
}
cb.registerComponent(this);
// Read back the client properties.
int cpCount = s.readInt();
if (cpCount > 0) {
clientProperties = new ArrayTable();
for (int counter = 0; counter < cpCount; counter++) {
clientProperties.put(s.readObject(),
s.readObject());
}
}
if (getToolTipText() != null) {
ToolTipManager.sharedInstance().registerComponent(this);
}
setWriteObjCounter(this, (byte)0);
revalidateRunnableScheduled = new AtomicBoolean(false);
}
/**
* Before writing a <code>JComponent</code> to an
* <code>ObjectOutputStream</code> we temporarily uninstall its UI.
* This is tricky to do because we want to uninstall
* the UI before any of the <code>JComponent</code>'s children
* (or its <code>LayoutManager</code> etc.) are written,
* and we don't want to restore the UI until the most derived
* <code>JComponent</code> subclass has been stored.
*
* @param s the <code>ObjectOutputStream</code> in which to write
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
ArrayTable.writeArrayTable(s, clientProperties);
}
/**
* Returns a string representation of this <code>JComponent</code>.
* This method
* is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not
* be <code>null</code>.
*
* @return a string representation of this <code>JComponent</code>
*/
protected String paramString() {
String preferredSizeString = (isPreferredSizeSet() ?
getPreferredSize().toString() : "");
String minimumSizeString = (isMinimumSizeSet() ?
getMinimumSize().toString() : "");
String maximumSizeString = (isMaximumSizeSet() ?
getMaximumSize().toString() : "");
String borderString = (border == null ? ""
: (border == this ? "this" : border.toString()));
return super.paramString() +
",alignmentX=" + alignmentX +
",alignmentY=" + alignmentY +
",border=" + borderString +
",flags=" + flags + // should beef this up a bit
",maximumSize=" + maximumSizeString +
",minimumSize=" + minimumSizeString +
",preferredSize=" + preferredSizeString;
}
/**
* {@inheritDoc}
*/
@Override
@Deprecated
public void hide() {
boolean showing = isShowing();
super.hide();
if (showing) {
Container parent = getParent();
if (parent != null) {
Rectangle r = getBounds();
parent.repaint(r.x, r.y, r.width, r.height);
}
revalidate();
}
}
}
| gpl-2.0 |
goffersoft/common-utils-java | src/main/java/com/goffersoft/common/net/openflow/OfpPortDescGenericProp.java | 9595 | /**
** File: OfpPortDescGenericProp.java
**
** Description : OpenFlow Generic Port Properties class
** (base class for all port properties classes)
** -- OpenFlow Switch Specification Version 1.4.0 - October 14th, 2013
**
** Date Author Comments
** 08/31/2013 Prakash Easwar Created
**/
package com.goffersoft.common.net.openflow;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.log4j.Logger;
import com.goffersoft.common.utils.EndianConversion;
import com.goffersoft.common.utils.ReadUtils;
public class OfpPortDescGenericProp
implements
OfpSerializable<OfpPortDescGenericProp> {
private static final Logger log = Logger
.getLogger(OfpPortDescGenericProp.class);
public static enum OfpPortDescPropType {
OFPPDPT_ETHERNET(0),
OFPPDPT_OPTICAL(1),
OFPPDPT_EXPERIMENTER(0xffff),
OFPPDPT_UNK(0), ;
public static final String propDescr[] = {
"Ethernet Property type",
"Optical proeprty type",
"Experimental property type",
"Unknown property type",
};
private short type;
private OfpPortDescPropType(int ptype) {
setValueInternal((short) ptype);
}
public short getValue() {
return type;
}
private void setValueInternal(short type) {
this.type = type;
}
public void setValue(short type) {
if (this == OFPPDPT_UNK) {
this.type = type;
}
}
public String getDescr() {
if (this == OFPPDPT_UNK) {
return String.format("%s Type=%d(0x%04x)",
propDescr[ordinal()], type & 0xffff, type & 0xffff);
}
return propDescr[ordinal()];
}
@Override
public String toString() {
return getDescr();
}
public static OfpPortDescPropType getEnum(short ptype) {
int tmp = ptype & 0xffff;
if (tmp == 0) {
return OFPPDPT_ETHERNET;
} else if (tmp == 1) {
return OFPPDPT_OPTICAL;
} else if (tmp == 0xffff) {
return OFPPDPT_EXPERIMENTER;
} else {
OfpPortDescPropType tmp1 = OFPPDPT_UNK;
tmp1.setValueInternal(ptype);
return tmp1;
}
}
}
private OfpPortDescPropType type;
private short length;
public static final int OFP_PORT_DESC_PROP_TYPE_OFFSET = 0;
public static final int OFP_PORT_DESC_PROP_LENGTH_OFFSET = 2;
public static final int OFP_PORT_DESC_PROP_BASE_LEN = 4;
public OfpPortDescGenericProp(OfpPortDescGenericProp hdr) {
setType(hdr.getType());
setLength(hdr.getLength());
}
public OfpPortDescGenericProp(OfpPortDescPropType type, short length) {
setType(type);
setLength(length);
}
public OfpPortDescGenericProp(byte[] data) {
this(data, 0);
}
public OfpPortDescGenericProp(byte[] data, int offset) {
setType(readType(data, offset));
setLength(readLength(data, offset));
}
public OfpPortDescGenericProp(InputStream is) throws IOException {
setType(readType(is));
setLength(readLength(is));
}
public OfpPortDescPropType getType() {
return type;
}
public void setType(OfpPortDescPropType type) {
this.type = type;
}
public short getLength() {
return length;
}
public short getAlignedLength() {
return (short) (((length + 7) / 8) * 8);
}
public static short getAlignedLength(int len) {
return (short) (((len + 7) / 8) * 8);
}
public int getPadLength() {
return getAlignedLength() - getLength();
}
public static int getPadLength(int len) {
return getAlignedLength(len) - len;
}
public void readPadding(InputStream is) throws IOException {
for (int i = 0; i < (getAlignedLength() - getLength()); i++) {
is.read();
}
}
public void writePadding(OutputStream os) throws IOException {
for (int i = 0; i < (getAlignedLength() - getLength()); i++) {
os.write(0x0);
}
}
public void writePadding(byte[] data) {
writePadding(data, 0);
}
public void writePadding(byte[] data, int offset) {
for (int i = offset; i < (getAlignedLength() - getLength()); i++) {
data[i] = 0x00;
}
}
public static void writePadding(byte[] data, int offset, int len) {
for (int i = offset; i < len; i++) {
data[i] = 0x00;
}
}
public static void readPadding(InputStream is, int len) throws IOException {
for (int i = 0; i < getAlignedLength(len) - len; i++) {
is.read();
}
}
public static void writePadding(OutputStream os, int len)
throws IOException {
for (int i = 0; i < getAlignedLength(len) - len; i++) {
os.write(0x0);
}
}
public void setLength(short length) {
this.length = length;
}
@Override
public OfpPortDescGenericProp fromInputStream(InputStream is)
throws IOException {
return readFromInputStream(is);
}
@Override
public OfpPortDescGenericProp fromByteArray(byte[] data) {
return new OfpPortDescGenericProp(data);
}
@Override
public OfpPortDescGenericProp fromByteArray(byte[] data, int offset) {
return new OfpPortDescGenericProp(data, offset);
}
@Override
public byte[] toByteArray() {
byte[] hdr = new byte[OFP_PORT_DESC_PROP_BASE_LEN];
return toByteArray(hdr, 0);
}
@Override
public byte[] toByteArray(byte[] data) {
return toByteArray(data, 0);
}
@Override
public byte[] toByteArray(byte[] data, int offset) {
writeType(data, offset);
writeLength(data, offset);
return data;
}
@Override
public OutputStream toOutputStream(OutputStream os) throws IOException {
writeType(os);
writeLength(os);
return os;
}
public byte[] writeType(byte[] data) {
return writeType(data, 0);
}
public byte[] writeType(byte[] data, int offset) {
EndianConversion.shortToByteArrayBE(data, offset, getType().getValue());
return data;
}
public OutputStream writeType(OutputStream os) throws IOException {
EndianConversion.shortToOutputStreamBE(os, getType().getValue());
return os;
}
public byte[] writeLength(byte[] data) {
return writeLength(data, 0);
}
public byte[] writeLength(byte[] data, int offset) {
EndianConversion.shortToByteArrayBE(data, offset, getLength());
return data;
}
public OutputStream writeLength(OutputStream os) throws IOException {
EndianConversion.shortToOutputStreamBE(os, getLength());
return os;
}
public static byte[] readOfpPortDescGenericProp(InputStream is)
throws IOException {
return readOfpPortDescGenericProp(is, null, 0);
}
public static
byte[]
readOfpPortDescGenericProp(InputStream is, byte[] data)
throws IOException {
return readOfpPortDescGenericProp(is, data, 0);
}
public static byte[] readOfpPortDescGenericProp(InputStream is,
byte[] data, int offset) throws IOException {
return ReadUtils.readInput(is, null, 0, OFP_PORT_DESC_PROP_BASE_LEN);
}
public static OfpPortDescGenericProp readFromInputStream(InputStream is)
throws IOException {
return new OfpPortDescGenericProp(is);
}
public static OfpPortDescPropType readType(byte[] portdescprop) {
return readType(portdescprop, 0);
}
public static OfpPortDescPropType readType(byte[] portdescprop, int offset) {
return OfpPortDescPropType.getEnum(EndianConversion.byteArrayToShortBE(
portdescprop, offset + OFP_PORT_DESC_PROP_TYPE_OFFSET));
}
public static OfpPortDescPropType readType(InputStream is)
throws IOException {
return OfpPortDescPropType.getEnum(EndianConversion
.inputStreamToShortBE(is));
}
public static short readLength(byte[] portdescprop) {
return readLength(portdescprop, 0);
}
public static short readLength(byte[] portdescprop, int offset) {
return EndianConversion.byteArrayToShortBE(portdescprop, offset
+ OFP_PORT_DESC_PROP_LENGTH_OFFSET);
}
public static short readLength(InputStream is) throws IOException {
return EndianConversion.inputStreamToShortBE(is);
}
@Override
public String toString() {
return String.format("Type=%s : Length=%d(0x%04x)\n", getType()
.toString(), getLength(), getLength());
}
public boolean equals(OfpPortDescGenericProp hdr) {
if ((getType() == hdr.getType()) && (getLength() == hdr.getLength())) {
return true;
}
return false;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o instanceof OfpPortDescGenericProp) {
return equals((OfpPortDescGenericProp) o);
}
return false;
}
} | gpl-2.0 |
chaodhib/TrinityCore | src/server/scripts/EasternKingdoms/ScarletEnclave/chapter1.cpp | 40263 | /*
* Copyright (C) 2008-2019 TrinityCore <https://www.trinitycore.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 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/>.
*/
#include "ScriptMgr.h"
#include "CombatAI.h"
#include "CreatureTextMgr.h"
#include "GameObject.h"
#include "GameObjectAI.h"
#include "Log.h"
#include "MotionMaster.h"
#include "MoveSplineInit.h"
#include "ObjectAccessor.h"
#include "ObjectMgr.h"
#include "PassiveAI.h"
#include "Player.h"
#include "ScriptedEscortAI.h"
#include "ScriptedGossip.h"
#include "SpellInfo.h"
#include "SpellScript.h"
#include "TemporarySummon.h"
#include "Vehicle.h"
/*######
##Quest 12848
######*/
#define GCD_CAST 1
enum UnworthyInitiate
{
SPELL_SOUL_PRISON_CHAIN_SELF = 54612,
SPELL_SOUL_PRISON_CHAIN = 54613,
SPELL_DK_INITIATE_VISUAL = 51519,
SPELL_ICY_TOUCH = 52372,
SPELL_PLAGUE_STRIKE = 52373,
SPELL_BLOOD_STRIKE = 52374,
SPELL_DEATH_COIL = 52375,
SAY_EVENT_START = 0,
SAY_EVENT_ATTACK = 1,
EVENT_ICY_TOUCH = 1,
EVENT_PLAGUE_STRIKE = 2,
EVENT_BLOOD_STRIKE = 3,
EVENT_DEATH_COIL = 4
};
enum UnworthyInitiatePhase
{
PHASE_CHAINED,
PHASE_TO_EQUIP,
PHASE_EQUIPING,
PHASE_TO_ATTACK,
PHASE_ATTACKING,
};
uint32 acherus_soul_prison[12] =
{
191577,
191580,
191581,
191582,
191583,
191584,
191585,
191586,
191587,
191588,
191589,
191590
};
uint32 acherus_unworthy_initiate[5] =
{
29519,
29520,
29565,
29566,
29567
};
class npc_unworthy_initiate : public CreatureScript
{
public:
npc_unworthy_initiate() : CreatureScript("npc_unworthy_initiate") { }
struct npc_unworthy_initiateAI : public ScriptedAI
{
npc_unworthy_initiateAI(Creature* creature) : ScriptedAI(creature)
{
Initialize();
me->SetReactState(REACT_PASSIVE);
if (!me->GetCurrentEquipmentId())
me->SetCurrentEquipmentId(me->GetOriginalEquipmentId());
wait_timer = 0;
anchorX = 0.f;
anchorY = 0.f;
}
void Initialize()
{
anchorGUID.Clear();
phase = PHASE_CHAINED;
}
ObjectGuid playerGUID;
UnworthyInitiatePhase phase;
uint32 wait_timer;
float anchorX, anchorY;
ObjectGuid anchorGUID;
EventMap events;
void Reset() override
{
Initialize();
events.Reset();
me->SetFaction(FACTION_CREATURE);
me->SetImmuneToPC(true);
me->SetStandState(UNIT_STAND_STATE_KNEEL);
me->LoadEquipment(0, true);
}
void JustEngagedWith(Unit* /*who*/) override
{
events.ScheduleEvent(EVENT_ICY_TOUCH, 1s, GCD_CAST);
events.ScheduleEvent(EVENT_PLAGUE_STRIKE, 3s, GCD_CAST);
events.ScheduleEvent(EVENT_BLOOD_STRIKE, 2s, GCD_CAST);
events.ScheduleEvent(EVENT_DEATH_COIL, 5s, GCD_CAST);
}
void MovementInform(uint32 type, uint32 id) override
{
if (type != POINT_MOTION_TYPE)
return;
if (id == 1)
{
wait_timer = 5000;
me->LoadEquipment(1);
me->CastSpell(me, SPELL_DK_INITIATE_VISUAL, true);
if (Player* starter = ObjectAccessor::GetPlayer(*me, playerGUID))
Talk(SAY_EVENT_ATTACK, starter);
phase = PHASE_TO_ATTACK;
}
}
void EventStart(Creature* anchor, Player* target)
{
wait_timer = 5000;
phase = PHASE_TO_EQUIP;
me->SetStandState(UNIT_STAND_STATE_STAND);
me->RemoveAurasDueToSpell(SPELL_SOUL_PRISON_CHAIN_SELF);
me->RemoveAurasDueToSpell(SPELL_SOUL_PRISON_CHAIN);
float z;
anchor->GetContactPoint(me, anchorX, anchorY, z, 1.0f);
playerGUID = target->GetGUID();
Talk(SAY_EVENT_START, target);
}
void UpdateAI(uint32 diff) override
{
switch (phase)
{
case PHASE_CHAINED:
if (!anchorGUID)
{
if (Creature* anchor = me->FindNearestCreature(29521, 30))
{
anchor->AI()->SetGUID(me->GetGUID());
anchor->CastSpell(me, SPELL_SOUL_PRISON_CHAIN, true);
anchorGUID = anchor->GetGUID();
}
else
TC_LOG_ERROR("scripts", "npc_unworthy_initiateAI: unable to find anchor!");
float dist = 99.0f;
GameObject* prison = nullptr;
for (uint8 i = 0; i < 12; ++i)
{
if (GameObject* temp_prison = me->FindNearestGameObject(acherus_soul_prison[i], 30))
{
if (me->IsWithinDist(temp_prison, dist, false))
{
dist = me->GetDistance2d(temp_prison);
prison = temp_prison;
}
}
}
if (prison)
prison->ResetDoorOrButton();
else
TC_LOG_ERROR("scripts", "npc_unworthy_initiateAI: unable to find prison!");
}
break;
case PHASE_TO_EQUIP:
if (wait_timer)
{
if (wait_timer > diff)
wait_timer -= diff;
else
{
me->GetMotionMaster()->MovePoint(1, anchorX, anchorY, me->GetPositionZ());
//TC_LOG_DEBUG("scripts", "npc_unworthy_initiateAI: move to %f %f %f", anchorX, anchorY, me->GetPositionZ());
phase = PHASE_EQUIPING;
wait_timer = 0;
}
}
break;
case PHASE_TO_ATTACK:
if (wait_timer)
{
if (wait_timer > diff)
wait_timer -= diff;
else
{
me->SetFaction(FACTION_MONSTER);
me->SetImmuneToPC(false);
phase = PHASE_ATTACKING;
if (Player* target = ObjectAccessor::GetPlayer(*me, playerGUID))
AttackStart(target);
wait_timer = 0;
}
}
break;
case PHASE_ATTACKING:
if (!UpdateVictim())
return;
events.Update(diff);
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_ICY_TOUCH:
DoCastVictim(SPELL_ICY_TOUCH);
events.DelayEvents(1000, GCD_CAST);
events.ScheduleEvent(EVENT_ICY_TOUCH, 5s, GCD_CAST);
break;
case EVENT_PLAGUE_STRIKE:
DoCastVictim(SPELL_PLAGUE_STRIKE);
events.DelayEvents(1000, GCD_CAST);
events.ScheduleEvent(EVENT_PLAGUE_STRIKE, 5s, GCD_CAST);
break;
case EVENT_BLOOD_STRIKE:
DoCastVictim(SPELL_BLOOD_STRIKE);
events.DelayEvents(1000, GCD_CAST);
events.ScheduleEvent(EVENT_BLOOD_STRIKE, 5s, GCD_CAST);
break;
case EVENT_DEATH_COIL:
DoCastVictim(SPELL_DEATH_COIL);
events.DelayEvents(1000, GCD_CAST);
events.ScheduleEvent(EVENT_DEATH_COIL, 5s, GCD_CAST);
break;
}
}
DoMeleeAttackIfReady();
break;
default:
break;
}
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_unworthy_initiateAI(creature);
}
};
class npc_unworthy_initiate_anchor : public CreatureScript
{
public:
npc_unworthy_initiate_anchor() : CreatureScript("npc_unworthy_initiate_anchor") { }
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_unworthy_initiate_anchorAI(creature);
}
struct npc_unworthy_initiate_anchorAI : public PassiveAI
{
npc_unworthy_initiate_anchorAI(Creature* creature) : PassiveAI(creature) { }
ObjectGuid prisonerGUID;
void SetGUID(ObjectGuid const& guid, int32 /*id*/) override
{
prisonerGUID = guid;
}
ObjectGuid GetGUID(int32 /*id*/) const override
{
return prisonerGUID;
}
};
};
class go_acherus_soul_prison : public GameObjectScript
{
public:
go_acherus_soul_prison() : GameObjectScript("go_acherus_soul_prison") { }
struct go_acherus_soul_prisonAI : public GameObjectAI
{
go_acherus_soul_prisonAI(GameObject* go) : GameObjectAI(go) { }
bool GossipHello(Player* player) override
{
if (Creature* anchor = me->FindNearestCreature(29521, 15))
if (ObjectGuid prisonerGUID = anchor->AI()->GetGUID())
if (Creature* prisoner = ObjectAccessor::GetCreature(*player, prisonerGUID))
ENSURE_AI(npc_unworthy_initiate::npc_unworthy_initiateAI, prisoner->AI())->EventStart(anchor, player);
return false;
}
};
GameObjectAI* GetAI(GameObject* go) const override
{
return new go_acherus_soul_prisonAI(go);
}
};
/*######
## npc_eye_of_acherus
######*/
enum EyeOfAcherus
{
SPELL_EYE_VISUAL = 51892,
SPELL_EYE_FLIGHT_BOOST = 51923,
SPELL_EYE_FLIGHT = 51890,
EVENT_MOVE_START = 1,
TALK_MOVE_START = 0,
TALK_CONTROL = 1,
POINT_EYE_FALL = 1,
POINT_EYE_MOVE_END = 3
};
Position const EyeOFAcherusFallPoint = { 2361.21f, -5660.45f, 496.7444f, 0.0f };
class npc_eye_of_acherus : public CreatureScript
{
public:
npc_eye_of_acherus() : CreatureScript("npc_eye_of_acherus") { }
struct npc_eye_of_acherusAI : public ScriptedAI
{
npc_eye_of_acherusAI(Creature* creature) : ScriptedAI(creature)
{
me->SetDisplayId(me->GetCreatureTemplate()->Modelid1);
DoCastSelf(SPELL_EYE_VISUAL);
me->SetReactState(REACT_PASSIVE);
me->SetDisableGravity(true);
me->SetControlled(true, UNIT_STATE_ROOT);
Movement::MoveSplineInit init(me);
init.MoveTo(EyeOFAcherusFallPoint.GetPositionX(), EyeOFAcherusFallPoint.GetPositionY(), EyeOFAcherusFallPoint.GetPositionZ(), false);
init.SetFall();
me->GetMotionMaster()->LaunchMoveSpline(std::move(init), POINT_EYE_FALL, MOTION_PRIORITY_NORMAL, POINT_MOTION_TYPE);
_events.ScheduleEvent(EVENT_MOVE_START, 7s);
}
void OnCharmed(bool /*isNew*/) override { }
void UpdateAI(uint32 diff) override
{
_events.Update(diff);
while (uint32 eventId = _events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_MOVE_START:
{
DoCastSelf(SPELL_EYE_FLIGHT_BOOST);
me->SetControlled(false, UNIT_STATE_ROOT);
if (Player* owner = me->GetCharmerOrOwner()->ToPlayer())
{
for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i)
me->SetSpeedRate(UnitMoveType(i), owner->GetSpeedRate(UnitMoveType(i)));
Talk(TALK_MOVE_START, owner);
}
me->GetMotionMaster()->MovePath(me->GetEntry() * 100, false);
break;
}
default:
break;
}
}
}
void MovementInform(uint32 movementType, uint32 pointId) override
{
if (movementType == WAYPOINT_MOTION_TYPE && pointId == POINT_EYE_MOVE_END - 1)
{
me->RemoveAllAuras();
if (Player* owner = me->GetCharmerOrOwner()->ToPlayer())
{
owner->RemoveAura(SPELL_EYE_FLIGHT_BOOST);
for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i)
me->SetSpeedRate(UnitMoveType(i), owner->GetSpeedRate(UnitMoveType(i)));
Talk(TALK_CONTROL, owner);
}
me->SetDisableGravity(false);
DoCastSelf(SPELL_EYE_FLIGHT);
}
}
private:
EventMap _events;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_eye_of_acherusAI(creature);
}
};
/*######
## npc_death_knight_initiate
######*/
enum Spells_DKI
{
SPELL_DUEL = 52996,
//SPELL_DUEL_TRIGGERED = 52990,
SPELL_DUEL_VICTORY = 52994,
SPELL_DUEL_FLAG = 52991,
SPELL_GROVEL = 7267,
};
enum Says_VBM
{
SAY_DUEL = 0,
};
enum Misc_VBN
{
QUEST_DEATH_CHALLENGE = 12733
};
class npc_death_knight_initiate : public CreatureScript
{
public:
npc_death_knight_initiate() : CreatureScript("npc_death_knight_initiate") { }
struct npc_death_knight_initiateAI : public CombatAI
{
npc_death_knight_initiateAI(Creature* creature) : CombatAI(creature)
{
Initialize();
}
void Initialize()
{
m_uiDuelerGUID.Clear();
m_uiDuelTimer = 5000;
m_bIsDuelInProgress = false;
lose = false;
}
bool lose;
ObjectGuid m_uiDuelerGUID;
uint32 m_uiDuelTimer;
bool m_bIsDuelInProgress;
void Reset() override
{
Initialize();
me->RestoreFaction();
CombatAI::Reset();
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_15);
}
void SpellHit(Unit* pCaster, SpellInfo const* pSpell) override
{
if (!m_bIsDuelInProgress && pSpell->Id == SPELL_DUEL)
{
m_uiDuelerGUID = pCaster->GetGUID();
Talk(SAY_DUEL, pCaster);
m_bIsDuelInProgress = true;
}
}
void DamageTaken(Unit* pDoneBy, uint32 &uiDamage) override
{
if (m_bIsDuelInProgress && pDoneBy && pDoneBy->IsControlledByPlayer())
{
if (pDoneBy->GetGUID() != m_uiDuelerGUID && pDoneBy->GetOwnerGUID() != m_uiDuelerGUID) // other players cannot help
uiDamage = 0;
else if (uiDamage >= me->GetHealth())
{
uiDamage = 0;
if (!lose)
{
pDoneBy->RemoveGameObject(SPELL_DUEL_FLAG, true);
pDoneBy->AttackStop();
me->CastSpell(pDoneBy, SPELL_DUEL_VICTORY, true);
lose = true;
me->CastSpell(me, SPELL_GROVEL, true);
me->RestoreFaction();
}
}
}
}
void UpdateAI(uint32 uiDiff) override
{
if (!UpdateVictim())
{
if (m_bIsDuelInProgress)
{
if (m_uiDuelTimer <= uiDiff)
{
me->SetFaction(FACTION_UNDEAD_SCOURGE_2);
if (Unit* unit = ObjectAccessor::GetUnit(*me, m_uiDuelerGUID))
AttackStart(unit);
}
else
m_uiDuelTimer -= uiDiff;
}
return;
}
if (m_bIsDuelInProgress)
{
if (lose)
{
if (!me->HasAura(SPELL_GROVEL))
EnterEvadeMode();
return;
}
else if (me->GetVictim() && me->EnsureVictim()->GetTypeId() == TYPEID_PLAYER && me->EnsureVictim()->HealthBelowPct(10))
{
me->EnsureVictim()->CastSpell(me->GetVictim(), SPELL_GROVEL, true); // beg
me->EnsureVictim()->RemoveGameObject(SPELL_DUEL_FLAG, true);
EnterEvadeMode();
return;
}
}
/// @todo spells
CombatAI::UpdateAI(uiDiff);
}
bool GossipSelect(Player* player, uint32 /*menuId*/, uint32 gossipListId) override
{
uint32 const action = player->PlayerTalkClass->GetGossipOptionAction(gossipListId);
ClearGossipMenuFor(player);
if (action == GOSSIP_ACTION_INFO_DEF)
{
CloseGossipMenuFor(player);
if (player->IsInCombat() || me->IsInCombat())
return true;
if (m_bIsDuelInProgress)
return true;
me->SetImmuneToPC(false);
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_15);
player->CastSpell(me, SPELL_DUEL, false);
player->CastSpell(player, SPELL_DUEL_FLAG, true);
}
return true;
}
bool GossipHello(Player* player) override
{
if (player->GetQuestStatus(QUEST_DEATH_CHALLENGE) == QUEST_STATUS_INCOMPLETE && me->IsFullHealth())
{
if (player->HealthBelowPct(10))
return true;
if (player->IsInCombat() || me->IsInCombat())
return true;
AddGossipItemFor(player, Player::GetDefaultGossipMenuForSource(me), 0, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF);
SendGossipMenuFor(player, player->GetGossipTextId(me), me->GetGUID());
}
return true;
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_death_knight_initiateAI(creature);
}
};
/*######
## npc_dark_rider_of_acherus
######*/
enum DarkRiderOfAcherus
{
SAY_DARK_RIDER = 0,
EVENT_START_MOVING = 1,
EVENT_DESPAWN_HORSE = 2,
EVENT_END_SCRIPT = 3,
SPELL_DESPAWN_HORSE = 52267
};
struct npc_dark_rider_of_acherus : public ScriptedAI
{
npc_dark_rider_of_acherus(Creature* creature) : ScriptedAI(creature) { }
void JustAppeared() override
{
if (TempSummon* summon = me->ToTempSummon())
_horseGUID = summon->GetSummonerGUID();
_events.ScheduleEvent(EVENT_START_MOVING, 1s);
}
void Reset() override
{
_events.Reset();
}
void UpdateAI(uint32 diff) override
{
_events.Update(diff);
while (uint32 eventId = _events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_START_MOVING:
me->SetTarget(_horseGUID);
if (Creature* horse = ObjectAccessor::GetCreature(*me, _horseGUID))
me->GetMotionMaster()->MoveChase(horse);
_events.ScheduleEvent(EVENT_DESPAWN_HORSE, 5s);
break;
case EVENT_DESPAWN_HORSE:
Talk(SAY_DARK_RIDER);
if (Creature* horse = ObjectAccessor::GetCreature(*me, _horseGUID))
DoCast(horse, SPELL_DESPAWN_HORSE, true);
_events.ScheduleEvent(EVENT_END_SCRIPT, 2s);
break;
case EVENT_END_SCRIPT:
me->DespawnOrUnsummon();
break;
default:
break;
}
}
}
void SpellHitTarget(Unit* target, SpellInfo const* spell) override
{
if (spell->Id == SPELL_DESPAWN_HORSE && target->GetGUID() == _horseGUID)
if (Creature* creature = target->ToCreature())
creature->DespawnOrUnsummon(2s);
}
private:
ObjectGuid _horseGUID;
EventMap _events;
};
/*######
## npc_salanar_the_horseman
######*/
enum SalanarTheHorseman
{
GOSSIP_SALANAR_MENU = 9739,
GOSSIP_SALANAR_OPTION = 0,
SALANAR_SAY = 0,
QUEST_INTO_REALM_OF_SHADOWS = 12687,
NPC_SALANAR_IN_REALM_OF_SHADOWS = 28788,
SPELL_EFFECT_STOLEN_HORSE = 52263,
SPELL_DELIVER_STOLEN_HORSE = 52264,
SPELL_CALL_DARK_RIDER = 52266,
SPELL_EFFECT_OVERTAKE = 52349,
SPELL_REALM_OF_SHADOWS = 52693
};
class npc_salanar_the_horseman : public CreatureScript
{
public:
npc_salanar_the_horseman() : CreatureScript("npc_salanar_the_horseman") { }
struct npc_salanar_the_horsemanAI : public ScriptedAI
{
npc_salanar_the_horsemanAI(Creature* creature) : ScriptedAI(creature) { }
bool GossipSelect(Player* player, uint32 menuId, uint32 gossipListId) override
{
if (menuId == GOSSIP_SALANAR_MENU && gossipListId == GOSSIP_SALANAR_OPTION)
{
player->CastSpell(player, SPELL_REALM_OF_SHADOWS, true);
player->PlayerTalkClass->SendCloseGossip();
}
return false;
}
void MoveInLineOfSight(Unit* who) override
{
ScriptedAI::MoveInLineOfSight(who);
if (who->GetTypeId() == TYPEID_UNIT && who->IsVehicle() && me->IsWithinDistInMap(who, 5.0f))
{
if (Unit* charmer = who->GetCharmer())
{
if (Player* player = charmer->ToPlayer())
{
// for quest Into the Realm of Shadows(QUEST_INTO_REALM_OF_SHADOWS)
if (me->GetEntry() == NPC_SALANAR_IN_REALM_OF_SHADOWS && player->GetQuestStatus(QUEST_INTO_REALM_OF_SHADOWS) == QUEST_STATUS_INCOMPLETE)
{
player->GroupEventHappens(QUEST_INTO_REALM_OF_SHADOWS, me);
Talk(SALANAR_SAY);
charmer->RemoveAurasDueToSpell(SPELL_EFFECT_OVERTAKE);
if (Creature* creature = who->ToCreature())
{
creature->DespawnOrUnsummon();
//creature->Respawn(true);
}
}
player->RemoveAurasDueToSpell(SPELL_REALM_OF_SHADOWS);
}
}
}
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_salanar_the_horsemanAI(creature);
}
};
enum HorseSeats
{
SEAT_ID_0 = 0
};
class spell_stable_master_repo : public AuraScript
{
PrepareAuraScript(spell_stable_master_repo);
void AfterApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/)
{
Creature* creature = GetTarget()->ToCreature();
if (!creature)
return;
if (Vehicle* vehicleKit = creature->GetVehicleKit())
if (Unit* passenger = vehicleKit->GetPassenger(SEAT_ID_0))
GetCaster()->EngageWithTarget(passenger);
creature->DespawnOrUnsummon(1s);
}
void Register() override
{
AfterEffectApply += AuraEffectApplyFn(spell_stable_master_repo::AfterApply, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL);
}
};
class spell_deliver_stolen_horse : public SpellScript
{
PrepareSpellScript(spell_deliver_stolen_horse);
bool Validate(SpellInfo const* /*spellInfo*/) override
{
return ValidateSpellInfo({ SPELL_DELIVER_STOLEN_HORSE, SPELL_EFFECT_STOLEN_HORSE });
}
void HandleScriptEffect(SpellEffIndex /*effIndex*/)
{
Unit* target = GetHitUnit();
target->RemoveAurasDueToSpell(SPELL_EFFECT_STOLEN_HORSE);
Unit* caster = GetCaster();
caster->RemoveAurasDueToSpell(SPELL_EFFECT_STOLEN_HORSE);
caster->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
caster->SetFaction(FACTION_FRIENDLY);
caster->CastSpell(caster, SPELL_CALL_DARK_RIDER, true);
}
void Register() override
{
OnEffectHitTarget += SpellEffectFn(spell_deliver_stolen_horse::HandleScriptEffect, EFFECT_1, SPELL_EFFECT_KILL_CREDIT2);
}
};
/*######
## npc_ros_dark_rider
######*/
class npc_ros_dark_rider : public CreatureScript
{
public:
npc_ros_dark_rider() : CreatureScript("npc_ros_dark_rider") { }
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_ros_dark_riderAI(creature);
}
struct npc_ros_dark_riderAI : public ScriptedAI
{
npc_ros_dark_riderAI(Creature* creature) : ScriptedAI(creature) { }
void JustEngagedWith(Unit* /*who*/) override
{
me->ExitVehicle();
}
void Reset() override
{
Creature* deathcharger = me->FindNearestCreature(28782, 30);
if (!deathcharger)
return;
deathcharger->RestoreFaction();
deathcharger->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
deathcharger->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
if (!me->GetVehicle() && deathcharger->IsVehicle() && deathcharger->GetVehicleKit()->HasEmptySeat(0))
me->EnterVehicle(deathcharger);
}
void JustDied(Unit* killer) override
{
Creature* deathcharger = me->FindNearestCreature(28782, 30);
if (!deathcharger || !killer)
return;
if (killer->GetTypeId() == TYPEID_PLAYER && deathcharger->GetTypeId() == TYPEID_UNIT && deathcharger->IsVehicle())
{
deathcharger->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
deathcharger->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
deathcharger->SetFaction(2096);
}
}
};
};
// correct way: 52312 52314 52555 ...
enum Creatures_SG
{
NPC_GHOULS = 28845,
NPC_GHOSTS = 28846,
};
class npc_dkc1_gothik : public CreatureScript
{
public:
npc_dkc1_gothik() : CreatureScript("npc_dkc1_gothik") { }
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_dkc1_gothikAI(creature);
}
struct npc_dkc1_gothikAI : public ScriptedAI
{
npc_dkc1_gothikAI(Creature* creature) : ScriptedAI(creature) { }
void MoveInLineOfSight(Unit* who) override
{
ScriptedAI::MoveInLineOfSight(who);
if (who->GetEntry() == NPC_GHOULS && me->IsWithinDistInMap(who, 10.0f))
{
if (Unit* owner = who->GetOwner())
{
if (Player* player = owner->ToPlayer())
{
Creature* creature = who->ToCreature();
if (player->GetQuestStatus(12698) == QUEST_STATUS_INCOMPLETE)
creature->CastSpell(owner, 52517, true);
/// @todo Creatures must not be removed, but, must instead
// stand next to Gothik and be commanded into the pit
// and dig into the ground.
creature->DespawnOrUnsummon();
if (player->GetQuestStatus(12698) == QUEST_STATUS_COMPLETE)
owner->RemoveAllMinionsByEntry(NPC_GHOSTS);
}
}
}
}
};
};
class npc_scarlet_ghoul : public CreatureScript
{
public:
npc_scarlet_ghoul() : CreatureScript("npc_scarlet_ghoul") { }
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_scarlet_ghoulAI(creature);
}
struct npc_scarlet_ghoulAI : public ScriptedAI
{
npc_scarlet_ghoulAI(Creature* creature) : ScriptedAI(creature)
{
// Ghouls should display their Birth Animation
// Crawling out of the ground
//DoCast(me, 35177, true);
//me->MonsterSay("Mommy?", LANG_UNIVERSAL, 0);
me->SetReactState(REACT_DEFENSIVE);
}
void FindMinions(Unit* owner)
{
std::list<Creature*> MinionList;
owner->GetAllMinionsByEntry(MinionList, NPC_GHOULS);
if (!MinionList.empty())
{
for (std::list<Creature*>::const_iterator itr = MinionList.begin(); itr != MinionList.end(); ++itr)
{
if ((*itr)->GetOwner()->GetGUID() == me->GetOwner()->GetGUID())
{
if ((*itr)->IsInCombat() && (*itr)->getAttackerForHelper())
{
AttackStart((*itr)->getAttackerForHelper());
}
}
}
}
}
void UpdateAI(uint32 /*diff*/) override
{
if (!me->IsInCombat())
{
if (Unit* owner = me->GetOwner())
{
Player* plrOwner = owner->ToPlayer();
if (plrOwner && plrOwner->IsInCombat())
{
if (plrOwner->getAttackerForHelper() && plrOwner->getAttackerForHelper()->GetEntry() == NPC_GHOSTS)
AttackStart(plrOwner->getAttackerForHelper());
else
FindMinions(owner);
}
}
}
if (!UpdateVictim() || !me->GetVictim())
return;
//ScriptedAI::UpdateAI(diff);
//Check if we have a current target
if (me->EnsureVictim()->GetEntry() == NPC_GHOSTS)
{
if (me->isAttackReady())
{
//If we are within range melee the target
if (me->IsWithinMeleeRange(me->GetVictim()))
{
me->AttackerStateUpdate(me->GetVictim());
me->resetAttackTimer();
}
}
}
}
};
};
/*####
## npc_scarlet_miner_cart
####*/
enum ScarletMinerCart
{
SPELL_CART_CHECK = 54173,
SPELL_SUMMON_CART = 52463,
SPELL_SUMMON_MINER = 52464,
SPELL_CART_DRAG = 52465,
NPC_MINER = 28841
};
class npc_scarlet_miner_cart : public CreatureScript
{
public:
npc_scarlet_miner_cart() : CreatureScript("npc_scarlet_miner_cart") { }
struct npc_scarlet_miner_cartAI : public PassiveAI
{
npc_scarlet_miner_cartAI(Creature* creature) : PassiveAI(creature)
{
me->SetDisplayId(me->GetCreatureTemplate()->Modelid1); // Modelid2 is a horse.
}
void JustSummoned(Creature* summon) override
{
if (summon->GetEntry() == NPC_MINER)
{
_minerGUID = summon->GetGUID();
summon->AI()->SetGUID(_playerGUID);
}
}
void SummonedCreatureDespawn(Creature* summon) override
{
if (summon->GetEntry() == NPC_MINER)
_minerGUID.Clear();
}
void DoAction(int32 /*param*/) override
{
if (Creature* miner = ObjectAccessor::GetCreature(*me, _minerGUID))
{
me->SetWalk(false);
// Not 100% correct, but movement is smooth. Sometimes miner walks faster
// than normal, this speed is fast enough to keep up at those times.
me->SetSpeedRate(MOVE_RUN, 1.25f);
me->GetMotionMaster()->MoveFollow(miner, 1.0f, 0);
}
}
void PassengerBoarded(Unit* who, int8 /*seatId*/, bool apply) override
{
if (apply)
{
_playerGUID = who->GetGUID();
me->CastSpell(nullptr, SPELL_SUMMON_MINER, true);
}
else
{
_playerGUID.Clear();
if (Creature* miner = ObjectAccessor::GetCreature(*me, _minerGUID))
miner->DespawnOrUnsummon();
}
}
private:
ObjectGuid _minerGUID;
ObjectGuid _playerGUID;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_scarlet_miner_cartAI(creature);
}
};
/*####
## npc_scarlet_miner
####*/
enum Says_SM
{
SAY_SCARLET_MINER_0 = 0,
SAY_SCARLET_MINER_1 = 1
};
class npc_scarlet_miner : public CreatureScript
{
public:
npc_scarlet_miner() : CreatureScript("npc_scarlet_miner") { }
struct npc_scarlet_minerAI : public EscortAI
{
npc_scarlet_minerAI(Creature* creature) : EscortAI(creature)
{
Initialize();
me->SetReactState(REACT_PASSIVE);
}
void Initialize()
{
carGUID.Clear();
IntroTimer = 0;
IntroPhase = 0;
}
uint32 IntroTimer;
uint32 IntroPhase;
ObjectGuid carGUID;
void Reset() override
{
Initialize();
}
void IsSummonedBy(Unit* summoner) override
{
carGUID = summoner->GetGUID();
}
void InitWaypoint()
{
AddWaypoint(1, 2389.03f, -5902.74f, 109.014f, 0.f, 5000);
AddWaypoint(2, 2341.812012f, -5900.484863f, 102.619743f);
AddWaypoint(3, 2306.561279f, -5901.738281f, 91.792419f);
AddWaypoint(4, 2300.098389f, -5912.618652f, 86.014885f);
AddWaypoint(5, 2294.142090f, -5927.274414f, 75.316849f);
AddWaypoint(6, 2286.984375f, -5944.955566f, 63.714966f);
AddWaypoint(7, 2280.001709f, -5961.186035f, 54.228283f);
AddWaypoint(8, 2259.389648f, -5974.197754f, 42.359348f);
AddWaypoint(9, 2242.882812f, -5984.642578f, 32.827850f);
AddWaypoint(10, 2217.265625f, -6028.959473f, 7.675705f);
AddWaypoint(11, 2202.595947f, -6061.325684f, 5.882018f);
AddWaypoint(12, 2188.974609f, -6080.866699f, 3.370027f);
if (urand(0, 1))
{
AddWaypoint(13, 2176.483887f, -6110.407227f, 1.855181f);
AddWaypoint(14, 2172.516602f, -6146.752441f, 1.074235f);
AddWaypoint(15, 2138.918457f, -6158.920898f, 1.342926f);
AddWaypoint(16, 2129.866699f, -6174.107910f, 4.380779f);
AddWaypoint(17, 2117.709473f, -6193.830078f, 13.3542f, 0.f, 10000);
}
else
{
AddWaypoint(13, 2184.190186f, -6166.447266f, 0.968877f);
AddWaypoint(14, 2234.265625f, -6163.741211f, 0.916021f);
AddWaypoint(15, 2268.071777f, -6158.750977f, 1.822252f);
AddWaypoint(16, 2270.028320f, -6176.505859f, 6.340538f);
AddWaypoint(17, 2271.739014f, -6195.401855f, 13.3542f, 0.f, 10000);
}
}
void SetGUID(ObjectGuid const& guid, int32 /*id*/) override
{
InitWaypoint();
Start(false, false, guid);
SetDespawnAtFar(false);
}
void WaypointReached(uint32 waypointId, uint32 /*pathId*/) override
{
switch (waypointId)
{
case 1:
if (Unit* car = ObjectAccessor::GetCreature(*me, carGUID))
me->SetFacingToObject(car);
Talk(SAY_SCARLET_MINER_0);
SetRun(true);
IntroTimer = 4000;
IntroPhase = 1;
break;
case 17:
if (Unit* car = ObjectAccessor::GetCreature(*me, carGUID))
{
me->SetFacingToObject(car);
car->RemoveAura(SPELL_CART_DRAG);
}
Talk(SAY_SCARLET_MINER_1);
break;
default:
break;
}
}
void UpdateAI(uint32 diff) override
{
if (IntroPhase)
{
if (IntroTimer <= diff)
{
if (IntroPhase == 1)
{
if (Creature* car = ObjectAccessor::GetCreature(*me, carGUID))
DoCast(car, SPELL_CART_DRAG);
IntroTimer = 800;
IntroPhase = 2;
}
else
{
if (Creature* car = ObjectAccessor::GetCreature(*me, carGUID))
car->AI()->DoAction(0);
IntroPhase = 0;
}
}
else
IntroTimer -= diff;
}
EscortAI::UpdateAI(diff);
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_scarlet_minerAI(creature);
}
};
// npc 28912 quest 17217 boss 29001 mob 29007 go 191092
void AddSC_the_scarlet_enclave_c1()
{
new npc_unworthy_initiate();
new npc_unworthy_initiate_anchor();
new go_acherus_soul_prison();
new npc_eye_of_acherus();
new npc_death_knight_initiate();
RegisterCreatureAI(npc_dark_rider_of_acherus);
new npc_salanar_the_horseman();
RegisterAuraScript(spell_stable_master_repo);
RegisterSpellScript(spell_deliver_stolen_horse);
new npc_ros_dark_rider();
new npc_dkc1_gothik();
new npc_scarlet_ghoul();
new npc_scarlet_miner();
new npc_scarlet_miner_cart();
}
| gpl-2.0 |
NeumimTo/NT-RPG | Skills/src/main/java/cz/neumimto/effects/negative/WatherBreathingEffectContainer.java | 449 | package cz.neumimto.effects.negative;
import cz.neumimto.rpg.effects.EffectContainer;
/**
* Created by NeumimTo on 3.6.2017.
*/
public class WatherBreathingEffectContainer extends EffectContainer<Object, WaterBreathing> {
public WatherBreathingEffectContainer(WaterBreathing effect) {
super(effect);
}
@Override
public void removeStack(WaterBreathing iEffect) {
if (getEffects().size() == 1) {
super.removeStack(iEffect);
}
}
}
| gpl-2.0 |
BruceWayneLin/mittag | admin/language/zh-TW/extension/shipping/free.php | 523 | <?php
// Heading
$_['heading_title'] = '免費配送';
// Text
$_['text_extension'] = '配送模組';
$_['text_success'] = '更新成功';
$_['text_edit'] = '編輯';
// Entry
$_['entry_total'] = '最低金額';
$_['entry_geo_zone'] = '適用區域';
$_['entry_status'] = '狀態';
$_['entry_sort_order'] = '排序';
// Help
$_['help_total'] = '商品小計金額須達到此設定才能使用免費配送';
// Error
$_['error_permission'] = '您沒有權限更改此模組的設置!'; | gpl-2.0 |
mikeymicrophone/greenchange | spec/models/tagging_spec.rb | 2583 | require File.dirname(__FILE__) + '/../spec_helper'
describe Tagging do
before do
@page1 = create_page
@page2 = create_page
end
it "should set tags" do
@page2.tag_with "hoppy pilsner"
@page2.tag_list.should == "hoppy pilsner"
end
it "should set tags with array" do
@page2.tag_with ["lager", "stout", "fruity", "seasonal"]
@page2.tag_list.should == "fruity lager seasonal stout"
end
describe "after adding tags" do
before do
@page1.tag_with "seasonal lager ipa"
@page2.tag_with ["lager", "stout", "fruity", "seasonal"]
@result1 = [@page1]
@result2 = [@page1.id, @page2.id].sort
end
it "should find tagged pages with tagged_with a tag" do
Page.tagged_with("ipa").to_a.should == @result1
end
it "should find pages tagged with space separated list" do
Page.tagged_with("ipa lager").to_a.should == @result1
end
it "should find pages by array" do
Page.tagged_with("ipa", "lager").to_a.should == @result1
end
it "should find all pages with a tag" do
Page.tagged_with("seasonal").map(&:id).sort.should == @result2
end
it "should find all pages with a space separated list" do
Page.tagged_with("seasonal lager").map(&:id).sort.should == @result2
end
it "should find all pages by array of tags" do
Page.tagged_with("seasonal", "lager").map(&:id).sort.should == @result2
end
end
describe "internal methods" do
before do
@page1.tag_with("pale")
@page2.tag_with("pale imperial")
@tag2 = Tag.find_by_name "imperial"
@tag1 = Tag.find_by_name "pale"
end
it "should add tags with _add_tags" do
@page1._add_tags "porter longneck"
Tag.find_by_name("porter").taggables.should include(@page1)
end
it "should add tags with _add_tags" do
@page1._add_tags "porter longneck"
Tag.find_by_name("longneck").taggables.should include(@page1)
end
it "should add tags with _add_tags" do
@page1._add_tags "porter longneck"
@page1.tag_list.should == "longneck pale porter"
end
it "should remove tags with _remove_tags" do
@page2._remove_tags [@tag2, @tag1]
@page2.tags.should be_empty
end
end
it "should not be taggable" do
tagging = new_tagging
tagging.save
tagging.send(:taggable?).should be_false
end
it "should raise an error on taggable if raise error flag is true" do
tagging = create_tagging
lambda { tagging.send(:taggable?, true) }.should raise_error(RuntimeError)
end
end
| gpl-2.0 |
newlifes01/UWP-learning | Windows10应用开发实战/第6章/Example_9/MyApp/MainPage.xaml.cs | 3100 | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=391641 上有介绍
namespace MyApp
{
/// <summary>
/// 可用于自身或导航至 Frame 内部的空白页。
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
lvMsgs.ItemsSource = new MessageEntity[]
{
new MessageEntity { MessageType = MessageEntity.MsgType.From, Content = "小明,你今天在家吗?" },
new MessageEntity { MessageType = MessageEntity.MsgType.To, Content = "在啊。" },
new MessageEntity { MessageType = MessageEntity.MsgType.From, Content = "待会儿帮你把东西送过去。"},
new MessageEntity { MessageType = MessageEntity.MsgType.To, Content = "好的,十分感谢。" }
};
}
/// <summary>
/// 在此页将要在 Frame 中显示时进行调用。
/// </summary>
/// <param name="e">描述如何访问此页的事件数据。
/// 此参数通常用于配置页。</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// TODO: 准备此处显示的页面。
// TODO: 如果您的应用程序包含多个页面,请确保
// 通过注册以下事件来处理硬件“后退”按钮:
// Windows.Phone.UI.Input.HardwareButtons.BackPressed 事件。
// 如果使用由某些模板提供的 NavigationHelper,
// 则系统会为您处理该事件。
}
}
public sealed class CustomDataTemplateSelector : DataTemplateSelector
{
/// <summary>
/// 显示收到的消息的模板
/// </summary>
public DataTemplate MessageFromTemplate { get; set; }
/// <summary>
/// 显示已发送消息的模板
/// </summary>
public DataTemplate MessageToTemplate { get; set; }
protected override DataTemplate SelectTemplateCore ( object item, DependencyObject container )
{
MessageEntity msgent = item as MessageEntity;
if (msgent != null)
{
// 判断消息类型,返回对应的模板
if (msgent.MessageType == MessageEntity.MsgType.From)
{
return MessageFromTemplate;
}
else
{
return MessageToTemplate;
}
}
return null;
}
}
}
| gpl-2.0 |
mleemaree/orgull | wp-content/plugins/wp-ultimate-post-grid/vendor/select2/js/i18n/zh-CN.js | 804 | /*! Select2wpupg 4.0.0 | https://github.com/select2wpupg/select2wpupg/blob/master/LICENSE.md */
(function(){if(jQuery&&jQuery.fn&&jQuery.fn.select2wpupg&&jQuery.fn.select2wpupg.amd)var e=jQuery.fn.select2wpupg.amd;return e.define("select2wpupg/i18n/zh-CN",[],function(){return{errorLoading:function(){return"无法载入结果。"},inputTooLong:function(e){var t=e.input.length-e.maximum,n="请删除"+t+"个字符";return n},inputTooShort:function(e){var t=e.minimum-e.input.length,n="请再输入至少"+t+"个字符";return n},loadingMore:function(){return"载入更多结果…"},maximumSelected:function(e){var t="最多只能选择"+e.maximum+"个项目";return t},noResults:function(){return"未找到结果"},searching:function(){return"搜索中…"}}}),{define:e.define,require:e.require}})(); | gpl-2.0 |
joomla-framework/google-api | src/Data/Plus/Comments.php | 3516 | <?php
/**
* Part of the Joomla Framework Google Package
*
* @copyright Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Google\Data\Plus;
use Joomla\Google\Data;
use Joomla\Google\Auth;
use Joomla\Registry\Registry;
/**
* Google+ data class for the Joomla Framework.
*
* @since 1.0
* @deprecated The joomla/google package is deprecated
*/
class Comments extends Data
{
/**
* Constructor.
*
* @param array|\ArrayAccess $options Google options object
* @param Auth $auth Google data http client object
*
* @since 1.0
*/
public function __construct($options = array(), Auth $auth = null)
{
parent::__construct($options, $auth);
if (isset($this->auth) && !$this->auth->getOption('scope'))
{
$this->auth->setOption('scope', 'https://www.googleapis.com/auth/plus.me');
}
}
/**
* List all of the comments for an activity.
*
* @param string $activityId The ID of the activity to get comments for.
* @param string $fields Used to specify the fields you want returned.
* @param integer $max The maximum number of people to include in the response, used for paging.
* @param string $order The order in which to sort the list of comments. Acceptable values are "ascending" and "descending".
* @param string $token The continuation token, used to page through large result sets. To get the next page of results, set this
* parameter to the value of "nextPageToken" from the previous response. This token may be of any length.
* @param string $alt Specifies an alternative representation type. Acceptable values are: "json" - Use JSON format (default)
*
* @return mixed Data from Google
*
* @since 1.0
*/
public function listComments($activityId, $fields = null, $max = 20, $order = null, $token = null, $alt = null)
{
if ($this->isAuthenticated())
{
$url = $this->getOption('api.url') . 'activities/' . $activityId . '/comments';
// Check if fields is specified.
if ($fields)
{
$url .= '?fields=' . $fields;
}
// Check if max is specified.
if ($max != 20)
{
$url .= (strpos($url, '?') === false) ? '?maxResults=' : '&maxResults=';
$url .= $max;
}
// Check if order is specified.
if ($order)
{
$url .= (strpos($url, '?') === false) ? '?orderBy=' : '&orderBy=';
$url .= $order;
}
// Check of token is specified.
if ($token)
{
$url .= (strpos($url, '?') === false) ? '?pageToken=' : '&pageToken=';
$url .= $token;
}
// Check if alt is specified.
if ($alt)
{
$url .= (strpos($url, '?') === false) ? '?alt=' : '&alt=';
$url .= $alt;
}
$jdata = $this->auth->query($url);
return json_decode($jdata->body, true);
}
return false;
}
/**
* Get a comment.
*
* @param string $id The ID of the comment to get.
* @param string $fields Used to specify the fields you want returned.
*
* @return mixed Data from Google
*
* @since 1.0
*/
public function getComment($id, $fields = null)
{
if ($this->isAuthenticated())
{
$url = $this->getOption('api.url') . 'comments/' . $id;
// Check if fields is specified.
if ($fields)
{
$url .= '?fields=' . $fields;
}
$jdata = $this->auth->query($url);
return json_decode($jdata->body, true);
}
return false;
}
}
| gpl-2.0 |
openvsip/openvsip | src/ovxx/view/traits.hpp | 3717 | //
// Copyright (c) 2005 CodeSourcery
// Copyright (c) 2013 Stefan Seefeld
// All rights reserved.
//
// This file is part of OpenVSIP. It is made available under the
// license contained in the accompanying LICENSE.BSD file.
#ifndef ovxx_view_traits_hpp_
#define ovxx_view_traits_hpp_
#include <ovxx/support.hpp>
#include <ovxx/block_traits.hpp>
#include <ovxx/length.hpp>
#include <vsip/impl/view_fwd.hpp>
#include <vsip/domain.hpp>
namespace ovxx
{
template <template <typename, typename> class View,
typename T,
typename Block>
View<T, typename distributed_local_block<Block>::type>
get_local_view(View<T, Block> v);
/// Return the view extent as a domain.
template <typename T, typename Block>
inline Domain<1> view_domain(const_Vector<T, Block> const &);
template <typename T, typename Block>
inline Domain<2> view_domain(const_Matrix<T, Block> const &);
template <typename T, typename Block>
inline Domain<3> view_domain(const_Tensor<T, Block> const &);
/// Return the view extent as a Length.
template <typename T, typename Block>
inline Length<1> extent(const_Vector<T, Block> const &);
template <typename T, typename Block>
inline Length<2> extent(const_Matrix<T, Block> const &);
template <typename T, typename Block>
inline Length<3> extent(const_Tensor<T, Block> const &);
template <typename T, typename Block>
T get(const_Vector<T, Block>, Index<1> const &);
template <typename T, typename Block>
T get(const_Matrix<T, Block>, Index<2> const &);
template <typename T, typename Block>
T get(const_Tensor<T, Block>, Index<3> const &);
template <typename T, typename Block>
void put(Vector<T, Block>, Index<1> const &, T);
template <typename T, typename Block>
void put(Matrix<T, Block>, Index<2> const &, T);
template <typename T, typename Block>
void put(Tensor<T, Block>, Index<3> const &, T);
/// As per the specification, the view type can be infered from its block type.
/// This meta-function encodes that dependency by mapping the latter to the former.
template <typename B, dimension_type D = B::dim>
struct view_of;
/// Trait that provides typedef 'type' iff VIEW is a valid view.
///
/// Views should provide specializations similar to:
/// template <> struct is_view_type<Matrix> { typedef void type; };
/// template <> struct is_view_type<const_Matrix> { typedef void type; };
template <typename> struct is_view_type { static bool const value = false;};
/// Trait that provides typedef 'type' iff VIEW is a valid const view.
template <typename> struct is_const_view_type
{ static bool const value = false;};
template <template <typename,typename> class View> struct dim_of_view;
template <> struct dim_of_view<vsip::Vector> { static const dimension_type dim = 1;};
template <> struct dim_of_view<vsip::Matrix> { static const dimension_type dim = 2;};
template <> struct dim_of_view<vsip::Tensor> { static const dimension_type dim = 3;};
template <> struct dim_of_view<vsip::const_Vector>
{ static const dimension_type dim = 1;};
template <> struct dim_of_view<vsip::const_Matrix>
{ static const dimension_type dim = 2;};
template <> struct dim_of_view<vsip::const_Tensor>
{ static const dimension_type dim = 3;};
template <template <typename,typename> class View, typename Block> struct const_of_view;
template <typename B> struct const_of_view<vsip::Vector, B>
{ typedef vsip::const_Vector<typename B::value_type,B> type;};
template <typename B> struct const_of_view<vsip::Matrix, B>
{ typedef vsip::const_Matrix<typename B::value_type, B> type;};
template <typename B> struct const_of_view<vsip::Tensor, B>
{ typedef vsip::const_Tensor<typename B::value_type, B> type;};
} // namespace ovxx
#endif
| gpl-2.0 |
Philmist/YPStandJS | peca_index.js | 539 | // fileencoding=utf-8
var peca = require("./peca");
var router = require("./yp_router");
var handler = require("./yp_handler");
var pcp_handler = require("./yp_handler_pcp");
var yp = require("./yp");
var util = require("util");
var channel = require("./channel_mem");
var handle = {};
handle["PCP"] = pcp_handler.Handler;
handle["HTTP"] = handler.HTTPHandler;
var chobj = channel.channel_mem;
var sv = yp.startServer(7146, router.YpRouter, handle, chobj);
//console.log("Main : Server instance is");
//console.log(util.inspect(sv));
| gpl-2.0 |
schleichdi2/OpenNfr_E2_Gui-6.0 | lib/python/Plugins/Extensions/MediaPortal/resources/tw_util.py | 4008 |
from twisted import __version__
tmp = tuple([x for x in __version__.split('.')])
__TW_VER__ = []
for x in tmp:
__TW_VER__.append(int(''.join([i for i in x if i.isdigit()])))
del tmp
import mp_globals
import sys
try:
from enigma import eMediaDatabase
mp_globals.isDreamOS = True
except:
mp_globals.isDreamOS = False
if __TW_VER__ >= [14, 0, 0]:
if mp_globals.isDreamOS:
mp_globals.requests = False
elif sys.version_info[:3] >= (2,7,9):
mp_globals.requests = False
else:
mp_globals.requests = True
else:
mp_globals.requests = True
if __TW_VER__ > [13, 0, 0]:
from twisted.web import client
from twisted.internet import endpoints
from twisted.web.iweb import IBodyProducer
elif __TW_VER__ >= [11, 1, 0]:
import tx
from tx import client
from tx import endpoints
from tx.iweb import IBodyProducer
else:
raise Exception("No HTTP 1.1 Support")
try:
from OpenSSL import SSL
from twisted.internet.ssl import ClientContextFactory
except:
twAgent = False
raise Exception("No SSL Support")
else:
twAgent = True
try:
from urlparse import urlunparse, urljoin, urldefrag
from urllib import splithost, splittype
except ImportError:
from urllib.parse import splithost, splittype, urljoin, urldefrag
from urllib.parse import urlunparse as _urlunparse
def urlunparse(parts):
result = _urlunparse(tuple([p.decode("charmap") for p in parts]))
return result.encode("charmap")
try:
# available since twisted 14.0
from twisted.internet._sslverify import ClientTLSOptions
except ImportError:
ClientTLSOptions = None
from Components.config import config
import twisted
from twisted.web import http
from twisted.internet.protocol import Protocol
from twisted.internet import reactor
from twisted.internet.defer import Deferred, succeed, fail
from twisted.web.http_headers import Headers
from twisted.web.http import PotentialDataLoss
from twisted.web.client import downloadPage, getPage
from twisted.internet.error import TimeoutError
from twisted.python import failure
from zope.interface import implements
def to_bytes(text, encoding=None, errors='strict'):
"""Return the binary representation of `text`. If `text`
is already a bytes object, return it as-is."""
if isinstance(text, bytes):
return text
if not isinstance(text, six.string_types):
raise TypeError('to_bytes must receive a unicode, str or bytes '
'object, got %s' % type(text).__name__)
if encoding is None:
encoding = 'utf-8'
return text.encode(encoding, errors)
def _parse(url, defaultPort=None):
from urlparse import urlunparse
url = url.strip()
parsed = http.urlparse(url)
scheme = parsed[0]
path = urlunparse(('', '') + parsed[2:])
if defaultPort is None:
if scheme == 'https':
defaultPort = 443
else:
defaultPort = 80
host, port = parsed[1], defaultPort
if ':' in host:
host, port = host.split(':')
try:
port = int(port)
except ValueError:
port = defaultPort
if path == '':
path = '/'
return scheme, '', host, port, path
class TwClientContextFactory(ClientContextFactory):
"A SSL context factory which is more permissive against SSL bugs."
def __init__(self):
self.method = SSL.TLSv1_METHOD
def getContext(self, hostname=None, port=None):
ctx = ClientContextFactory.getContext(self)
# Enable all workarounds to SSL bugs as documented by
# http://www.openssl.org/docs/ssl/SSL_CTX_set_options.html
ctx.set_options(SSL.OP_ALL)
if hostname and ClientTLSOptions is not None: # workaround for TLS SNI
ClientTLSOptions(hostname, ctx)
return ctx
Agent = client.Agent
ProxyAgent = client.ProxyAgent
CookieAgent = client.CookieAgent
ResponseDone = client.ResponseDone
TCP4ClientEndpoint = endpoints.TCP4ClientEndpoint
downloadPage = twisted.web.client.downloadPage
getPage = twisted.web.client.getPage
HTTPConnectionPool = client.HTTPConnectionPool
BrowserLikeRedirectAgent = client.BrowserLikeRedirectAgent
ContentDecoderAgent = client.ContentDecoderAgent
GzipDecoder = client.GzipDecoder | gpl-2.0 |
Ankama/harvey | src/com/ankamagames/dofus/harvey/engine/generic/comparators/ContinuousComparator.java | 457 | /**
*
*/
package com.ankamagames.dofus.harvey.engine.generic.comparators;
import java.util.Comparator;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
/**
* @author sgros
*
*/
@NonNullByDefault
public interface ContinuousComparator<E>
extends Comparator<E>
{
@Override
int compare(@Nullable E o1, @Nullable E o2);
double compareContinuous(@Nullable E o1, @Nullable E o2);
}
| gpl-2.0 |
alkhwarizmix/moqawalati | source/moqawalatiWeb/src/test/java/dz/alkhwarizmix/framework/java/blazeds/messaging/AlKhwarizmixMessageBrokerServletTest.java | 2136 | ////////////////////////////////////////////////////////////////////////////////
// بسم الله الرحمن الرحيم
//
// حقوق التأليف والنشر ١٤٣٦ هجري، فارس بلحواس (Copyright 2015 Fares Belhaouas)
// كافة الحقوق محفوظة (All Rights Reserved)
//
// NOTICE: Fares Belhaouas permits you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
package dz.alkhwarizmix.framework.java.blazeds.messaging;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import dz.alkhwarizmix.framework.java.AlKhwarizmixException;
/**
* <p>
* TODO: Javadoc
* </p>
*
* @author فارس بلحواس (Fares Belhaouas)
* @since ٠٧ رجب ١٤٣٦ (April 26, 2015)
*/
@RunWith(MockitoJUnitRunner.class)
@SuppressWarnings("PMD.MethodNamingConventions")
public class AlKhwarizmixMessageBrokerServletTest {
// --------------------------------------------------------------------------
//
// Setup & Teardown
//
// --------------------------------------------------------------------------
private AlKhwarizmixMessageBrokerServlet utAlKhwarizmixMessageBrokerServlet;
@Before
public void setUp() {
utAlKhwarizmixMessageBrokerServlet = newAlKhwarizmixMessageBrokerServlet();
}
private AlKhwarizmixMessageBrokerServlet newAlKhwarizmixMessageBrokerServlet() {
return new AlKhwarizmixMessageBrokerServlet();
}
// --------------------------------------------------------------------------
//
// Helpers
//
// --------------------------------------------------------------------------
// EMPTY
// --------------------------------------------------------------------------
//
// Tests
//
// --------------------------------------------------------------------------
@Test
public void test00_constructor1() throws AlKhwarizmixException {
Assert.assertNotNull(utAlKhwarizmixMessageBrokerServlet);
}
} // Class
| gpl-2.0 |
dl4gbe/kernel | include/data/base_tables/cls_base_drupal_cache_form.php | 27494 | <?php
if(!defined('kernel_entry') || !kernel_entry) die('Not A Valid Entry Point');
require_once('include/data/cls_datatable_base.php');
require_once('include/data/cls_data_result.php');
abstract class cls_base_drupal_cache_form extends cls_datatable_base
{
private static $p_cmmon;
private $p_serialized = null;
private $p_serialized_original = null;
private $p_created = null;
private $p_created_original = null;
private $p_expire = null;
private $p_expire_original = null;
private $p_data = null;
private $p_data_original = null;
private $p_cid = null;
private $p_cid_original = null;
private $p_serialized_is_dirty = false;
private $p_created_is_dirty = false;
private $p_expire_is_dirty = false;
private $p_data_is_dirty = false;
private $p_cid_is_dirty = false;
public function _get_table_name()
{
return 'drupal_cache_form';
}
public function get_table_fields()
{
return array('id','serialized','created','expire','data','cid');
}
public function get_table_select($delimiter = '"')
{
return 'select id as ' . $delimiter . 'drupal_cache_form.id' . $delimiter . ',serialized as ' . $delimiter . 'drupal_cache_form.serialized' . $delimiter . ',created as ' . $delimiter . 'drupal_cache_form.created' . $delimiter . ',expire as ' . $delimiter . 'drupal_cache_form.expire' . $delimiter . ',data as ' . $delimiter . 'drupal_cache_form.data' . $delimiter . ',cid as ' . $delimiter . 'drupal_cache_form.cid' . $delimiter . ' from drupal_cache_form';
}
public function get_search_fields()
{
$search_fields = array();
return $search_fields;
}
public function get_serialized()
{
return $this->p_serialized;
}
public function get_serialized_original()
{
return $this->p_serialized_original;
}
public function set_serialized($value)
{
if ($this->p_serialized === $value)
{
return;
}
$this->set_dirty(true);
$this->p_serialized_is_dirty = true;
$this->p_serialized = $value;
}
public function set_serialized_original($value)
{
$this->p_serialized_original = $value;
}
public function get_serialized_is_dirty()
{
return $this->p_serialized_is_dirty;
}
public function get_created()
{
return $this->p_created;
}
public function get_created_original()
{
return $this->p_created_original;
}
public function set_created($value)
{
if ($this->p_created === $value)
{
return;
}
$this->set_dirty(true);
$this->p_created_is_dirty = true;
$this->p_created = $value;
}
public function set_created_original($value)
{
$this->p_created_original = $value;
}
public function get_created_is_dirty()
{
return $this->p_created_is_dirty;
}
public function get_expire()
{
return $this->p_expire;
}
public function get_expire_original()
{
return $this->p_expire_original;
}
public function set_expire($value)
{
if ($this->p_expire === $value)
{
return;
}
$this->set_dirty(true);
$this->p_expire_is_dirty = true;
$this->p_expire = $value;
}
public function set_expire_original($value)
{
$this->p_expire_original = $value;
}
public function get_expire_is_dirty()
{
return $this->p_expire_is_dirty;
}
public function get_data()
{
return $this->p_data;
}
public function get_data_original()
{
return $this->p_data_original;
}
public function set_data($value)
{
if ($this->p_data === $value)
{
return;
}
$this->set_dirty(true);
$this->p_data_is_dirty = true;
$this->p_data = $value;
}
public function set_data_original($value)
{
$this->p_data_original = $value;
}
public function get_data_is_dirty()
{
return $this->p_data_is_dirty;
}
public function get_cid()
{
return $this->p_cid;
}
public function get_cid_original()
{
return $this->p_cid_original;
}
public function set_cid($value)
{
if ($this->p_cid === $value)
{
return;
}
$this->set_dirty(true);
$this->p_cid_is_dirty = true;
$this->p_cid = $value;
}
public function set_cid_original($value)
{
$this->p_cid_original = $value;
}
public function get_cid_is_dirty()
{
return $this->p_cid_is_dirty;
}
public function reset_dirty($reset_values = false)
{
$this->p_serialized_is_dirty = false;
$this->p_created_is_dirty = false;
$this->p_expire_is_dirty = false;
$this->p_data_is_dirty = false;
$this->p_cid_is_dirty = false;
if ($reset_values)
{
$this->p_serialized = $this->p_serialized_original;
$this->p_created = $this->p_created_original;
$this->p_expire = $this->p_expire_original;
$this->p_data = $this->p_data_original;
$this->p_cid = $this->p_cid_original;
}
}
public function fill($row,$reset = true)
{
foreach ($row as $key => $val)
{
switch ($key)
{
case "drupal_cache_form.id":
$this->set_id($val);
break;
case "drupal_cache_form.serialized":
$this->set_serialized($val);
$this->set_serialized_original($val);
break;
case "drupal_cache_form.created":
$this->set_created($val);
$this->set_created_original($val);
break;
case "drupal_cache_form.expire":
$this->set_expire($val);
$this->set_expire_original($val);
break;
case "drupal_cache_form.data":
$this->set_data($val);
$this->set_data_original($val);
break;
case "drupal_cache_form.cid":
$this->set_cid($val);
$this->set_cid_original($val);
break;
}
}
if ($reset)
{
$this->reset_dirty(false);
}
}
public function get_by_id($id,$db_manager,$application = null)
{
$sql = $this->get_table_select($db_manager->get_delimeter());
$sql .= " where id = '" . $id . "'";
$result = $db_manager->query($sql);
if (!is_null($result))
{
require_once('include/data/table_factory/cls_table_factory.php');
$drupal_cache_form = cls_table_factory::create_instance('drupal_cache_form');
$row = $db_manager->fetch_row($result);
$drupal_cache_form->fill($row);
return $drupal_cache_form;
}
}
public function save($db_manager,$application)
{
require_once('include/data/base_table_savers/cls_save_drupal_cache_form.php');
return cls_save_drupal_cache_form::save_object($this,$db_manager,$application);
}
public function save_array($data,$db_manager,$application)
{
require_once('include/data/base_table_savers/cls_save_drupal_cache_form.php');
return cls_save_drupal_cache_form::save_array($data,$db_manager,$application);
}
function save_data($data,$db_manager,$application)
{
}
public function get_drupal_cache_forms($db_manager,$application,$search_values,$limit = 0,$offset = 0,$use_key_value = false)
{
$result = null;
if (empty($seach_values))
{
$result = $db_manager->search_for_records('drupal_cache_form',null,null,$limit,$offset);
}
else
{
$result = $db_manager->search_for_records('drupal_cache_form',$this->get_search_fields(),$seach_values,$limit,$offset);
}
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$drupal_cache_form = cls_table_factory::create_instance('drupal_cache_form');
$drupal_cache_form->fill($row);
$data[] = $drupal_cache_form;
}
return $data;
}
public function get_table_test_data($drupal_cache_forms,$db_manager,$application,$use_key_value = false)
{
$result = $db_manager->get_records('table_test_data',$this->get_id(),'id_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$table_test_data = cls_table_factory::create_instance('table_test_data');
$table_test_data->fill($row);
if ($use_key_value)
{
$data[$row['id']] = $table_test_data;
}
else
{
$data[] = $table_test_data;
}
}
return $data;
}
public function get_multi_table_test_data($drupal_cache_forms,$db_manager,$application)
{
$result = $db_manager->get_records_by_ids('table_test_data',$drupal_cache_forms,'id_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$table_test_data = cls_table_factory::create_instance('table_test_data');
$table_test_data->fill($row);
if (!array_key_exists($data[$row['id_data']]))
{
$data[$row['id_data']] = array();
}
$data[$row['id_data']][] = $table_test_data;
}
return $data;
}
public function get_communication_reason($drupal_cache_forms,$db_manager,$application,$use_key_value = false)
{
$result = $db_manager->get_records('communication_reason',$this->get_id(),'id_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$communication_reason = cls_table_factory::create_instance('communication_reason');
$communication_reason->fill($row);
if ($use_key_value)
{
$data[$row['id']] = $communication_reason;
}
else
{
$data[] = $communication_reason;
}
}
return $data;
}
public function get_multi_communication_reason($drupal_cache_forms,$db_manager,$application)
{
$result = $db_manager->get_records_by_ids('communication_reason',$drupal_cache_forms,'id_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$communication_reason = cls_table_factory::create_instance('communication_reason');
$communication_reason->fill($row);
if (!array_key_exists($data[$row['id_data']]))
{
$data[$row['id_data']] = array();
}
$data[$row['id_data']][] = $communication_reason;
}
return $data;
}
public function get_data_change($drupal_cache_forms,$db_manager,$application,$use_key_value = false)
{
$result = $db_manager->get_records('data_change',$this->get_id(),'id_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$data_change = cls_table_factory::create_instance('data_change');
$data_change->fill($row);
if ($use_key_value)
{
$data[$row['id']] = $data_change;
}
else
{
$data[] = $data_change;
}
}
return $data;
}
public function get_multi_data_change($drupal_cache_forms,$db_manager,$application)
{
$result = $db_manager->get_records_by_ids('data_change',$drupal_cache_forms,'id_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$data_change = cls_table_factory::create_instance('data_change');
$data_change->fill($row);
if (!array_key_exists($data[$row['id_data']]))
{
$data[$row['id_data']] = array();
}
$data[$row['id_data']][] = $data_change;
}
return $data;
}
public function get_data_help($drupal_cache_forms,$db_manager,$application,$use_key_value = false)
{
$result = $db_manager->get_records('data_help',$this->get_id(),'id_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$data_help = cls_table_factory::create_instance('data_help');
$data_help->fill($row);
if ($use_key_value)
{
$data[$row['id']] = $data_help;
}
else
{
$data[] = $data_help;
}
}
return $data;
}
public function get_multi_data_help($drupal_cache_forms,$db_manager,$application)
{
$result = $db_manager->get_records_by_ids('data_help',$drupal_cache_forms,'id_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$data_help = cls_table_factory::create_instance('data_help');
$data_help->fill($row);
if (!array_key_exists($data[$row['id_data']]))
{
$data[$row['id_data']] = array();
}
$data[$row['id_data']][] = $data_help;
}
return $data;
}
public function get_data_location($drupal_cache_forms,$db_manager,$application,$use_key_value = false)
{
$result = $db_manager->get_records('data_location',$this->get_id(),'id_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$data_location = cls_table_factory::create_instance('data_location');
$data_location->fill($row);
if ($use_key_value)
{
$data[$row['id']] = $data_location;
}
else
{
$data[] = $data_location;
}
}
return $data;
}
public function get_multi_data_location($drupal_cache_forms,$db_manager,$application)
{
$result = $db_manager->get_records_by_ids('data_location',$drupal_cache_forms,'id_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$data_location = cls_table_factory::create_instance('data_location');
$data_location->fill($row);
if (!array_key_exists($data[$row['id_data']]))
{
$data[$row['id_data']] = array();
}
$data[$row['id_data']][] = $data_location;
}
return $data;
}
public function get_data_posting($drupal_cache_forms,$db_manager,$application,$use_key_value = false)
{
$result = $db_manager->get_records('data_posting',$this->get_id(),'id_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$data_posting = cls_table_factory::create_instance('data_posting');
$data_posting->fill($row);
if ($use_key_value)
{
$data[$row['id']] = $data_posting;
}
else
{
$data[] = $data_posting;
}
}
return $data;
}
public function get_multi_data_posting($drupal_cache_forms,$db_manager,$application)
{
$result = $db_manager->get_records_by_ids('data_posting',$drupal_cache_forms,'id_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$data_posting = cls_table_factory::create_instance('data_posting');
$data_posting->fill($row);
if (!array_key_exists($data[$row['id_data']]))
{
$data[$row['id_data']] = array();
}
$data[$row['id_data']][] = $data_posting;
}
return $data;
}
public function get_offer_event($drupal_cache_forms,$db_manager,$application,$use_key_value = false)
{
$result = $db_manager->get_records('offer_event',$this->get_id(),'id_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$offer_event = cls_table_factory::create_instance('offer_event');
$offer_event->fill($row);
if ($use_key_value)
{
$data[$row['id']] = $offer_event;
}
else
{
$data[] = $offer_event;
}
}
return $data;
}
public function get_multi_offer_event($drupal_cache_forms,$db_manager,$application)
{
$result = $db_manager->get_records_by_ids('offer_event',$drupal_cache_forms,'id_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$offer_event = cls_table_factory::create_instance('offer_event');
$offer_event->fill($row);
if (!array_key_exists($data[$row['id_data']]))
{
$data[$row['id_data']] = array();
}
$data[$row['id_data']][] = $offer_event;
}
return $data;
}
public function get_supplier_data($drupal_cache_forms,$db_manager,$application,$use_key_value = false)
{
$result = $db_manager->get_records('supplier_data',$this->get_id(),'id_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$supplier_data = cls_table_factory::create_instance('supplier_data');
$supplier_data->fill($row);
if ($use_key_value)
{
$data[$row['id']] = $supplier_data;
}
else
{
$data[] = $supplier_data;
}
}
return $data;
}
public function get_multi_supplier_data($drupal_cache_forms,$db_manager,$application)
{
$result = $db_manager->get_records_by_ids('supplier_data',$drupal_cache_forms,'id_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$supplier_data = cls_table_factory::create_instance('supplier_data');
$supplier_data->fill($row);
if (!array_key_exists($data[$row['id_data']]))
{
$data[$row['id_data']] = array();
}
$data[$row['id_data']][] = $supplier_data;
}
return $data;
}
public function get_address($drupal_cache_forms,$db_manager,$application,$use_key_value = false)
{
$result = $db_manager->get_records('address',$this->get_id(),'id_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$address = cls_table_factory::create_instance('address');
$address->fill($row);
if ($use_key_value)
{
$data[$row['id']] = $address;
}
else
{
$data[] = $address;
}
}
return $data;
}
public function get_multi_address($drupal_cache_forms,$db_manager,$application)
{
$result = $db_manager->get_records_by_ids('address',$drupal_cache_forms,'id_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$address = cls_table_factory::create_instance('address');
$address->fill($row);
if (!array_key_exists($data[$row['id_data']]))
{
$data[$row['id_data']] = array();
}
$data[$row['id_data']][] = $address;
}
return $data;
}
public function get_data_property($drupal_cache_forms,$db_manager,$application,$use_key_value = false)
{
$result = $db_manager->get_records('data_property',$this->get_id(),'id_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$data_property = cls_table_factory::create_instance('data_property');
$data_property->fill($row);
if ($use_key_value)
{
$data[$row['id']] = $data_property;
}
else
{
$data[] = $data_property;
}
}
return $data;
}
public function get_multi_data_property($drupal_cache_forms,$db_manager,$application)
{
$result = $db_manager->get_records_by_ids('data_property',$drupal_cache_forms,'id_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$data_property = cls_table_factory::create_instance('data_property');
$data_property->fill($row);
if (!array_key_exists($data[$row['id_data']]))
{
$data[$row['id_data']] = array();
}
$data[$row['id_data']][] = $data_property;
}
return $data;
}
public function get_data_translation($drupal_cache_forms,$db_manager,$application,$use_key_value = false)
{
$result = $db_manager->get_records('data_translation',$this->get_id(),'id_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$data_translation = cls_table_factory::create_instance('data_translation');
$data_translation->fill($row);
if ($use_key_value)
{
$data[$row['id']] = $data_translation;
}
else
{
$data[] = $data_translation;
}
}
return $data;
}
public function get_multi_data_translation($drupal_cache_forms,$db_manager,$application)
{
$result = $db_manager->get_records_by_ids('data_translation',$drupal_cache_forms,'id_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$data_translation = cls_table_factory::create_instance('data_translation');
$data_translation->fill($row);
if (!array_key_exists($data[$row['id_data']]))
{
$data[$row['id_data']] = array();
}
$data[$row['id_data']][] = $data_translation;
}
return $data;
}
public function get_dms($drupal_cache_forms,$db_manager,$application,$use_key_value = false)
{
$result = $db_manager->get_records('dms',$this->get_id(),'id_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$dms = cls_table_factory::create_instance('dms');
$dms->fill($row);
if ($use_key_value)
{
$data[$row['id']] = $dms;
}
else
{
$data[] = $dms;
}
}
return $data;
}
public function get_multi_dms($drupal_cache_forms,$db_manager,$application)
{
$result = $db_manager->get_records_by_ids('dms',$drupal_cache_forms,'id_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$dms = cls_table_factory::create_instance('dms');
$dms->fill($row);
if (!array_key_exists($data[$row['id_data']]))
{
$data[$row['id_data']] = array();
}
$data[$row['id_data']][] = $dms;
}
return $data;
}
public function get_data_relation_id_data1($drupal_cache_forms,$db_manager,$application,$use_key_value = false)
{
$result = $db_manager->get_records('data_relation',$this->get_id(),'id_data1');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$data_relation = cls_table_factory::create_instance('data_relation');
$data_relation->fill($row);
if ($use_key_value)
{
$data[$row['id']] = $data_relation;
}
else
{
$data[] = $data_relation;
}
}
return $data;
}
public function get_multi_data_relation_id_data1($drupal_cache_forms,$db_manager,$application)
{
$result = $db_manager->get_records_by_ids('data_relation',$drupal_cache_forms,'id_data1');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$data_relation = cls_table_factory::create_instance('data_relation');
$data_relation->fill($row);
if (!array_key_exists($data[$row['id_data1']]))
{
$data[$row['id_data1']] = array();
}
$data[$row['id_data1']][] = $data_relation;
}
return $data;
}
public function get_data_relation_id_data2($drupal_cache_forms,$db_manager,$application,$use_key_value = false)
{
$result = $db_manager->get_records('data_relation',$this->get_id(),'id_data2');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$data_relation = cls_table_factory::create_instance('data_relation');
$data_relation->fill($row);
if ($use_key_value)
{
$data[$row['id']] = $data_relation;
}
else
{
$data[] = $data_relation;
}
}
return $data;
}
public function get_multi_data_relation_id_data2($drupal_cache_forms,$db_manager,$application)
{
$result = $db_manager->get_records_by_ids('data_relation',$drupal_cache_forms,'id_data2');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$data_relation = cls_table_factory::create_instance('data_relation');
$data_relation->fill($row);
if (!array_key_exists($data[$row['id_data2']]))
{
$data[$row['id_data2']] = array();
}
$data[$row['id_data2']][] = $data_relation;
}
return $data;
}
public function get_data_property_id_link_data($drupal_cache_forms,$db_manager,$application,$use_key_value = false)
{
$result = $db_manager->get_records('data_property',$this->get_id(),'id_link_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$data_property = cls_table_factory::create_instance('data_property');
$data_property->fill($row);
if ($use_key_value)
{
$data[$row['id']] = $data_property;
}
else
{
$data[] = $data_property;
}
}
return $data;
}
public function get_multi_data_property_id_link_data($drupal_cache_forms,$db_manager,$application)
{
$result = $db_manager->get_records_by_ids('data_property',$drupal_cache_forms,'id_link_data');
if (is_null($result)) return null;
if (count($result) == 0) return null;
require_once('include/data/table_factory/cls_table_factory.php');
$data = array();
while (($row=$db_manager->fetch_by_assoc($result)) !=null)
{
$data_property = cls_table_factory::create_instance('data_property');
$data_property->fill($row);
if (!array_key_exists($data[$row['id_link_data']]))
{
$data[$row['id_link_data']] = array();
}
$data[$row['id_link_data']][] = $data_property;
}
return $data;
}
}
?>
| gpl-2.0 |
NagVis/nagvis | share/server/core/classes/CoreAuthorisationModMySQL.php | 1472 | <?php
/*******************************************************************************
*
* CoreAuthorisationModMySQL.php - Authorsiation module based on MySQL
*
* Copyright (c) 2004-2016 NagVis Project (Contact: info@nagvis.org)
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* 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.
*
******************************************************************************/
class CoreAuthorisationModMySQL extends CoreAuthorisationModPDO {
public function getConfig() {
return array(
'driver' => 'mysql',
'params' => array(
'dbhost' => cfg('auth_mysql', 'dbhost'),
'dbport' => cfg('auth_mysql', 'dbport'),
'dbname' => cfg('auth_mysql', 'dbname'),
),
'username' => cfg('auth_mysql', 'dbuser'),
'password' => cfg('auth_mysql', 'dbpass'),
);
}
}
?>
| gpl-2.0 |
uqlibrary/fez | public/researcherid_proxy.php | 5146 | <?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | Fez - Digital Repository System |
// +----------------------------------------------------------------------+
// | Copyright (c) 2005, 2006, 2007 The University of Queensland, |
// | Australian Partnership for Sustainable Repositories, |
// | eScholarship Project |
// | |
// | Some of the Fez code was derived from Eventum (Copyright 2003, 2004 |
// | MySQL AB - http://dev.mysql.com/downloads/other/eventum/ - GPL) |
// | |
// | 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: |
// | |
// | Free Software Foundation, Inc. |
// | 59 Temple Place - Suite 330 |
// | Boston, MA 02111-1307, USA. |
// +----------------------------------------------------------------------+
// | Authors: Andrew Martlew <a.martlew@library.uq.edu.au> |
// +----------------------------------------------------------------------+
//
include_once('config.inc.php');
include_once(APP_INC_PATH . "class.db_api.php");
include_once(APP_INC_PATH . "class.author.php");
include_once(APP_INC_PATH . "class.researcherid.php");
include_once(APP_INC_PATH . "class.auth.php");
include_once(APP_INC_PATH . "class.user.php");
Auth::checkAuthentication(APP_SESSION);
$user = Auth::getUsername();
$isAdministrator = User::isUserAdministrator($user);
$isSuperAdministrator = User::isUserSuperAdministrator($user);
if (!($isAdministrator || $isSuperAdministrator)) {
exit;
}
// Docs: http://framework.zend.com/manual/1.11/en/zend.json.server.html
$server = new Zend_Json_Server();
// Indicate what functionality is available
$server->setClass('ResearcherIDProxy');
if ('GET' == $_SERVER['REQUEST_METHOD']) {
// Indicate the URL endpoint, and the JSON-RPC version used:
$server->setTarget($_SERVER["SCRIPT_NAME"])
->setEnvelope(Zend_Json_Server_Smd::ENV_JSONRPC_2);
// Grab the SMD. SMD = Service Mapping Description, a JSON schema that defines how a client can interact with a particular web service
$smd = $server->getServiceMap();
// Set Dojo compatibility:
$smd->setDojoCompatible(true);
// Return the SMD to the client
header('Content-Type: application/json');
echo $smd;
return;
}
// Handle the request
$server->handle();
class ResearcherIDProxy
{
/**
* Creates a ResearcherID account for an author
*
* @param string $aut_id ID of the author to create a ResearcherID account for
* @param string $alt_email Optional alternate email to register with
*
* @return string
*/
public function register($aut_id, $alt_email)
{
$log = FezLog::get();
$db = DB_API::get();
if (ResearcherID::profileUpload($aut_id, $alt_email)) {
Author::setResearcherIdByAutId($aut_id, '-1');
return 'true';
} else {
return 'false';
}
}
/**
* Downloads publications for a researcher using the ResearcherID Batch Download Service
* @param string $researcher_id The ResearcherID to download publications for
* @return string
*/
public function download($researcher_id)
{
$log = FezLog::get();
$db = DB_API::get();
$dateAddedFrom[0] = '2007';
$dateAddedFrom[1] = '01';
$dateAddedFrom[2] = '01';
if (ResearcherID::downloadRequest(array($researcher_id), 'researcherIDs', 'researcherID', $dateAddedFrom)) {
return 'true';
} else {
return 'false';
}
}
/**
* Uploads publications for a researcher using the ResearcherID Batch Upload Service
* @param string $aut_id ID of the author to upload publications for
* @return string
*/
public function upload($aut_id)
{
$log = FezLog::get();
$db = DB_API::get();
if (ResearcherID::publicationsUpload(array($aut_id))) {
return 'true';
} else {
return 'false';
}
}
}
| gpl-2.0 |
madbosun/aces-ansatz | src/core/io_utils.cpp | 2931 | /*! io_utils.cpp Contains routines to read and write primitive types and arrays from
* binary and text files.
*
*
* Created on: Jul 7, 2013
* Author: Beverly Sanders
*/
#include "core.h"
#include "io_utils.h"
#include <stdexcept>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include "abort.h"
namespace setup{
void ReadFileExists(const std::string& name) {
struct stat buffer;
if (stat (name.c_str(), &buffer)) {
std::cout << "File " << name << " does not exist" << std::endl;
all_abort();
}
}
/* Default constructors and destructors for OutputFile */
OutputStream::OutputStream():stream_(NULL){}
OutputStream::~OutputStream(){
if(stream_) {
//stream_->close();
delete stream_;
}
}
/* BinaryOutputFile */
BinaryOutputFile::BinaryOutputFile(const std::string& name) : file_name_(name){
file_stream_ = new std::ofstream(name.c_str(), std::ios::binary | std::ios::trunc);
stream_ = file_stream_;
if (!file_stream_->is_open()){
std::cout << stream_->eof() << "\t" << stream_->fail() << "\t" << stream_->bad();
std :: cerr << "File "<< name <<" could not be opened !";
exit(-1);
}
}
BinaryOutputFile::~BinaryOutputFile(){
if (file_stream_->is_open())
file_stream_->close();
}
void BinaryOutputStream::write_string(const std::string& aString) {
//trim trailing spaces
size_t endpos = aString.find_last_not_of(" ");
std::string trimmed = (endpos == std::string::npos) ? "" : aString.substr(0,endpos+1);
int length = (int) trimmed.length() + 1; //extra for null
write_int(length);
//std::cout << "writing string " << trimmed << ", length=" << length << std::endl;
stream_->write(trimmed.c_str(), length);
}
void BinaryOutputStream::write_int( int value) {
stream_->write(reinterpret_cast<char *>(&value), sizeof(int));
}
void BinaryOutputStream::write_int_array(int size, int values[]) {
write_int(size);
stream_->write(reinterpret_cast<char *>(values), sizeof(int) * size);
}
void BinaryOutputStream::write_double(double value) {
stream_->write(reinterpret_cast<char *>(&value), sizeof(double));
}
void BinaryOutputStream::write_double_array(int size, double values[]) {
write_int(size);
stream_->write( reinterpret_cast<char *>(values), sizeof(double) * size);
}
void BinaryOutputStream::write_size_t_val(size_t value) {
stream_->write( reinterpret_cast<char *>(&value), sizeof(size_t));
}
BinaryOutputByteStream::BinaryOutputByteStream(char *char_stream, int size){
char_stream_ = new CharStreamBuf(char_stream, char_stream + size);
this->stream_ = new std::ostream(char_stream_);
}
BinaryOutputByteStream::~BinaryOutputByteStream(){
delete char_stream_;
}
InputStream::InputStream():stream_(NULL){}
InputStream::~InputStream(){
if ((stream_)) {
//if (stream->is_open()){ stream->close();}
delete stream_;
}
}
} /*namespace setup*/
| gpl-2.0 |
drunomics/service-utils | tests/src/user/SharedTempStoreFactoryTraitTest.php | 2110 | <?php
namespace drunomics\ServiceUtils\Tests\user;
use drunomics\ServiceUtils\user\SharedTempStoreFactoryTrait;
use Drupal\Core\DependencyInjection\Container;
use Drupal\user\SharedTempStoreFactory;
/**
* @coversDefaultClass \drunomics\ServiceUtils\user\SharedTempStoreFactoryTrait
* @group ServiceUtils
*/
class SharedTempStoreFactoryTraitTest extends \PHPUnit_Framework_TestCase {
use SharedTempStoreFactoryTrait;
/**
* The id of the trait's service.
*
* @var string
*/
protected $serviceId = 'user.shared_tempstore';
/**
* @covers ::getSharedTempStoreFactory
*/
public function testGetter() {
// Verify the container is used once and the right service is returned.
$service = $this->mockContainerWithFakeService(['calls' => 1]);
$this->assertsame($service, $this->getSharedTempStoreFactory());
// Multiple calls should fetch the service from the container only once.
$this->getSharedTempStoreFactory();
}
/**
* @covers ::setFileUsage
*/
public function testSetter() {
// Verify the set service is returned.
$this->mockContainerWithFakeService(['calls' => 0]);
$service = $this->prophesize()
->willExtend(SharedTempStoreFactory::class)
->reveal();
$this->setSharedTempStoreFactory($service);
$this->assertsame($service, $this->getSharedTempStoreFactory());
}
/**
* Helper to mock the container with a stub service.
*
* @param int[] $options
* An array with the following keys:
* - calls: The number of calls to get the service the mocked container
* expects.
*
* @return object
* The fake service returned by the container.
*/
protected function mockContainerWithFakeService(array $options) {
$service = new \Stdclass();
$container = $this->prophesize(Container::class);
$prophecy = $container->get($this->serviceId);
/** @var \Prophecy\Prophecy\MethodProphecy $prophecy */
$prophecy->shouldBeCalledTimes($options['calls']);
$prophecy->willReturn($service);
\Drupal::setContainer($container->reveal());
return $service;
}
}
| gpl-2.0 |
Batname/lifehouse.com.ua | wp-content/themes/lotus/admin/include/price/assets/js/pt.js | 7428 | ;(function($){
/////////////////// data ///////////////////////
var blankColumn,restoreData,removeIndex,$confirmDialog,removeQue;
$confirmDialog = $("div.pb_confirm");
blankColumn = [{ name:"", price:"", period:"", desc:"", rows:[], btnLabel:"", btnLink:"", type:"regular", color:"" }];
restoreData = blankColumn;
try{
if(pt_data.length) restoreData = pt_data;// pt_data is stored data on server
}catch(e){ console.log(e); }
////////////// Custome Binder /////////////////
///////////////// Model ///////////////////////
function ColumnModel(obj){
var self, _rows;
self = this;
self.name = ko.observable("");
self.price = ko.observable("");
self.period = ko.observable("");
self.desc = ko.observable("");
self.rows = ko.observableArray([]);
self.btnLabel = ko.observable("");
self.btnLink = ko.observable("");
self.type = ko.observable("regular");
self.color = ko.observable("");
for(prop in obj){
if(prop != "rows")
self[prop](obj[prop]);
else{
self.rows([]);PtViewModel.rows([]);
for(var i=0,len=obj["rows"].length;i<len;++i){
PtViewModel.rows.push("");
self.rows.push({name:obj["rows"][i]});
}
}
}
self.remove = function(){
removeQue = this;
$confirmDialog.css({ display:"block" }).data("type","col");
//PtViewModel.columns.remove(this);
};
self.addRow = function(data){
self.rows.push({name:data});
};
self.onNewRowAdded = ko.computed(function(){
//console.log(getStorableData());
var cache = self.rows();
// this is size of viewModel observer
var len = this.rows().length;//console.log(len,cache.length, removeIndex);
// if the size of observers are not the same,update it
if(len > cache.length){
while(self.rows().length != len)
self.addRow("");
}else if(len < cache.length){
if(removeIndex == undefined) return;
cache.splice(removeIndex,1);
self.rows(cache);
}
}, PtViewModel);
};
/////////////// View Model ////////////////////
PtViewModel = {
columns : ko.observableArray([]),
rows : ko.observableArray([])
};
PtViewModel.addNewCol = function(item){
var newItem = new ColumnModel();
PtViewModel.columns.push(newItem);
}
PtViewModel.addNewRow = function(item){
PtViewModel.rows.push("");
}
PtViewModel.removeRow = function(elem, event){
removeIndex = $(event.target.parentElement).index();
$confirmDialog.css({ display:"block" }).data("type","row");
}
PtViewModel.removeRowNow = function(){
PtViewModel.rows().splice(removeIndex, 1);
PtViewModel.rows.valueHasMutated();
}
// slides up and then removes column
PtViewModel.hideColumn = function(elem) {
if (elem.nodeType === 1) {
$elem = $(elem);
$elem.animate({width:'toggle'},500, function() { $elem.remove(); });
}
};
ko.applyBindings(PtViewModel);
////////////// functions //////////////////////
function getStorableData(){
var cols = PtViewModel.columns();
var res = [];
for(var i=0,len=cols.length;i<len;++i){
var obj = {};
obj["name"] = cols[i].name();
obj["price"] = cols[i].price();
obj["period"] = cols[i].period();
obj["desc"] = cols[i].desc();
obj["btnLabel"] = cols[i].btnLabel();
obj["btnLink"] = cols[i].btnLink();
obj["type"] = cols[i].type();
obj["color"] = cols[i].color();
obj["rows"] = [];
var rows = cols[i].rows();
for(var j=0,l=rows.length;j<l;++j){
obj.rows.push(rows[j].name);
}
res.push(obj);
}
return res;
};
function restoreColumns(columnsArray){
PtViewModel.rows([]);
for(var i=0,len=columnsArray.length;i<len;++i){
restoreColumn(columnsArray[i]);
}
};
function restoreColumn (columnObj){
var newItem = new ColumnModel(columnObj);
PtViewModel.columns.push(newItem);
};
restoreColumns(restoreData);
////////////// confirm dialog //////////////////
$confirmDialog.find("a").on("click", function(event){
event.preventDefault();
if(event.target.getAttribute("data-name") == "yes"){
if($confirmDialog.data("type") == "col")
PtViewModel.columns.remove(removeQue);
else if($confirmDialog.data("type") == "row")
PtViewModel.removeRowNow();
else
console.log("no confirm data recieved.");
}
$confirmDialog.css({ display:"none" });
});
//>>>>>>>>>>>>>>>>>>>>>> End of MVVM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<//
//>>>>>>>>>>>>>>>>>>>>>> Edit Page modification <<<<<<<<<<<<<<<<<<<<//
/// select one column layout on page load ////////
function axiom_lock_slider_screen_options(){
// get screen optipn panel
var $screen_settings = $('form#adv-settings');
// select one column layout on page load
setTimeout(function(){
$screen_settings.find('.columns-prefs input[type="radio"]').eq(0).trigger('click');
}, 100);
}
axiom_lock_slider_screen_options();
/// remove premalink slug ////////////////////////
$slug_box = $('#edit-slug-box');
$slug_box.remove();
/// send data via ajax on click save btn /////////
$('#save_box.av3_container .save_slides').on('click', function(event){
event.preventDefault();
try{
var data = {
post_id: pt_id,
nonce : pt_nonce,
action: 'pt_data',
columns: getStorableData(),
post_title : $('#titlediv #title').first().val()
}
}
catch(err){ console.log("Post ID not found"); return; }
console.log(data);
var $savebox = $(this).closest('#save_box');
$savebox.find('.ajax-loading')
.css({ 'display':'inline','visibility':'visible'})
.siblings("span").text("Saving Changes ..");
$.post(
axiom.ajaxurl,
data ,
function(res){
console.log(res);
// if data sent successfuly
if(res.success == true){
$savebox.find('.ajax-loading').css({ 'display':'inline','visibility':'hidden'})
.siblings("span").text("Data Saved");;
}else
console.log("Error From server");
},
"json");
});
})(jQuery);
| gpl-2.0 |
JorgeMoralesMV/cydia-repo-codes | detect_ios.php | 1093 | <?php
///Detector iOS by @JorgeMoralesMV
//iOS 7
if (strstr($_SERVER['HTTP_USER_AGENT'], 'OS 7_0')) { echo "iOS 7.0"; }
elseif (strstr($_SERVER['HTTP_USER_AGENT'], 'OS 7_0_1')) { echo "iOS 7.0.1"; }
elseif (strstr($_SERVER['HTTP_USER_AGENT'], 'OS 7_0_2')) { echo "iOS 7.0.2"; }
elseif (strstr($_SERVER['HTTP_USER_AGENT'], 'OS 7_0_3')) { echo "iOS 7.0.3"; }
elseif (strstr($_SERVER['HTTP_USER_AGENT'], 'OS 7_0_4')) { echo "iOS 7.0.4"; }
elseif (strstr($_SERVER['HTTP_USER_AGENT'], 'OS 7_0_5')) { echo "iOS 7.0.5"; }
elseif (strstr($_SERVER['HTTP_USER_AGENT'], 'OS 7_0_6')) { echo "iOS 7.0.6"; }
//iOS 8
elseif (strstr($_SERVER['HTTP_USER_AGENT'], 'OS 8_0')) { echo "iOS 8.0"; }
elseif (strstr($_SERVER['HTTP_USER_AGENT'], 'OS 8_0_1')) { echo "iOS 8.0.1"; }
elseif (strstr($_SERVER['HTTP_USER_AGENT'], 'OS 8_0_2')) { echo "iOS 8.0.2"; }
elseif (strstr($_SERVER['HTTP_USER_AGENT'], 'OS 8_1')) { echo "iOS 8.1"; }
elseif (strstr($_SERVER['HTTP_USER_AGENT'], 'OS 8_1_1')) { echo "iOS 8.1.1"; }
elseif (strstr($_SERVER['HTTP_USER_AGENT'], 'OS 8_1_2')) { echo "iOS 8.1.2"; }
else {
echo "N/A";
}
?> | gpl-2.0 |
andela-sdamian/make-me-shot | app/helpers/application_helper.rb | 375 | module ApplicationHelper
def full_url(url)
request.base_url + '/' + url
end
def notify
if flash[:notice].present?
msg = flash[:notice]
toast = <<-NOTICE
<script>Materialize.toast("#{msg}", 3000)</script>
NOTICE
toast.html_safe
end
end
def active_class(link_path, css)
current_page?(link_path) ? css : ''
end
end
| gpl-2.0 |
freestyleinternet/oxford-cartographers | wp-content/themes/oxford-cartographers/page-blog.php | 6692 | <?php
/*
Template Name: News/Blog
*/
get_header(); ?>
<div class="pageContent">
<main role="main">
<div class="wrapper">
<section>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php get_search_form(); ?>
<?php the_content(); ?>
<?php endwhile; endif; ?>
<div class="posts">
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array( 'post_type' => 'post', 'orderby' => 'date', 'order' => 'DESC', 'paged' => $paged);
$wp_query = new WP_Query($args);
while ( have_posts() ) : the_post();
?>
<article>
<a href="<?php echo get_permalink(); ?>">
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail('newsthumb', array('class' => 'alignleft'));
}
?>
<h1><?php the_title(); ?></h1>
<h2><?php the_time('jS M Y'); ?></h2>
<p><?php echo truncate($post->post_content, 180); ?> <span><img src="<?php bloginfo('template_directory'); ?>/assets/images/small-right-arrow-black.svg"></span></p>
</a>
</article>
<?php endwhile; ?>
<?php if(function_exists('wp_paginate')) {
wp_paginate();
} ?>
</div>
<div class="sharethisbar"><?php get_template_part( 'templates/partials/inc-socialbuttons'); ?></div>
</section>
<?php
$result = '';
$subscribeError = '';
if (isset($_POST['email']) AND $_POST['email'] != '')
{
include("lib/class.mailchimp.php");
// in mailchimp this is held in account > api
$api = new MCAPI('89d78b2b770f72e8b9e73052e56494c9-us5');
$merge_vars = array
(
'FNAME' => $_POST['lname'],
'LNAME' => $_POST['fname'],
'MPOSITION' => $_POST['position'],
'MCOMPANY' => $_POST['company'],
'MTEL' => $_POST['mtel'],
'EMAIL' => $_POST['email']
);
// in mailchimp this is held in the lists > settings > list settings and unique api
$result = $api->listSubscribe('ad51084415', $_POST['email'], $merge_vars);
$subscribeError = '';
if ($api->errorCode)
{
$subscribeError = $api->errorMessage;
}
}
?>
<aside>
<div class="sharethisbar"><?php get_template_part( 'templates/partials/inc-socialbuttons'); ?></div>
<div class="signup">
<h2>SIGN UP FOR OUR E-NEWS</h2>
<?php if ($subscribeError == TRUE) { ?><p class="errormsg"><?php echo $subscribeError; ?></p><?php } ?>
<?php if ($subscribeError !=='')
{
?>
<?php
}
?>
<?php if ($result == TRUE) { ?>
<div class="thankyou">
<p>
Thank you for signing up to our mailing list.<br /><br />
A confirmation email has been sent to the address provided.
Please click on the link in that email to confirm your subscription.
</p>
</div>
<?php
}
else
{
?>
<form method="post" action="" />
<label>First Name</label>
<input name="fname" type="text" required>
<label>Last Name</label>
<input name="lname" type="text" required>
<label>Position</label>
<input name="position" type="text">
<label>Company</label>
<input name="company" type="text">
<label>Email</label>
<input name="email" id="email" type="email" required/>
<label>Telephone</label>
<input name="mtel" type="text">
<input class="yellowimg rightarrow" type="submit" value="Submit">
</form>
<?php } ?>
</div>
<!--<div class="col homeblock">
<a href="<?php the_field('link_to_page', 6); ?>">
<img class="absolute" src="<?php the_field('featured_image', 6); ?>">
<h2>OUR PRINCIPLES</h2>
<p><?php the_field('our_principles_introduction_text', 6); ?></p>
<span class="yellowimg arrow thinner">Read More</span>
</a>
</div>-->
<?php
$sidebox = get_field('show_sidebox', 9);
if( in_array('FWT Update', $sidebox) ) {
?>
<div class="homeblock first update">
<a href="<?php bloginfo('url'); ?>/news/">
<img src="<?php the_field('fwt_update_featured_image', 6); ?>">
<h2>FWT UPDATE</h2>
<p><?php the_field('fwt_update_box_text', 6); ?></p>
<span class="yellowimg thinner">News</span>
</a>
</div>
<?php
}
if ( in_array('Contact us', $sidebox)) {
?>
<div class="col homeblock contactblock">
<a href="<?php the_field('contact_us_map_link', 6); ?>" target="_blank">
<h2>CONTACT US</h2>
<span class="yellowimg thinner">View</span>
</a>
</div>
<?php
}
if ( in_array('Our principles', $sidebox)) {
?>
<div class="col homeblock">
<a href="<?php the_field('link_to_page', 6); ?>">
<img class="absolute" src="<?php the_field('featured_image', 6); ?>">
<h2>OUR PRINCIPLES</h2>
<p><?php the_field('our_principles_introduction_text', 6); ?></p>
<span class="yellowimg thinner">Read More</span>
</a>
</div>
<?php
}
?>
</aside>
</div>
</main> <!-- /#main -->
<?php get_footer(); ?>
| gpl-2.0 |
SubwayRocketTeam/Prototype | cocos2d/cocos/2d/CCTextFieldTTF.cpp | 10022 | /****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "2d/CCTextFieldTTF.h"
#include "base/CCDirector.h"
NS_CC_BEGIN
static int _calcCharCount(const char * text)
{
int n = 0;
char ch = 0;
while ((ch = *text))
{
CC_BREAK_IF(! ch);
if (0x80 != (0xC0 & ch))
{
++n;
}
++text;
}
return n;
}
//////////////////////////////////////////////////////////////////////////
// constructor and destructor
//////////////////////////////////////////////////////////////////////////
TextFieldTTF::TextFieldTTF()
: _delegate(0)
, _charCount(0)
, _inputText("")
, _placeHolder("") // prevent Label initWithString assertion
, _secureTextEntry(false)
, _colorText(Color4B::WHITE)
{
_colorSpaceHolder.r = _colorSpaceHolder.g = _colorSpaceHolder.b = 127;
_colorSpaceHolder.a = 255;
}
TextFieldTTF::~TextFieldTTF()
{
}
//////////////////////////////////////////////////////////////////////////
// static constructor
//////////////////////////////////////////////////////////////////////////
TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const std::string& placeholder, const Size& dimensions, TextHAlignment alignment, const std::string& fontName, float fontSize)
{
TextFieldTTF *ret = new (std::nothrow) TextFieldTTF();
if(ret && ret->initWithPlaceHolder("", dimensions, alignment, fontName, fontSize))
{
ret->autorelease();
if (placeholder.size()>0)
{
ret->setPlaceHolder(placeholder);
}
return ret;
}
CC_SAFE_DELETE(ret);
return nullptr;
}
TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize)
{
TextFieldTTF *ret = new (std::nothrow) TextFieldTTF();
if(ret && ret->initWithPlaceHolder("", fontName, fontSize))
{
ret->autorelease();
if (placeholder.size()>0)
{
ret->setPlaceHolder(placeholder);
}
return ret;
}
CC_SAFE_DELETE(ret);
return nullptr;
}
//////////////////////////////////////////////////////////////////////////
// initialize
//////////////////////////////////////////////////////////////////////////
bool TextFieldTTF::initWithPlaceHolder(const std::string& placeholder, const Size& dimensions, TextHAlignment alignment, const std::string& fontName, float fontSize)
{
_placeHolder = placeholder;
setDimensions(dimensions.width,dimensions.height);
setSystemFontName(fontName);
setSystemFontSize(fontSize);
setAlignment(alignment,TextVAlignment::CENTER);
Label::setTextColor(_colorSpaceHolder);
Label::setString(_placeHolder);
return true;
}
bool TextFieldTTF::initWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize)
{
_placeHolder = std::string(placeholder);
setSystemFontName(fontName);
setSystemFontSize(fontSize);
Label::setTextColor(_colorSpaceHolder);
Label::setString(_placeHolder);
return true;
}
//////////////////////////////////////////////////////////////////////////
// IMEDelegate
//////////////////////////////////////////////////////////////////////////
bool TextFieldTTF::attachWithIME()
{
bool ret = IMEDelegate::attachWithIME();
if (ret)
{
// open keyboard
auto pGlView = Director::getInstance()->getOpenGLView();
if (pGlView)
{
pGlView->setIMEKeyboardState(true);
}
}
return ret;
}
bool TextFieldTTF::detachWithIME()
{
bool ret = IMEDelegate::detachWithIME();
if (ret)
{
// close keyboard
auto glView = Director::getInstance()->getOpenGLView();
if (glView)
{
glView->setIMEKeyboardState(false);
}
}
return ret;
}
bool TextFieldTTF::canAttachWithIME()
{
return (_delegate) ? (! _delegate->onTextFieldAttachWithIME(this)) : true;
}
bool TextFieldTTF::canDetachWithIME()
{
return (_delegate) ? (! _delegate->onTextFieldDetachWithIME(this)) : true;
}
void TextFieldTTF::insertText(const char * text, size_t len)
{
std::string insert(text, len);
// insert \n means input end
int pos = static_cast<int>(insert.find('\n'));
if ((int)insert.npos != pos)
{
len = pos;
insert.erase(pos);
}
if (len > 0)
{
if (_delegate && _delegate->onTextFieldInsertText(this, insert.c_str(), len))
{
// delegate doesn't want to insert text
return;
}
_charCount += _calcCharCount(insert.c_str());
std::string sText(_inputText);
sText.append(insert);
setString(sText);
}
if ((int)insert.npos == pos) {
return;
}
// '\n' inserted, let delegate process first
if (_delegate && _delegate->onTextFieldInsertText(this, "\n", 1))
{
return;
}
// if delegate hasn't processed, detach from IME by default
detachWithIME();
}
void TextFieldTTF::deleteBackward()
{
size_t len = _inputText.length();
if (! len)
{
// there is no string
return;
}
// get the delete byte number
size_t deleteLen = 1; // default, erase 1 byte
while(0x80 == (0xC0 & _inputText.at(len - deleteLen)))
{
++deleteLen;
}
if (_delegate && _delegate->onTextFieldDeleteBackward(this, _inputText.c_str() + len - deleteLen, static_cast<int>(deleteLen)))
{
// delegate doesn't wan't to delete backwards
return;
}
// if all text deleted, show placeholder string
if (len <= deleteLen)
{
_inputText = "";
_charCount = 0;
Label::setTextColor(_colorSpaceHolder);
Label::setString(_placeHolder);
return;
}
// set new input text
std::string text(_inputText.c_str(), len - deleteLen);
setString(text);
}
const std::string& TextFieldTTF::getContentText()
{
return _inputText;
}
void TextFieldTTF::setTextColor(const Color4B &color)
{
_colorText = color;
if (_inputText.length() > 0) {
Label::setTextColor(_colorText);
}
}
void TextFieldTTF::visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags)
{
if (_delegate && _delegate->onVisit(this,renderer,parentTransform,parentFlags))
{
return;
}
Label::visit(renderer,parentTransform,parentFlags);
}
const Color4B& TextFieldTTF::getColorSpaceHolder()
{
return _colorSpaceHolder;
}
void TextFieldTTF::setColorSpaceHolder(const Color3B& color)
{
_colorSpaceHolder.r = color.r;
_colorSpaceHolder.g = color.g;
_colorSpaceHolder.b = color.b;
_colorSpaceHolder.a = 255;
if (0 == _inputText.length())
{
Label::setTextColor(_colorSpaceHolder);
}
}
void TextFieldTTF::setColorSpaceHolder(const Color4B& color)
{
_colorSpaceHolder = color;
if (0 == _inputText.length()) {
Label::setTextColor(_colorSpaceHolder);
}
}
//////////////////////////////////////////////////////////////////////////
// properties
//////////////////////////////////////////////////////////////////////////
// input text property
void TextFieldTTF::setString(const std::string &text)
{
static char bulletString[] = {(char)0xe2, (char)0x80, (char)0xa2, (char)0x00};
std::string displayText;
size_t length;
if (text.length()>0)
{
_inputText = text;
displayText = _inputText;
if (_secureTextEntry)
{
displayText = "";
length = _inputText.length();
while (length)
{
displayText.append(bulletString);
--length;
}
}
}
else
{
_inputText = "";
}
// if there is no input text, display placeholder instead
if (0 == _inputText.length())
{
Label::setTextColor(_colorSpaceHolder);
Label::setString(_placeHolder);
}
else
{
Label::setTextColor(_colorText);
Label::setString(displayText);
}
_charCount = _calcCharCount(_inputText.c_str());
}
const std::string& TextFieldTTF::getString() const
{
return _inputText;
}
// place holder text property
void TextFieldTTF::setPlaceHolder(const std::string& text)
{
_placeHolder = text;
if (0 == _inputText.length())
{
Label::setTextColor(_colorSpaceHolder);
Label::setString(_placeHolder);
}
}
const std::string& TextFieldTTF::getPlaceHolder() const
{
return _placeHolder;
}
// secureTextEntry
void TextFieldTTF::setSecureTextEntry(bool value)
{
if (_secureTextEntry != value)
{
_secureTextEntry = value;
setString(_inputText);
}
}
bool TextFieldTTF::isSecureTextEntry()
{
return _secureTextEntry;
}
NS_CC_END
| gpl-2.0 |