repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
lamsfoundation/lams | 3rdParty_sources/hibernate-core/org/hibernate/hql/internal/ast/SqlGenerator.java | 11995 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.hql.internal.ast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.hibernate.NullPrecedence;
import org.hibernate.QueryException;
import org.hibernate.dialect.function.SQLFunction;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.hql.internal.antlr.SqlGeneratorBase;
import org.hibernate.hql.internal.antlr.SqlTokenTypes;
import org.hibernate.hql.internal.ast.tree.FromElement;
import org.hibernate.hql.internal.ast.tree.FunctionNode;
import org.hibernate.hql.internal.ast.tree.Node;
import org.hibernate.hql.internal.ast.tree.ParameterContainer;
import org.hibernate.hql.internal.ast.tree.ParameterNode;
import org.hibernate.hql.internal.ast.util.ASTPrinter;
import org.hibernate.hql.internal.ast.util.TokenPrinters;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.CollectionHelper;
import org.hibernate.param.ParameterSpecification;
import org.hibernate.type.Type;
import antlr.RecognitionException;
import antlr.collections.AST;
/**
* Generates SQL by overriding callback methods in the base class, which does
* the actual SQL AST walking.
*
* @author Joshua Davis
* @author Steve Ebersole
*/
public class SqlGenerator extends SqlGeneratorBase implements ErrorReporter {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( SqlGenerator.class );
public static boolean REGRESSION_STYLE_CROSS_JOINS;
/**
* all append invocations on the buf should go through this Output instance variable.
* The value of this variable may be temporarily substituted by sql function processing code
* to catch generated arguments.
* This is because sql function templates need arguments as separate string chunks
* that will be assembled into the target dialect-specific function call.
*/
private SqlWriter writer = new DefaultWriter();
private ParseErrorHandler parseErrorHandler;
private SessionFactoryImplementor sessionFactory;
private LinkedList<SqlWriter> outputStack = new LinkedList<SqlWriter>();
private List<ParameterSpecification> collectedParameters = new ArrayList<ParameterSpecification>();
// handle trace logging ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private int traceDepth;
@Override
public void traceIn(String ruleName, AST tree) {
if ( !LOG.isTraceEnabled() ) {
return;
}
if ( inputState.guessing > 0 ) {
return;
}
String prefix = StringHelper.repeat( '-', ( traceDepth++ * 2 ) ) + "-> ";
String traceText = ruleName + " (" + buildTraceNodeName( tree ) + ")";
LOG.trace( prefix + traceText );
}
private String buildTraceNodeName(AST tree) {
return tree == null
? "???"
: tree.getText() + " [" + TokenPrinters.SQL_TOKEN_PRINTER.getTokenTypeName( tree.getType() ) + "]";
}
@Override
public void traceOut(String ruleName, AST tree) {
if ( !LOG.isTraceEnabled() ) {
return;
}
if ( inputState.guessing > 0 ) {
return;
}
String prefix = "<-" + StringHelper.repeat( '-', ( --traceDepth * 2 ) ) + " ";
LOG.trace( prefix + ruleName );
}
public List<ParameterSpecification> getCollectedParameters() {
return collectedParameters;
}
@Override
protected void out(String s) {
if ( exprs.size() > 1 ) {
super.out( s );
}
else {
writer.clause( s );
}
}
@Override
protected void out(AST n) {
if ( n instanceof Node ) {
out( ( (Node) n ).getRenderText( sessionFactory ) );
}
else {
super.out( n );
}
if ( n instanceof ParameterNode ) {
collectedParameters.add( ( (ParameterNode) n ).getHqlParameterSpecification() );
}
else if ( n instanceof ParameterContainer ) {
if ( ( (ParameterContainer) n ).hasEmbeddedParameters() ) {
ParameterSpecification[] specifications = ( (ParameterContainer) n ).getEmbeddedParameters();
if ( specifications != null ) {
collectedParameters.addAll( Arrays.asList( specifications ) );
}
}
}
}
@Override
protected void betweenFunctionArguments() {
writer.betweenFunctionArguments();
}
@Override
public void reportError(RecognitionException e) {
parseErrorHandler.reportError( e );
}
@Override
public void reportError(String s) {
parseErrorHandler.reportError( s );
}
@Override
public void reportWarning(String s) {
parseErrorHandler.reportWarning( s );
}
public ParseErrorHandler getParseErrorHandler() {
return parseErrorHandler;
}
public SqlGenerator(SessionFactoryImplementor sfi) {
super();
parseErrorHandler = new ErrorTracker();
sessionFactory = sfi;
}
public String getSQL() {
return getStringBuilder().toString();
}
@Override
protected void optionalSpace() {
int c = getLastChar();
switch ( c ) {
case -1:
return;
case ' ':
return;
case ')':
return;
case '(':
return;
default:
out( " " );
}
}
@Override
protected void beginFunctionTemplate(AST node, AST nameNode) {
// NOTE for AGGREGATE both nodes are the same; for METHOD the first is the METHOD, the second is the
// METHOD_NAME
FunctionNode functionNode = (FunctionNode) node;
SQLFunction sqlFunction = functionNode.getSQLFunction();
if ( sqlFunction == null ) {
// if SQLFunction is null we just write the function out as it appears in the hql statement
super.beginFunctionTemplate( node, nameNode );
}
else {
// this function has a registered SQLFunction -> redirect output and catch the arguments
outputStack.addFirst( writer );
if ( node.getType() == CAST ) {
writer = new CastFunctionArguments();
}
else {
writer = new StandardFunctionArguments();
}
}
}
@Override
protected void endFunctionTemplate(AST node) {
FunctionNode functionNode = (FunctionNode) node;
SQLFunction sqlFunction = functionNode.getSQLFunction();
if ( sqlFunction == null ) {
super.endFunctionTemplate( node );
}
else {
final Type functionType = functionNode.getFirstArgumentType();
// this function has a registered SQLFunction -> redirect output and catch the arguments
FunctionArgumentsCollectingWriter functionArguments = (FunctionArgumentsCollectingWriter) writer;
writer = outputStack.removeFirst();
out( sqlFunction.render( functionType, functionArguments.getArgs(), sessionFactory ) );
}
}
// --- Inner classes (moved here from sql-gen.g) ---
/**
* Writes SQL fragments.
*/
interface SqlWriter {
void clause(String clause);
void betweenFunctionArguments();
}
interface FunctionArgumentsCollectingWriter extends SqlWriter {
public List getArgs();
}
/**
* SQL function processing code redirects generated SQL output to an instance of this class
* which catches function arguments.
*/
static class StandardFunctionArguments implements FunctionArgumentsCollectingWriter {
private int argInd;
private final List<String> args = new ArrayList<String>( 3 );
@Override
public void clause(String clause) {
if ( argInd == args.size() ) {
args.add( clause );
}
else {
args.set( argInd, args.get( argInd ) + clause );
}
}
@Override
public void betweenFunctionArguments() {
++argInd;
}
public List getArgs() {
return args;
}
}
/**
* SQL function processing code redirects generated SQL output to an instance of this class
* which catches function arguments.
*/
static class CastFunctionArguments implements FunctionArgumentsCollectingWriter {
private String castExpression;
private String castTargetType;
private boolean startedType;
@Override
public void clause(String clause) {
if ( startedType ) {
if ( castTargetType == null ) {
castTargetType = clause;
}
else {
castTargetType += clause;
}
}
else {
if ( castExpression == null ) {
castExpression = clause;
}
else {
castExpression += clause;
}
}
}
@Override
public void betweenFunctionArguments() {
if ( startedType ) {
throw new QueryException( "CAST function should only have 2 arguments" );
}
startedType = true;
}
public List getArgs() {
List<String> rtn = CollectionHelper.arrayList( 2 );
rtn.add( castExpression );
rtn.add( castTargetType );
return rtn;
}
}
/**
* The default SQL writer.
*/
class DefaultWriter implements SqlWriter {
@Override
public void clause(String clause) {
getStringBuilder().append( clause );
}
@Override
public void betweenFunctionArguments() {
getStringBuilder().append( ", " );
}
}
public static void panic() {
throw new QueryException( "TreeWalker: panic" );
}
@Override
protected void fromFragmentSeparator(AST a) {
// check two "adjecent" nodes at the top of the from-clause tree
AST next = a.getNextSibling();
if ( next == null || !hasText( a ) ) {
return;
}
FromElement left = (FromElement) a;
FromElement right = (FromElement) next;
///////////////////////////////////////////////////////////////////////
// HACK ALERT !!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Attempt to work around "ghost" ImpliedFromElements that occasionally
// show up between the actual things being joined. This consistently
// occurs from index nodes (at least against many-to-many). Not sure
// if there are other conditions
//
// Essentially, look-ahead to the next FromElement that actually
// writes something to the SQL
while ( right != null && !hasText( right ) ) {
right = (FromElement) right.getNextSibling();
}
if ( right == null ) {
return;
}
///////////////////////////////////////////////////////////////////////
if ( !hasText( right ) ) {
return;
}
if ( right.getType() == ENTITY_JOIN ) {
out( " " );
}
else if ( right.getRealOrigin() == left ||
( right.getRealOrigin() != null && right.getRealOrigin() == left.getRealOrigin() ) ) {
// right represents a joins originating from left; or
// both right and left reprersent joins originating from the same FromElement
if ( right.getJoinSequence() != null && right.getJoinSequence().isThetaStyle() ) {
writeCrossJoinSeparator();
}
else {
out( " " );
}
}
else {
// these are just two unrelated table references
writeCrossJoinSeparator();
}
}
private void writeCrossJoinSeparator() {
if ( REGRESSION_STYLE_CROSS_JOINS ) {
out( ", " );
}
else {
out( sessionFactory.getDialect().getCrossJoinSeparator() );
}
}
@Override
protected void nestedFromFragment(AST d, AST parent) {
// check a set of parent/child nodes in the from-clause tree
// to determine if a comma is required between them
if ( d != null && hasText( d ) ) {
if ( parent != null && hasText( parent ) ) {
// again, both should be FromElements
FromElement left = (FromElement) parent;
FromElement right = (FromElement) d;
if ( right.getRealOrigin() == left ) {
// right represents a joins originating from left...
if ( right.getJoinSequence() != null && right.getJoinSequence().isThetaStyle() ) {
writeCrossJoinSeparator();
}
else {
out( " " );
}
}
else {
// not so sure this is even valid subtree. but if it was, it'd
// represent two unrelated table references...
writeCrossJoinSeparator();
}
}
out( d );
}
}
@Override
protected String renderOrderByElement(String expression, String order, String nulls) {
final NullPrecedence nullPrecedence = NullPrecedence.parse( nulls,
sessionFactory.getSettings()
.getDefaultNullPrecedence()
);
return sessionFactory.getDialect().renderOrderByElement( expression, null, order, nullPrecedence );
}
}
| gpl-2.0 |
Sincerelysynatx/CubeProject | DirectXTest/Cube.cpp | 1381 | #include "Cube.h"
#define DEG2RAD(x) (x * (D3DX_PI / 180.0f)) // Converts degrees to radians
#define RAD2DEG(x) (x * (180.0f / D3DX_PI)) // Converts radians to degrees
#define XRGB(r, g, b) D3DCOLOR_XRGB(r, g, b)
Cube::Cube()
{
}
Cube::Cube(float length, float height, float width, int x, int y, int z, float rotationX, float rotationY, bool render)
{
}
Cube::Cube(int x, int y, int z, bool render)
{
m_x = x;
m_y = y;
m_z = z;
m_render = render;
position.x = x;
position.y = y;
position.z = z;
m_rotationX = 0;
m_rotationY = 0;
}
Cube::~Cube()
{
}
void Cube::render(D3DManager *d3dManager, D3DXMATRIXA16 &bM, D3DXMATRIXA16 &wM, D3DXMATRIXA16 &rM1, D3DXMATRIXA16 &rM2, D3DXMATRIXA16 &tM)
{
if (m_render)
{
wM = bM * *D3DXMatrixRotationX(&rM2, m_rotationX) *
*D3DXMatrixRotationY(&rM1, m_rotationY) *
*D3DXMatrixTranslation(&tM, m_x * 2.0f + position.x, m_y * 2.0f + position.y, m_z * 2.0f + position.z);
d3dManager->getDevice().SetTransform(D3DTS_WORLD, &wM);
for (int i = 0; i < 6; i++)
d3dManager->getDevice().DrawIndexedPrimitive(D3DPT_TRIANGLESTRIP, 0, 0, 8, i * 4, 2);
}
}
void Cube::update(const float dt)
{
//m_rotationX += DEG2RAD(0.2f * dt);
//m_rotationY += DEG2RAD(0.5f * dt);
}
void Cube::move(const float dt, const float &x, const float &y, const float &z)
{
position.x += x * dt;
position.y += y * dt;
position.z += z * dt;
} | gpl-2.0 |
lukasmonk/lucaschess | Engines/Windows/demolito/src/sort.cc | 2756 | /*
* Demolito, a UCI chess engine.
* Copyright 2015 lucasart.
*
* Demolito 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.
*
* Demolito 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 "sort.h"
#include "pst.h"
#include "eval.h"
namespace search {
void Selector::generate(const Position& pos, int depth)
{
move_t *it = moves;
if (pos.checkers())
it = gen::check_escapes(pos, it, depth > 0);
else {
const Color us = pos.turn();
const bitboard_t pieceTargets = depth > 0 ? ~pos.by_color(us) : pos.by_color(~us);
const bitboard_t pawnTargets = pieceTargets | ep_square_bb(pos) | bb::rank(relative_rank(us,
RANK_8));
it = gen::piece_moves(pos, it, pieceTargets);
it = gen::pawn_moves(pos, it, pawnTargets, depth > 0);
if (depth > 0)
it = gen::castling_moves(pos, it);
}
cnt = it - moves;
}
void Selector::score(const Position& pos, move_t ttMove)
{
const Color us = pos.turn();
for (size_t i = 0; i < cnt; i++) {
if (moves[i] == ttMove)
scores[i] = +INF;
else {
const Move m(moves[i]);
if (m.is_capture(pos))
scores[i] = m.see(pos);
else {
const Piece p = pos.piece_on(m.to);
const eval_t delta = us == WHITE
? pst::table[us][p][m.to] - pst::table[us][p][m.from]
: pst::table[us][p][m.from] - pst::table[us][p][m.to];
scores[i] = blend(pos, delta);
}
}
}
}
Selector::Selector(const Position& pos, int depth, move_t ttMove)
{
generate(pos, depth);
score(pos, ttMove);
idx = 0;
}
Move Selector::select(const Position& pos, int& see)
{
int maxScore = -INF;
size_t swapIdx = idx;
for (size_t i = idx; i < cnt; i++)
if (scores[i] > maxScore)
swapIdx = i;
if (swapIdx != idx) {
std::swap(moves[idx], moves[swapIdx]);
std::swap(scores[idx], scores[swapIdx]);
}
const Move m(moves[idx]);
see = m.is_capture(pos) ? scores[idx] : m.see(pos);
return moves[idx++];
}
} // namespace search
| gpl-2.0 |
fvcproductions/CS-HU | CSC-151/Various/Hawaii_5_0.java | 1690 | // FVCproductions
// Assignment #1
// Java Bits
// Date: February 18, 2014
// Location: my evil lair
import java.util.Scanner; // importing Scanner method
public class Hawaii_5_0 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in); // creating Scanner object
System.out.println("Hello there, welcome to my program! \n");
// reading in int variables of a, b, and r by prompting user while defining them
System.out.print("Please enter the number a : ");
double a = keyboard.nextInt();
System.out.println();
System.out.print("Great, now enter the number b please : ");
double b = keyboard.nextInt();
System.out.println();
System.out.print("Finally, please enter the number r : ");
double r = keyboard.nextInt();
// defining results 1 through 4 using Math power method
double result1 = (Math.pow(a,6.0) - 9.0);
double result2 = Math.pow(a,4.0) - 5.0*a*b + Math.pow(b,3.0);
double result3 = ( ((3.0*a - 2.0)/(4.0)) + ((2.0*b-1.0)/(8.0)) );
double result4 = ( (4.0*r*5.0 + 2.0)/(3.0) );
System.out.println();
// printing out values of a, b, and r
System.out.println("Value a is equal to " + a);
System.out.println("Value b is equal to " + b);
System.out.println("Value r is equal to " + r);
System.out.println();
// printing out results 1 through 4
System.out.println("Result 1 is equal to " + result1);
System.out.println("Result 2 is equal to " + result2);
System.out.println("Result 3 is equal to " + result3);
System.out.println("Result 4 is equal to " + result4);
System.out.println();
System.out.println("Thank you, come again.");
}
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/test/java/awt/Multiscreen/WPanelPeerPerf/WPanelPeerPerf.java | 6530 | /*
* Copyright 2004-2007 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
@test
@bug 5085626
@summary Exponential performance regression in AWT components (multiple mon)
@run main WPanelPeerPerf
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* This test must be run on a multi-screen system.
* This test works by moving a Frame back and forth between the screens a few
* times. When the bug is active, the first move will overwhelm the EDT with
* recursive display change calls. The test fails if it takes too long to
* service the setLocation() calls and send componentMoved() events.
*/
public class WPanelPeerPerf {
private static final int NESTED_PANELS = 25;
private static final int ITERATIONS_PER_SCREEN = 3;
private static final int MAX_WAIT_PER_SCREEN = 2500;
private static final int PAUSE_BETWEEN_MOVES = 500;
private static Object showLock = new Object();
private static Counter instance = null;
public static Counter getCounter() {
if (instance == null) {
instance = new Counter();
}
return instance;
}
private static class Counter {
int counter;
Counter() { counter = 0; }
}
// This one is very slow!
public static void testAWT() {
// fail if only on one screen
int numScreens = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices().length;
if (numScreens < 2) {
System.err.println("Test must be run on a multiscreen system");
return;
}
final Frame frame = new Frame("AWT WPanelPeerPerf");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent ev) {
System.exit(0);
}
public void windowOpened(WindowEvent e) {
synchronized(showLock) {
showLock.notify();
}
}
});
frame.setLayout(new BorderLayout());
Label label = new Label("Hello world");
frame.add(label, BorderLayout.NORTH);
Panel panel = new Panel(new BorderLayout());
Panel currentPanel = panel;
for (int i = 0; i < NESTED_PANELS; i++) {
Panel newPanel = new Panel(new BorderLayout());
currentPanel.add(newPanel, BorderLayout.CENTER);
currentPanel = newPanel;
}
currentPanel.add(new Label("WPanelPeerPerf"));
frame.add(panel, BorderLayout.CENTER);
Button btn = new Button("OK");
frame.add(btn, BorderLayout.SOUTH);
frame.pack();
frame.addComponentListener(new ComponentAdapter() {
public void componentMoved(ComponentEvent e) {
System.out.println("Frame moved: ");
Counter ctr = getCounter();
synchronized(ctr) {
ctr.counter++;
ctr.notify();
}
}
});
synchronized(showLock) {
try {
frame.setVisible(true);
showLock.wait();
}
catch (InterruptedException e) {
e.printStackTrace();
throw new RuntimeException("Problem with showLock");
}
}
runTest(frame);
}
public static void runTest(Frame theFrame) {
System.out.println("Running test");
GraphicsDevice[] devs = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
Point[] points = new Point[devs.length];
for (int i = 0; i < points.length; i++) {
Rectangle bounds = devs[i].getDefaultConfiguration().getBounds();
points[i] = new Point(bounds.x + (bounds.width / 2),
bounds.y + (bounds.height / 2));
System.out.println("Added point:" + points[i]);
}
final Frame localFrame = theFrame;
for (int n = 0; n < ITERATIONS_PER_SCREEN; n++) {
for (int i = 0; i < points.length; i++) {
final Point contextPoint = points[i];
SwingUtilities.invokeLater(new Runnable() {
public void run() {
localFrame.setLocation(contextPoint);
}
});
try {
Thread.sleep(PAUSE_BETWEEN_MOVES);
}
catch (InterruptedException e) {
System.out.println("Interrupted during iteration");
}
}
}
Counter ctr = getCounter();
synchronized(ctr) {
try {
if (ctr.counter < ITERATIONS_PER_SCREEN * devs.length) {
// If test hasn't finished, wait for maximum time
// If we get interrupted, test fails
ctr.wait((long)(ITERATIONS_PER_SCREEN * MAX_WAIT_PER_SCREEN * devs.length));
System.out.println("after wait");
if (ctr.counter < ITERATIONS_PER_SCREEN * devs.length) {
throw new RuntimeException("Waited too long for all the componentMoved()s");
}
}
}
catch(InterruptedException e) {
e.printStackTrace();
throw new RuntimeException("Wait interrupted - ???");
}
System.out.println("Counter reads: " + ctr.counter);
}
}
public static void main(String[] args) {
testAWT();
}
}
| gpl-2.0 |
ndubey/mysql-php-song-database | MainPage.php | 652 | <html>
<head>
<title>MUSIC DATABASE</title>
</head>
<body bgcolor="#CCCCCC">
<h1 align="center">MUSIC DATABASE</h1>
<table align="center" >
<tr align="center"><form name="form1" method="post" action="list.php">
<td>
Search : <input name="Search" type="text" id="Search">
</td>
<td>
<input name="search" type ="submit" value="Search">
</td></tr>
<tr><td> </td><td><b>Artist</b><input name="Artist" type="checkbox" value="Artist"></td><td> </td>
<td><b>Album</b><input name="Album" type="checkbox" value="Album"></td><td> </td>
<td><b>Year</b><input name="Year" type="checkbox" value="Year"></td>
</tr>
</form>
</table>
</body>
</html>
| gpl-2.0 |
t-zuehlsdorff/wesnoth | src/gui/dialogs/editor/editor_edit_side.cpp | 4182 | /*
Copyright (C) 2010 - 2016 by Fabian Müller <fabianmueller5@gmx.de>
Part of the Battle for Wesnoth Project http://www.wesnoth.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.
See the COPYING file for more details.
*/
#define GETTEXT_DOMAIN "wesnoth-lib"
#include "gui/dialogs/editor/editor_edit_side.hpp"
#include "gui/dialogs/field.hpp"
#include "gui/widgets/toggle_button.hpp"
#include "gui/widgets/settings.hpp"
#include <boost/bind.hpp>
namespace gui2
{
/*WIKI
* @page = GUIWindowDefinitionWML
* @order = 2_edit_side
*
* == Edit side ==
*
* Dialog for editing gamemap sides.
*
* @begin{table}{dialog_widgets}
*
* title & & label & m &
* Dialog title label. $
*
* id & & text_box & m &
* Input field for the id. $
*
* team_only_toggle & & toggle_button & m &
* Checkbox for whether to make the label visible to the player's team
* only or not. $
*
* @end{table}
*/
REGISTER_DIALOG(editor_edit_side)
teditor_edit_side::teditor_edit_side(int side,
std::string& id,
std::string& name,
int& gold,
int& income,
int& village_income,
int& village_support,
bool& fog,
bool& shroud,
team::SHARE_VISION& share_vision,
team::CONTROLLER& controller,
bool& no_leader,
bool& hidden)
: controller_(controller)
, share_vision_(share_vision)
{
std::stringstream side_stream;
side_stream << side;
register_label("side_number", true, side_stream.str(), true);
register_text("team_name", true, id, true);
register_text("user_team_name", true, name, true);
register_integer("gold", true, gold);
register_integer("income", true, income);
register_integer("village_income", true, village_income);
register_integer("village_support", true, village_support);
register_bool("fog", true, fog);
register_bool("shroud", true, shroud);
register_bool("no_leader", true, no_leader);
register_bool("hidden", true, hidden);
}
void teditor_edit_side::pre_show(CVideo& /*video*/, twindow& window)
{
register_radio_toggle<team::CONTROLLER>(window, "controller_human", team::CONTROLLER::HUMAN, controller_, controller_tgroup_);
register_radio_toggle<team::CONTROLLER>(window, "controller_ai", team::CONTROLLER::AI, controller_, controller_tgroup_);
register_radio_toggle<team::CONTROLLER>(window, "controller_null", team::CONTROLLER::EMPTY, controller_, controller_tgroup_);
register_radio_toggle<team::SHARE_VISION>(window, "vision_all", team::SHARE_VISION::ALL, share_vision_, vision_tgroup_);
register_radio_toggle<team::SHARE_VISION>(window, "vision_shroud", team::SHARE_VISION::SHROUD, share_vision_, vision_tgroup_);
register_radio_toggle<team::SHARE_VISION>(window, "vision_null", team::SHARE_VISION::NONE, share_vision_, vision_tgroup_);
}
template <typename T>
void teditor_edit_side::register_radio_toggle(twindow& window, const std::string& toggle_id, T enum_value, T& current_value, std::vector<std::pair<ttoggle_button*, T> >& dst)
{
ttoggle_button* b = &find_widget<ttoggle_button>(
&window, toggle_id, false);
b->set_value(enum_value == current_value);
connect_signal_mouse_left_click(*b,
boost::bind(
&teditor_edit_side::toggle_radio_callback<T>, this, boost::ref(dst), boost::ref(current_value), b));
dst.push_back(std::make_pair(b, enum_value));
}
template <typename C>
void teditor_edit_side::toggle_radio_callback(const std::vector<std::pair<ttoggle_button*, C> >& vec, C& value, ttoggle_button* active)
{
FOREACH(const AUTO & e, vec)
{
ttoggle_button* const b = e.first;
if(b == NULL) {
continue;
} else if(b == active && !b->get_value()) {
b->set_value(true);
} else if(b == active) {
value = e.second;
} else if(b != active && b->get_value()) {
b->set_value(false);
}
}
}
} // end namespace gui2
| gpl-2.0 |
marcoargenti/Cleaner | src/main/java/cleandb/information_schema/tables/records/InnodbBufferPageLruRecord.java | 21017 | /**
* This class is generated by jOOQ
*/
package cleandb.information_schema.tables.records;
/**
* This class is generated by jOOQ.
*/
@javax.annotation.Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.5.4"
},
comments = "This class is generated by jOOQ"
)
@java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class InnodbBufferPageLruRecord extends org.jooq.impl.TableRecordImpl<cleandb.information_schema.tables.records.InnodbBufferPageLruRecord> implements org.jooq.Record20<org.jooq.types.ULong, org.jooq.types.ULong, org.jooq.types.ULong, org.jooq.types.ULong, java.lang.String, org.jooq.types.ULong, org.jooq.types.ULong, java.lang.String, org.jooq.types.ULong, org.jooq.types.ULong, org.jooq.types.ULong, java.lang.String, java.lang.String, org.jooq.types.ULong, org.jooq.types.ULong, org.jooq.types.ULong, java.lang.String, java.lang.String, java.lang.String, org.jooq.types.ULong> {
private static final long serialVersionUID = 978266893;
/**
* Setter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.POOL_ID</code>.
*/
public void setPoolId(org.jooq.types.ULong value) {
setValue(0, value);
}
/**
* Getter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.POOL_ID</code>.
*/
public org.jooq.types.ULong getPoolId() {
return (org.jooq.types.ULong) getValue(0);
}
/**
* Setter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.LRU_POSITION</code>.
*/
public void setLruPosition(org.jooq.types.ULong value) {
setValue(1, value);
}
/**
* Getter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.LRU_POSITION</code>.
*/
public org.jooq.types.ULong getLruPosition() {
return (org.jooq.types.ULong) getValue(1);
}
/**
* Setter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.SPACE</code>.
*/
public void setSpace(org.jooq.types.ULong value) {
setValue(2, value);
}
/**
* Getter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.SPACE</code>.
*/
public org.jooq.types.ULong getSpace() {
return (org.jooq.types.ULong) getValue(2);
}
/**
* Setter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.PAGE_NUMBER</code>.
*/
public void setPageNumber(org.jooq.types.ULong value) {
setValue(3, value);
}
/**
* Getter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.PAGE_NUMBER</code>.
*/
public org.jooq.types.ULong getPageNumber() {
return (org.jooq.types.ULong) getValue(3);
}
/**
* Setter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.PAGE_TYPE</code>.
*/
public void setPageType(java.lang.String value) {
setValue(4, value);
}
/**
* Getter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.PAGE_TYPE</code>.
*/
public java.lang.String getPageType() {
return (java.lang.String) getValue(4);
}
/**
* Setter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.FLUSH_TYPE</code>.
*/
public void setFlushType(org.jooq.types.ULong value) {
setValue(5, value);
}
/**
* Getter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.FLUSH_TYPE</code>.
*/
public org.jooq.types.ULong getFlushType() {
return (org.jooq.types.ULong) getValue(5);
}
/**
* Setter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.FIX_COUNT</code>.
*/
public void setFixCount(org.jooq.types.ULong value) {
setValue(6, value);
}
/**
* Getter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.FIX_COUNT</code>.
*/
public org.jooq.types.ULong getFixCount() {
return (org.jooq.types.ULong) getValue(6);
}
/**
* Setter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.IS_HASHED</code>.
*/
public void setIsHashed(java.lang.String value) {
setValue(7, value);
}
/**
* Getter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.IS_HASHED</code>.
*/
public java.lang.String getIsHashed() {
return (java.lang.String) getValue(7);
}
/**
* Setter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.NEWEST_MODIFICATION</code>.
*/
public void setNewestModification(org.jooq.types.ULong value) {
setValue(8, value);
}
/**
* Getter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.NEWEST_MODIFICATION</code>.
*/
public org.jooq.types.ULong getNewestModification() {
return (org.jooq.types.ULong) getValue(8);
}
/**
* Setter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.OLDEST_MODIFICATION</code>.
*/
public void setOldestModification(org.jooq.types.ULong value) {
setValue(9, value);
}
/**
* Getter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.OLDEST_MODIFICATION</code>.
*/
public org.jooq.types.ULong getOldestModification() {
return (org.jooq.types.ULong) getValue(9);
}
/**
* Setter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.ACCESS_TIME</code>.
*/
public void setAccessTime(org.jooq.types.ULong value) {
setValue(10, value);
}
/**
* Getter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.ACCESS_TIME</code>.
*/
public org.jooq.types.ULong getAccessTime() {
return (org.jooq.types.ULong) getValue(10);
}
/**
* Setter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.TABLE_NAME</code>.
*/
public void setTableName(java.lang.String value) {
setValue(11, value);
}
/**
* Getter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.TABLE_NAME</code>.
*/
public java.lang.String getTableName() {
return (java.lang.String) getValue(11);
}
/**
* Setter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.INDEX_NAME</code>.
*/
public void setIndexName(java.lang.String value) {
setValue(12, value);
}
/**
* Getter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.INDEX_NAME</code>.
*/
public java.lang.String getIndexName() {
return (java.lang.String) getValue(12);
}
/**
* Setter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.NUMBER_RECORDS</code>.
*/
public void setNumberRecords(org.jooq.types.ULong value) {
setValue(13, value);
}
/**
* Getter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.NUMBER_RECORDS</code>.
*/
public org.jooq.types.ULong getNumberRecords() {
return (org.jooq.types.ULong) getValue(13);
}
/**
* Setter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.DATA_SIZE</code>.
*/
public void setDataSize(org.jooq.types.ULong value) {
setValue(14, value);
}
/**
* Getter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.DATA_SIZE</code>.
*/
public org.jooq.types.ULong getDataSize() {
return (org.jooq.types.ULong) getValue(14);
}
/**
* Setter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.COMPRESSED_SIZE</code>.
*/
public void setCompressedSize(org.jooq.types.ULong value) {
setValue(15, value);
}
/**
* Getter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.COMPRESSED_SIZE</code>.
*/
public org.jooq.types.ULong getCompressedSize() {
return (org.jooq.types.ULong) getValue(15);
}
/**
* Setter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.COMPRESSED</code>.
*/
public void setCompressed(java.lang.String value) {
setValue(16, value);
}
/**
* Getter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.COMPRESSED</code>.
*/
public java.lang.String getCompressed() {
return (java.lang.String) getValue(16);
}
/**
* Setter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.IO_FIX</code>.
*/
public void setIoFix(java.lang.String value) {
setValue(17, value);
}
/**
* Getter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.IO_FIX</code>.
*/
public java.lang.String getIoFix() {
return (java.lang.String) getValue(17);
}
/**
* Setter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.IS_OLD</code>.
*/
public void setIsOld(java.lang.String value) {
setValue(18, value);
}
/**
* Getter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.IS_OLD</code>.
*/
public java.lang.String getIsOld() {
return (java.lang.String) getValue(18);
}
/**
* Setter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.FREE_PAGE_CLOCK</code>.
*/
public void setFreePageClock(org.jooq.types.ULong value) {
setValue(19, value);
}
/**
* Getter for <code>information_schema.INNODB_BUFFER_PAGE_LRU.FREE_PAGE_CLOCK</code>.
*/
public org.jooq.types.ULong getFreePageClock() {
return (org.jooq.types.ULong) getValue(19);
}
// -------------------------------------------------------------------------
// Record20 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Row20<org.jooq.types.ULong, org.jooq.types.ULong, org.jooq.types.ULong, org.jooq.types.ULong, java.lang.String, org.jooq.types.ULong, org.jooq.types.ULong, java.lang.String, org.jooq.types.ULong, org.jooq.types.ULong, org.jooq.types.ULong, java.lang.String, java.lang.String, org.jooq.types.ULong, org.jooq.types.ULong, org.jooq.types.ULong, java.lang.String, java.lang.String, java.lang.String, org.jooq.types.ULong> fieldsRow() {
return (org.jooq.Row20) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Row20<org.jooq.types.ULong, org.jooq.types.ULong, org.jooq.types.ULong, org.jooq.types.ULong, java.lang.String, org.jooq.types.ULong, org.jooq.types.ULong, java.lang.String, org.jooq.types.ULong, org.jooq.types.ULong, org.jooq.types.ULong, java.lang.String, java.lang.String, org.jooq.types.ULong, org.jooq.types.ULong, org.jooq.types.ULong, java.lang.String, java.lang.String, java.lang.String, org.jooq.types.ULong> valuesRow() {
return (org.jooq.Row20) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<org.jooq.types.ULong> field1() {
return cleandb.information_schema.tables.InnodbBufferPageLru.INNODB_BUFFER_PAGE_LRU.POOL_ID;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<org.jooq.types.ULong> field2() {
return cleandb.information_schema.tables.InnodbBufferPageLru.INNODB_BUFFER_PAGE_LRU.LRU_POSITION;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<org.jooq.types.ULong> field3() {
return cleandb.information_schema.tables.InnodbBufferPageLru.INNODB_BUFFER_PAGE_LRU.SPACE;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<org.jooq.types.ULong> field4() {
return cleandb.information_schema.tables.InnodbBufferPageLru.INNODB_BUFFER_PAGE_LRU.PAGE_NUMBER;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.String> field5() {
return cleandb.information_schema.tables.InnodbBufferPageLru.INNODB_BUFFER_PAGE_LRU.PAGE_TYPE;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<org.jooq.types.ULong> field6() {
return cleandb.information_schema.tables.InnodbBufferPageLru.INNODB_BUFFER_PAGE_LRU.FLUSH_TYPE;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<org.jooq.types.ULong> field7() {
return cleandb.information_schema.tables.InnodbBufferPageLru.INNODB_BUFFER_PAGE_LRU.FIX_COUNT;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.String> field8() {
return cleandb.information_schema.tables.InnodbBufferPageLru.INNODB_BUFFER_PAGE_LRU.IS_HASHED;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<org.jooq.types.ULong> field9() {
return cleandb.information_schema.tables.InnodbBufferPageLru.INNODB_BUFFER_PAGE_LRU.NEWEST_MODIFICATION;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<org.jooq.types.ULong> field10() {
return cleandb.information_schema.tables.InnodbBufferPageLru.INNODB_BUFFER_PAGE_LRU.OLDEST_MODIFICATION;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<org.jooq.types.ULong> field11() {
return cleandb.information_schema.tables.InnodbBufferPageLru.INNODB_BUFFER_PAGE_LRU.ACCESS_TIME;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.String> field12() {
return cleandb.information_schema.tables.InnodbBufferPageLru.INNODB_BUFFER_PAGE_LRU.TABLE_NAME;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.String> field13() {
return cleandb.information_schema.tables.InnodbBufferPageLru.INNODB_BUFFER_PAGE_LRU.INDEX_NAME;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<org.jooq.types.ULong> field14() {
return cleandb.information_schema.tables.InnodbBufferPageLru.INNODB_BUFFER_PAGE_LRU.NUMBER_RECORDS;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<org.jooq.types.ULong> field15() {
return cleandb.information_schema.tables.InnodbBufferPageLru.INNODB_BUFFER_PAGE_LRU.DATA_SIZE;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<org.jooq.types.ULong> field16() {
return cleandb.information_schema.tables.InnodbBufferPageLru.INNODB_BUFFER_PAGE_LRU.COMPRESSED_SIZE;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.String> field17() {
return cleandb.information_schema.tables.InnodbBufferPageLru.INNODB_BUFFER_PAGE_LRU.COMPRESSED;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.String> field18() {
return cleandb.information_schema.tables.InnodbBufferPageLru.INNODB_BUFFER_PAGE_LRU.IO_FIX;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.String> field19() {
return cleandb.information_schema.tables.InnodbBufferPageLru.INNODB_BUFFER_PAGE_LRU.IS_OLD;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<org.jooq.types.ULong> field20() {
return cleandb.information_schema.tables.InnodbBufferPageLru.INNODB_BUFFER_PAGE_LRU.FREE_PAGE_CLOCK;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.types.ULong value1() {
return getPoolId();
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.types.ULong value2() {
return getLruPosition();
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.types.ULong value3() {
return getSpace();
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.types.ULong value4() {
return getPageNumber();
}
/**
* {@inheritDoc}
*/
@Override
public java.lang.String value5() {
return getPageType();
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.types.ULong value6() {
return getFlushType();
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.types.ULong value7() {
return getFixCount();
}
/**
* {@inheritDoc}
*/
@Override
public java.lang.String value8() {
return getIsHashed();
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.types.ULong value9() {
return getNewestModification();
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.types.ULong value10() {
return getOldestModification();
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.types.ULong value11() {
return getAccessTime();
}
/**
* {@inheritDoc}
*/
@Override
public java.lang.String value12() {
return getTableName();
}
/**
* {@inheritDoc}
*/
@Override
public java.lang.String value13() {
return getIndexName();
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.types.ULong value14() {
return getNumberRecords();
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.types.ULong value15() {
return getDataSize();
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.types.ULong value16() {
return getCompressedSize();
}
/**
* {@inheritDoc}
*/
@Override
public java.lang.String value17() {
return getCompressed();
}
/**
* {@inheritDoc}
*/
@Override
public java.lang.String value18() {
return getIoFix();
}
/**
* {@inheritDoc}
*/
@Override
public java.lang.String value19() {
return getIsOld();
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.types.ULong value20() {
return getFreePageClock();
}
/**
* {@inheritDoc}
*/
@Override
public InnodbBufferPageLruRecord value1(org.jooq.types.ULong value) {
setPoolId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public InnodbBufferPageLruRecord value2(org.jooq.types.ULong value) {
setLruPosition(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public InnodbBufferPageLruRecord value3(org.jooq.types.ULong value) {
setSpace(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public InnodbBufferPageLruRecord value4(org.jooq.types.ULong value) {
setPageNumber(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public InnodbBufferPageLruRecord value5(java.lang.String value) {
setPageType(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public InnodbBufferPageLruRecord value6(org.jooq.types.ULong value) {
setFlushType(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public InnodbBufferPageLruRecord value7(org.jooq.types.ULong value) {
setFixCount(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public InnodbBufferPageLruRecord value8(java.lang.String value) {
setIsHashed(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public InnodbBufferPageLruRecord value9(org.jooq.types.ULong value) {
setNewestModification(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public InnodbBufferPageLruRecord value10(org.jooq.types.ULong value) {
setOldestModification(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public InnodbBufferPageLruRecord value11(org.jooq.types.ULong value) {
setAccessTime(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public InnodbBufferPageLruRecord value12(java.lang.String value) {
setTableName(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public InnodbBufferPageLruRecord value13(java.lang.String value) {
setIndexName(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public InnodbBufferPageLruRecord value14(org.jooq.types.ULong value) {
setNumberRecords(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public InnodbBufferPageLruRecord value15(org.jooq.types.ULong value) {
setDataSize(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public InnodbBufferPageLruRecord value16(org.jooq.types.ULong value) {
setCompressedSize(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public InnodbBufferPageLruRecord value17(java.lang.String value) {
setCompressed(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public InnodbBufferPageLruRecord value18(java.lang.String value) {
setIoFix(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public InnodbBufferPageLruRecord value19(java.lang.String value) {
setIsOld(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public InnodbBufferPageLruRecord value20(org.jooq.types.ULong value) {
setFreePageClock(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public InnodbBufferPageLruRecord values(org.jooq.types.ULong value1, org.jooq.types.ULong value2, org.jooq.types.ULong value3, org.jooq.types.ULong value4, java.lang.String value5, org.jooq.types.ULong value6, org.jooq.types.ULong value7, java.lang.String value8, org.jooq.types.ULong value9, org.jooq.types.ULong value10, org.jooq.types.ULong value11, java.lang.String value12, java.lang.String value13, org.jooq.types.ULong value14, org.jooq.types.ULong value15, org.jooq.types.ULong value16, java.lang.String value17, java.lang.String value18, java.lang.String value19, org.jooq.types.ULong value20) {
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached InnodbBufferPageLruRecord
*/
public InnodbBufferPageLruRecord() {
super(cleandb.information_schema.tables.InnodbBufferPageLru.INNODB_BUFFER_PAGE_LRU);
}
/**
* Create a detached, initialised InnodbBufferPageLruRecord
*/
public InnodbBufferPageLruRecord(org.jooq.types.ULong poolId, org.jooq.types.ULong lruPosition, org.jooq.types.ULong space, org.jooq.types.ULong pageNumber, java.lang.String pageType, org.jooq.types.ULong flushType, org.jooq.types.ULong fixCount, java.lang.String isHashed, org.jooq.types.ULong newestModification, org.jooq.types.ULong oldestModification, org.jooq.types.ULong accessTime, java.lang.String tableName, java.lang.String indexName, org.jooq.types.ULong numberRecords, org.jooq.types.ULong dataSize, org.jooq.types.ULong compressedSize, java.lang.String compressed, java.lang.String ioFix, java.lang.String isOld, org.jooq.types.ULong freePageClock) {
super(cleandb.information_schema.tables.InnodbBufferPageLru.INNODB_BUFFER_PAGE_LRU);
setValue(0, poolId);
setValue(1, lruPosition);
setValue(2, space);
setValue(3, pageNumber);
setValue(4, pageType);
setValue(5, flushType);
setValue(6, fixCount);
setValue(7, isHashed);
setValue(8, newestModification);
setValue(9, oldestModification);
setValue(10, accessTime);
setValue(11, tableName);
setValue(12, indexName);
setValue(13, numberRecords);
setValue(14, dataSize);
setValue(15, compressedSize);
setValue(16, compressed);
setValue(17, ioFix);
setValue(18, isOld);
setValue(19, freePageClock);
}
}
| gpl-2.0 |
csuyzb/AndroidLinkup | Linkup/src/com/znv/linkup/view/animation/view/AnimatorImage.java | 789 | package com.znv.linkup.view.animation.view;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
import com.znv.linkup.view.animation.AnimatorProxy;
import com.znv.linkup.view.animation.path.PathPoint;
/**
* 图片动画视图
*
* @author yzb
*
*/
public class AnimatorImage extends ImageView implements IAnimatorView {
private AnimatorProxy proxy = null;
public AnimatorImage(Context context, AttributeSet attrs) {
super(context, attrs);
proxy = AnimatorProxy.wrap(this);
}
/**
* 设置定位路径点
*
* @param pp
* 路径点
*/
public void setLocation(PathPoint pp) {
proxy.setTranslationX(pp.mX);
proxy.setTranslationY(pp.mY);
}
}
| gpl-2.0 |
dandelionmood/torrentvolve | site/master/js/login.js | 1686 | /*
TorrentVolve - A lightweight, fully functional torrent client.
Copyright (C) 2006 TorrentVolve
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
var highlight = "#CC6600";
function validateInput(name, highLight) {
if(document.getElementsByName(name)[0].value == "") {
document.getElementById(highLight).style.color = highlight;
} else {
document.getElementById(highLight).style.color = "";
}
}
function validateForm() {
var valid = true;
var message = "";
// Manage the username box
if(document.LoginForm.UserName.value == "") {
valid = false;
document.getElementById("divUsernameLabel").style.color = highlight;
message += "Please enter a username.<br />";
}
// Manage the password box
if(document.LoginForm.PassWord.value == "") {
valid = false;
document.getElementById("divPasswordLabel").style.color = highlight;
message += "Please enter a password.<br />";
}
// Set up the message
document.getElementById("divStatus").innerHTML = message;
return valid;
} | gpl-2.0 |
nologic/nabs | client/trunk/shared/db/db-4.6.21/java/src/com/sleepycat/bind/serial/SerialSerialBinding.java | 3417 | /*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2000,2007 Oracle. All rights reserved.
*
* $Id: SerialSerialBinding.java,v 12.5 2007/05/04 00:28:24 mark Exp $
*/
package com.sleepycat.bind.serial;
import com.sleepycat.bind.EntityBinding;
import com.sleepycat.db.DatabaseEntry;
/**
* An abstract <code>EntityBinding</code> that treats an entity's key entry and
* data entry as serialized objects.
*
* <p>This class takes care of serializing and deserializing the key and
* data entry automatically. Its three abstract methods must be implemented by
* a concrete subclass to convert the deserialized objects to/from an entity
* object.</p>
* <ul>
* <li> {@link #entryToObject(Object,Object)} </li>
* <li> {@link #objectToKey(Object)} </li>
* <li> {@link #objectToData(Object)} </li>
* </ul>
*
* @author Mark Hayes
*/
public abstract class SerialSerialBinding implements EntityBinding {
private SerialBinding keyBinding;
private SerialBinding dataBinding;
/**
* Creates a serial-serial entity binding.
*
* @param classCatalog is the catalog to hold shared class information and
* for a database should be a {@link StoredClassCatalog}.
*
* @param keyClass is the key base class.
*
* @param dataClass is the data base class.
*/
public SerialSerialBinding(ClassCatalog classCatalog,
Class keyClass,
Class dataClass) {
this(new SerialBinding(classCatalog, keyClass),
new SerialBinding(classCatalog, dataClass));
}
/**
* Creates a serial-serial entity binding.
*
* @param keyBinding is the key binding.
*
* @param dataBinding is the data binding.
*/
public SerialSerialBinding(SerialBinding keyBinding,
SerialBinding dataBinding) {
this.keyBinding = keyBinding;
this.dataBinding = dataBinding;
}
// javadoc is inherited
public Object entryToObject(DatabaseEntry key, DatabaseEntry data) {
return entryToObject(keyBinding.entryToObject(key),
dataBinding.entryToObject(data));
}
// javadoc is inherited
public void objectToKey(Object object, DatabaseEntry key) {
object = objectToKey(object);
keyBinding.objectToEntry(object, key);
}
// javadoc is inherited
public void objectToData(Object object, DatabaseEntry data) {
object = objectToData(object);
dataBinding.objectToEntry(object, data);
}
/**
* Constructs an entity object from deserialized key and data objects.
*
* @param keyInput is the deserialized key object.
*
* @param dataInput is the deserialized data object.
*
* @return the entity object constructed from the key and data.
*/
public abstract Object entryToObject(Object keyInput, Object dataInput);
/**
* Extracts a key object from an entity object.
*
* @param object is the entity object.
*
* @return the deserialized key object.
*/
public abstract Object objectToKey(Object object);
/**
* Extracts a data object from an entity object.
*
* @param object is the entity object.
*
* @return the deserialized data object.
*/
public abstract Object objectToData(Object object);
}
| gpl-2.0 |
product31/zardoc | xampp/navi.php | 4324 | <?php
include 'langsettings.php';
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta name="author" content="Kai Oswald Seidler, Kay Vogelgesang, Carsten Wiedmann">
<link href="xampp.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="xampp.js"></script>
<title></title>
</head>
<body class="n">
<table border="0" cellpadding="0" cellspacing="0">
<tr valign="top">
<td align="right" class="navi">
<img src="img/blank.gif" alt="" width="145" height="15"><br>
<span class="nh"><?php echo trim(@file_get_contents('../../install/xampp_modell.txt')); ?></span><br>
<span class="navi">[PHP: <?php echo phpversion(); ?>]</span><br><br>
</td>
</tr>
<tr>
<td height="1" bgcolor="#fb7922" colspan="1" style="background-image:url(img/strichel.gif)" class="white"></td>
</tr>
<tr valign="top">
<td align="right" class="navi">
<a name="start" id="start" class="nh" target="content" onclick="h(this);" href="start.php"><?php echo $TEXT['navi-welcome']; ?></a><br>
<a class="n" target="content" onclick="h(this);" href="status.php"><?php echo $TEXT['navi-status']; ?></a><br>
<a class="n" target="new" onclick="h(this);" href="/security/lang.php?<?php echo file_get_contents("../../install/xampp_language.txt"); ?>"><?php echo $TEXT['navi-security']; ?></a><br>
<a class="n" target="content" onclick="h(this);" href="manuals.php"><?php echo $TEXT['navi-doc']; ?></a><br>
<a class="n" target="content" onclick="h(this);" href="components.php"><?php echo $TEXT['navi-components']; ?></a><br>
<a class="n" target="content" onclick="h(this);" href="phpinfo.php">phpinfo()</a><br><br>
<span class=nh><?php echo $TEXT['navi-demos']; ?></span><br>
</td>
</tr>
<tr><td height="1" bgcolor="#fb7922" colspan="1" style="background-image:url(img/strichel.gif)" class="white"></td></tr>
<tr valign="top">
<td align="right" class="navi">
<?php
$navi = array('navibasics.inc', 'naviperl.inc', 'navipython.inc', 'navijava.inc');
foreach ($navi as $inc) {
if (is_readable($inc)) {
include $inc;
}
}
?>
<br><br><span class="nh"><?php echo $TEXT['navi-tools']; ?></span><br>
</td>
</tr>
<tr>
<td height="1" bgcolor="#fb7922" colspan="1" style="background-image:url(img/strichel.gif)" class="white"></td>
</tr>
<tr valign="top">
<td align="right" class="navi">
<?php
$navi = array('navitools.inc', 'naviservers.inc', 'naviother.inc');
foreach ($navi as $inc) {
if (is_readable($inc)) {
include $inc;
}
}
?>
<br><br>
</td>
</tr>
<tr>
<td height="1" bgcolor="#fb7922" colspan="1" style="background-image:url(img/strichel.gif)" class="white"></td>
</tr>
<tr valign="top">
<td align="right" class="navi">
<p class="navi">©2002-2009<br>
<?php if (file_get_contents('../../install/xampp_language.txt') == "de") { ?>
<a target=content href="http://www.apachefriends.org/de/"><img border="0" alt="" src="img/apachefriends.gif"></a></p>
<?php } else { ?>
<a target=content href="http://www.apachefriends.org/en/"><img border="0" alt="" src="img/apachefriends.gif"></a></p>
<?php } ?>
</td>
</tr>
</table>
</body>
</html>
| gpl-2.0 |
greshniksv/VkListDownloadWpf | VkListDownloader2/winComplete.xaml.cs | 1882 | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Windows;
using Microsoft.Win32;
using VkListDownloader2.DTO;
namespace VkListDownloader2
{
/// <summary>
/// Interaction logic for winComplete.xaml
/// </summary>
public partial class WinComplete : Window
{
public Dictionary<string, Uri> Result { get; set; }
private readonly ObservableCollection<SkipedItem> skipedItems = new ObservableCollection<SkipedItem>();
public WinComplete()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
foreach (var item in Result)
{
skipedItems.Add(new SkipedItem {Name = item.Key, Url = item.Value });
}
lvSkipedList.ItemsSource = skipedItems;
}
private void btnExportToHtml_Click(object sender, RoutedEventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog {Filter = "HTML file (*.html)|*.html"};
saveFileDialog.ShowDialog();
using (TextWriter textWriter = new StreamWriter(saveFileDialog.FileName, false, Encoding.Unicode))
{
textWriter.WriteLine("<h1> Skiped files: <h1> <hr /> ");
textWriter.WriteLine(
"<table border='1'> <tr><th style='width: 200px;'> Name </th><th style='width: 100px;'> Url </th><tr> ");
foreach (var skipedItem in skipedItems)
{
textWriter.WriteLine(
$" <tr><td> {skipedItem.Name} </td><td> <a href='{skipedItem.Url}' download='{skipedItem.Name}' > Download </a> </td></tr> ");
}
textWriter.WriteLine("</table>");
}
}
}
}
| gpl-2.0 |
MostafaEllethy/SmartAds | config/app.php | 9066 | <?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
|
*/
'name' => 'Smartads',
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => 'local',
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => true,
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => 'http://smartads',
'asset_url' => env('ASSET_URL', null),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'en',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
/*
|--------------------------------------------------------------------------
| Faker Locale
|--------------------------------------------------------------------------
|
| This locale will be used by the Faker PHP library when generating fake
| data for your database seeds. For example, this will be used to get
| localized telephone numbers, street address information and more.
|
*/
'faker_locale' => 'en_US',
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => 'base64:++WAUjYCQT3ZgECMLPKkMy0DdFilKVX94797TkAHm5g=',
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider::class,
Illuminate\Encryption\EncryptionServiceProvider::class,
Illuminate\Filesystem\FilesystemServiceProvider::class,
Illuminate\Foundation\Providers\FoundationServiceProvider::class,
Illuminate\Hashing\HashServiceProvider::class,
Illuminate\Mail\MailServiceProvider::class,
Illuminate\Notifications\NotificationServiceProvider::class,
Illuminate\Pagination\PaginationServiceProvider::class,
Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
Illuminate\Redis\RedisServiceProvider::class,
Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
Illuminate\Session\SessionServiceProvider::class,
Illuminate\Translation\TranslationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
/*
* Package Service Providers...
*/
/*
* Application Service Providers...
*/
Smartads\Providers\AppServiceProvider::class,
Smartads\Providers\AuthServiceProvider::class,
Smartads\Providers\BroadcastServiceProvider::class,
Smartads\Providers\EventServiceProvider::class,
Smartads\Providers\RouteServiceProvider::class,
],
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
'Blade' => Illuminate\Support\Facades\Blade::class,
'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
'Bus' => Illuminate\Support\Facades\Bus::class,
'Cache' => Illuminate\Support\Facades\Cache::class,
'Config' => Illuminate\Support\Facades\Config::class,
'Cookie' => Illuminate\Support\Facades\Cookie::class,
'Crypt' => Illuminate\Support\Facades\Crypt::class,
'DB' => Illuminate\Support\Facades\DB::class,
'Eloquent' => Illuminate\Database\Eloquent\Model::class,
'Event' => Illuminate\Support\Facades\Event::class,
'File' => Illuminate\Support\Facades\File::class,
'Gate' => Illuminate\Support\Facades\Gate::class,
'Hash' => Illuminate\Support\Facades\Hash::class,
'Lang' => Illuminate\Support\Facades\Lang::class,
'Log' => Illuminate\Support\Facades\Log::class,
'Mail' => Illuminate\Support\Facades\Mail::class,
'Notification' => Illuminate\Support\Facades\Notification::class,
'Password' => Illuminate\Support\Facades\Password::class,
'Queue' => Illuminate\Support\Facades\Queue::class,
'Redirect' => Illuminate\Support\Facades\Redirect::class,
'Redis' => Illuminate\Support\Facades\Redis::class,
'Request' => Illuminate\Support\Facades\Request::class,
'Response' => Illuminate\Support\Facades\Response::class,
'Route' => Illuminate\Support\Facades\Route::class,
'Schema' => Illuminate\Support\Facades\Schema::class,
'Session' => Illuminate\Support\Facades\Session::class,
'Storage' => Illuminate\Support\Facades\Storage::class,
'URL' => Illuminate\Support\Facades\URL::class,
'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class,
],
];
| gpl-2.0 |
JohnCrossley/straw | straw/src/main/java/com/jccworld/straw/activity/BaseActivity.java | 1536 | package com.jccworld.straw.activity;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import com.jccworld.straw.UIComponentProxy;
/**
* Created by johncrossley on 26/10/15.
*/
public abstract class BaseActivity extends Activity implements ActivityCallbacks {
private UIComponentProxy uiComponentProxy;
public BaseActivity() {
super();
logV("Constructor()");
}
private void logV(final String message) {
Log.v(getClass().getSimpleName(), "[straw] " + message);
}
//----------------------------------------------------------------------------------------------
@Override
protected void onCreate(final Bundle savedInstanceState) {
logV("onCreate(savedInstanceState: " + savedInstanceState + ")");
super.onCreate(savedInstanceState);
uiComponentProxy = new UIComponentProxy(this);
uiComponentProxy.handleOnCreated(savedInstanceState);
}
@Override
protected void onSaveInstanceState(final Bundle outState) {
logV("onSaveInstanceState(outState: " + outState + ")");
uiComponentProxy.onSaveInstanceState(outState);
super.onSaveInstanceState(outState);//must be done last
}
@Override
protected void onResume() {
logV("onResume()");
super.onResume();
uiComponentProxy.handleOnResume();
}
@Override
protected void onPause() {
logV("onPause()");
super.onPause();
uiComponentProxy.handleOnPause();
}
}
| gpl-2.0 |
micovo/tidy_storage | src/TidyStorage/Suppliers/DigikeySupplier.cs | 6415 | using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
using System.Net.Security;
using System.Web;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Diagnostics;
using HtmlAgilityPack;
using TidyStorage.Suppliers.Data;
namespace TidyStorage.Suppliers
{
public class DigikeySupplier : Supplier
{
SupplierPart part;
public override string Name { get { return "Digikey"; } }
/// <summary>
/// Constructor
/// </summary>
/// <param name="part_number"></param>
public DigikeySupplier(string part_number) : base(part_number)
{
//Nothing to do here
}
/// <summary>
/// Function creates URL for the provided supplier part number
/// </summary>
/// <returns>Part URL</returns>
public override string GetLink()
{
string error = "";
string responce = "";
string url = "https://www.digikey.com/products/en?keywords=" + part_number;
string output = "";
output = url;
return output;
}
/// <summary>
/// Function downloads part details for the provided supplier part number
/// </summary>
/// <returns>Supplier Part</returns>
public override SupplierPart DownloadPart()
{
part = new SupplierPart();
part.order_num = part_number;
string error = "";
string responce = "";
string url = GetLink();
using (HttpWebResponse resp = WebClient.Request(url, out error, null))
{
if (resp != null)
{
StreamReader reader = new StreamReader(resp.GetResponseStream());
responce = reader.ReadToEnd();
HtmlDocument document = new HtmlDocument();
document.LoadHtml(responce);
if (document != null)
{
GetPrices(document);
GetProductDescriptors(document);
}
}
}
return part;
}
/// <summary>
/// Parser for reading product details from the prvided HTML document
/// </summary>
/// <param name="document">HTML document to be parsed</param>
private void GetProductDescriptors(HtmlDocument document)
{
part.rows = new List<PartRow>();
HtmlNodeCollection hnc;
hnc = document.DocumentNode.SelectNodes("//table[@id='product-details']");
if (hnc != null)
{
var specs_table = hnc.First();
var rows = specs_table.SelectNodes(".//tr");
for (int i = 1; i < rows.Count; i++)
{
HtmlNode row = rows[i];
var head_cell = row.SelectNodes(".//th");
var value_cell = row.SelectNodes(".//td");
if ((head_cell != null) && (value_cell != null))
{
string name = head_cell.First().InnerText.Trim().Trim(':');
string value = value_cell.First().InnerText.Trim().Replace(" ", "");
part.rows.Add(new PartRow(name, value));
}
}
}
hnc = document.DocumentNode.SelectNodes("//table[@id='prod-att-table']");
if (hnc != null)
{
var specs_table = hnc.First();
var rows = specs_table.SelectNodes(".//tr");
for (int i = 1; i < rows.Count; i++)
{
HtmlNode row = rows[i];
var head_cell = row.SelectNodes(".//th");
var value_cell = row.SelectNodes(".//td");
if ((head_cell != null) && (value_cell != null))
{
string name = head_cell.First().InnerText.Trim().Trim(':');
string value = value_cell.First().InnerText.Trim().Replace(" ", "");
part.rows.Add(new PartRow(name, value));
}
}
}
}
/// <summary>
/// Parser for reading product prices from the prvided HTML document
/// </summary>
/// <param name="document">HTML document to be parsed</param>
private void GetPrices(HtmlDocument document)
{
var hnc = document.DocumentNode.SelectNodes("//table[contains(@id,'product-dollars')]");
if (hnc != null)
{
var main = hnc.First();
var rows = main.SelectNodes(".//tr");
if ((rows != null) && (rows.Count > 1))
{
part.prices = new List<PartPrice>();
for (int i = 1; i < rows.Count; i++)
{
var cells = rows[i].SelectNodes(".//td");
string quantity_str = cells[0].InnerText.Trim();
string price_str = cells[1].InnerText.Trim();
int min;
float price;
part.currency = "USD";
price_str = price_str.Trim();
price_str = price_str.Replace(",", System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
price_str = price_str.Replace(".", System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
quantity_str = quantity_str.Replace(".", "");
quantity_str = quantity_str.Replace(",", "");
if (int.TryParse(quantity_str, out min) && float.TryParse(price_str, out price))
{
part.prices.Add(new PartPrice(min, price));
}
}
}
}
}
}
}
| gpl-2.0 |
cbjs/wp-theme-post-each-day | header.php | 1366 | <?php
/**
* The Header for our theme.
*
* Displays all of the <head> section and everything up till <div id="content">
*
* @package post_each_day
*/
?><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php wp_title( '|', true, 'right' ); ?></title>
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>">
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<div id="page" class="hfeed site">
<?php do_action( 'before' ); ?>
<header id="masthead" class="site-header" role="banner">
<div class="site-branding">
<h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1>
<h2 class="site-description"><?php bloginfo( 'description' ); ?></h2>
</div>
<nav id="site-navigation" class="main-navigation" role="navigation">
<h1 class="menu-toggle"><?php _e( 'Menu', 'post_each_day' ); ?></h1>
<a class="skip-link screen-reader-text" href="#content"><?php _e( 'Skip to content', 'post_each_day' ); ?></a>
<?php wp_nav_menu( array( 'theme_location' => 'primary' ) ); ?>
</nav><!-- #site-navigation -->
</header><!-- #masthead -->
<div id="content" class="site-content">
| gpl-2.0 |
pilt/stream-server | live-media/liveMedia/MPEG2IndexFromTransportStream.cpp | 21319 | /**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
**********/
// "liveMedia"
// Copyright (c) 1996-2007 Live Networks, Inc. All rights reserved.
// A filter that produces a sequence of I-frame indices from a MPEG-2 Transport Stream
// Implementation
#include "MPEG2IndexFromTransportStream.hh"
////////// IndexRecord definition //////////
enum RecordType {
RECORD_UNPARSED = 0,
RECORD_VSH = 1,
RECORD_GOP = 2,
RECORD_PIC_NON_IFRAME = 3, // includes slices
RECORD_PIC_IFRAME = 4, // includes slices
RECORD_JUNK
};
class IndexRecord {
public:
IndexRecord(u_int8_t startOffset, u_int8_t size,
unsigned long transportPacketNumber, float pcr);
virtual ~IndexRecord();
RecordType& recordType() { return fRecordType; }
void setFirstFlag() { fRecordType = (RecordType)(((u_int8_t)fRecordType) | 0x80); }
u_int8_t startOffset() const { return fStartOffset; }
u_int8_t& size() { return fSize; }
float pcr() const { return fPCR; }
unsigned long transportPacketNumber() const { return fTransportPacketNumber; }
IndexRecord* next() const { return fNext; }
void addAfter(IndexRecord* prev);
void unlink();
private:
// Index records are maintained in a doubly-linked list:
IndexRecord* fNext;
IndexRecord* fPrev;
RecordType fRecordType;
u_int8_t fStartOffset; // within the Transport Stream packet
u_int8_t fSize; // in bytes, following "fStartOffset".
// Note: fStartOffset + fSize <= TRANSPORT_PACKET_SIZE
float fPCR;
unsigned long fTransportPacketNumber;
};
#ifdef DEBUG
static char const* recordTypeStr[] = {
"UNPARSED",
"VSH",
"GOP",
"PIC(non-I-frame)",
"PIC(I-frame)",
"JUNK"
};
UsageEnvironment& operator<<(UsageEnvironment& env, IndexRecord& r) {
return env << "[" << ((r.recordType()&0x80) != 0 ? "1" : "")
<< recordTypeStr[r.recordType()&0x7F] << ":"
<< (unsigned)r.transportPacketNumber() << ":" << r.startOffset()
<< "(" << r.size() << ")@" << r.pcr() << "]";
}
#endif
////////// MPEG2IFrameIndexFromTransportStream implementation //////////
MPEG2IFrameIndexFromTransportStream*
MPEG2IFrameIndexFromTransportStream::createNew(UsageEnvironment& env,
FramedSource* inputSource) {
return new MPEG2IFrameIndexFromTransportStream(env, inputSource);
}
// The largest expected frame size (in bytes):
#define MAX_FRAME_SIZE 400000
// Make our parse buffer twice as large as this, to ensure that at least one
// complete frame will fit inside it:
#define PARSE_BUFFER_SIZE (2*MAX_FRAME_SIZE)
// The PID used for the PAT (as defined in the MPEG Transport Stream standard):
#define PAT_PID 0
MPEG2IFrameIndexFromTransportStream
::MPEG2IFrameIndexFromTransportStream(UsageEnvironment& env,
FramedSource* inputSource)
: FramedFilter(env, inputSource),
fInputTransportPacketCounter((unsigned)-1), fClosureNumber(0),
fLastContinuityCounter(~0),
fFirstPCR(0.0), fLastPCR(0.0), fHaveSeenFirstPCR(False),
fPMT_PID(0x10), fVideo_PID(0xE0), // default values
fParseBufferSize(PARSE_BUFFER_SIZE),
fParseBufferFrameStart(0), fParseBufferParseEnd(4), fParseBufferDataEnd(0),
fHeadIndexRecord(NULL), fTailIndexRecord(NULL) {
fParseBuffer = new unsigned char[fParseBufferSize];
}
MPEG2IFrameIndexFromTransportStream::~MPEG2IFrameIndexFromTransportStream() {
delete fHeadIndexRecord;
delete[] fParseBuffer;
}
void MPEG2IFrameIndexFromTransportStream::doGetNextFrame() {
// Begin by trying to deliver an index record (for an already-parsed frame)
// to the client:
if (deliverIndexRecord()) return;
// No more index records are left to deliver, so try to parse a new frame:
if (parseFrame()) { // success - try again
doGetNextFrame();
return;
}
// We need to read some more Transport Stream packets. Check whether we have room:
if (fParseBufferSize - fParseBufferDataEnd < TRANSPORT_PACKET_SIZE) {
// There's no room left. Compact the buffer, and check again:
compactParseBuffer();
if (fParseBufferSize - fParseBufferDataEnd < TRANSPORT_PACKET_SIZE) {
envir() << "ERROR: parse buffer full; increase MAX_FRAME_SIZE\n";
// Treat this as if the input source ended:
handleInputClosure1();
return;
}
}
// Arrange to read a new Transport Stream packet:
fInputSource->getNextFrame(fInputBuffer, sizeof fInputBuffer,
afterGettingFrame, this,
handleInputClosure, this);
}
void MPEG2IFrameIndexFromTransportStream
::afterGettingFrame(void* clientData, unsigned frameSize,
unsigned numTruncatedBytes,
struct timeval presentationTime,
unsigned durationInMicroseconds) {
MPEG2IFrameIndexFromTransportStream* source
= (MPEG2IFrameIndexFromTransportStream*)clientData;
source->afterGettingFrame1(frameSize, numTruncatedBytes,
presentationTime, durationInMicroseconds);
}
void MPEG2IFrameIndexFromTransportStream
::afterGettingFrame1(unsigned frameSize,
unsigned numTruncatedBytes,
struct timeval presentationTime,
unsigned durationInMicroseconds) {
if (frameSize < TRANSPORT_PACKET_SIZE || fInputBuffer[0] != 0x47/*sync byte*/) {
if (fInputBuffer[0] != 0x47) {
envir() << "Bad TS sync byte: 0x" << fInputBuffer[0] << "\n";
}
// Handle this as if the source ended:
handleInputClosure1();
return;
}
++fInputTransportPacketCounter;
// Figure out how much of this Transport Packet contains PES data:
u_int8_t adaptation_field_control = (fInputBuffer[3]&0x30)>>4;
u_int8_t totalHeaderSize
= adaptation_field_control == 1 ? 4 : 5 + fInputBuffer[4];
// Check for a PCR:
if (totalHeaderSize > 5 && (fInputBuffer[5]&0x10) != 0) {
// There's a PCR:
u_int32_t pcrBaseHigh
= (fInputBuffer[6]<<24)|(fInputBuffer[7]<<16)
|(fInputBuffer[8]<<8)|fInputBuffer[9];
float pcr = pcrBaseHigh/45000.0f;
if ((fInputBuffer[10]&0x80) != 0) pcr += 1/90000.0f; // add in low-bit (if set)
unsigned short pcrExt = ((fInputBuffer[10]&0x01)<<8) | fInputBuffer[11];
pcr += pcrExt/27000000.0f;
if (!fHaveSeenFirstPCR) {
fFirstPCR = pcr;
fHaveSeenFirstPCR = True;
}
fLastPCR = pcr;
}
// Get the PID from the packet, and check for special tables: the PAT and PMT:
u_int16_t PID = ((fInputBuffer[1]&0x1F)<<8) | fInputBuffer[2];
if (PID == PAT_PID) {
analyzePAT(&fInputBuffer[totalHeaderSize], TRANSPORT_PACKET_SIZE-totalHeaderSize);
} else if (PID == fPMT_PID) {
analyzePMT(&fInputBuffer[totalHeaderSize], TRANSPORT_PACKET_SIZE-totalHeaderSize);
}
// Ignore transport packets for non-video programs,
// or packets with no data, or packets that duplicate the previous packet:
u_int8_t continuity_counter = fInputBuffer[3]&0x0F;
if ((PID != fVideo_PID) ||
!(adaptation_field_control == 1 || adaptation_field_control == 3) ||
continuity_counter == fLastContinuityCounter) {
doGetNextFrame();
return;
}
fLastContinuityCounter = continuity_counter;
// Also, if this is the start of a PES packet, then skip over the PES header:
Boolean payload_unit_start_indicator = (fInputBuffer[1]&0x40) != 0;
//fprintf(stderr, "PUSI: %d\n", payload_unit_start_indicator);//#####
if (payload_unit_start_indicator) {
// Note: The following works only for MPEG-2 data #####
u_int8_t PES_header_data_length = fInputBuffer[totalHeaderSize+8];
//fprintf(stderr, "PES_header_data_length: %d\n", PES_header_data_length);//#####
totalHeaderSize += 9 + PES_header_data_length;
if (totalHeaderSize >= TRANSPORT_PACKET_SIZE) {
envir() << "Unexpectedly large PES header size: " << PES_header_data_length << "\n";
// Handle this as if the source ended:
handleInputClosure1();
return;
}
}
// The remaining data is Video Elementary Stream data. Add it to our parse buffer:
unsigned vesSize = TRANSPORT_PACKET_SIZE - totalHeaderSize;
memmove(&fParseBuffer[fParseBufferDataEnd], &fInputBuffer[totalHeaderSize], vesSize);
fParseBufferDataEnd += vesSize;
// And add a new index record noting where it came from:
addToTail(new IndexRecord(totalHeaderSize, vesSize, fInputTransportPacketCounter,
fLastPCR - fFirstPCR));
// Try again:
doGetNextFrame();
}
void MPEG2IFrameIndexFromTransportStream::handleInputClosure(void* clientData) {
MPEG2IFrameIndexFromTransportStream* source
= (MPEG2IFrameIndexFromTransportStream*)clientData;
source->handleInputClosure1();
}
#define VIDEO_SEQUENCE_START_CODE 0xB3 // MPEG-1 or 2
#define VISUAL_OBJECT_SEQUENCE_START_CODE 0xB0 // MPEG-4
#define GROUP_START_CODE 0xB8 // MPEG-1 or 2
#define GROUP_VOP_START_CODE 0xB3 // MPEG-4
#define PICTURE_START_CODE 0x00 // MPEG-1 or 2
#define VOP_START_CODE 0xB6 // MPEG-4
void MPEG2IFrameIndexFromTransportStream::handleInputClosure1() {
if (++fClosureNumber == 1 && fParseBufferDataEnd > fParseBufferFrameStart
&& fParseBufferDataEnd <= fParseBufferSize - 4) {
// This is the first time we saw EOF, and there's still data remaining to be
// parsed. Hack: Append a Picture Header code to the end of the unparsed
// data, and try again. This should use up all of the unparsed data.
fParseBuffer[fParseBufferDataEnd++] = 0;
fParseBuffer[fParseBufferDataEnd++] = 0;
fParseBuffer[fParseBufferDataEnd++] = 1;
fParseBuffer[fParseBufferDataEnd++] = PICTURE_START_CODE;
// Try again:
doGetNextFrame();
} else {
// Handle closure in the regular way:
FramedSource::handleClosure(this);
}
}
void MPEG2IFrameIndexFromTransportStream
::analyzePAT(unsigned char* pkt, unsigned size) {
// Get the PMT_PID (we assume that's there just 1 program):
if (size < 16) return; // table too small
u_int16_t program_number = (pkt[9]<<8) | pkt[10];
if (program_number != 0) {
fPMT_PID = ((pkt[11]&0x1F)<<8) | pkt[12];
}
}
void MPEG2IFrameIndexFromTransportStream
::analyzePMT(unsigned char* pkt, unsigned size) {
// Scan the "elementary_PID"s in the map, until we see the first video stream.
// First, get the "section_length", to get the table's size:
u_int16_t section_length = ((pkt[2]&0x0F)<<8) | pkt[3];
if ((unsigned)(4+section_length) < size) size = (4+section_length);
// Then, skip any descriptors following the "program_info_length":
if (size < 22) return; // not enough data
unsigned program_info_length = ((pkt[11]&0x0F)<<8) | pkt[12];
pkt += 13; size -= 13;
if (size < program_info_length) return; // not enough data
pkt += program_info_length; size -= program_info_length;
// Look at each ("stream_type","elementary_PID") pair, looking for a video stream
// ("stream_type" == 1 or 2):
while (size >= 9) {
u_int8_t stream_type = pkt[0];
u_int16_t elementary_PID = ((pkt[1]&0x1F)<<8) | pkt[2];
if (stream_type == 1 || stream_type == 2) {
fVideo_PID = elementary_PID;
return;
}
u_int16_t ES_info_length = ((pkt[3]&0x0F)<<8) | pkt[4];
pkt += 5; size -= 5;
if (size < ES_info_length) return; // not enough data
pkt += ES_info_length; size -= ES_info_length;
}
}
Boolean MPEG2IFrameIndexFromTransportStream::deliverIndexRecord() {
IndexRecord* head = fHeadIndexRecord;
if (head == NULL) return False;
// Check whether the head record has been parsed yet:
if (head->recordType() == RECORD_UNPARSED) return False;
// Remove the head record (the one whose data we'll be delivering):
IndexRecord* next = head->next();
head->unlink();
if (next == head) {
fHeadIndexRecord = fTailIndexRecord = NULL;
} else {
fHeadIndexRecord = next;
}
if (head->recordType() == RECORD_JUNK) {
// Don't actually deliver the data to the client:
delete head;
return True;
}
// Deliver data from the head record:
#ifdef DEBUG
envir() << "delivering: " << *head << "\n";
#endif
if (fMaxSize < 11) {
fFrameSize = 0;
} else {
fTo[0] = (u_int8_t)(head->recordType());
fTo[1] = head->startOffset();
fTo[2] = head->size();
// Deliver the PCR, as 24 bits (integer part; little endian) + 8 bits (fractional part)
float pcr = head->pcr();
unsigned pcr_int = (unsigned)pcr;
u_int8_t pcr_frac = (u_int8_t)(256*(pcr-pcr_int));
fTo[3] = (unsigned char)(pcr_int);
fTo[4] = (unsigned char)(pcr_int>>8);
fTo[5] = (unsigned char)(pcr_int>>16);
fTo[6] = (unsigned char)(pcr_frac);
// Deliver the transport packet number (in little-endian order):
unsigned long tpn = head->transportPacketNumber();
fTo[7] = (unsigned char)(tpn);
fTo[8] = (unsigned char)(tpn>>8);
fTo[9] = (unsigned char)(tpn>>16);
fTo[10] = (unsigned char)(tpn>>24);
fFrameSize = 11;
}
// Free the (former) head record (as we're now done with it):
delete head;
// Complete delivery to the client:
afterGetting(this);
return True;
}
Boolean MPEG2IFrameIndexFromTransportStream::parseFrame() {
// At this point, we have a queue of >=0 (unparsed) index records, representing
// the data in the parse buffer from "fParseBufferFrameStart"
// to "fParseBufferDataEnd". We now parse through this data, looking for
// a complete 'frame' (where a 'frame', in this case, means
// a Video Sequence Header, GOP Header, Picture Header, or Slice).
// Inspect the frame's initial 4-byte code, to make sure it starts with a system code:
if (fParseBufferDataEnd-fParseBufferFrameStart < 4) return False; // not enough data
unsigned numInitialBadBytes = 0;
unsigned char const* p = &fParseBuffer[fParseBufferFrameStart];
if (!(p[0] == 0 && p[1] == 0 && p[2] == 1)) {
// There's no system code at the beginning. Parse until we find one:
if (fParseBufferParseEnd == fParseBufferFrameStart + 4) {
// Start parsing from the beginning of the frame data:
fParseBufferParseEnd = fParseBufferFrameStart;
}
unsigned char nextCode;
if (!parseToNextCode(nextCode)) return False;
numInitialBadBytes = fParseBufferParseEnd - fParseBufferFrameStart;
//fprintf(stderr, "#####numInitialBadBytes: 0x%x\n", numInitialBadBytes);
fParseBufferFrameStart = fParseBufferParseEnd;
fParseBufferParseEnd += 4; // skip over the code that we just saw
p = &fParseBuffer[fParseBufferFrameStart];
}
unsigned char curCode = p[3];
RecordType curRecordType;
unsigned char nextCode;
switch (curCode) {
case VIDEO_SEQUENCE_START_CODE:
case VISUAL_OBJECT_SEQUENCE_START_CODE: {
curRecordType = RECORD_VSH;
while (1) {
if (!parseToNextCode(nextCode)) return False;
if (nextCode == GROUP_START_CODE || /*nextCode == GROUP_VOP_START_CODE ||*/
nextCode == PICTURE_START_CODE || nextCode == VOP_START_CODE) break;
fParseBufferParseEnd += 4; // skip over the code that we just saw
}
break;
}
case GROUP_START_CODE:
/*case GROUP_VOP_START_CODE:*/ {
curRecordType = RECORD_GOP;
while (1) {
if (!parseToNextCode(nextCode)) return False;
if (nextCode == PICTURE_START_CODE || nextCode == VOP_START_CODE) break;
fParseBufferParseEnd += 4; // skip over the code that we just saw
}
break;
}
default: { // picture (including slices)
curRecordType = RECORD_PIC_NON_IFRAME; // may get changed to IFRAME later
while (1) {
if (!parseToNextCode(nextCode)) return False;
if (nextCode == VIDEO_SEQUENCE_START_CODE || nextCode == VISUAL_OBJECT_SEQUENCE_START_CODE ||
nextCode == GROUP_START_CODE || nextCode == GROUP_VOP_START_CODE ||
nextCode == PICTURE_START_CODE || nextCode == VOP_START_CODE) break;
fParseBufferParseEnd += 4; // skip over the code that we just saw
}
break;
}
}
if (curRecordType == RECORD_PIC_NON_IFRAME) {
if (curCode == VOP_START_CODE) { // MPEG-4
//fprintf(stderr, "#####parseFrame()1(4): 0x%x, 0x%x\n", curCode, fParseBuffer[fParseBufferFrameStart+4]&0xC0);
if ((fParseBuffer[fParseBufferFrameStart+4]&0xC0) == 0) {
// This is actually an I-frame. Note it as such:
curRecordType = RECORD_PIC_IFRAME;
}
} else { // MPEG-1 or 2
//fprintf(stderr, "#####parseFrame()1(!4): 0x%x, 0x%x\n", curCode, fParseBuffer[fParseBufferFrameStart+5]&0x38);
if ((fParseBuffer[fParseBufferFrameStart+5]&0x38) == 0x08) {
// This is actually an I-frame. Note it as such:
curRecordType = RECORD_PIC_IFRAME;
}
}
}
// There is now a parsed 'frame', from "fParseBufferFrameStart"
// to "fParseBufferParseEnd". Tag the corresponding index records to note this:
unsigned frameSize = fParseBufferParseEnd - fParseBufferFrameStart + numInitialBadBytes;
#ifdef DEBUG
envir() << "parsed " << recordTypeStr[curRecordType] << "; length "
<< frameSize << "\n";
#endif
for (IndexRecord* r = fHeadIndexRecord; ; r = r->next()) {
if (numInitialBadBytes >= r->size()) {
r->recordType() = RECORD_JUNK;
numInitialBadBytes -= r->size();
} else {
r->recordType() = curRecordType;
}
if (r == fHeadIndexRecord) r->setFirstFlag();
// indicates that this is the first record for this frame
if (r->size() > frameSize) {
// This record contains extra data that's not part of the frame.
// Shorten this record, and move the extra data to a new record
// that comes afterwards:
u_int8_t newOffset = r->startOffset() + frameSize;
u_int8_t newSize = r->size() - frameSize;
r->size() = frameSize;
#ifdef DEBUG
envir() << "tagged record (modified): " << *r << "\n";
#endif
IndexRecord* newRecord
= new IndexRecord(newOffset, newSize, r->transportPacketNumber(), r->pcr());
newRecord->addAfter(r);
if (fTailIndexRecord == r) fTailIndexRecord = newRecord;
#ifdef DEBUG
envir() << "added extra record: " << *newRecord << "\n";
#endif
} else {
#ifdef DEBUG
envir() << "tagged record: " << *r << "\n";
#endif
}
frameSize -= r->size();
if (frameSize == 0) break;
if (r == fTailIndexRecord) { // this shouldn't happen
envir() << "!!!!!Internal consistency error!!!!!\n";
return False;
}
}
// Finally, update our parse state (to skip over the now-parsed data):
fParseBufferFrameStart = fParseBufferParseEnd;
fParseBufferParseEnd += 4; // to skip over the next code (that we found)
return True;
}
Boolean MPEG2IFrameIndexFromTransportStream
::parseToNextCode(unsigned char& nextCode) {
unsigned char const* p = &fParseBuffer[fParseBufferParseEnd];
unsigned char const* end = &fParseBuffer[fParseBufferDataEnd];
while (p <= end-4) {
if (p[2] > 1) p += 3; // common case (optimized)
else if (p[2] == 0) ++p;
else if (p[0] == 0 && p[1] == 0) { // && p[2] == 1
// We found a code here:
nextCode = p[3];
fParseBufferParseEnd = p - &fParseBuffer[0]; // where we've gotten to
return True;
} else p += 3;
}
fParseBufferParseEnd = p - &fParseBuffer[0]; // where we've gotten to
return False; // no luck this time
}
void MPEG2IFrameIndexFromTransportStream::compactParseBuffer() {
#ifdef DEBUG
envir() << "Compacting parse buffer: [" << fParseBufferFrameStart
<< "," << fParseBufferParseEnd << "," << fParseBufferDataEnd << "]";
#endif
memmove(&fParseBuffer[0], &fParseBuffer[fParseBufferFrameStart],
fParseBufferDataEnd - fParseBufferFrameStart);
fParseBufferDataEnd -= fParseBufferFrameStart;
fParseBufferParseEnd -= fParseBufferFrameStart;
fParseBufferFrameStart = 0;
#ifdef DEBUG
envir() << "-> [" << fParseBufferFrameStart
<< "," << fParseBufferParseEnd << "," << fParseBufferDataEnd << "]\n";
#endif
}
void MPEG2IFrameIndexFromTransportStream::addToTail(IndexRecord* newIndexRecord) {
#ifdef DEBUG
envir() << "adding new: " << *newIndexRecord << "\n";
#endif
if (fTailIndexRecord == NULL) {
fHeadIndexRecord = fTailIndexRecord = newIndexRecord;
} else {
newIndexRecord->addAfter(fTailIndexRecord);
fTailIndexRecord = newIndexRecord;
}
}
////////// IndexRecord implementation //////////
IndexRecord::IndexRecord(u_int8_t startOffset, u_int8_t size,
unsigned long transportPacketNumber, float pcr)
: fNext(this), fPrev(this), fRecordType(RECORD_UNPARSED),
fStartOffset(startOffset), fSize(size),
fPCR(pcr), fTransportPacketNumber(transportPacketNumber) {
}
IndexRecord::~IndexRecord() {
IndexRecord* nextRecord = next();
unlink();
if (nextRecord != this) delete nextRecord;
}
void IndexRecord::addAfter(IndexRecord* prev) {
fNext = prev->fNext;
fPrev = prev;
prev->fNext->fPrev = this;
prev->fNext = this;
}
void IndexRecord::unlink() {
fNext->fPrev = fPrev;
fPrev->fNext = fNext;
fNext = fPrev = this;
}
| gpl-2.0 |
wicaksono/sistem-booking | protected/models/CommBookingEdition.php | 612 | <?php
/**
* Class CommBookingEdition
*
* @author Niko Wicaksono <wicaksono@nodews.com>
*/
class CommBookingEdition extends ActiveRecord {
public $cb_id;
public $ne_id;
public $created_at;
public static function model($className = __CLASS__)
{
return parent::model($className);
}
public function tableName()
{
return 'comm_booking_edition';
}
public function relations()
{
return array(
'cb' => [static::BELONGS_TO, 'CommBooking', 'cb_id'],
'ne' => [static::BELONGS_TO, 'NewsEdition', 'ne_id']
);
}
}
| gpl-2.0 |
Ten10/Burtle | Burtle/BurtleTest/BurtleTestDlg.cpp | 3888 |
// BurtleTestDlg.cpp : implementation file
//
#include "stdafx.h"
#include "BurtleTest.h"
#include "BurtleTestDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CBurtleTestDlg dialog
CBurtleTestDlg::CBurtleTestDlg()
{
//m_hIcon = LoadIcon(IDR_MAINFRAME);
}
void CBurtleTestDlg::DoDataExchange(CDataExchange& DataExchange)
{
__super::DoDataExchange(DataExchange);
}
// CBurtleTestDlg message handlers
bool CBurtleTestDlg::OnInitDialog()
{
CDialog::OnInitDialog();
CString sOptions = theApp.GetString(_T("Workspace"), _T("Options"));
m_Parameters = ::SysAllocString(sOptions.c_str());
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, true); // Set big icon
SetIcon(m_hIcon, false); // Set small icon
// TODO: Add extra initialization here
return TRUE; // return TRUE unless you set the focus to a control
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CBurtleTestDlg::OnPaint(const CWindow* pSender, CPaintArgs& Args)
{
if (IsIconic())
{
if (!Args.pPaintDC)
return;
CDC& dc = *Args.pPaintDC;
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(static_cast<HDC>(dc)), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect = GetClientRect();
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.Draw(x, y, m_hIcon);
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
void CBurtleTestDlg::OnQueryDragIcon(const CWindow* pSender, CQueryDragIconArgs& Args)
{
Args.DragIcon = m_hIcon;
}
void CBurtleTestDlg::OnBnClickedOptionsButton(const CWindow* pSender)
{
auto& provider = theApp.GetBugTraqProvider();
BSTR newParametes;
VARIANT_BOOL bHasOptions;
if (SUCCEEDED(provider.HasOptions(&bHasOptions)) && bHasOptions == VARIANT_TRUE)
{
HRESULT hr = provider.ShowOptionsDialog(m_hWnd, m_Parameters, &newParametes);
if (hr == S_OK)
{
m_Parameters = newParametes;
CString params = m_Parameters;
theApp.WriteString(_T("Workspace"), _T("Options"), params);
}
if (newParametes)
::SysFreeString(newParametes);
}
}
void CBurtleTestDlg::OnBnClickedGetCommitMessageButton(const CWindow* pSender)
{
auto& provider = theApp.GetBugTraqProvider();
provider.GetCommitMessage2(m_hWnd, m_Parameters, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
}
void CBurtleTestDlg::OnBnClickedOnCommitFinishedButton(const CWindow* pSender)
{
BSTR error = nullptr;
auto& provider = theApp.GetBugTraqProvider();
provider.OnCommitFinished(m_hWnd, nullptr, nullptr, nullptr, 100, &error);
if (error)
{
::MessageBox(m_hWnd, error, _T("Commit Finished"), MB_OK);
::SysFreeString(error);
}
}
void CBurtleTestDlg::InitializeEventMap()
{
__super::InitializeEventMap();
CWindowBase::OnPaint += CEventHandler<CPaintArgs>(&CBurtleTestDlg::OnPaint, *this);
CWindowBase::OnQueryDragIcon += CEventHandler<CQueryDragIconArgs>(&CBurtleTestDlg::OnQueryDragIcon, *this);
CButtonPressEvent<IDC_OPTIONS_BUTTON>(m_EventMap) += CEventHandler<CNoEventArgs>(&CBurtleTestDlg::OnBnClickedOptionsButton, *this);
CButtonPressEvent<IDC_GET_COMMIT_MESSAGE_BUTTON>(m_EventMap) += CEventHandler<CNoEventArgs>(&CBurtleTestDlg::OnBnClickedGetCommitMessageButton, *this);
CButtonPressEvent<IDC_ON_COMMIT_FINISHED_BUTTON>(m_EventMap) += CEventHandler<CNoEventArgs>(&CBurtleTestDlg::OnBnClickedOnCommitFinishedButton, *this);
} | gpl-2.0 |
creative2020/ue2 | wp-content/plugins/wp-time-capsule/Classes/Processed/Restoredfiles.php | 7387 | <?php
/**
* A class with functions the perform a backup of WordPress
*
* @copyright Copyright (C) 2011-2014 Awesoft Pty. Ltd. All rights reserved.
* @author Michael De Wildt (http://www.mikeyd.com.au/)
* @license This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA.
*/
class WPTC_Processed_Restoredfiles extends WPTC_Processed_Base
{
protected function getTableName()
{
return 'restored_files';
}
protected function getProcessType()
{
$options_obj = WPTC_Factory::get('config');
if(!$options_obj->get_option('is_bridge_process'))
{
return null;
}
else
{
return 'restore';
}
}
protected function getId()
{
return 'file';
}
protected function getRevisionId() {
return 'revision_id';
}
protected function getRestoreTableName()
{
return 'restored_files';
}
protected function getFileId()
{
return 'file_id';
}
protected function getUploadMtime()
{
return 'mtime_during_upload';
}
public function get_restored_files_from_base()
{
return $this->get_processed_restores();
}
public function get_restore_queue_from_base()
{
return $this->get_all_restores();
}
public function get_file_count()
{
//file_put_contents(WP_CONTENT_DIR .'/DE_clientPluginSIde.php',"\n ------calling this get_file_count-------- \n",FILE_APPEND);
return count($this->processed);
}
public function get_file($file_name)
{
////file_put_contents(WP_CONTENT_DIR .'/DE_clientPluginSIde.php',"\n ------processed file-------- ".var_export($this -> processed,true)."\n",FILE_APPEND);
foreach ($this->processed as $file) {
if ($file->file == $file_name){
return $file;
}
}
}
public function file_complete($file)
{
$this->update_file($file, 0, 0);
}
public function update_file($file, $upload_id = null, $offset, $backupID = 0, $chunked = null)
{
////file_put_contents(WP_CONTENT_DIR .'/DE_clientPluginSIde.php',"\n ----getTcCookie---- ".var_export(getTcCookie('backupID'),true)."\n",FILE_APPEND);
//am adding few conditions to insert the new file with new backup id if the file is modified //manual
$may_be_stored_file_obj = $this->get_file($file);
if($offset > 0)
{
$download_status = 'done';
}
else
{
$download_status = 'notDone';
}
if($may_be_stored_file_obj)
{
$may_be_stored_file_id = $may_be_stored_file_obj -> file_id;
}
if(!empty($may_be_stored_file_obj) && !empty($may_be_stored_file_id))
{ //this condition is to update the tables based on file_id
$upsert_array = array(
'file' => $file,
'offset' => $offset,
'backupID' => getTcCookie('backupID'), //get the backup ID from cookie
'file_id' => $may_be_stored_file_id,
);
}
else
{
$upsert_array = array(
'file' => $file,
'offset' => $offset,
'download_status' => $download_status,
'backupID' => getTcCookie('backupID'),
);
}
//file_put_contents(WP_CONTENT_DIR .'/DE_clientPluginSIde.php',"\n -----track download offset update file------- ".var_export($upsert_array,true)."\n",FILE_APPEND);
$this->upsert($upsert_array);
}
public function add_files_for_restoring($files_to_restore){
//this is totally a new function to store the files-to-be-restored in the DB table
//file_put_contents(WP_CONTENT_DIR .'/DE_clientPluginSIde.php',"\n ----add_files_for_restoring - files to restore------ ".var_export($files_to_restore,true)."\n",FILE_APPEND);
if(!empty($files_to_restore))
{
//file_put_contents(WP_CONTENT_DIR .'/DE_clientPluginSIde.php',"\n -----not empty-------\n",FILE_APPEND);
foreach ($files_to_restore as $revision => $file_dets) {
//preparing the file name for the sql file
$this_filename = $file_dets['file_name'];
if((false !== strpos($this_filename, "backup.sql")) && (false !== strpos($this_filename, "wptc-secret")))
{
$this_pos = strripos($this_filename, ".sql") + 4;
$this_filename = substr($this_filename, 0, $this_pos);
}
//file_put_contents(WP_CONTENT_DIR .'/DE_clientPluginSIde.php',"\n ----foreach add_files_for_restoring------- ".var_export($this_filename,true)."\n",FILE_APPEND);
if($this_filename!=""){
$this->upsert(array(
'file' => $this_filename,
'revision_id' => $revision,
'offset' => null,
'backupID' => getTcCookie('backupID'),
'uploaded_file_size' => $file_dets['file_size'],
'download_status' => ($file_dets['file_size'] > 4024000) ? 'done' : 'notDone', //am adding an extra condition for chunked download
));
}
}
}
}
public function add_files($new_files)
{
//file_put_contents(WP_CONTENT_DIR .'/DE_clientPluginSIde.php',"\n -----add files of restore--- \n",FILE_APPEND);
foreach ($new_files as $file) {
/* //am adding few conditions to insert the new file with new backup id if the file is modified //manual
$may_be_stored_file_obj = $this->get_file($file['filename']);
$may_be_stored_filename = $may_be_stored_file_obj -> file;
$may_be_stored_upload_mtime = $may_be_stored_file_obj -> mtime_during_upload;
//if ($this->get_file($file['filename'])) { //manual
if (!empty($may_be_stored_file_obj) && ($may_be_stored_upload_mtime == $file['mtime_during_upload'])) {
//file_put_contents(WP_CONTENT_DIR .'/DE_clientPluginSIde.php',"\n ------skipping-------- ".var_export($file['file'],true)."\n",FILE_APPEND);
continue;
}
*/
//file_put_contents(WP_CONTENT_DIR .'/DEBUG.php',"\n -----Files to be added--- \n",FILE_APPEND);
//file_put_contents(WP_CONTENT_DIR .'/DEBUG.php', var_export($file,true),FILE_APPEND);
$this->upsert(array(
'file' => $file['file'],
'uploadid' => null,
'offset' => null,
'backupID' => getTcCookie('backupID'),
'revision_number' => $file['revision_number'],
'revision_id' => $file['revision_id'],
'mtime_during_upload' => $file['mtime_during_upload'],
'download_status' => 'done',
'copy_status' => $file['copy_status'],
));
}
return $this;
}
}
| gpl-2.0 |
shalkam/crud-generator | src/Shalkam/CrudGenerator/views/entry/details.blade.php | 1508 | @extends('crud::app')
@section('title')
{{ $entry->name }}
<button type="button" class="btn btn-danger btn-sm pull-right" style="margin-top: -5px" data-toggle="modal" data-target="#myModal">
<i class="glyphicon glyphicon-remove"></i> Delete {{ $params['name'] }}
</button>
@endsection
@section('content')
<ul>
@foreach ($entry->getAttributes() as $id=> $val)
<li>{{ $id }} : {{$val}}</li>
@endforeach
</ul>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Delete {{ $params['name'] }}</h4>
</div>
{!! Form::model($entry, array('route' => array($params['route'].'.destroy', $entry->id), 'method'=>'DELETE')) !!}
<div class="modal-body">
Are you sure you want to delete this {{ $params['name'] }} data?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
{!! Form::submit("Delete {$params['name']}", ['class'=>'btn btn-danger' ]) !!}
</div>
{!! Form::close() !!}
</div>
</div>
</div>
@endsection | gpl-2.0 |
josdavidmo/siruc | system/buffer/loadConfig.php | 1062 | <?php
$dir = "system/lang/".LANG_DIR."/";
$handle = opendir($dir);
while ($file = readdir($handle)) {
if ($file != "." && $file != "..") {
require_once($dir . $file);
}
}
closedir($handle);
$path = "system/database";
require_once "$path/Persistence.php";
require_once "$path/PersistenceImpl.php";
$implementor = NULL;
switch (DB_DRIVER) {
case "MySQL":
$driver = "MySQLPersistenceImplementor.php";
require_once "$path/drivers/$driver";
$implementor = new MySQLPersistenceImplementor(DB_HOST, DB_USER, DB_PASS, DB_SCHEMA);
break;
}
$dir = "system/classes/dao/";
$handle = opendir($dir);
while ($file = readdir($handle)) {
if ($file != "." && $file != "..") {
require_once($dir . $file);
}
}
closedir($handle);
$dir = "system/classes/model/";
$handle = opendir($dir);
while ($file = readdir($handle)) {
if ($file != "." && $file != "..") {
require_once($dir . $file);
}
}
closedir($handle);
require_once 'system/html/docs/table.php'; | gpl-2.0 |
testmycode/tmc-netbeans | tmc-plugin/src/fi/helsinki/cs/tmc/ui/CourseListWindow.java | 7492 | package fi.helsinki.cs.tmc.ui;
import com.google.common.base.Optional;
import fi.helsinki.cs.tmc.actions.ShowSettingsAction;
import fi.helsinki.cs.tmc.core.domain.Course;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
import fi.helsinki.cs.tmc.model.CourseDb;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.BoxLayout;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;
public class CourseListWindow extends JPanel {
private static JFrame frame;
private final JLabel title;
private final JList<Course> courses;
private PreferencesPanel prefPanel;
private static JButton button;
public CourseListWindow(List<Course> courses, PreferencesPanel prefPanel) {
this.prefPanel = prefPanel;
this.title = new JLabel("Select a course:");
Font titleFont = this.title.getFont();
this.title.setFont(new Font(titleFont.getName(), Font.BOLD, 20));
this.title.setBorder(new MatteBorder(new Insets(10, 10, 5, 10), getBackground()));
Course[] courseArray = courses.toArray(new Course[courses.size()]);
this.courses = new JList<>(courseArray);
this.courses.setFixedCellHeight(107);
this.courses.setFixedCellWidth(346);
this.courses.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.button = new JButton("Select");
button.addActionListener(new SelectCourseListener(this));
this.courses.setCellRenderer(new CourseCellRenderer());
this.courses.setVisibleRowCount(4);
JScrollPane pane = new JScrollPane(this.courses);
Dimension d = pane.getPreferredSize();
d.width = 800;
d.height = (int) (d.height * 1.12);
pane.setPreferredSize(d);
pane.setBorder(new EmptyBorder(5, 0, 5, 0));
pane.setViewportBorder(new EmptyBorder(0, 0, 0, 0));
pane.getVerticalScrollBar().setUnitIncrement(10);
this.courses.setBackground(new Color(242, 241, 240));
this.courses.setSelectedIndex(setDefaultSelectedIndex());
this.courses.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent event) {
if (event.getClickCount() >= 2) {
button.doClick();
}
}
});
add(title);
add(pane);
add(button);
}
public static void display() throws Exception {
PreferencesPanel prefPanel;
if (PreferencesUIFactory.getInstance().getCurrentUI() == null) {
prefPanel = (PreferencesPanel) PreferencesUIFactory.getInstance().createCurrentPreferencesUI();
} else {
prefPanel = (PreferencesPanel) PreferencesUIFactory.getInstance().getCurrentUI();
}
if (frame == null) {
frame = new JFrame("Courses");
}
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
List<Course> courses = prefPanel.getAvailableCourses();
CourseDb.getInstance().setAvailableCourses(courses);
final CourseListWindow courseListWindow = new CourseListWindow(courses, prefPanel);
frame.setContentPane(courseListWindow);
button.setMinimumSize(new Dimension(courseListWindow.getWidth(), button.getHeight()));
button.setMaximumSize(new Dimension(courseListWindow.getWidth(), button.getHeight()));
courseListWindow.addComponentListener(new ComponentListener() {
@Override
public void componentResized(ComponentEvent event) {
button.setMinimumSize(new Dimension(courseListWindow.getWidth(), button.getHeight()));
button.setMaximumSize(new Dimension(courseListWindow.getWidth(), button.getHeight()));
}
@Override
public void componentMoved(ComponentEvent e) {
}
@Override
public void componentShown(ComponentEvent e) {
}
@Override
public void componentHidden(ComponentEvent e) {
}
});
if (hasCourses(courses, prefPanel)) {
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
public static boolean isWindowVisible() {
if (frame == null) {
return false;
}
return frame.isVisible();
}
private static boolean hasCourses(List<Course> courses, PreferencesPanel panel) {
if (courses.isEmpty()) {
JOptionPane.showMessageDialog(panel, "Organization has no courses!", "Error", JOptionPane.ERROR_MESSAGE);
frame.setVisible(false);
frame.dispose();
return false;
}
return true;
}
private int setDefaultSelectedIndex() {
final Optional<Course> currentCourse = TmcSettingsHolder.get().getCurrentCourse();
if (!currentCourse.isPresent()) {
return 0;
}
String selectedCourseName = currentCourse.get().getName();
final ListModel<Course> list = courses.getModel();
for (int i = 0; i < list.getSize(); i++) {
if (list.getElementAt(i).getName().equals(selectedCourseName)) {
return i;
}
}
return 0;
}
class SelectCourseListener implements ActionListener {
public SelectCourseListener(CourseListWindow window) {
}
@Override
public void actionPerformed(ActionEvent e) {
prefPanel.setSelectedCourse(courses.getSelectedValue());
frame.setVisible(false);
frame.dispose();
new ShowSettingsAction().run();
}
}
}
class CourseCellRenderer extends DefaultListCellRenderer {
private static final Color HIGHLIGHT_COLOR = new Color(240, 119, 70);
private final Map<Course, CourseCard> cachedCourses;
public CourseCellRenderer() {
this.cachedCourses = new HashMap<>();
}
@Override
public Component getListCellRendererComponent(final JList list,
final Object value, final int index, final boolean isSelected,
final boolean hasFocus) {
final Course course = (Course)value;
if (!this.cachedCourses.containsKey(course)) {
this.cachedCourses.put(course, new CourseCard(course));
}
CourseCard courseCard = this.cachedCourses.get(course);
if (isSelected) {
courseCard.setColors(Color.white, HIGHLIGHT_COLOR);
} else {
courseCard.setColors(new Color(76, 76, 76), Color.white);
}
return courseCard;
}
}
| gpl-2.0 |
AlanGuerraQuispe/SisAtuxPerfumeria | atux-jrcp/src/main/java/com/aw/swing/mvp/binding/component/support/ButtonColumn.java | 1548 | package com.aw.swing.mvp.binding.component.support;
import com.aw.core.cache.loader.MetaLoader;
/**
* User: gmc
* Date: 29/04/2009
*/
public class ButtonColumn extends ColumnInfo {
String text = null;
public ButtonColumn(String columnHeader, String fieldName, int width, int alignment) {
super(columnHeader, fieldName, width, alignment);
isPrintable = false;
setAsEditable(BUTTON);
setRptChrs(0);
}
public ButtonColumn setAsEditable(int editorType) {
super.setAsEditable(editorType);
return this;
}
public ButtonColumn setText(String text) {
this.text = text;
return this;
}
public ButtonColumn setTextFromFieldName(String fieldName) {
this.fieldName = fieldName;
this.text = null;
return this;
}
@Override
public Object getValue(Object object, int index, int row) {
if (metaLoader!=null){
return super.getValue(object, index, row);
}
return text != null ? text : super.getValue(object, index, row);
}
@Override
public void setValue(Object object, Object value, int row) {
// no es necesario llamar a este metodo pues se hace dinamicamente en el editor
//executeChangeValueListener(object, value, value);
}
@Override
public ColumnInfo setDropDownFormatter(MetaLoader metaLoader) {
this.metaLoader = metaLoader;
return this;
}
public boolean isEditable() {
return false;
}
} | gpl-2.0 |
micpe083/backup-utils | src/main/java/backup/gui/explorer/FileInfoTablePanel.java | 4777 | package backup.gui.explorer;
import java.util.List;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import backup.api.BackupUtil;
import backup.api.FileInfo;
import backup.api.FileInfoPath;
import backup.api.FileManager;
import backup.gui.common.GuiUtils;
public class FileInfoTablePanel extends BorderPane
{
private final ObservableList<FileInfoPath> tableItems;
private final Label label;
private final TableView<FileInfoPath> tableView;
public FileInfoTablePanel()
{
tableItems = FXCollections.observableArrayList();
tableView = new TableView<>(tableItems);
final TableColumn<FileInfoPath, String> col0 = new TableColumn<>("Name");
col0.setCellValueFactory(p -> new ReadOnlyObjectWrapper<>(p.getValue().getFileInfo().getFilename()));
col0.prefWidthProperty().bind(tableView.widthProperty().multiply(0.3));
tableView.getColumns().add(col0);
final TableColumn<FileInfoPath, String> col1 = new TableColumn<>("Path");
col1.setCellValueFactory(p -> new ReadOnlyObjectWrapper<>(p.getValue().getPath()));
col1.prefWidthProperty().bind(tableView.widthProperty().multiply(0.6));
tableView.getColumns().add(col1);
final TableColumn<FileInfoPath, String> col2 = new TableColumn<>("Size");
col2.setCellValueFactory(p -> new ReadOnlyObjectWrapper<>(BackupUtil.humanReadableByteCount(p.getValue().getFileInfo().getSize())));
col2.prefWidthProperty().bind(tableView.widthProperty().multiply(0.1));
tableView.getColumns().add(col2);
final TableColumn<FileInfoPath, String> col3 = new TableColumn<>("Alg");
col3.setCellValueFactory(p -> new ReadOnlyObjectWrapper<>(p.getValue().getFileInfo().getDigestAlg().name()));
col3.prefWidthProperty().bind(tableView.widthProperty().multiply(0.1));
tableView.getColumns().add(col3);
final TableColumn<FileInfoPath, String> col4 = new TableColumn<>("Digest");
col4.setCellValueFactory(p -> new ReadOnlyObjectWrapper<>(p.getValue().getFileInfo().getDigest()));
col4.prefWidthProperty().bind(tableView.widthProperty().multiply(0.2));
tableView.getColumns().add(col4);
final TableColumn<FileInfoPath, String> col5 = new TableColumn<>("Timestamp");
col5.setCellValueFactory(p -> new ReadOnlyObjectWrapper<>(p.getValue().getFileInfo().getLastModifiedStr()));
col5.prefWidthProperty().bind(tableView.widthProperty().multiply(0.2));
tableView.getColumns().add(col5);
final TableColumn<FileInfoPath, Integer> col6 = new TableColumn<>("Path Len");
col6.setCellValueFactory(p -> new ReadOnlyObjectWrapper<>(p.getValue().getPath().length()));
col6.prefWidthProperty().bind(tableView.widthProperty().multiply(0.1));
tableView.getColumns().add(col6);
tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
//pathList.setVisibleRowCount(4);
tableView.setPrefHeight(100);
label = new Label();
final ScrollPane scrollPane = GuiUtils.createScrollPane(tableView);
setCenter(scrollPane);
setBottom(label);
setFileInfo(null, null);
}
public TableView<FileInfoPath> getTableView()
{
return tableView;
}
public void addFiles(final FileManager fileManager)
{
tableItems.clear();
for (final FileInfo fileInfo : fileManager.getMap().keySet())
{
addFile(fileManager, fileInfo);
}
}
public void setFileInfo(final FileManager fileManager,
final FileInfo fileInfo)
{
tableItems.clear();
addFile(fileManager, fileInfo);
}
public void addFile(final FileManager fileManager,
final FileInfo fileInfo)
{
if (fileManager == null ||
fileInfo == null)
{
label.setText("-");
}
else
{
final List<String> paths = fileManager.getMap().get(fileInfo);
for (final String path : paths)
{
final FileInfoPath fileInfoPath = new FileInfoPath(fileInfo, path);
tableItems.add(fileInfoPath);
}
label.setText("File Count: " + paths.size());
}
}
}
| gpl-2.0 |
HannesMann/dolphin-hau | Source/Core/Core/HW/DVD/FileMonitor.cpp | 4304 | // Copyright 2009 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
#include "Core/HW/DVD/FileMonitor.h"
#include <algorithm>
#include <cctype>
#include <memory>
#include <string>
#include <unordered_set>
#include "Common/CommonTypes.h"
#include "Common/Logging/Log.h"
#include "Common/Logging/LogManager.h"
#include "Common/StringUtil.h"
#include "DiscIO/Enums.h"
#include "DiscIO/Filesystem.h"
#include "DiscIO/Volume.h"
namespace FileMonitor
{
static const DiscIO::IVolume* s_volume = nullptr;
static bool s_wii_disc;
static std::unique_ptr<DiscIO::IFileSystem> s_filesystem;
static std::string s_previous_file;
// Filtered files
static bool IsSoundFile(const std::string& filename)
{
std::string extension;
SplitPath(filename, nullptr, nullptr, &extension);
std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);
static const std::unordered_set<std::string> extensions = {
".adp", // 1080 Avalanche, Crash Bandicoot, etc.
".adx", // Sonic Adventure 2 Battle, etc.
".afc", // Zelda WW
".ast", // Zelda TP, Mario Kart
".brstm", // Wii Sports, Wario Land, etc.
".dsp", // Metroid Prime
".hps", // SSB Melee
".ogg", // Tony Hawk's Underground 2
".sad", // Disaster
".snd", // Tales of Symphonia
".song", // Tales of Symphonia
".ssm", // Custom Robo, Kirby Air Ride, etc.
".str", // Harry Potter & the Sorcerer's Stone
};
return extensions.find(extension) != extensions.end();
}
void SetFileSystem(const DiscIO::IVolume* volume)
{
// Instead of creating the file system object right away, we will let Log
// create it later once we know that it actually will get used
s_volume = volume;
// If the volume that was passed in was nullptr, Log won't try to create a
// file system object later, so we have to set s_filesystem to nullptr right away
s_filesystem = nullptr;
}
// Logs access to files in the file system set by SetFileSystem
void Log(u64 offset, bool decrypt)
{
// Do nothing if the log isn't selected
if (!LogManager::GetInstance()->IsEnabled(LogTypes::FILEMON, LogTypes::LWARNING))
return;
// If a new volume has been set, use the file system of that volume
if (s_volume)
{
s_wii_disc = s_volume->GetVolumeType() == DiscIO::Platform::WII_DISC;
if (decrypt != s_wii_disc)
return;
s_filesystem = DiscIO::CreateFileSystem(s_volume);
s_volume = nullptr;
s_previous_file.clear();
}
// For Wii discs, FileSystemGCWii will only load file systems from encrypted partitions
if (decrypt != s_wii_disc)
return;
// Do nothing if there is no valid file system
if (!s_filesystem)
return;
const std::string filename = s_filesystem->GetFileName(offset);
// Do nothing if no file was found at that offset
if (filename.empty())
return;
// Do nothing if we found the same file again
if (s_previous_file == filename)
return;
const u64 size = s_filesystem->GetFileSize(filename);
const std::string size_string = ThousandSeparate(size / 1000, 7);
const std::string log_string =
StringFromFormat("%s kB %s", size_string.c_str(), filename.c_str());
if (IsSoundFile(filename))
INFO_LOG(FILEMON, "%s", log_string.c_str());
else
WARN_LOG(FILEMON, "%s", log_string.c_str());
// Update the last accessed file
s_previous_file = filename;
}
// based on Log(u64 offset, bool decrypt)
std::string GetFileNameAt(u64 offset, bool decrypt)
{
// If a new volume has been set, use the file system of that volume
if (s_volume)
{
s_wii_disc = s_volume->GetVolumeType() == DiscIO::Platform::WII_DISC;
if (decrypt != s_wii_disc)
return "";
s_filesystem = DiscIO::CreateFileSystem(s_volume);
s_volume = nullptr;
s_previous_file.clear();
}
// For Wii discs, FileSystemGCWii will only load file systems from encrypted partitions
if (decrypt != s_wii_disc)
return "";
// Do nothing if there is no valid file system
if (!s_filesystem)
return "";
const std::string filename = s_filesystem->GetFileName(offset);
// Do nothing if no file was found at that offset
if (filename.empty())
return "";
return filename;
}
} // namespace FileMonitor
| gpl-2.0 |
hardvain/mono-compiler | class/System.Web/System.Web.UI.WebControls/ObjectDataSourceMethodEventHandler.cs | 1411 | //
// System.Web.UI.WebContrls.ObjectDataSourceMethodEventHandler.cs;
//
// Authors:
// Sanjay Gupta (gsanjay@novell.com)
//
// (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.
//
namespace System.Web.UI.WebControls {
public delegate void ObjectDataSourceMethodEventHandler (object sender, ObjectDataSourceMethodEventArgs e);
}
| gpl-2.0 |
ovpn-to/oVPN.to-Client-Software | idle.py | 457 | # -*- coding: utf-8 -*-
from ctypes import Structure, windll, c_uint, sizeof, byref
class LASTINPUTINFO(Structure):
_fields_ = [
('cbSize', c_uint),
('dwTime', c_uint),
]
def get_idle_duration():
lastInputInfo = LASTINPUTINFO()
lastInputInfo.cbSize = sizeof(lastInputInfo)
windll.user32.GetLastInputInfo(byref(lastInputInfo))
millis = windll.kernel32.GetTickCount() - lastInputInfo.dwTime
return millis / 1000.0 | gpl-2.0 |
tphillips/SERV | SERVDAL/RunLogDAL.cs | 11885 | using System;
using System.Collections.Generic;
using SERVDataContract.DbLinq;
using System.Data;
using SERV.Utils.Data;
using System.Linq;
namespace SERVDAL
{
public class RunLogDAL
{
private SERVDataContract.DbLinq.SERVDB db;
public RunLogDAL()
{
db = new SERVDataContract.DbLinq.SERVDB(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]);
}
public RunLog Get(int runLogID)
{
return (from rl in db.RunLog
where rl.RunLogID == runLogID
select rl).FirstOrDefault();
}
public void SetAcceptedDateTime(int runLogId)
{
RunLog l = (from rl in db.RunLog where rl.RunLogID == runLogId select rl).FirstOrDefault();
l.AcceptedDateTime = DateTime.Now;
db.SubmitChanges();
}
public List<RunLog> ListQueuedOrders()
{
return (from rl in db.RunLog where rl.AcceptedDateTime == null && rl.RiderMemberID == null
orderby rl.CallDateTime descending
select rl).ToList();
}
public List<RunLog> ListQueuedOrdersForMember(int memberID)
{
return (from rl in db.RunLog where rl.AcceptedDateTime == null && rl.RiderMemberID == memberID
orderby rl.CallDateTime descending
select rl).ToList();
}
public List<RunLog> ListRecent(int recent)
{
return (from rl in db.RunLog where rl.DeliverDateTime != null
orderby rl.CallDateTime descending
select rl).Take(recent).ToList();
}
public List<RunLog> ListYesterdays()
{
List<RunLog> ret = (from rl in db.RunLog
where rl.DeliverDateTime != null
//&& rl.CallDateTime >= new DateTime(DateTime.Now.AddDays(-1).Year, DateTime.Now.AddDays(-1).Month, DateTime.Now.AddDays(-1).Day) &&
//rl.CallDateTime < new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 13, 00,00)
orderby rl.CallDateTime descending
select rl).Take(100).ToList(); // This is a complete hack until I can get the commented out clause above working :S
return (from rl in ret
where rl.DutyDate >= new DateTime(DateTime.Now.AddDays(-1).Year, DateTime.Now.AddDays(-1).Month, DateTime.Now.AddDays(-1).Day) &&
rl.DutyDate < new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day)
select rl).ToList();
}
public bool CreateRawRecord(RawRunLog raw)
{
db.RawRunLog.InsertOnSubmit(raw);
db.SubmitChanges();
return true;
}
public void CreateRawRecords(List<RawRunLog> records)
{
foreach (RawRunLog r in records)
{
db.RawRunLog.InsertOnSubmit(r);
}
db.SubmitChanges();
}
public int CreateRunLog(RunLog log, List<int> prods)
{
db.RunLog.InsertOnSubmit(log);
db.SubmitChanges();
LinkRunLogToProducts(log, prods);
return log.RunLogID;
}
public void DeleteRunLog(int runLogID)
{
RunLog d = Get(runLogID);
foreach (RunLogProduct rlp in d.RunLogProduct)
{
db.RunLogProduct.DeleteOnSubmit(rlp);
}
db.RunLog.DeleteOnSubmit(d);
db.SubmitChanges();
}
private void LinkRunLogToProducts(RunLog log, List<int> prods)
{
Dictionary<int, int> prodD = new Dictionary<int, int>();
foreach (int p in prods)
{
if (prodD.ContainsKey(p))
{
prodD[p] = prodD[p] + 1;
}
else
{
prodD.Add(p, 1);
}
}
foreach (int p in prodD.Keys)
{
RunLogProduct rlp = new RunLogProduct();
rlp.ProductID = p;
rlp.RunLogID = log.RunLogID;
rlp.Quantity = prodD[p];
log.Description += string.Format("{0} x {1} ", prodD[p], (from prod in db.Product
where prod.ProductID == p
select prod).FirstOrDefault().Product1);
db.RunLogProduct.InsertOnSubmit(rlp);
}
db.SubmitChanges();
}
public void TruncateRawRunLog()
{
db.ExecuteCommand("truncate table RawRunLog");
}
public DataTable GetMemberUniqueRuns(int memberID)
{
string sql = "select distinct l.Location, p.Product from RunLog rl " +
"join RunLog_Product rlp on rlp.RunLogID = rl.RunLogID " +
"join Product p on rlp.ProductID = p.ProductID " +
"join Location l on l.LocationID = rl.DeliverToLocationID " +
"where rl.RiderMemberID = " + memberID + " " +
"order by Location";
return DBHelperFactory.DBHelper().ExecuteDataTable(sql);
}
public DataTable RunReport(SERVDataContract.Report report)
{
return DBHelperFactory.DBHelper().ExecuteDataTable(report.Query);
}
public DataTable ExecuteSQL(string sql)
{
return DBHelperFactory.DBHelper().ExecuteDataTable(sql);
}
/*
public DataTable Report_RecentRunLog()
{
string sql =
"SELECT " +
"date(CallDate) as Date, " +
"TIME(rpad(replace(CallTime, '.',':'), 5, '0')) as Time, " +
"CONCAT(m.FirstName, ' ', m.LastName) as Rider, " +
"Consignment, " +
"CollectFrom as Origin, " +
"Destination, " +
"CONCAT(con.FirstName, ' ', con.LastName) as Controller " +
"FROM RawRunLog rr " +
"LEFT JOIN Member m on rr.Rider = (CONCAT(m.LastName, ' ', m.FirstName)) " +
"LEFT JOIN Member con on rr.Controller = (CONCAT(con.LastName, ' ', con.FirstName)) " +
"order by CallDate desc, RawRunLogID desc " +
"LIMIT 100;";
return DBHelperFactory.DBHelper().ExecuteDataTable(sql);
}
public DataTable Report_Top10Riders()
{
string sql =
"select Name from " +
"(select CONCAT(m.FirstName, ' ', m.LastName) Name, count(*) Runs " +
"from RunLog rl " +
"LEFT join Member m on m.MemberID = rl.RiderMemberID " +
"group by Name " +
"order by Runs desc " +
"LIMIT 10) top " +
"order by Name;";
return DBHelperFactory.DBHelper().ExecuteDataTable(sql);
}
public DataTable Report_Top102013Riders()
{
string sql =
"select Name from " +
"(select CONCAT(m.FirstName, ' ', m.LastName) Name, count(*) Runs " +
"from RawRunLog rr " +
"LEFT join Member m on rr.Rider = (CONCAT(m.LastName, ' ', m.FirstName)) " +
"where m.FirstName is not null " +
"group by Name " +
"order by Runs desc " +
"LIMIT 10) sub " +
"order by Name;";
return DBHelperFactory.DBHelper().ExecuteDataTable(sql);
}
public DataTable Report_RunButNoLogin()
{
string sql = "select CONCAT(m.FirstName, ' ', m.LastName) as Rider, date(m.JoinDate) as Joined, m.EmailAddress as Email, date(max(rr.CallDate)) as LastRun, count(*) as Runs " +
"from RawRunLog rr " +
"LEFT join Member m on rr.Rider = (CONCAT(m.LastName, ' ', m.FirstName)) " +
"where m.MemberID not in " +
"(select m.MemberID from User u join Member m on m.MemberID = u.MemberID where u.lastLoginDate is not null) " +
"and rr.CallDate > '2013-05-01' " +
"and m.LeaveDate is null " +
"group by m.MemberID " +
"order by max(rr.CallDate) desc;";
return DBHelperFactory.DBHelper().ExecuteDataTable(sql);
}
public DataTable Report_AverageCallsPerDay()
{
string sql = "SELECT dayname(case when Hour(CallTime) > 17 then CallDate else AddDate(CallDate, -1) end) as ShiftDay " +
", round(count(*) / 34.28) as AverageCalls " +
//", ceil((count(*) / @weeks) * @riderfactor) as RidersRequired " +
"FROM RawRunLog " +
"WHERE CallDate > AddDate(CURRENT_DATE, -240) " +
"AND(Consignment like '%blood%' " +
"or Consignment like '%plate%' " +
"or Consignment like '%plas%' " +
"or Consignment like '%ffp%' " +
"or Consignment like '%sample%' " +
"or Consignment like '%drugs%' " +
"or Consignment like '%cd%' " +
"or Consignment like '%data%' " +
"or Consignment like '%disk%' " +
"or Consignment like '%disc%' " +
"or Consignment like '%package%') " +
"GROUP BY dayname(case when Hour(CallTime) > 17 then CallDate else AddDate(CallDate, -1) end) " +
"ORDER BY dayofweek(case when Hour(CallTime) > 17 then CallDate else AddDate(CallDate, -1) end);";
return DBHelperFactory.DBHelper().ExecuteDataTable(sql);
}
public DataTable Report_CallsPerHourHeatMap()
{
string sql = "select dayname(case when Hour(CallTime) > 17 then CallDate else AddDate(CallDate, -1) end) as Day, " +
"Hour(CallTime) as Hour, count(*) as Calls " +
"from RawRunLog " +
"WHERE CallDate > AddDate(CURRENT_DATE, -240) " +
"AND Hour(CallTime) >= 0 AND Hour(CallTime) <= 23 " +
"AND(Consignment like '%blood%' " +
"or Consignment like '%plate%' " +
"or Consignment like '%plas%' " +
"or Consignment like '%ffp%' " +
"or Consignment like '%sample%' " +
"or Consignment like '%drugs%' " +
"or Consignment like '%cd%' " +
"or Consignment like '%data%' " +
"or Consignment like '%disk%' " +
"or Consignment like '%disc%' " +
"or Consignment like '%package%') " +
"group by dayname(case when Hour(CallTime) > 17 then CallDate else AddDate(CallDate, -1) end), Hour(CallTime) " +
"ORDER BY dayofweek(case when Hour(CallTime) > 17 then CallDate else AddDate(CallDate, -1) end), Hour(CallTime)";
return DBHelperFactory.DBHelper().ExecuteDataTable(sql);
}
public DataTable Report_TodaysUsers()
{
string sql = "select CONCAT(m.FirstName, ' ', m.LastName) as Member " +
"from User u join Member m on m.MemberID = u.MemberID where u.lastLoginDate > CURRENT_DATE() " +
"order by lastLoginDate desc;";
return DBHelperFactory.DBHelper().ExecuteDataTable(sql);
}
public DataTable Report_BoxesByProductByMonth()
{
string sql = "select concat(MONTHNAME(rl.DutyDate), ' ', year(rl.DutyDate)) as Month " +
", p.Product, sum(rlp.Quantity) as BoxesCarried from RunLog rl " +
"join RunLog_Product rlp on rlp.RunLogID = rl.RunLogID " +
"join Product p on p.ProductID = rlp.ProductID " +
"group by Month, Product " +
"order by month(rl.DutyDate), Product;";
return DBHelperFactory.DBHelper().ExecuteDataTable(sql);
}
*/
public DataTable Report_RunLog()
{
string sql = "select RunLogID as ID, date_format(DutyDate, '%Y-%m-%d') as 'DutyDate', " +
"coalesce(date_format(CallDateTime, '%Y-%m-%d %H:%i'), 'N/A') as 'CallDateTime', cf.Location as 'CallFrom', cl.Location as 'From', " +
"dl.Location as 'To', coalesce(date_format(rl.CollectDateTime, '%H:%i'), 'NOT ACCEPTED') as Collected, " +
"date_format(rl.DeliverDateTime, '%H:%i') as Delivered, " +
//"timediff(rl.DeliverDateTime, rl.CollectDateTime) as 'Run Time', " +
"fl.Location as 'Destination', concat(m.FirstName, ' ', m.LastName) as Rider, " +
"v.VehicleType as 'Vehicle', rl.Description as 'Consignment', " +
"concat(c.FirstName, ' ', c.LastName) as Controller from RunLog rl " +
"left join Member m on m.MemberID = rl.RiderMemberID " +
"join Member c on c.MemberID = rl.ControllerMemberID " +
"join Location cf on cf.LocationID = rl.CallFromLocationID " +
"join Location cl on cl.LocationID = rl.CollectionLocationID " +
"join Location dl on dl.LocationID = rl.DeliverToLocationID " +
"join Location fl on fl.LocationID = rl.FinalDestinationLocationID " +
"left join VehicleType v on v.VehicleTypeID = rl.VehicleTypeID " +
"where DutyDate > '2016-12-31' or CallDateTime > '2016-12-31' " +
"order by rl.DutyDate desc, rl.CallDateTime desc;";
DataTable ret = DBHelperFactory.DBHelper().ExecuteDataTable(sql);
return ret;
}
public void Dispose()
{
db.Dispose();
}
}
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/hotspot/agent/src/share/classes/sun/jvm/hotspot/jdi/StringReferenceImpl.java | 1616 | /*
* Copyright 2002-2003 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*
*/
package sun.jvm.hotspot.jdi;
import com.sun.jdi.*;
import sun.jvm.hotspot.oops.Instance;
import sun.jvm.hotspot.oops.OopUtilities;
public class StringReferenceImpl extends ObjectReferenceImpl
implements StringReference
{
private String value;
StringReferenceImpl(VirtualMachine aVm, sun.jvm.hotspot.oops.Instance oRef) {
super(aVm,oRef);
value = OopUtilities.stringOopToString(oRef);
}
public String value() {
return value;
}
public String toString() {
return "\"" + value() + "\"";
}
}
| gpl-2.0 |
Cephra/pytubeserv | server.py | 2444 | #!/usr/bin/python3
import http.server
import os
import json
from urllib.parse import parse_qs
from config import *
from api import *
class PyTubeServHandler(http.server.SimpleHTTPRequestHandler):
def __init__(self, request, client_address, server):
http.server.SimpleHTTPRequestHandler.__init__(self, request, client_address, server)
def send_json(self, data):
self.wfile.write(bytes(json.dumps(data), "UTF-8"))
def send_plain(self, data):
self.wfile.write(bytes(data, "UTF-8"))
def deny_access(self):
self.send_response(403)
self.send_header("Content-Type", "text/plain")
self.end_headers()
self.send_plain("Access denied.")
def grant_access(self):
self.send_response(200)
self.send_header("Content-Type", "text/json")
self.end_headers()
def do_GET(self):
if self.path.startswith("/api/"):
## AUTH
path = query = None
query = self.path.split("?")
if len(query) > 1:
path = query[0]
query = parse_qs(query[1])
if not API().checkKey(query["apiKey"][0]):
self.deny_access()
return
else:
self.grant_access()
else:
self.deny_access()
return
## API
if path == "/api/list":
self.send_json(API().apiVideoList())
elif path == "/api/next":
self.send_json(API().apiNextVideo())
elif path == "/api/state":
self.send_json(API().apiState())
elif path == "/api/add":
videoID = query["videoID"][0]
force = True if (query["force"][0] == "1") else False
API().addVideoID(videoID, force)
self.send_json("Added {} to list".format(videoID))
elif path == "/api/message":
msgSender = query["sender"][0]
msgBody = query["body"][0]
self.send_json(API().apiAddMessage(msgSender, msgBody))
else:
self.send_json("Unknown API node")
else:
http.server.SimpleHTTPRequestHandler.do_GET(self)
if __name__ == "__main__":
Config()
httpd = http.server.HTTPServer(("", 1234), PyTubeServHandler)
os.chdir("./player")
httpd.serve_forever()
| gpl-2.0 |
Drop-it-Like-its-HotSpot/HotSpot_Android | app/src/main/java/com/ticknardif/hotspot/RESTresponses/UserResponse.java | 998 | package com.ticknardif.hotspot.RESTresponses;
/**
* Created by Vatsal on 11/2/2014.
*/
public class UserResponse {
public int User_id;
public String DisplayName;
public String Email_id;
public double radius;
public double latitude;
public double longitude;
public boolean success;
public UserResponse(int userId, String displayName, String emailId, double radius, double latitude, double longitude, boolean success){
this.User_id = userId;
this.DisplayName = displayName;
this.Email_id = emailId;
this.radius = radius;
this.latitude = latitude;
this.longitude = longitude;
this.success = success;
}
public String toString()
{
return "User ID: " + User_id + " Display Name: " + DisplayName + " Email ID: " + Email_id +
" Radius: " + radius + " Latitude: " + latitude + " Longitude: " + longitude;
}
public String getDisplayName() {
return DisplayName;
}
}
| gpl-2.0 |
404pnf/4u2u | sites/quiz.2u4u.com.cn/themes/stable/page-oral-test.tpl.php | 5729 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language ?>" lang="<?php print $language->language ?>" dir="<?php print $language->dir ?>">
<head>
<title><?php print $head_title; ?></title>
<?php print $head; ?>
<link href="http://2u4u.com.cn/sites/2u4u.com.cn/themes/stable/css/common.css" media="all" rel="stylesheet" type="text/css">
<?php print $styles; ?>
<!--[if lte IE 6]><style type="text/css" media="all">@import "<?php print $base_path . path_to_theme() ?>/css/ie6.css";</style><![endif]-->
<!--[if IE 7]><style type="text/css" media="all">@import "<?php print $base_path . path_to_theme() ?>/css/ie7.css";</style><![endif]-->
<script type="text/javascript" src="<?php print $base_path .drupal_get_path('module', 'aispeech') ?>/load_core.js"></script>
<?php print $scripts; ?>
<?php $node_url=drupal_get_path_alias($_GET['q']);?>
<?php $pos=strpos($node_url,'disney');?>
<?php if($pos!== false ): ?>
<script type="text/javascript" src="http://cdn1.2u4u.com.cn/disney/js/submit.js"></script>
<?php endif;?>
</head>
<body class="<?php print $body_classes; ?>">
<div id="skip"><a href="#content">Skip to Content</a> <a href="#navigation">Skip to Navigation</a></div>
<div id="page">
<div id="header">
<div id="header-middle">
<div id="logo-title">
<?php if (!empty($logo)): ?>
<a href="http://2u4u.com.cn" title="悠游网" rel="home" id="logo">
<img src="<?php print $logo; ?>" alt="<?php print $site_name; ?>"/>
</a>
<?php endif; ?>
</div> <!-- /logo-title -->
<?php if ($header): ?>
<div id="header-region">
<?php print $header; ?>
</div>
<?php endif; ?>
<?php print $search_box; ?>
</div>
<?php if (!empty($primary_links) or !empty($secondary_links)): ?>
<div id="navigation" class="menu <?php if (!empty($primary_links)) { print "with-main-menu"; } if (!empty($secondary_links)) { print " with-sub-menu"; } ?>">
<?php if (!empty($primary_links)){ print theme('links', $primary_links, array('id' => 'primary', 'class' => 'links main-menu')); } ?>
<?php if (!empty($secondary_links)){ print theme('links', $secondary_links, array('id' => 'secondary', 'class' => 'links sub-menu')); } ?>
</div> <!-- /navigation -->
<?php endif; ?>
</div> <!-- /header -->
<!-- ______________________ MAIN _______________________ -->
<div id="main" class="clearfix">
<div id="content">
<div id="content-inner" class="inner column center">
<?php if ($content_top): ?>
<div id="content-top">
<?php print $content_top; ?>
</div> <!-- /#content-top -->
<?php endif; ?>
<?php if ($breadcrumb || $title || $mission || $messages || $help || $tabs): ?>
<div id="content-header">
<?php if(!empty($node) && $node->type == 'readthink'): ?>
<?php print $breadcrumb; ?>
<?php endif; ?>
<?php if(!empty($title) && $node->nid != 55446 && $node->type != 'og_group'): ?>
<div class="title_bg"><h1 class="title"><?php print $title; ?></h1></div>
<?php endif; ?>
<?php print $messages; ?>
<?php print $help; ?>
<?php if ($tabs): ?>
<div class="tabs"><?php print $tabs; ?></div>
<?php endif; ?>
</div> <!-- /#content-header -->
<?php endif; ?>
<div id="content-area">
<?php print $content; ?>
</div> <!-- /#content-area -->
<?php print $feed_icons; ?>
<?php if ($content_bottom): ?>
<div id="content-bottom">
<?php print $content_bottom; ?>
</div><!-- /#content-bottom -->
<?php endif; ?>
</div>
</div> <!-- /content-inner /content -->
<?php if ($right): ?>
<div id="sidebar-second" class="column sidebar second">
<div id="sidebar-second-inner" class="inner">
<?php print $right; ?>
</div>
</div>
<?php endif; ?> <!-- /sidebar-second -->
</div> <!-- /main -->
<!-- ______________________ FOOTER _______________________ -->
<?php if(!empty($footer_message) || !empty($footer_block)): ?>
<div id="footer">
<?php print $footer_message; ?>
<?php print $footer_block; ?>
</div> <!-- /footer -->
<?php endif; ?>
</div> <!-- /page -->
<?php print $scripts; ?>
<script type="text/javascript">
$(function(){
$('a:[href^=http://test.]').attr('target','_blank');
$('a:[href^=http://u.]').attr('target','_blank');
$('a:[href^=http://frenchfriend.]').attr('target','_blank');
$('#primary li.menu-41193 a').addClass('active');
});
</script>
<script type="text/javascript">
var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://");
document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3F116fea821e3bfb6c5a7d4b187a50b502' type='text/javascript'%3E%3C/script%3E"));
</script>
<SCRIPT type="text/javascript" src="<?php print $base_path.$directory?>/js/jquery-ui.min.js"></SCRIPT>
<SCRIPT type="text/javascript" src="<?php print $base_path.$directory?>/js/jquery.spasticNav.js"></SCRIPT>
<?php if($closure_region): ?>
<div id="closure_region">
<?php print $closure_region; ?>
</div>
<?php endif; ?>
<?php print $closure; ?>
</body>
</html>
| gpl-2.0 |
moulderr/pm | wp-content/themes/lucy/helpers/settings/grid_panel.php | 486 | <?php
defined('_JEXEC') or die('Restricted access');
$settings = new UniteFrameworkSettingsUF();
$settings->loadXMLFile(GlobalsUG::$pathHelpersSettings."grid_panel.xml");
$settings->updateSelectToAlignCombo("gridpanel_grid_align");
$settings->updateSelectToSkins("gridpanel_arrows_skin", "");
$settings->updateSelectToAlignCombo("gridpanel_handle_align");
$settings->updateSelectToSkins("gridpanel_handle_skin", "");
$settings->updateSelectToEasing("grid_transition_easing");
?> | gpl-2.0 |
joebowen/landing_zone_project | openrocket-release-15.03/core/src/net/sf/openrocket/preset/xml/MaterialDTO.java | 2898 | package net.sf.openrocket.preset.xml;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import net.sf.openrocket.database.Databases;
import net.sf.openrocket.material.Material;
import net.sf.openrocket.util.Chars;
/**
* XML handler for materials.
*/
@XmlRootElement(name = "Material")
@XmlAccessorType(XmlAccessType.FIELD)
public class MaterialDTO {
@XmlElement(name = "Name")
private String name;
@XmlElement(name = "Density")
private double density;
@XmlElement(name = "Type")
private MaterialTypeDTO type;
@XmlAttribute(name = "UnitsOfMeasure")
private String uom;
/**
* Default constructor.
*/
public MaterialDTO() {
}
public MaterialDTO(final Material theMaterial) {
this(theMaterial.getName(), theMaterial.getDensity(), MaterialTypeDTO.asDTO(theMaterial.getType()),
theMaterial.getType().getUnitGroup().getDefaultUnit().toString());
}
public MaterialDTO(final String theName, final double theDensity, final MaterialTypeDTO theType, final String theUom) {
name = theName;
density = theDensity;
type = theType;
uom = theUom;
}
public String getName() {
return name;
}
public void setName(final String theName) {
name = theName;
}
public double getDensity() {
return density;
}
public void setDensity(final double theDensity) {
density = theDensity;
}
public MaterialTypeDTO getType() {
return type;
}
public void setType(final MaterialTypeDTO theType) {
type = theType;
}
public String getUom() {
return uom;
}
public void setUom(final String theUom) {
uom = theUom;
}
Material asMaterial() {
return Databases.findMaterial(type.getORMaterialType(), name, density);
}
/**
* Special directive to the JAXB system. After the object is parsed from xml,
* we replace the '2' with Chars.SQUARED, and '3' with Chars.CUBED. Just the
* opposite transformation as doen in beforeMarshal.
* @param unmarshaller
* @param parent
*/
@SuppressWarnings("unused")
private void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {
if (uom != null) {
uom = uom.replace('2', Chars.SQUARED);
uom = uom.replace('3', Chars.CUBED);
}
}
/**
* Special directive to the JAXB system. Before the object is serialized into xml,
* we strip out the special unicode characters for cubed and squared so they appear
* as simple "3" and "2" chars. The reverse transformation is done in afterUnmarshal.
* @param marshaller
*/
@SuppressWarnings("unused")
private void beforeMarshal(Marshaller marshaller) {
if (uom != null) {
uom = uom.replace(Chars.SQUARED, '2');
uom = uom.replace(Chars.CUBED, '3');
}
}
}
| gpl-2.0 |
angguss/OpenTTD-vita | src/saveload/newgrf_sl.cpp | 3567 | /* $Id: newgrf_sl.cpp 27772 2017-03-07 20:18:54Z frosch $ */
/*
* This file is part of OpenTTD.
* OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
* OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file newgrf_sl.cpp Code handling saving and loading of newgrf config */
#include "../stdafx.h"
#include "../fios.h"
#include "saveload.h"
#include "newgrf_sl.h"
#include "../safeguards.h"
/** Save and load the mapping between a spec and the NewGRF it came from. */
static const SaveLoad _newgrf_mapping_desc[] = {
SLE_VAR(EntityIDMapping, grfid, SLE_UINT32),
SLE_VAR(EntityIDMapping, entity_id, SLE_UINT8),
SLE_VAR(EntityIDMapping, substitute_id, SLE_UINT8),
SLE_END()
};
/**
* Save a GRF ID + local id -> OpenTTD's id mapping.
* @param mapping The mapping to save.
*/
void Save_NewGRFMapping(const OverrideManagerBase &mapping)
{
for (uint i = 0; i < mapping.GetMaxMapping(); i++) {
SlSetArrayIndex(i);
SlObject(&mapping.mapping_ID[i], _newgrf_mapping_desc);
}
}
/**
* Load a GRF ID + local id -> OpenTTD's id mapping.
* @param mapping The mapping to load.
*/
void Load_NewGRFMapping(OverrideManagerBase &mapping)
{
/* Clear the current mapping stored.
* This will create the manager if ever it is not yet done */
mapping.ResetMapping();
uint max_id = mapping.GetMaxMapping();
int index;
while ((index = SlIterateArray()) != -1) {
if ((uint)index >= max_id) SlErrorCorrupt("Too many NewGRF entity mappings");
SlObject(&mapping.mapping_ID[index], _newgrf_mapping_desc);
}
}
static const SaveLoad _grfconfig_desc[] = {
SLE_STR(GRFConfig, filename, SLE_STR, 0x40),
SLE_VAR(GRFConfig, ident.grfid, SLE_UINT32),
SLE_ARR(GRFConfig, ident.md5sum, SLE_UINT8, 16),
SLE_CONDVAR(GRFConfig, version, SLE_UINT32, 151, SL_MAX_VERSION),
SLE_ARR(GRFConfig, param, SLE_UINT32, 0x80),
SLE_VAR(GRFConfig, num_params, SLE_UINT8),
SLE_CONDVAR(GRFConfig, palette, SLE_UINT8, 101, SL_MAX_VERSION),
SLE_END()
};
static void Save_NGRF()
{
int index = 0;
for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
if (HasBit(c->flags, GCF_STATIC)) continue;
SlSetArrayIndex(index++);
SlObject(c, _grfconfig_desc);
}
}
static void Load_NGRF_common(GRFConfig *&grfconfig)
{
ClearGRFConfigList(&grfconfig);
while (SlIterateArray() != -1) {
GRFConfig *c = new GRFConfig();
SlObject(c, _grfconfig_desc);
if (IsSavegameVersionBefore(101)) c->SetSuitablePalette();
AppendToGRFConfigList(&grfconfig, c);
}
}
static void Load_NGRF()
{
Load_NGRF_common(_grfconfig);
if (_game_mode == GM_MENU) {
/* Intro game must not have NewGRF. */
if (_grfconfig != NULL) SlErrorCorrupt("The intro game must not use NewGRF");
/* Activate intro NewGRFs (townnames) */
ResetGRFConfig(false);
} else {
/* Append static NewGRF configuration */
AppendStaticGRFConfigs(&_grfconfig);
}
}
static void Check_NGRF()
{
Load_NGRF_common(_load_check_data.grfconfig);
}
extern const ChunkHandler _newgrf_chunk_handlers[] = {
{ 'NGRF', Save_NGRF, Load_NGRF, NULL, Check_NGRF, CH_ARRAY | CH_LAST }
};
| gpl-2.0 |
panhainan/ds | src/main/java/com/ds/dreamstation/dto/ProjectInfo.java | 3443 | package com.ds.dreamstation.dto;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author phn
* @date 2015-5-24
* @email 1016593477@qq.com
* @TODO
*/
public class ProjectInfo {
/**
* 编号
*/
private int id;
/**
* 项目名称
*/
private String name;
/**
* 项目简介
*/
private String summary;
/**
* 项目详细情况
*/
private String details;
/**
* 项目访问地址
*/
private String website;
/**
* 项目展示图片
*/
private String picture;
/**
* 项目负责人(成员)
*/
private String author;
/**
* 项目小组人员
*/
private String groupMember;
/**
* 项目审核状态:待审核,正在审核,审核通过
*/
private String status;
/**
* 项目发布时间
*/
private String publishTime;
public ProjectInfo() {
super();
}
/**
* @param id
* @param name
* @param summary
* @param details
* @param website
* @param picture
* @param author
* @param groupMember
* @param status
* @param publishTime
*/
public ProjectInfo(int id, String name, String summary, String details,
String website, String picture, String author, String groupMember,
byte status, Date publishTime) {
super();
this.id = id;
this.name = name;
this.summary = summary;
this.details = details;
this.website = website;
this.picture = picture;
this.author = author;
this.groupMember = groupMember;
this.setStatus(status);
this.setPublishTime(publishTime);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDetails() {
return details;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public void setDetails(String details) {
this.details = details;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getGroupMember() {
return groupMember;
}
public void setGroupMember(String groupMember) {
this.groupMember = groupMember;
}
public String getStatus() {
return status;
}
public void setStatus(byte status) {
// 0待审核,1审核通过,2审核失败
switch (status) {
case 0:
this.status = "待审核";
break;
case 1:
this.status = "审核通过";
break;
case 2:
this.status = "审核失败";
break;
default:
this.status = "待审核";
break;
}
}
public String getPublishTime() {
return publishTime;
}
public void setPublishTime(Date publishTime) {
if(publishTime==null){
this.publishTime = "";
}else{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
this.publishTime = sdf.format(publishTime);
}
}
@Override
public String toString() {
return "ProjectInfo [id=" + id + ", name=" + name + ", summary="
+ summary + ", details=" + details + ", website=" + website
+ ", picture=" + picture + ", author=" + author
+ ", groupMember=" + groupMember + ", status=" + status
+ ", publishTime=" + publishTime + "]";
}
}
| gpl-2.0 |
jazzisparis/JIP-NVSE-Plugin | common/IDataStream.cpp | 8192 | #include "IDataStream.h"
/**** IDataStream *************************************************************/
IDataStream::IDataStream()
:streamLength(0), streamOffset(0), swapBytes(false)
{
}
IDataStream::~IDataStream()
{
}
/**
* Reads and returns an 8-bit value from the stream
*/
UInt8 IDataStream::Read8(void)
{
UInt8 out;
ReadBuf(&out, sizeof(UInt8));
return out;
}
/**
* Reads and returns a 16-bit value from the stream
*/
UInt16 IDataStream::Read16(void)
{
UInt16 out;
ReadBuf(&out, sizeof(UInt16));
if(swapBytes)
out = Swap16(out);
return out;
}
/**
* Reads and returns a 32-bit value from the stream
*/
UInt32 IDataStream::Read32(void)
{
UInt32 out;
ReadBuf(&out, sizeof(UInt32));
if(swapBytes)
out = Swap32(out);
return out;
}
/**
* Reads and returns a 64-bit value from the stream
*/
UInt64 IDataStream::Read64(void)
{
UInt64 out;
ReadBuf(&out, sizeof(UInt64));
if(swapBytes)
out = Swap64(out);
return out;
}
/**
* Reads and returns a 32-bit floating point value from the stream
*/
float IDataStream::ReadFloat(void)
{
UInt32 out = Read32();
return *((float *)&out);
}
/**
* Reads a null-or-return-terminated string from the stream
*
* If the buffer is too small to hold the entire string, it is truncated and
* properly terminated.
*
* @param buf the output buffer
* @param bufLength the size of the output buffer
* @return the number of characters written to the buffer
*/
UInt32 IDataStream::ReadString(char * buf, UInt32 bufLength, char altTerminator, char altTerminator2)
{
char * traverse = buf;
bool breakOnReturns = false;
if((altTerminator == '\n') || (altTerminator2 == '\n'))
breakOnReturns = true;
ASSERT_STR(bufLength > 0, "IDataStream::ReadString: zero-sized buffer");
if(bufLength == 1)
{
buf[0] = 0;
return 0;
}
bufLength--;
for(UInt32 i = 0; i < bufLength; i++)
{
UInt8 data = Read8();
if(breakOnReturns)
{
if(data == 0x0D)
{
if(Peek8() == 0x0A)
Skip(1);
break;
}
}
if(!data || (data == altTerminator) || (data == altTerminator2))
{
break;
}
*traverse++ = data;
}
*traverse++ = 0;
return traverse - buf - 1;
}
/**
* Reads and returns an 8-bit value from the stream without advancing the stream's position
*/
UInt8 IDataStream::Peek8(void)
{
IDataStream_PositionSaver saver(this);
return Read8();
}
/**
* Reads and returns a 16-bit value from the stream without advancing the stream's position
*/
UInt16 IDataStream::Peek16(void)
{
IDataStream_PositionSaver saver(this);
return Read16();
}
/**
* Reads and returns a 32-bit value from the stream without advancing the stream's position
*/
UInt32 IDataStream::Peek32(void)
{
IDataStream_PositionSaver saver(this);
return Read32();
}
/**
* Reads and returns a 32-bit value from the stream without advancing the stream's position
*/
UInt64 IDataStream::Peek64(void)
{
IDataStream_PositionSaver saver(this);
return Read64();
}
/**
* Reads and returns a 32-bit floating point value from the stream without advancing the stream's position
*/
float IDataStream::PeekFloat(void)
{
IDataStream_PositionSaver saver(this);
return ReadFloat();
}
/**
* Reads raw data into a buffer without advancing the stream's position
*/
void IDataStream::PeekBuf(void * buf, UInt32 inLength)
{
IDataStream_PositionSaver saver(this);
ReadBuf(buf, inLength);
}
/**
* Skips a specified number of bytes down the stream
*/
void IDataStream::Skip(SInt64 inBytes)
{
SetOffset(GetOffset() + inBytes);
}
/**
* Writes an 8-bit value to the stream.
*/
void IDataStream::Write8(UInt8 inData)
{
WriteBuf(&inData, sizeof(UInt8));
}
/**
* Writes a 16-bit value to the stream.
*/
void IDataStream::Write16(UInt16 inData)
{
if(swapBytes)
inData = Swap16(inData);
WriteBuf(&inData, sizeof(UInt16));
}
/**
* Writes a 32-bit value to the stream.
*/
void IDataStream::Write32(UInt32 inData)
{
if(swapBytes)
inData = Swap32(inData);
WriteBuf(&inData, sizeof(UInt32));
}
/**
* Writes a 64-bit value to the stream.
*/
void IDataStream::Write64(UInt64 inData)
{
if(swapBytes)
inData = Swap64(inData);
WriteBuf(&inData, sizeof(UInt64));
}
/**
* Writes a 32-bit floating point value to the stream.
*/
void IDataStream::WriteFloat(float inData)
{
if(swapBytes)
{
UInt32 temp = *((UInt32 *)&inData);
temp = Swap32(temp);
WriteBuf(&temp, sizeof(UInt32));
}
else
{
WriteBuf(&inData, sizeof(float));
}
}
/**
* Writes a null-terminated string to the stream.
*/
void IDataStream::WriteString(const char * buf)
{
WriteBuf(buf, std::strlen(buf) + 1);
}
/**
* Returns the length of the stream
*/
SInt64 IDataStream::GetLength(void)
{
return streamLength;
}
/**
* Returns the number of bytes remaining in the stream
*/
SInt64 IDataStream::GetRemain(void)
{
return streamLength - streamOffset;
}
/**
* Returns the current offset into the stream
*/
SInt64 IDataStream::GetOffset(void)
{
return streamOffset;
}
/**
* Returns whether we have reached the end of the stream or not
*/
bool IDataStream::HitEOF(void)
{
return streamOffset >= streamLength;
}
/**
* Moves the current offset into the stream
*/
void IDataStream::SetOffset(SInt64 inOffset)
{
streamOffset = inOffset;
}
/**
* Enables or disables byte swapping for basic data transfers
*/
void IDataStream::SwapBytes(bool inSwapBytes)
{
swapBytes = inSwapBytes;
}
IDataStream * IDataStream::GetRootParent(void)
{
IDataStream * parent = GetParent();
if(parent)
return parent->GetRootParent();
else
return this;
}
void IDataStream::CopyStreams(IDataStream * out, IDataStream * in, UInt64 bufferSize, UInt8 * buf)
{
in->Rewind();
bool ourBuffer = false;
if(!buf)
{
buf = new UInt8[bufferSize];
ourBuffer = true;
}
UInt64 remain = in->GetLength();
while(remain > 0)
{
UInt64 transferSize = remain;
if(transferSize > bufferSize)
transferSize = bufferSize;
in->ReadBuf(buf, transferSize);
out->WriteBuf(buf, transferSize);
remain -= transferSize;
}
if(ourBuffer)
delete [] buf;
}
void IDataStream::CopySubStreams(IDataStream * out, IDataStream * in, UInt64 remain, UInt64 bufferSize, UInt8 * buf)
{
bool ourBuffer = false;
if(!buf)
{
buf = new UInt8[bufferSize];
ourBuffer = true;
}
while(remain > 0)
{
UInt64 transferSize = remain;
if(transferSize > bufferSize)
transferSize = bufferSize;
in->ReadBuf(buf, transferSize);
out->WriteBuf(buf, transferSize);
remain -= transferSize;
}
if(ourBuffer)
delete [] buf;
}
/**** IDataStream_PositionSaver ***********************************************/
/**
* The constructor; save the stream's position
*/
IDataStream_PositionSaver::IDataStream_PositionSaver(IDataStream * tgt)
{
stream = tgt;
offset = tgt->GetOffset();
}
/**
* The destructor; restore the stream's saved position
*/
IDataStream_PositionSaver::~IDataStream_PositionSaver()
{
stream->SetOffset(offset);
}
/**** IDataSubStream **********************************************************/
IDataSubStream::IDataSubStream()
:stream(NULL), subBase(0)
{
//
}
IDataSubStream::IDataSubStream(IDataStream * inStream, SInt64 inOffset, SInt64 inLength)
{
stream = inStream;
subBase = inOffset;
streamLength = inLength;
stream->SetOffset(inOffset);
}
IDataSubStream::~IDataSubStream()
{
}
void IDataSubStream::Attach(IDataStream * inStream, SInt64 inOffset, SInt64 inLength)
{
stream = inStream;
subBase = inOffset;
streamLength = inLength;
stream->SetOffset(inOffset);
}
void IDataSubStream::ReadBuf(void * buf, UInt32 inLength)
{
ASSERT_STR(inLength <= GetRemain(), "IDataSubStream::ReadBuf: hit eof");
if(stream->GetOffset() != subBase + streamOffset)
stream->SetOffset(subBase + streamOffset);
stream->ReadBuf(buf, inLength);
streamOffset += inLength;
}
void IDataSubStream::WriteBuf(const void * buf, UInt32 inLength)
{
if(stream->GetOffset() != subBase + streamOffset)
stream->SetOffset(subBase + streamOffset);
stream->WriteBuf(buf, inLength);
streamOffset += inLength;
if(streamLength < streamOffset)
streamLength = streamOffset;
}
void IDataSubStream::SetOffset(SInt64 inOffset)
{
stream->SetOffset(subBase + inOffset);
streamOffset = inOffset;
}
| gpl-2.0 |
JSansalone/VirtualBox4.1.18 | src/VBox/Runtime/testcase/tstTimerLR.cpp | 10306 | /* $Id: tstTimerLR.cpp $ */
/** @file
* IPRT Testcase - Low Resolution Timers.
*/
/*
* Copyright (C) 2006-2008 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#include <iprt/timer.h>
#include <iprt/time.h>
#include <iprt/thread.h>
#include <iprt/initterm.h>
#include <iprt/stream.h>
#include <iprt/err.h>
/*******************************************************************************
* Global Variables *
*******************************************************************************/
static volatile unsigned gcTicks;
static volatile uint64_t gu64Min;
static volatile uint64_t gu64Max;
static volatile uint64_t gu64Prev;
static DECLCALLBACK(void) TimerLRCallback(RTTIMERLR hTimerLR, void *pvUser, uint64_t iTick)
{
gcTicks++;
const uint64_t u64Now = RTTimeNanoTS();
if (gu64Prev)
{
const uint64_t u64Delta = u64Now - gu64Prev;
if (u64Delta < gu64Min)
gu64Min = u64Delta;
if (u64Delta > gu64Max)
gu64Max = u64Delta;
}
gu64Prev = u64Now;
}
int main()
{
/*
* Init runtime
*/
unsigned cErrors = 0;
int rc = RTR3Init();
if (RT_FAILURE(rc))
{
RTPrintf("tstTimer: RTR3Init() -> %d\n", rc);
return 1;
}
/*
* Check that the clock is reliable.
*/
RTPrintf("tstTimer: TESTING - RTTimeNanoTS() for 2sec\n");
uint64_t uTSMillies = RTTimeMilliTS();
uint64_t uTSBegin = RTTimeNanoTS();
uint64_t uTSLast = uTSBegin;
uint64_t uTSDiff;
uint64_t cIterations = 0;
do
{
uint64_t uTS = RTTimeNanoTS();
if (uTS < uTSLast)
{
RTPrintf("tstTimer: FAILURE - RTTimeNanoTS() is unreliable. uTS=%RU64 uTSLast=%RU64\n", uTS, uTSLast);
cErrors++;
}
if (++cIterations > (2*1000*1000*1000))
{
RTPrintf("tstTimer: FAILURE - RTTimeNanoTS() is unreliable. cIterations=%RU64 uTS=%RU64 uTSBegin=%RU64\n", cIterations, uTS, uTSBegin);
return 1;
}
uTSLast = uTS;
uTSDiff = uTSLast - uTSBegin;
} while (uTSDiff < (2*1000*1000*1000));
uTSMillies = RTTimeMilliTS() - uTSMillies;
if (uTSMillies >= 2500 || uTSMillies <= 1500)
{
RTPrintf("tstTimer: FAILURE - uTSMillies=%RI64 uTSBegin=%RU64 uTSLast=%RU64 uTSDiff=%RU64\n",
uTSMillies, uTSBegin, uTSLast, uTSDiff);
cErrors++;
}
if (!cErrors)
RTPrintf("tstTimer: OK - RTTimeNanoTS()\n");
/*
* Tests.
*/
static struct
{
unsigned uMilliesInterval;
unsigned uMilliesWait;
unsigned cLower;
unsigned cUpper;
} aTests[] =
{
{ 1000, 2500, 3, 3 }, /* (keep in mind the immediate first tick) */
{ 250, 2000, 6, 10 },
{ 100, 2000, 17, 23 },
};
unsigned i = 0;
for (i = 0; i < RT_ELEMENTS(aTests); i++)
{
//aTests[i].cLower = (aTests[i].uMilliesWait - aTests[i].uMilliesWait / 10) / aTests[i].uMilliesInterval;
//aTests[i].cUpper = (aTests[i].uMilliesWait + aTests[i].uMilliesWait / 10) / aTests[i].uMilliesInterval;
RTPrintf("\n"
"tstTimer: TESTING - %d ms interval, %d ms wait, expects %d-%d ticks.\n",
aTests[i].uMilliesInterval, aTests[i].uMilliesWait, aTests[i].cLower, aTests[i].cUpper);
/*
* Start timer which ticks every 10ms.
*/
gcTicks = 0;
RTTIMERLR hTimerLR;
gu64Max = 0;
gu64Min = UINT64_MAX;
gu64Prev = 0;
rc = RTTimerLRCreateEx(&hTimerLR, aTests[i].uMilliesInterval * (uint64_t)1000000, 0, TimerLRCallback, NULL);
if (RT_FAILURE(rc))
{
RTPrintf("RTTimerLRCreateEX(,%u*1M,,,) -> %d\n", aTests[i].uMilliesInterval, rc);
cErrors++;
continue;
}
/*
* Start the timer an actively wait for it for the period requested.
*/
uTSBegin = RTTimeNanoTS();
rc = RTTimerLRStart(hTimerLR, 0);
if (RT_FAILURE(rc))
{
RTPrintf("tstTimer: FAILURE - RTTimerLRStart() -> %Rrc\n", rc);
cErrors++;
}
while (RTTimeNanoTS() - uTSBegin < (uint64_t)aTests[i].uMilliesWait * 1000000)
/* nothing */;
/* don't stop it, destroy it because there are potential races in destroying an active timer. */
rc = RTTimerLRDestroy(hTimerLR);
if (RT_FAILURE(rc))
{
RTPrintf("tstTimer: FAILURE - RTTimerLRDestroy() -> %d gcTicks=%d\n", rc, gcTicks);
cErrors++;
}
uint64_t uTSEnd = RTTimeNanoTS();
uTSDiff = uTSEnd - uTSBegin;
RTPrintf("uTS=%RI64 (%RU64 - %RU64)\n", uTSDiff, uTSBegin, uTSEnd);
/* Check that it really stopped. */
unsigned cTicks = gcTicks;
RTThreadSleep(aTests[i].uMilliesInterval * 2);
if (gcTicks != cTicks)
{
RTPrintf("tstTimer: FAILURE - RTTimerLRDestroy() didn't really stop the timer! gcTicks=%d cTicks=%d\n", gcTicks, cTicks);
cErrors++;
continue;
}
/*
* Check the number of ticks.
*/
if (gcTicks < aTests[i].cLower)
{
RTPrintf("tstTimer: FAILURE - Too few ticks gcTicks=%d (expected %d-%d)", gcTicks, aTests[i].cUpper, aTests[i].cLower);
cErrors++;
}
else if (gcTicks > aTests[i].cUpper)
{
RTPrintf("tstTimer: FAILURE - Too many ticks gcTicks=%d (expected %d-%d)", gcTicks, aTests[i].cUpper, aTests[i].cLower);
cErrors++;
}
else
RTPrintf("tstTimer: OK - gcTicks=%d", gcTicks);
RTPrintf(" min=%RU64 max=%RU64\n", gu64Min, gu64Max);
}
/*
* Test changing the interval dynamically
*/
RTPrintf("\n"
"tstTimer: Testing dynamic changes of timer interval...\n");
do
{
RTTIMERLR hTimerLR;
rc = RTTimerLRCreateEx(&hTimerLR, aTests[0].uMilliesInterval * (uint64_t)1000000, 0, TimerLRCallback, NULL);
if (RT_FAILURE(rc))
{
RTPrintf("RTTimerLRCreateEX(,%u*1M,,,) -> %d\n", aTests[i].uMilliesInterval, rc);
cErrors++;
continue;
}
for (i = 0; i < RT_ELEMENTS(aTests); i++)
{
RTPrintf("\n"
"tstTimer: TESTING - %d ms interval, %d ms wait, expects %d-%d ticks.\n",
aTests[i].uMilliesInterval, aTests[i].uMilliesWait, aTests[i].cLower, aTests[i].cUpper);
gcTicks = 0;
gu64Max = 0;
gu64Min = UINT64_MAX;
gu64Prev = 0;
/*
* Start the timer an actively wait for it for the period requested.
*/
uTSBegin = RTTimeNanoTS();
if (i == 0)
{
rc = RTTimerLRStart(hTimerLR, 0);
if (RT_FAILURE(rc))
{
RTPrintf("tstTimer: FAILURE - RTTimerLRStart() -> %Rrc\n", rc);
cErrors++;
}
}
else
{
rc = RTTimerLRChangeInterval(hTimerLR, aTests[i].uMilliesInterval * (uint64_t)1000000);
if (RT_FAILURE(rc))
{
RTPrintf("tstTimer: FAILURE - RTTimerLRChangeInterval() -> %d gcTicks=%d\n", rc, gcTicks);
cErrors++;
}
}
while (RTTimeNanoTS() - uTSBegin < (uint64_t)aTests[i].uMilliesWait * 1000000)
/* nothing */;
uint64_t uTSEnd = RTTimeNanoTS();
uTSDiff = uTSEnd - uTSBegin;
RTPrintf("uTS=%RI64 (%RU64 - %RU64)\n", uTSDiff, uTSBegin, uTSEnd);
/*
* Check the number of ticks.
*/
if (gcTicks < aTests[i].cLower)
{
RTPrintf("tstTimer: FAILURE - Too few ticks gcTicks=%d (expected %d-%d)\n", gcTicks, aTests[i].cUpper, aTests[i].cLower);
cErrors++;
}
else if (gcTicks > aTests[i].cUpper)
{
RTPrintf("tstTimer: FAILURE - Too many ticks gcTicks=%d (expected %d-%d)\n", gcTicks, aTests[i].cUpper, aTests[i].cLower);
cErrors++;
}
else
RTPrintf("tstTimer: OK - gcTicks=%d\n", gcTicks);
// RTPrintf(" min=%RU64 max=%RU64\n", gu64Min, gu64Max);
}
/* don't stop it, destroy it because there are potential races in destroying an active timer. */
rc = RTTimerLRDestroy(hTimerLR);
if (RT_FAILURE(rc))
{
RTPrintf("tstTimer: FAILURE - RTTimerLRDestroy() -> %d gcTicks=%d\n", rc, gcTicks);
cErrors++;
}
} while (0);
/*
* Test multiple timers running at once.
*/
/** @todo multiple LR timer testcase. */
/*
* Summary.
*/
if (!cErrors)
RTPrintf("tstTimer: SUCCESS\n");
else
RTPrintf("tstTimer: FAILURE %d errors\n", cErrors);
return !!cErrors;
}
| gpl-2.0 |
chaodhib/TrinityCore | src/server/game/Entities/Unit/StatSystem.cpp | 53348 | /*
* Copyright (C) 2008-2019 TrinityCore <https://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 "Unit.h"
#include "Creature.h"
#include "Item.h"
#include "Pet.h"
#include "Player.h"
#include "SharedDefines.h"
#include "SpellAuras.h"
#include "SpellAuraEffects.h"
#include "SpellMgr.h"
#include "World.h"
#include <numeric>
inline bool _ModifyUInt32(bool apply, uint32& baseValue, int32& amount)
{
// If amount is negative, change sign and value of apply.
if (amount < 0)
{
apply = !apply;
amount = -amount;
}
if (apply)
baseValue += amount;
else
{
// Make sure we do not get uint32 overflow.
if (amount > int32(baseValue))
amount = baseValue;
baseValue -= amount;
}
return apply;
}
/*#######################################
######## ########
######## UNIT STAT SYSTEM ########
######## ########
#######################################*/
void Unit::UpdateAllResistances()
{
for (uint8 i = SPELL_SCHOOL_NORMAL; i < MAX_SPELL_SCHOOL; ++i)
UpdateResistances(i);
}
void Unit::UpdateDamagePhysical(WeaponAttackType attType)
{
float totalMin = 0.f;
float totalMax = 0.f;
float tmpMin, tmpMax;
for (uint8 i = 0; i < MAX_ITEM_PROTO_DAMAGES; ++i)
{
CalculateMinMaxDamage(attType, false, true, tmpMin, tmpMax, i);
totalMin += tmpMin;
totalMax += tmpMax;
}
switch (attType)
{
case BASE_ATTACK:
default:
SetStatFloatValue(UNIT_FIELD_MINDAMAGE, totalMin);
SetStatFloatValue(UNIT_FIELD_MAXDAMAGE, totalMax);
break;
case OFF_ATTACK:
SetStatFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, totalMin);
SetStatFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, totalMax);
break;
case RANGED_ATTACK:
SetStatFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, totalMin);
SetStatFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, totalMax);
break;
}
}
/*#######################################
######## ########
######## PLAYERS STAT SYSTEM ########
######## ########
#######################################*/
bool Player::UpdateStats(Stats stat)
{
if (stat > STAT_SPIRIT)
return false;
// value = ((base_value * base_pct) + total_value) * total_pct
float value = GetTotalStatValue(stat);
SetStat(stat, int32(value));
if (stat == STAT_STAMINA || stat == STAT_INTELLECT || stat == STAT_STRENGTH)
{
Pet* pet = GetPet();
if (pet)
pet->UpdateStats(stat);
}
switch (stat)
{
case STAT_STRENGTH:
UpdateShieldBlockValue();
break;
case STAT_AGILITY:
UpdateArmor();
UpdateAllCritPercentages();
UpdateDodgePercentage();
break;
case STAT_STAMINA:
UpdateMaxHealth();
break;
case STAT_INTELLECT:
UpdateMaxPower(POWER_MANA);
UpdateAllSpellCritChances();
UpdateArmor(); //SPELL_AURA_MOD_RESISTANCE_OF_INTELLECT_PERCENT, only armor currently
break;
case STAT_SPIRIT:
break;
default:
break;
}
if (stat == STAT_STRENGTH)
{
UpdateAttackPowerAndDamage(false);
if (HasAuraTypeWithMiscvalue(SPELL_AURA_MOD_RANGED_ATTACK_POWER_OF_STAT_PERCENT, stat))
UpdateAttackPowerAndDamage(true);
}
else if (stat == STAT_AGILITY)
{
UpdateAttackPowerAndDamage(false);
UpdateAttackPowerAndDamage(true);
}
else
{
// Need update (exist AP from stat auras)
if (HasAuraTypeWithMiscvalue(SPELL_AURA_MOD_ATTACK_POWER_OF_STAT_PERCENT, stat))
UpdateAttackPowerAndDamage(false);
if (HasAuraTypeWithMiscvalue(SPELL_AURA_MOD_RANGED_ATTACK_POWER_OF_STAT_PERCENT, stat))
UpdateAttackPowerAndDamage(true);
}
UpdateSpellDamageAndHealingBonus();
UpdateManaRegen();
// Update ratings in exist SPELL_AURA_MOD_RATING_FROM_STAT and only depends from stat
uint32 mask = 0;
AuraEffectList const& modRatingFromStat = GetAuraEffectsByType(SPELL_AURA_MOD_RATING_FROM_STAT);
for (AuraEffectList::const_iterator i = modRatingFromStat.begin(); i != modRatingFromStat.end(); ++i)
if (Stats((*i)->GetMiscValueB()) == stat)
mask |= (*i)->GetMiscValue();
if (mask)
{
for (uint32 rating = 0; rating < MAX_COMBAT_RATING; ++rating)
if (mask & (1 << rating))
ApplyRatingMod(CombatRating(rating), 0, true);
}
return true;
}
void Player::ApplySpellPowerBonus(int32 amount, bool apply)
{
apply = _ModifyUInt32(apply, m_baseSpellPower, amount);
// For speed just update for client
ApplyModUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS, amount, apply);
for (int i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; ++i)
ApplyModUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + i, amount, apply);
}
void Player::UpdateSpellDamageAndHealingBonus()
{
// Magic damage modifiers implemented in Unit::SpellDamageBonusDone
// This information for client side use only
// Get healing bonus for all schools
SetStatInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS, SpellBaseHealingBonusDone(SPELL_SCHOOL_MASK_ALL));
// Get damage bonus for all schools
Unit::AuraEffectList const& modDamageAuras = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE);
for (uint16 i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; ++i)
{
SetInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG + i, std::accumulate(modDamageAuras.begin(), modDamageAuras.end(), 0, [i](int32 negativeMod, AuraEffect const* aurEff)
{
if (aurEff->GetAmount() < 0 && aurEff->GetMiscValue() & (1 << i))
negativeMod += aurEff->GetAmount();
return negativeMod;
}));
SetStatInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + i, SpellBaseDamageBonusDone(SpellSchoolMask(1 << i)) - GetInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG + i));
}
}
bool Player::UpdateAllStats()
{
for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i)
{
float value = GetTotalStatValue(Stats(i));
SetStat(Stats(i), int32(value));
}
UpdateArmor();
UpdateAttackPowerAndDamage(false);
UpdateAttackPowerAndDamage(true);
UpdateMaxHealth();
for (uint8 i = POWER_MANA; i < MAX_POWERS; ++i)
UpdateMaxPower(Powers(i));
UpdateAllRatings();
UpdateAllCritPercentages();
UpdateAllSpellCritChances();
UpdateDefenseBonusesMod();
UpdateShieldBlockValue();
UpdateSpellDamageAndHealingBonus();
UpdateManaRegen();
UpdateExpertise(BASE_ATTACK);
UpdateExpertise(OFF_ATTACK);
RecalculateRating(CR_ARMOR_PENETRATION);
UpdateAllResistances();
return true;
}
void Player::ApplySpellPenetrationBonus(int32 amount, bool apply)
{
ApplyModInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE, -amount, apply);
m_spellPenetrationItemMod += apply ? amount : -amount;
}
void Player::UpdateResistances(uint32 school)
{
if (school > SPELL_SCHOOL_NORMAL)
{
float value = GetTotalAuraModValue(UnitMods(UNIT_MOD_RESISTANCE_START + school));
SetResistance(SpellSchools(school), int32(value));
Pet* pet = GetPet();
if (pet)
pet->UpdateResistances(school);
}
else
UpdateArmor();
}
void Player::UpdateArmor()
{
UnitMods unitMod = UNIT_MOD_ARMOR;
float value = GetFlatModifierValue(unitMod, BASE_VALUE); // base armor (from items)
value *= GetPctModifierValue(unitMod, BASE_PCT); // armor percent from items
value += GetStat(STAT_AGILITY) * 2.0f; // armor bonus from stats
value += GetFlatModifierValue(unitMod, TOTAL_VALUE);
//add dynamic flat mods
AuraEffectList const& mResbyIntellect = GetAuraEffectsByType(SPELL_AURA_MOD_RESISTANCE_OF_STAT_PERCENT);
for (AuraEffectList::const_iterator i = mResbyIntellect.begin(); i != mResbyIntellect.end(); ++i)
{
if ((*i)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL)
value += CalculatePct(GetStat(Stats((*i)->GetMiscValueB())), (*i)->GetAmount());
}
value *= GetPctModifierValue(unitMod, TOTAL_PCT);
SetArmor(int32(value));
Pet* pet = GetPet();
if (pet)
pet->UpdateArmor();
}
float Player::GetHealthBonusFromStamina()
{
float stamina = GetStat(STAT_STAMINA);
float baseStam = std::min(20.0f, stamina);
float moreStam = stamina - baseStam;
return baseStam + (moreStam*10.0f);
}
float Player::GetManaBonusFromIntellect()
{
float intellect = GetStat(STAT_INTELLECT);
float baseInt = std::min(20.0f, intellect);
float moreInt = intellect - baseInt;
return baseInt + (moreInt * 15.0f);
}
void Player::UpdateMaxHealth()
{
UnitMods unitMod = UNIT_MOD_HEALTH;
float value = GetFlatModifierValue(unitMod, BASE_VALUE) + GetCreateHealth();
value *= GetPctModifierValue(unitMod, BASE_PCT);
value += GetFlatModifierValue(unitMod, TOTAL_VALUE) + GetHealthBonusFromStamina();
value *= GetPctModifierValue(unitMod, TOTAL_PCT);
SetMaxHealth((uint32)value);
}
void Player::UpdateMaxPower(Powers power)
{
UnitMods unitMod = UnitMods(UNIT_MOD_POWER_START + power);
float bonusPower = (power == POWER_MANA && GetCreatePowerValue(power) > 0) ? GetManaBonusFromIntellect() : 0;
float value = GetFlatModifierValue(unitMod, BASE_VALUE) + GetCreatePowerValue(power);
value *= GetPctModifierValue(unitMod, BASE_PCT);
value += GetFlatModifierValue(unitMod, TOTAL_VALUE) + bonusPower;
value *= GetPctModifierValue(unitMod, TOTAL_PCT);
SetMaxPower(power, uint32(std::lroundf(value)));
}
void Player::ApplyFeralAPBonus(int32 amount, bool apply)
{
_ModifyUInt32(apply, m_baseFeralAP, amount);
UpdateAttackPowerAndDamage();
}
void Player::UpdateAttackPowerAndDamage(bool ranged)
{
float val2 = 0.0f;
float level = float(getLevel());
UnitMods unitMod = ranged ? UNIT_MOD_ATTACK_POWER_RANGED : UNIT_MOD_ATTACK_POWER;
uint16 index = UNIT_FIELD_ATTACK_POWER;
uint16 index_mod = UNIT_FIELD_ATTACK_POWER_MODS;
uint16 index_mult = UNIT_FIELD_ATTACK_POWER_MULTIPLIER;
if (ranged)
{
index = UNIT_FIELD_RANGED_ATTACK_POWER;
index_mod = UNIT_FIELD_RANGED_ATTACK_POWER_MODS;
index_mult = UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER;
switch (getClass())
{
case CLASS_HUNTER:
val2 = level * 2.0f + GetStat(STAT_AGILITY) - 10.0f;
break;
case CLASS_ROGUE:
val2 = level + GetStat(STAT_AGILITY) - 10.0f;
break;
case CLASS_WARRIOR:
val2 = level + GetStat(STAT_AGILITY) - 10.0f;
break;
case CLASS_DRUID:
switch (GetShapeshiftForm())
{
case FORM_CAT:
case FORM_BEAR:
case FORM_DIREBEAR:
val2 = 0.0f; break;
default:
val2 = GetStat(STAT_AGILITY) - 10.0f; break;
}
break;
default: val2 = GetStat(STAT_AGILITY) - 10.0f; break;
}
}
else
{
switch (getClass())
{
case CLASS_WARRIOR:
val2 = level * 3.0f + GetStat(STAT_STRENGTH) * 2.0f - 20.0f;
break;
case CLASS_PALADIN:
val2 = level * 3.0f + GetStat(STAT_STRENGTH) * 2.0f - 20.0f;
break;
case CLASS_DEATH_KNIGHT:
val2 = level * 3.0f + GetStat(STAT_STRENGTH) * 2.0f - 20.0f;
break;
case CLASS_ROGUE:
val2 = level * 2.0f + GetStat(STAT_STRENGTH) + GetStat(STAT_AGILITY) - 20.0f;
break;
case CLASS_HUNTER:
val2 = level * 2.0f + GetStat(STAT_STRENGTH) + GetStat(STAT_AGILITY) - 20.0f;
break;
case CLASS_SHAMAN:
val2 = level * 2.0f + GetStat(STAT_STRENGTH) + GetStat(STAT_AGILITY) - 20.0f;
break;
case CLASS_DRUID:
{
// Check if Predatory Strikes is skilled
float levelBonus = 0.0f;
float weaponBonus = 0.0f;
if (IsInFeralForm())
{
if (AuraEffect const* levelMod = GetAuraEffect(SPELL_AURA_DUMMY, SPELLFAMILY_DRUID, 1563, EFFECT_0))
levelBonus = CalculatePct(1.0f, levelMod->GetAmount());
// = 0 if removing the weapon, do not calculate bonus (uses template)
if (m_baseFeralAP)
{
if (Item const* weapon = m_items[EQUIPMENT_SLOT_MAINHAND])
{
if (AuraEffect const* weaponMod = GetAuraEffect(SPELL_AURA_DUMMY, SPELLFAMILY_DRUID, 1563, EFFECT_1))
{
ItemTemplate const* itemTemplate = weapon->GetTemplate();
int32 bonusAP = itemTemplate->GetTotalAPBonus() + m_baseFeralAP;
weaponBonus = CalculatePct(static_cast<float>(bonusAP), weaponMod->GetAmount());
}
}
}
}
switch (GetShapeshiftForm())
{
case FORM_CAT:
val2 = getLevel() * levelBonus + GetStat(STAT_STRENGTH) * 2.0f + GetStat(STAT_AGILITY) - 20.0f + weaponBonus + m_baseFeralAP;
break;
case FORM_BEAR:
case FORM_DIREBEAR:
val2 = getLevel() * levelBonus + GetStat(STAT_STRENGTH) * 2.0f - 20.0f + weaponBonus + m_baseFeralAP;
break;
case FORM_MOONKIN:
val2 = GetStat(STAT_STRENGTH) * 2.0f - 20.0f + m_baseFeralAP;
break;
default:
val2 = GetStat(STAT_STRENGTH) * 2.0f - 20.0f;
break;
}
break;
}
case CLASS_MAGE:
val2 = GetStat(STAT_STRENGTH) - 10.0f;
break;
case CLASS_PRIEST:
val2 = GetStat(STAT_STRENGTH) - 10.0f;
break;
case CLASS_WARLOCK:
val2 = GetStat(STAT_STRENGTH) - 10.0f;
break;
}
}
SetStatFlatModifier(unitMod, BASE_VALUE, val2);
float base_attPower = GetFlatModifierValue(unitMod, BASE_VALUE) * GetPctModifierValue(unitMod, BASE_PCT);
float attPowerMod = GetFlatModifierValue(unitMod, TOTAL_VALUE);
//add dynamic flat mods
if (ranged)
{
if ((getClassMask() & CLASSMASK_WAND_USERS) == 0)
{
AuraEffectList const& mRAPbyStat = GetAuraEffectsByType(SPELL_AURA_MOD_RANGED_ATTACK_POWER_OF_STAT_PERCENT);
for (AuraEffect const* aurEff : mRAPbyStat)
attPowerMod += CalculatePct(GetStat(Stats(aurEff->GetMiscValue())), aurEff->GetAmount());
}
}
else
{
AuraEffectList const& mAPbyStat = GetAuraEffectsByType(SPELL_AURA_MOD_ATTACK_POWER_OF_STAT_PERCENT);
for (AuraEffect const* aurEff : mAPbyStat)
attPowerMod += CalculatePct(GetStat(Stats(aurEff->GetMiscValue())), aurEff->GetAmount());
}
// applies to both, amount updated in PeriodicTick each 30 seconds
attPowerMod += GetTotalAuraModifier(SPELL_AURA_MOD_ATTACK_POWER_OF_ARMOR);
float attPowerMultiplier = GetPctModifierValue(unitMod, TOTAL_PCT) - 1.0f;
SetInt32Value(index, (uint32)base_attPower); //UNIT_FIELD_(RANGED)_ATTACK_POWER field
SetInt32Value(index_mod, (uint32)attPowerMod); //UNIT_FIELD_(RANGED)_ATTACK_POWER_MODS field
SetFloatValue(index_mult, attPowerMultiplier); //UNIT_FIELD_(RANGED)_ATTACK_POWER_MULTIPLIER field
Pet* pet = GetPet(); //update pet's AP
Guardian* guardian = GetGuardianPet();
//automatically update weapon damage after attack power modification
if (ranged)
{
UpdateDamagePhysical(RANGED_ATTACK);
if (pet && pet->IsHunterPet()) // At ranged attack change for hunter pet
pet->UpdateAttackPowerAndDamage();
}
else
{
UpdateDamagePhysical(BASE_ATTACK);
if (CanDualWield() && haveOffhandWeapon()) //allow update offhand damage only if player knows DualWield Spec and has equipped offhand weapon
UpdateDamagePhysical(OFF_ATTACK);
if (getClass() == CLASS_SHAMAN || getClass() == CLASS_PALADIN) // mental quickness
UpdateSpellDamageAndHealingBonus();
if (pet && (pet->IsPetGhoul() || pet->IsRisenAlly())) // At melee attack power change for DK pet
pet->UpdateAttackPowerAndDamage();
if (guardian && guardian->IsSpiritWolf()) // At melee attack power change for Shaman feral spirit
guardian->UpdateAttackPowerAndDamage();
}
}
void Player::UpdateShieldBlockValue()
{
SetUInt32Value(PLAYER_SHIELD_BLOCK, GetShieldBlockValue());
}
void Player::CalculateMinMaxDamage(WeaponAttackType attType, bool normalized, bool addTotalPct, float& minDamage, float& maxDamage, uint8 damageIndex) const
{
// Only proto damage, not affected by any mods
if (damageIndex != 0)
{
minDamage = 0.0f;
maxDamage = 0.0f;
if (!IsInFeralForm() && CanUseAttackType(attType))
{
minDamage = GetWeaponDamageRange(attType, MINDAMAGE, damageIndex);
maxDamage = GetWeaponDamageRange(attType, MAXDAMAGE, damageIndex);
}
return;
}
UnitMods unitMod;
switch (attType)
{
case BASE_ATTACK:
default:
unitMod = UNIT_MOD_DAMAGE_MAINHAND;
break;
case OFF_ATTACK:
unitMod = UNIT_MOD_DAMAGE_OFFHAND;
break;
case RANGED_ATTACK:
unitMod = UNIT_MOD_DAMAGE_RANGED;
break;
}
float const attackPowerMod = std::max(GetAPMultiplier(attType, normalized), 0.25f);
float baseValue = GetFlatModifierValue(unitMod, BASE_VALUE);
baseValue += GetTotalAttackPowerValue(attType) / 14.0f * attackPowerMod;
float basePct = GetPctModifierValue(unitMod, BASE_PCT);
float totalValue = GetFlatModifierValue(unitMod, TOTAL_VALUE);
float totalPct = addTotalPct ? GetPctModifierValue(unitMod, TOTAL_PCT) : 1.0f;
float weaponMinDamage = GetWeaponDamageRange(attType, MINDAMAGE);
float weaponMaxDamage = GetWeaponDamageRange(attType, MAXDAMAGE);
// check if player is druid and in cat or bear forms
if (IsInFeralForm())
{
uint8 lvl = getLevel();
if (lvl > 60)
lvl = 60;
weaponMinDamage = lvl * 0.85f * attackPowerMod;
weaponMaxDamage = lvl * 1.25f * attackPowerMod;
}
else if (!CanUseAttackType(attType)) // check if player not in form but still can't use (disarm case)
{
// cannot use ranged/off attack, set values to 0
if (attType != BASE_ATTACK)
{
minDamage = 0.f;
maxDamage = 0.f;
return;
}
weaponMinDamage = BASE_MINDAMAGE;
weaponMaxDamage = BASE_MAXDAMAGE;
}
else if (attType == RANGED_ATTACK) // add ammo DPS to ranged primary damage
{
weaponMinDamage += GetAmmoDPS() * attackPowerMod;
weaponMaxDamage += GetAmmoDPS() * attackPowerMod;
}
minDamage = ((weaponMinDamage + baseValue) * basePct + totalValue) * totalPct;
maxDamage = ((weaponMaxDamage + baseValue) * basePct + totalValue) * totalPct;
}
void Player::UpdateDefenseBonusesMod()
{
UpdateBlockPercentage();
UpdateParryPercentage();
UpdateDodgePercentage();
}
void Player::UpdateBlockPercentage()
{
// No block
float value = 0.0f;
if (CanBlock())
{
// Base value
value = 5.0f;
// Modify value from defense skill
value += (int32(GetDefenseSkillValue()) - int32(GetMaxSkillValueForLevel())) * 0.04f;
// Increase from SPELL_AURA_MOD_BLOCK_PERCENT aura
value += GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_PERCENT);
// Increase from rating
value += GetRatingBonusValue(CR_BLOCK);
if (sWorld->getBoolConfig(CONFIG_STATS_LIMITS_ENABLE))
value = value > sWorld->getFloatConfig(CONFIG_STATS_LIMITS_BLOCK) ? sWorld->getFloatConfig(CONFIG_STATS_LIMITS_BLOCK) : value;
value = value < 0.0f ? 0.0f : value;
}
SetStatFloatValue(PLAYER_BLOCK_PERCENTAGE, value);
}
void Player::UpdateCritPercentage(WeaponAttackType attType)
{
BaseModGroup modGroup;
uint16 index;
CombatRating cr;
switch (attType)
{
case OFF_ATTACK:
modGroup = OFFHAND_CRIT_PERCENTAGE;
index = PLAYER_OFFHAND_CRIT_PERCENTAGE;
cr = CR_CRIT_MELEE;
break;
case RANGED_ATTACK:
modGroup = RANGED_CRIT_PERCENTAGE;
index = PLAYER_RANGED_CRIT_PERCENTAGE;
cr = CR_CRIT_RANGED;
break;
case BASE_ATTACK:
default:
modGroup = CRIT_PERCENTAGE;
index = PLAYER_CRIT_PERCENTAGE;
cr = CR_CRIT_MELEE;
break;
}
// flat = bonus from crit auras, pct = bonus from agility, combat rating = mods from items
float value = GetBaseModValue(modGroup, FLAT_MOD) + GetBaseModValue(modGroup, PCT_MOD) + GetRatingBonusValue(cr);
// Modify crit from weapon skill and maximized defense skill of same level victim difference
value += (int32(GetWeaponSkillValue(attType)) - int32(GetMaxSkillValueForLevel())) * 0.04f;
if (sWorld->getBoolConfig(CONFIG_STATS_LIMITS_ENABLE))
value = value > sWorld->getFloatConfig(CONFIG_STATS_LIMITS_CRIT) ? sWorld->getFloatConfig(CONFIG_STATS_LIMITS_CRIT) : value;
value = std::max(0.0f, value);
SetStatFloatValue(index, value);
}
void Player::UpdateAllCritPercentages()
{
float value = GetMeleeCritFromAgility();
SetBaseModPctValue(CRIT_PERCENTAGE, value);
SetBaseModPctValue(OFFHAND_CRIT_PERCENTAGE, value);
SetBaseModPctValue(RANGED_CRIT_PERCENTAGE, value);
UpdateCritPercentage(BASE_ATTACK);
UpdateCritPercentage(OFF_ATTACK);
UpdateCritPercentage(RANGED_ATTACK);
}
float const m_diminishing_k[MAX_CLASSES] =
{
0.9560f, // Warrior
0.9560f, // Paladin
0.9880f, // Hunter
0.9880f, // Rogue
0.9830f, // Priest
0.9560f, // DK
0.9880f, // Shaman
0.9830f, // Mage
0.9830f, // Warlock
0.0f, // ??
0.9720f // Druid
};
// helper function
float CalculateDiminishingReturns(float const (&capArray)[MAX_CLASSES], uint8 playerClass, float nonDiminishValue, float diminishValue)
{
// 1 1 k cx
// --- = --- + --- <=> x' = --------
// x' c x x + ck
// where:
// k is m_diminishing_k for that class
// c is capArray for that class
// x is chance before DR (diminishValue)
// x' is chance after DR (our result)
uint32 const classIdx = playerClass - 1;
float const k = m_diminishing_k[classIdx];
float const c = capArray[classIdx];
float result = c * diminishValue / (diminishValue + c * k);
result += nonDiminishValue;
return result;
}
float const miss_cap[MAX_CLASSES] =
{
16.00f, // Warrior //correct
16.00f, // Paladin //correct
16.00f, // Hunter //?
16.00f, // Rogue //?
16.00f, // Priest //?
16.00f, // DK //correct
16.00f, // Shaman //?
16.00f, // Mage //?
16.00f, // Warlock //?
0.0f, // ??
16.00f // Druid //?
};
float Player::GetMissPercentageFromDefense() const
{
float diminishing = 0.0f, nondiminishing = 0.0f;
// Modify value from defense skill (only bonus from defense rating diminishes)
nondiminishing += (int32(GetSkillValue(SKILL_DEFENSE)) - int32(GetMaxSkillValueForLevel())) * 0.04f;
diminishing += (GetRatingBonusValue(CR_DEFENSE_SKILL) * 0.04f);
// apply diminishing formula to diminishing miss chance
return CalculateDiminishingReturns(miss_cap, getClass(), nondiminishing, diminishing);
}
float const parry_cap[MAX_CLASSES] =
{
47.003525f, // Warrior
47.003525f, // Paladin
145.560408f, // Hunter
145.560408f, // Rogue
0.0f, // Priest
47.003525f, // DK
145.560408f, // Shaman
0.0f, // Mage
0.0f, // Warlock
0.0f, // ??
0.0f // Druid
};
void Player::UpdateParryPercentage()
{
// No parry
float value = 0.0f;
uint32 pclass = getClass() - 1;
if (CanParry() && parry_cap[pclass] > 0.0f)
{
float nondiminishing = 5.0f;
// Parry from rating
float diminishing = GetRatingBonusValue(CR_PARRY);
// Modify value from defense skill (only bonus from defense rating diminishes)
nondiminishing += (int32(GetSkillValue(SKILL_DEFENSE)) - int32(GetMaxSkillValueForLevel())) * 0.04f;
diminishing += (GetRatingBonusValue(CR_DEFENSE_SKILL) * 0.04f);
// Parry from SPELL_AURA_MOD_PARRY_PERCENT aura
nondiminishing += GetTotalAuraModifier(SPELL_AURA_MOD_PARRY_PERCENT);
// apply diminishing formula to diminishing parry chance
value = CalculateDiminishingReturns(parry_cap, getClass(), nondiminishing, diminishing);
if (sWorld->getBoolConfig(CONFIG_STATS_LIMITS_ENABLE))
value = value > sWorld->getFloatConfig(CONFIG_STATS_LIMITS_PARRY) ? sWorld->getFloatConfig(CONFIG_STATS_LIMITS_PARRY) : value;
value = value < 0.0f ? 0.0f : value;
}
SetStatFloatValue(PLAYER_PARRY_PERCENTAGE, value);
}
float const dodge_cap[MAX_CLASSES] =
{
88.129021f, // Warrior
88.129021f, // Paladin
145.560408f, // Hunter
145.560408f, // Rogue
150.375940f, // Priest
88.129021f, // DK
145.560408f, // Shaman
150.375940f, // Mage
150.375940f, // Warlock
0.0f, // ??
116.890707f // Druid
};
void Player::UpdateDodgePercentage()
{
float diminishing = 0.0f, nondiminishing = 0.0f;
GetDodgeFromAgility(diminishing, nondiminishing);
// Modify value from defense skill (only bonus from defense rating diminishes)
nondiminishing += (int32(GetSkillValue(SKILL_DEFENSE)) - int32(GetMaxSkillValueForLevel())) * 0.04f;
diminishing += (GetRatingBonusValue(CR_DEFENSE_SKILL) * 0.04f);
// Dodge from SPELL_AURA_MOD_DODGE_PERCENT aura
nondiminishing += GetTotalAuraModifier(SPELL_AURA_MOD_DODGE_PERCENT);
// Dodge from rating
diminishing += GetRatingBonusValue(CR_DODGE);
// apply diminishing formula to diminishing dodge chance
float value = CalculateDiminishingReturns(dodge_cap, getClass(), nondiminishing, diminishing);
if (sWorld->getBoolConfig(CONFIG_STATS_LIMITS_ENABLE))
value = value > sWorld->getFloatConfig(CONFIG_STATS_LIMITS_DODGE) ? sWorld->getFloatConfig(CONFIG_STATS_LIMITS_DODGE) : value;
value = value < 0.0f ? 0.0f : value;
SetStatFloatValue(PLAYER_DODGE_PERCENTAGE, value);
}
void Player::UpdateSpellCritChance(uint32 school)
{
// For normal school set zero crit chance
if (school == SPELL_SCHOOL_NORMAL)
{
SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1, 0.0f);
return;
}
// For others recalculate it from:
float crit = 0.0f;
// Crit from Intellect
crit += GetSpellCritFromIntellect();
// Increase crit from SPELL_AURA_MOD_SPELL_CRIT_CHANCE
crit += GetTotalAuraModifier(SPELL_AURA_MOD_SPELL_CRIT_CHANCE);
// Increase crit from SPELL_AURA_MOD_CRIT_PCT
crit += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PCT);
// Increase crit by school from SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL
crit += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, 1<<school);
// Increase crit from spell crit ratings
crit += GetRatingBonusValue(CR_CRIT_SPELL);
// Store crit value
SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1 + school, crit);
}
void Player::UpdateArmorPenetration(int32 amount)
{
// Store Rating Value
SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + CR_ARMOR_PENETRATION, amount);
}
void Player::UpdateMeleeHitChances()
{
m_modMeleeHitChance = GetRatingBonusValue(CR_HIT_MELEE);
}
void Player::UpdateRangedHitChances()
{
m_modRangedHitChance = GetRatingBonusValue(CR_HIT_RANGED);
}
void Player::UpdateSpellHitChances()
{
m_modSpellHitChance = (float)GetTotalAuraModifier(SPELL_AURA_MOD_SPELL_HIT_CHANCE);
m_modSpellHitChance += GetRatingBonusValue(CR_HIT_SPELL);
}
void Player::UpdateAllSpellCritChances()
{
for (int i = SPELL_SCHOOL_NORMAL; i < MAX_SPELL_SCHOOL; ++i)
UpdateSpellCritChance(i);
}
void Player::UpdateExpertise(WeaponAttackType attack)
{
if (attack == RANGED_ATTACK)
return;
int32 expertise = int32(GetRatingBonusValue(CR_EXPERTISE));
Item const* weapon = GetWeaponForAttack(attack, true);
expertise += GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE, [weapon](AuraEffect const* aurEff) -> bool
{
return aurEff->GetSpellInfo()->IsItemFitToSpellRequirements(weapon);
});
if (expertise < 0)
expertise = 0;
switch (attack)
{
case BASE_ATTACK:
SetUInt32Value(PLAYER_EXPERTISE, expertise);
break;
case OFF_ATTACK:
SetUInt32Value(PLAYER_OFFHAND_EXPERTISE, expertise);
break;
default:
break;
}
}
void Player::ApplyManaRegenBonus(int32 amount, bool apply)
{
_ModifyUInt32(apply, m_baseManaRegen, amount);
UpdateManaRegen();
}
void Player::ApplyHealthRegenBonus(int32 amount, bool apply)
{
_ModifyUInt32(apply, m_baseHealthRegen, amount);
}
void Player::UpdateManaRegen()
{
float Intellect = GetStat(STAT_INTELLECT);
// Mana regen from spirit and intellect
float power_regen = std::sqrt(Intellect) * OCTRegenMPPerSpirit();
// Apply PCT bonus from SPELL_AURA_MOD_POWER_REGEN_PERCENT aura on spirit base regen
power_regen *= GetTotalAuraMultiplierByMiscValue(SPELL_AURA_MOD_POWER_REGEN_PERCENT, POWER_MANA);
// Mana regen from SPELL_AURA_MOD_POWER_REGEN aura
float power_regen_mp5 = (GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_POWER_REGEN, POWER_MANA) + m_baseManaRegen) / 5.0f;
// Get bonus from SPELL_AURA_MOD_MANA_REGEN_FROM_STAT aura
AuraEffectList const& regenAura = GetAuraEffectsByType(SPELL_AURA_MOD_MANA_REGEN_FROM_STAT);
for (AuraEffectList::const_iterator i = regenAura.begin(); i != regenAura.end(); ++i)
power_regen_mp5 += GetStat(Stats((*i)->GetMiscValue())) * (*i)->GetAmount() / 500.0f;
// Set regen rate in cast state apply only on spirit based regen
int32 modManaRegenInterrupt = GetTotalAuraModifier(SPELL_AURA_MOD_MANA_REGEN_INTERRUPT);
if (modManaRegenInterrupt > 100)
modManaRegenInterrupt = 100;
SetStatFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER, power_regen_mp5 + CalculatePct(power_regen, modManaRegenInterrupt));
SetStatFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER, power_regen_mp5 + power_regen);
}
void Player::UpdateRuneRegen(RuneType rune)
{
if (rune >= NUM_RUNE_TYPES)
return;
uint32 cooldown = 0;
for (uint32 i = 0; i < MAX_RUNES; ++i)
if (GetBaseRune(i) == rune)
{
cooldown = GetRuneBaseCooldown(i);
break;
}
if (cooldown <= 0)
return;
float regen = float(1 * IN_MILLISECONDS) / float(cooldown);
SetFloatValue(PLAYER_RUNE_REGEN_1 + uint8(rune), regen);
}
void Player::_ApplyAllStatBonuses()
{
SetCanModifyStats(false);
_ApplyAllAuraStatMods();
_ApplyAllItemMods();
SetCanModifyStats(true);
UpdateAllStats();
}
void Player::_RemoveAllStatBonuses()
{
SetCanModifyStats(false);
_RemoveAllItemMods();
_RemoveAllAuraStatMods();
SetCanModifyStats(true);
UpdateAllStats();
}
/*#######################################
######## ########
######## MOBS STAT SYSTEM ########
######## ########
#######################################*/
bool Creature::UpdateStats(Stats /*stat*/)
{
return true;
}
bool Creature::UpdateAllStats()
{
UpdateMaxHealth();
UpdateAttackPowerAndDamage();
UpdateAttackPowerAndDamage(true);
for (uint8 i = POWER_MANA; i < MAX_POWERS; ++i)
UpdateMaxPower(Powers(i));
UpdateAllResistances();
return true;
}
void Creature::UpdateResistances(uint32 school)
{
if (school > SPELL_SCHOOL_NORMAL)
{
float value = GetTotalAuraModValue(UnitMods(UNIT_MOD_RESISTANCE_START + school));
SetResistance(SpellSchools(school), int32(value));
}
else
UpdateArmor();
}
void Creature::UpdateArmor()
{
float value = GetTotalAuraModValue(UNIT_MOD_ARMOR);
SetArmor(int32(value));
}
void Creature::UpdateMaxHealth()
{
float value = GetTotalAuraModValue(UNIT_MOD_HEALTH);
SetMaxHealth(uint32(value));
}
void Creature::UpdateMaxPower(Powers power)
{
UnitMods unitMod = UnitMods(UNIT_MOD_POWER_START + power);
float value = GetFlatModifierValue(unitMod, BASE_VALUE) + GetCreatePowerValue(power);
value *= GetPctModifierValue(unitMod, BASE_PCT);
value += GetFlatModifierValue(unitMod, TOTAL_VALUE);
value *= GetPctModifierValue(unitMod, TOTAL_PCT);
SetMaxPower(power, uint32(std::lroundf(value)));
}
void Creature::UpdateAttackPowerAndDamage(bool ranged)
{
UnitMods unitMod = ranged ? UNIT_MOD_ATTACK_POWER_RANGED : UNIT_MOD_ATTACK_POWER;
uint16 index = UNIT_FIELD_ATTACK_POWER;
uint16 indexMod = UNIT_FIELD_ATTACK_POWER_MODS;
uint16 indexMulti = UNIT_FIELD_ATTACK_POWER_MULTIPLIER;
if (ranged)
{
index = UNIT_FIELD_RANGED_ATTACK_POWER;
indexMod = UNIT_FIELD_RANGED_ATTACK_POWER_MODS;
indexMulti = UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER;
}
float baseAttackPower = GetFlatModifierValue(unitMod, BASE_VALUE) * GetPctModifierValue(unitMod, BASE_PCT);
float attackPowerMod = GetFlatModifierValue(unitMod, TOTAL_VALUE);
float attackPowerMultiplier = GetPctModifierValue(unitMod, TOTAL_PCT) - 1.0f;
SetInt32Value(index, uint32(baseAttackPower)); // UNIT_FIELD_(RANGED)_ATTACK_POWER
SetInt32Value(indexMod, uint32(attackPowerMod)); // UNIT_FIELD_(RANGED)_ATTACK_POWER_MODS
SetFloatValue(indexMulti, attackPowerMultiplier); // UNIT_FIELD_(RANGED)_ATTACK_POWER_MULTIPLIER
// automatically update weapon damage after attack power modification
if (ranged)
UpdateDamagePhysical(RANGED_ATTACK);
else
{
UpdateDamagePhysical(BASE_ATTACK);
UpdateDamagePhysical(OFF_ATTACK);
}
}
void Creature::CalculateMinMaxDamage(WeaponAttackType attType, bool normalized, bool addTotalPct, float& minDamage, float& maxDamage, uint8 damageIndex /*= 0*/) const
{
// creatures only have one damage
if (damageIndex != 0)
{
minDamage = 0.f;
maxDamage = 0.f;
return;
}
float variance = 1.0f;
UnitMods unitMod;
switch (attType)
{
case BASE_ATTACK:
default:
variance = GetCreatureTemplate()->BaseVariance;
unitMod = UNIT_MOD_DAMAGE_MAINHAND;
break;
case OFF_ATTACK:
variance = GetCreatureTemplate()->BaseVariance;
unitMod = UNIT_MOD_DAMAGE_OFFHAND;
break;
case RANGED_ATTACK:
variance = GetCreatureTemplate()->RangeVariance;
unitMod = UNIT_MOD_DAMAGE_RANGED;
break;
}
if (attType == OFF_ATTACK && !haveOffhandWeapon())
{
minDamage = 0.0f;
maxDamage = 0.0f;
return;
}
float weaponMinDamage = GetWeaponDamageRange(attType, MINDAMAGE);
float weaponMaxDamage = GetWeaponDamageRange(attType, MAXDAMAGE);
if (!CanUseAttackType(attType)) // disarm case
{
weaponMinDamage = 0.0f;
weaponMaxDamage = 0.0f;
}
float attackPower = GetTotalAttackPowerValue(attType);
float attackSpeedMulti = GetAPMultiplier(attType, normalized);
float baseValue = GetFlatModifierValue(unitMod, BASE_VALUE) + (attackPower / 14.0f) * variance;
float basePct = GetPctModifierValue(unitMod, BASE_PCT) * attackSpeedMulti;
float totalValue = GetFlatModifierValue(unitMod, TOTAL_VALUE);
float totalPct = addTotalPct ? GetPctModifierValue(unitMod, TOTAL_PCT) : 1.0f;
float dmgMultiplier = GetCreatureTemplate()->ModDamage; // = ModDamage * _GetDamageMod(rank);
minDamage = ((weaponMinDamage + baseValue) * dmgMultiplier * basePct + totalValue) * totalPct;
maxDamage = ((weaponMaxDamage + baseValue) * dmgMultiplier * basePct + totalValue) * totalPct;
}
/*#######################################
######## ########
######## PETS STAT SYSTEM ########
######## ########
#######################################*/
#define ENTRY_IMP 416
#define ENTRY_VOIDWALKER 1860
#define ENTRY_SUCCUBUS 1863
#define ENTRY_FELHUNTER 417
#define ENTRY_FELGUARD 17252
#define ENTRY_WATER_ELEMENTAL 510
#define ENTRY_TREANT 1964
#define ENTRY_FIRE_ELEMENTAL 15438
#define ENTRY_GHOUL 26125
#define ENTRY_BLOODWORM 28017
bool Guardian::UpdateStats(Stats stat)
{
if (stat >= MAX_STATS)
return false;
// value = ((base_value * base_pct) + total_value) * total_pct
float value = GetTotalStatValue(stat);
//ApplyStatBuffMod(stat, m_statFromOwner[stat], false);
float ownersBonus = 0.0f;
Unit* owner = GetOwner();
// Handle Death Knight Glyphs and Talents
float mod = 0.75f;
if ((IsPetGhoul() || IsRisenAlly()) && (stat == STAT_STAMINA || stat == STAT_STRENGTH))
{
if (stat == STAT_STAMINA)
mod = 0.3f; // Default Owner's Stamina scale
else
mod = 0.7f; // Default Owner's Strength scale
// Check just if owner has Ravenous Dead since it's effect is not an aura
AuraEffect const* aurEff = owner->GetAuraEffect(SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE, SPELLFAMILY_DEATHKNIGHT, 3010, 0);
if (aurEff)
{
SpellInfo const* spellInfo = aurEff->GetSpellInfo(); // Then get the SpellProto and add the dummy effect value
AddPct(mod, spellInfo->Effects[EFFECT_1].CalcValue()); // Ravenous Dead edits the original scale
}
// Glyph of the Ghoul
aurEff = owner->GetAuraEffect(58686, 0);
if (aurEff)
mod += CalculatePct(1.0f, aurEff->GetAmount()); // Glyph of the Ghoul adds a flat value to the scale mod
ownersBonus = float(owner->GetStat(stat)) * mod;
value += ownersBonus;
}
else if (stat == STAT_STAMINA)
{
if (owner->getClass() == CLASS_WARLOCK && IsPet())
{
ownersBonus = CalculatePct(owner->GetStat(STAT_STAMINA), 75);
value += ownersBonus;
}
else
{
mod = 0.45f;
if (IsPet())
{
PetSpellMap::const_iterator itr = (ToPet()->m_spells.find(62758)); // Wild Hunt rank 1
if (itr == ToPet()->m_spells.end())
itr = ToPet()->m_spells.find(62762); // Wild Hunt rank 2
if (itr != ToPet()->m_spells.end()) // If pet has Wild Hunt
{
SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(itr->first); // Then get the SpellProto and add the dummy effect value
AddPct(mod, spellInfo->Effects[EFFECT_0].CalcValue());
}
}
ownersBonus = float(owner->GetStat(stat)) * mod;
value += ownersBonus;
}
}
//warlock's and mage's pets gain 30% of owner's intellect
else if (stat == STAT_INTELLECT)
{
if (owner->getClass() == CLASS_WARLOCK || owner->getClass() == CLASS_MAGE)
{
ownersBonus = CalculatePct(owner->GetStat(stat), 30);
value += ownersBonus;
}
}
/*
else if (stat == STAT_STRENGTH)
{
if (IsPetGhoul())
value += float(owner->GetStat(stat)) * 0.3f;
}
*/
SetStat(stat, int32(value));
m_statFromOwner[stat] = ownersBonus;
UpdateStatBuffMod(stat);
switch (stat)
{
case STAT_STRENGTH: UpdateAttackPowerAndDamage(); break;
case STAT_AGILITY: UpdateArmor(); break;
case STAT_STAMINA: UpdateMaxHealth(); break;
case STAT_INTELLECT: UpdateMaxPower(POWER_MANA); break;
case STAT_SPIRIT:
default:
break;
}
return true;
}
bool Guardian::UpdateAllStats()
{
UpdateMaxHealth();
for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i)
UpdateStats(Stats(i));
for (uint8 i = POWER_MANA; i < MAX_POWERS; ++i)
UpdateMaxPower(Powers(i));
UpdateAllResistances();
return true;
}
void Guardian::UpdateResistances(uint32 school)
{
if (school > SPELL_SCHOOL_NORMAL)
{
float value = GetTotalAuraModValue(UnitMods(UNIT_MOD_RESISTANCE_START + school));
// hunter and warlock pets gain 40% of owner's resistance
if (IsPet())
value += float(CalculatePct(m_owner->GetResistance(SpellSchools(school)), 40));
SetResistance(SpellSchools(school), int32(value));
}
else
UpdateArmor();
}
void Guardian::UpdateArmor()
{
float value = 0.0f;
float bonus_armor = 0.0f;
UnitMods unitMod = UNIT_MOD_ARMOR;
// hunter and warlock pets gain 35% of owner's armor value
if (IsPet())
bonus_armor = float(CalculatePct(m_owner->GetArmor(), 35));
value = GetFlatModifierValue(unitMod, BASE_VALUE);
value *= GetPctModifierValue(unitMod, BASE_PCT);
value += GetStat(STAT_AGILITY) * 2.0f;
value += GetFlatModifierValue(unitMod, TOTAL_VALUE) + bonus_armor;
value *= GetPctModifierValue(unitMod, TOTAL_PCT);
SetArmor(int32(value));
}
void Guardian::UpdateMaxHealth()
{
UnitMods unitMod = UNIT_MOD_HEALTH;
float stamina = GetStat(STAT_STAMINA) - GetCreateStat(STAT_STAMINA);
float multiplicator;
switch (GetEntry())
{
case ENTRY_IMP: multiplicator = 8.4f; break;
case ENTRY_VOIDWALKER: multiplicator = 11.0f; break;
case ENTRY_SUCCUBUS: multiplicator = 9.1f; break;
case ENTRY_FELHUNTER: multiplicator = 9.5f; break;
case ENTRY_FELGUARD: multiplicator = 11.0f; break;
case ENTRY_BLOODWORM: multiplicator = 1.0f; break;
default: multiplicator = 10.0f; break;
}
float value = GetFlatModifierValue(unitMod, BASE_VALUE) + GetCreateHealth();
value *= GetPctModifierValue(unitMod, BASE_PCT);
value += GetFlatModifierValue(unitMod, TOTAL_VALUE) + stamina * multiplicator;
value *= GetPctModifierValue(unitMod, TOTAL_PCT);
SetMaxHealth((uint32)value);
}
void Guardian::UpdateMaxPower(Powers power)
{
UnitMods unitMod = UnitMods(UNIT_MOD_POWER_START + power);
float addValue = (power == POWER_MANA) ? GetStat(STAT_INTELLECT) - GetCreateStat(STAT_INTELLECT) : 0.0f;
float multiplicator = 15.0f;
switch (GetEntry())
{
case ENTRY_IMP: multiplicator = 4.95f; break;
case ENTRY_VOIDWALKER:
case ENTRY_SUCCUBUS:
case ENTRY_FELHUNTER:
case ENTRY_FELGUARD: multiplicator = 11.5f; break;
default: multiplicator = 15.0f; break;
}
float value = GetFlatModifierValue(unitMod, BASE_VALUE) + GetCreatePowerValue(power);
value *= GetPctModifierValue(unitMod, BASE_PCT);
value += GetFlatModifierValue(unitMod, TOTAL_VALUE) + addValue * multiplicator;
value *= GetPctModifierValue(unitMod, TOTAL_PCT);
SetMaxPower(power, uint32(value));
}
void Guardian::UpdateAttackPowerAndDamage(bool ranged)
{
if (ranged)
return;
float val = 0.0f;
float bonusAP = 0.0f;
UnitMods unitMod = UNIT_MOD_ATTACK_POWER;
if (GetEntry() == ENTRY_IMP) // imp's attack power
val = GetStat(STAT_STRENGTH) - 10.0f;
else
val = 2 * GetStat(STAT_STRENGTH) - 20.0f;
Unit* owner = GetOwner();
if (owner && owner->GetTypeId() == TYPEID_PLAYER)
{
if (IsHunterPet()) //hunter pets benefit from owner's attack power
{
float mod = 1.0f; //Hunter contribution modifier
if (IsPet())
{
PetSpellMap::const_iterator itr = ToPet()->m_spells.find(62758); //Wild Hunt rank 1
if (itr == ToPet()->m_spells.end())
itr = ToPet()->m_spells.find(62762); //Wild Hunt rank 2
if (itr != ToPet()->m_spells.end()) // If pet has Wild Hunt
{
SpellInfo const* sProto = sSpellMgr->AssertSpellInfo(itr->first); // Then get the SpellProto and add the dummy effect value
mod += CalculatePct(1.0f, sProto->Effects[1].CalcValue());
}
}
bonusAP = owner->GetTotalAttackPowerValue(RANGED_ATTACK) * 0.22f * mod;
if (AuraEffect* aurEff = owner->GetAuraEffectOfRankedSpell(34453, EFFECT_1, owner->GetGUID())) // Animal Handler
{
AddPct(bonusAP, aurEff->GetAmount());
AddPct(val, aurEff->GetAmount());
}
SetBonusDamage(int32(owner->GetTotalAttackPowerValue(RANGED_ATTACK) * 0.1287f * mod));
}
else if (IsPetGhoul() || IsRisenAlly()) //ghouls benefit from deathknight's attack power (may be summon pet or not)
{
bonusAP = owner->GetTotalAttackPowerValue(BASE_ATTACK) * 0.22f;
SetBonusDamage(int32(owner->GetTotalAttackPowerValue(BASE_ATTACK) * 0.1287f));
}
else if (IsSpiritWolf()) //wolf benefit from shaman's attack power
{
float dmg_multiplier = 0.31f;
if (m_owner->GetAuraEffect(63271, 0)) // Glyph of Feral Spirit
dmg_multiplier = 0.61f;
bonusAP = owner->GetTotalAttackPowerValue(BASE_ATTACK) * dmg_multiplier;
SetBonusDamage(int32(owner->GetTotalAttackPowerValue(BASE_ATTACK) * dmg_multiplier));
}
//demons benefit from warlocks shadow or fire damage
else if (IsPet())
{
int32 fire = owner->GetInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_FIRE) - owner->GetInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG + SPELL_SCHOOL_FIRE);
int32 shadow = owner->GetInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_SHADOW) - owner->GetInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG + SPELL_SCHOOL_SHADOW);
int32 maximum = (fire > shadow) ? fire : shadow;
if (maximum < 0)
maximum = 0;
SetBonusDamage(int32(maximum * 0.15f));
bonusAP = maximum * 0.57f;
}
//water elementals benefit from mage's frost damage
else if (GetEntry() == ENTRY_WATER_ELEMENTAL)
{
int32 frost = owner->GetInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_FROST) - owner->GetInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG + SPELL_SCHOOL_FROST);
if (frost < 0)
frost = 0;
SetBonusDamage(int32(frost * 0.4f));
}
}
SetStatFlatModifier(UNIT_MOD_ATTACK_POWER, BASE_VALUE, val + bonusAP);
//in BASE_VALUE of UNIT_MOD_ATTACK_POWER for creatures we store data of meleeattackpower field in DB
float base_attPower = GetFlatModifierValue(unitMod, BASE_VALUE) * GetPctModifierValue(unitMod, BASE_PCT);
float attPowerMod = GetFlatModifierValue(unitMod, TOTAL_VALUE);
float attPowerMultiplier = GetPctModifierValue(unitMod, TOTAL_PCT) - 1.0f;
//UNIT_FIELD_(RANGED)_ATTACK_POWER field
SetInt32Value(UNIT_FIELD_ATTACK_POWER, (int32)base_attPower);
//UNIT_FIELD_(RANGED)_ATTACK_POWER_MODS field
SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, (int32)attPowerMod);
//UNIT_FIELD_(RANGED)_ATTACK_POWER_MULTIPLIER field
SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER, attPowerMultiplier);
//automatically update weapon damage after attack power modification
UpdateDamagePhysical(BASE_ATTACK);
}
void Guardian::UpdateDamagePhysical(WeaponAttackType attType)
{
if (attType > BASE_ATTACK)
return;
float bonusDamage = 0.0f;
if (m_owner->GetTypeId() == TYPEID_PLAYER)
{
//force of nature
if (GetEntry() == ENTRY_TREANT)
{
int32 spellDmg = m_owner->GetInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_NATURE) - m_owner->GetInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG + SPELL_SCHOOL_NATURE);
if (spellDmg > 0)
bonusDamage = spellDmg * 0.09f;
}
//greater fire elemental
else if (GetEntry() == ENTRY_FIRE_ELEMENTAL)
{
int32 spellDmg = m_owner->GetInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_FIRE) - m_owner->GetInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG + SPELL_SCHOOL_FIRE);
if (spellDmg > 0)
bonusDamage = spellDmg * 0.4f;
}
}
UnitMods unitMod = UNIT_MOD_DAMAGE_MAINHAND;
float att_speed = float(GetAttackTime(BASE_ATTACK))/1000.0f;
float base_value = GetFlatModifierValue(unitMod, BASE_VALUE) + GetTotalAttackPowerValue(attType) / 14.0f * att_speed + bonusDamage;
float base_pct = GetPctModifierValue(unitMod, BASE_PCT);
float total_value = GetFlatModifierValue(unitMod, TOTAL_VALUE);
float total_pct = GetPctModifierValue(unitMod, TOTAL_PCT);
float weapon_mindamage = GetWeaponDamageRange(BASE_ATTACK, MINDAMAGE);
float weapon_maxdamage = GetWeaponDamageRange(BASE_ATTACK, MAXDAMAGE);
float mindamage = ((base_value + weapon_mindamage) * base_pct + total_value) * total_pct;
float maxdamage = ((base_value + weapon_maxdamage) * base_pct + total_value) * total_pct;
// Pet's base damage changes depending on happiness
if (IsHunterPet())
{
switch (ToPet()->GetHappinessState())
{
case HAPPY:
// 125% of normal damage
mindamage = mindamage * 1.25f;
maxdamage = maxdamage * 1.25f;
break;
case CONTENT:
// 100% of normal damage, nothing to modify
break;
case UNHAPPY:
// 75% of normal damage
mindamage = mindamage * 0.75f;
maxdamage = maxdamage * 0.75f;
break;
}
}
/// @todo: remove this
Unit::AuraEffectList const& mDummy = GetAuraEffectsByType(SPELL_AURA_MOD_ATTACKSPEED);
for (Unit::AuraEffectList::const_iterator itr = mDummy.begin(); itr != mDummy.end(); ++itr)
{
switch ((*itr)->GetSpellInfo()->Id)
{
case 61682:
case 61683:
AddPct(mindamage, -(*itr)->GetAmount());
AddPct(maxdamage, -(*itr)->GetAmount());
break;
default:
break;
}
}
SetStatFloatValue(UNIT_FIELD_MINDAMAGE, mindamage);
SetStatFloatValue(UNIT_FIELD_MAXDAMAGE, maxdamage);
}
void Guardian::SetBonusDamage(int32 damage)
{
m_bonusSpellDamage = damage;
if (GetOwner()->GetTypeId() == TYPEID_PLAYER)
GetOwner()->SetUInt32Value(PLAYER_PET_SPELL_POWER, damage);
}
| gpl-2.0 |
ahmedalaahagag/HospitalManagementSystem | wp-content/plugins/hospital-management/admin/includes/medicine/index.php | 6225 | <?php
$obj_medicine = new Hmgtmedicine();
$active_tab = isset($_GET['tab'])?$_GET['tab']:'medicinelist';
?>
<!-- POP up code -->
<div class="popup-bg">
<div class="overlay-content">
<div class="modal-content">
<div class="category_list">
</div>
</div>
</div>
</div>
<!-- End POP-UP Code -->
<div class="page-inner" style="min-height:1631px !important">
<div class="page-title">
<h3><img src="<?php echo get_option( 'hmgt_hospital_logo' ) ?>" class="img-circle head_logo" width="40" height="40" /><?php echo get_option( 'hmgt_hospital_name' );?></h3>
</div>
<?php
if(isset($_REQUEST['save_category']))
{
$result = $obj_medicine->hmgt_add_medicinecategory($_POST);
if($result)
{
?>
<div id="message" class="updated below-h2">
<?php
_e('Medicine Category Insert Successfully.','hospital_mgt');
?></div><?php
}
}
if(isset($_REQUEST['save_medicine']))
{
if(isset($_REQUEST['action']) && ($_REQUEST['action'] == 'insert' || $_REQUEST['action'] == 'edit'))
{
$result = $obj_medicine->hmgt_add_medicine($_POST);
if($result)
{
if($_REQUEST['action'] == 'edit')
{
wp_redirect ( admin_url().'admin.php?page=hmgt_medicine&tab=medicinelist&message=2'); }
else
{
wp_redirect ( admin_url().'admin.php?page=hmgt_medicine&tab=medicinelist&message=1');
}
}
}
}
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'delete')
{
$result = $obj_medicine->delete_medicine($_REQUEST['medicine_id']);
if($result)
{
wp_redirect ( admin_url().'admin.php?page=hmgt_medicine&tab=medicinelist&message=3');
}
}
if(isset($_REQUEST['message']))
{
$message =$_REQUEST['message'];
if($message == 1)
{?>
<div id="message" class="updated below-h2 ">
<p>
<?php
_e('Record inserted successfully','hospital_mgt');
?></p></div>
<?php
}
elseif($message == 2)
{?><div id="message" class="updated below-h2 "><p><?php
_e("Record updated successfully",'hospital_mgt');
?></p>
</div>
<?php
}
elseif($message == 3)
{?>
<div id="message" class="updated below-h2"><p>
<?php
_e('Record deleted successfully','hospital_mgt');
?></div></p><?php
}
}
?>
<div id="main-wrapper">
<div class="row">
<div class="col-md-12">
<div class="panel panel-white">
<div class="panel-body">
<h2 class="nav-tab-wrapper">
<a href="?page=hmgt_medicine&tab=medicinelist" class="nav-tab <?php echo $active_tab == 'medicinelist' ? 'nav-tab-active' : ''; ?>">
<?php echo '<span class="dashicons dashicons-menu"></span>'.__('Medicine List', 'hospital_mgt'); ?></a>
<?php if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit')
{?>
<a href="?page=hmgt_medicine&tab=addmedicine&&action=edit&medicine_id=<?php echo $_REQUEST['medicine_id'];?>" class="nav-tab <?php echo $active_tab == 'addmedicine' ? 'nav-tab-active' : ''; ?>">
<?php _e('Edit Medicine', 'hospital_mgt'); ?></a>
<?php
}
else
{?>
<a href="?page=hmgt_medicine&tab=addmedicine" class="nav-tab <?php echo $active_tab == 'addmedicine' ? 'nav-tab-active' : ''; ?>">
<?php echo '<span class="dashicons dashicons-plus-alt"></span>'.__('Add New Medicine', 'hospital_mgt'); ?></a>
<?php }?>
</h2>
<?php
//Report 1
if($active_tab == 'medicinelist')
{
?>
<script type="text/javascript">
$(document).ready(function() {
jQuery('#medicine_list').DataTable({
"aoColumns":[
{"bSortable": true},
{"bSortable": true},
{"bSortable": true},
{"bSortable": true},
{"bSortable": false}]});
} );
</script>
<form name="medicine" action="" method="post">
<div class="panel-body">
<div class="table-responsive">
<table id="medicine_list" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th><?php _e( 'Medicine Name', 'hospital_mgt' ) ;?></th>
<th><?php _e( 'Category', 'hospital_mgt' ) ;?></th>
<th><?php _e( 'Price', 'hospital_mgt' ) ;?></th>
<th><?php _e( 'Stock', 'hospital_mgt' ) ;?></th>
<th><?php _e( 'Action', 'hospital_mgt' ) ;?></th>
</tr>
</thead>
<tfoot>
<tr>
<th><?php _e( 'Medicine Name', 'hospital_mgt' ) ;?></th>
<th><?php _e( 'Category', 'hospital_mgt' ) ;?></th>
<th><?php _e( 'Price', 'hospital_mgt' ) ;?></th>
<th><?php _e( 'Stock', 'hospital_mgt' ) ;?></th>
<th><?php _e( 'Action', 'hospital_mgt' ) ;?></th>
</tr>
</tfoot>
<tbody>
<?php
$medicinedata=$obj_medicine->get_all_medicine();
if(!empty($medicinedata))
{
foreach ($medicinedata as $retrieved_data){
?>
<tr>
<td class="medicine_name"><?php echo $retrieved_data->medicine_name; ?></td>
<td class="category"><?php echo $obj_medicine->get_medicine_categoryname($retrieved_data->med_cat_id);?></td>
<td class="price"><?php echo $retrieved_data->medicine_price; ?></td>
<td class="medicine_qty"><?php echo $retrieved_data->medicine_stock;?></td>
<td class="action"> <a href="?page=hmgt_medicine&tab=addmedicine&action=edit&medicine_id=<?php echo $retrieved_data->medicine_id;?>" class="btn btn-info"> <?php _e('Edit', 'hospital_mgt' ) ;?></a>
<a href="?page=hmgt_medicine&tab=medicinelist&action=delete&medicine_id=<?php echo $retrieved_data->medicine_id;?>" class="btn btn-danger"
onclick="return confirm('<?php _e('Are you sure you want to delete this record?','hospital_mgt');?>');">
<?php _e( 'Delete', 'hospital_mgt' ) ;?> </a>
</td>
</tr>
<?php }
}?>
</tbody>
</table>
</div>
</div>
</form>
<?php
}
if($active_tab == 'addmedicine')
{
require_once HMS_PLUGIN_DIR. '/admin/includes/medicine/add_medicine.php';
}
?>
</div>
</div>
</div>
</div>
<?php //} ?> | gpl-2.0 |
rompe/digikam-core-yolo | utilities/importui/views/importthumbnailbar.cpp | 6218 | /* ============================================================
*
* This file is a part of digiKam project
* http://www.digikam.org
*
* Date : 2012-20-07
* Description : Thumbnail bar for import tool
*
* Copyright (C) 2012 by Islam Wazery <wazery at ubuntu dot com>
* Copyright (C) 2012-2015 by Gilles Caulier <caulier dot gilles 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, 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.
*
* ============================================================ */
#include "importthumbnailbar.h"
// Local includes
#include "digikam_debug.h"
#include "importsettings.h"
#include "importdelegate.h"
#include "importfiltermodel.h"
#include "importoverlays.h"
namespace Digikam
{
class ImportThumbnailBar::Private
{
public:
Private()
{
scrollPolicy = Qt::ScrollBarAlwaysOn;
duplicatesFilter = 0;
}
Qt::ScrollBarPolicy scrollPolicy;
NoDuplicatesImportFilterModel* duplicatesFilter;
};
ImportThumbnailBar::ImportThumbnailBar(QWidget* const parent)
: ImportCategorizedView(parent), d(new Private())
{
setItemDelegate(new ImportThumbnailDelegate(this));
setSpacing(3);
setUsePointingHandCursor(false);
setScrollStepGranularity(5);
setScrollBarPolicy(Qt::ScrollBarAlwaysOn);
setDragEnabled(true);
setAcceptDrops(true);
setDropIndicatorShown(false);
//TODO: Implement Import Tool settings
//setToolTipEnabled(ImportSettings::instance()->showToolTipsIsValid());
connect(ImportSettings::instance(), SIGNAL(setupChanged()),
this, SLOT(slotSetupChanged()));
slotSetupChanged();
setFlow(LeftToRight);
}
ImportThumbnailBar::~ImportThumbnailBar()
{
delete d;
}
void ImportThumbnailBar::setModelsFiltered(ImportImageModel* model, ImportSortFilterModel* filterModel)
{
if (!d->duplicatesFilter)
{
d->duplicatesFilter = new NoDuplicatesImportFilterModel(this);
}
d->duplicatesFilter->setSourceFilterModel(filterModel);
ImportCategorizedView::setModels(model, d->duplicatesFilter);
}
void ImportThumbnailBar::installOverlays()
{
ImportRatingOverlay* const ratingOverlay = new ImportRatingOverlay(this);
addOverlay(ratingOverlay);
connect(ratingOverlay, SIGNAL(ratingEdited(QList<QModelIndex>,int)),
this, SLOT(assignRating(QList<QModelIndex>,int)));
addOverlay(new ImportLockOverlay(this));
addOverlay(new ImportDownloadOverlay(this));
addOverlay(new ImportCoordinatesOverlay(this));
}
void ImportThumbnailBar::slotDockLocationChanged(Qt::DockWidgetArea area)
{
if (area == Qt::LeftDockWidgetArea || area == Qt::RightDockWidgetArea)
{
setFlow(TopToBottom);
}
else
{
setFlow(LeftToRight);
}
scrollTo(currentIndex());
}
void ImportThumbnailBar::setScrollBarPolicy(Qt::ScrollBarPolicy policy)
{
if (policy == Qt::ScrollBarAsNeeded)
{
// Delegate resizing will cause endless relayouting, see bug #228807
qCDebug(LOG_IMPORTUI) << "The Qt::ScrollBarAsNeeded policy is not supported by ImportThumbnailBar";
}
d->scrollPolicy = policy;
if (flow() == TopToBottom)
{
setVerticalScrollBarPolicy(d->scrollPolicy);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}
else
{
setHorizontalScrollBarPolicy(d->scrollPolicy);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}
}
void ImportThumbnailBar::setFlow(QListView::Flow flow)
{
setWrapping(false);
ImportCategorizedView::setFlow(flow);
ImportThumbnailDelegate* del = static_cast<ImportThumbnailDelegate*>(delegate());
del->setFlow(flow);
// Reset the minimum and maximum sizes.
setMinimumSize(QSize(0, 0));
setMaximumSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX));
// Adjust minimum and maximum width to thumbnail sizes.
if (flow == TopToBottom)
{
int viewportFullWidgetOffset = size().width() - viewport()->size().width();
setMinimumWidth(del->minimumSize() + viewportFullWidgetOffset);
setMaximumWidth(del->maximumSize() + viewportFullWidgetOffset);
}
else
{
int viewportFullWidgetOffset = size().height() - viewport()->size().height();
setMinimumHeight(del->minimumSize() + viewportFullWidgetOffset);
setMaximumHeight(del->maximumSize() + viewportFullWidgetOffset);
}
setScrollBarPolicy(d->scrollPolicy);
}
void ImportThumbnailBar::slotSetupChanged()
{
setToolTipEnabled(ImportSettings::instance()->showToolTipsIsValid());
setFont(ImportSettings::instance()->getIconViewFont());
ImportCategorizedView::slotSetupChanged();
}
void ImportThumbnailBar::assignRating(const QList<QModelIndex>& indexes, int rating)
{
QList<QModelIndex> mappedIndexes = importSortFilterModel()->mapListToSource(indexes);
foreach(const QModelIndex& index, mappedIndexes)
{
if (index.isValid())
{
importImageModel()->camItemInfoRef(index).rating = rating;
}
}
}
bool ImportThumbnailBar::event(QEvent* e)
{
// reset widget max/min sizes
if (e->type() == QEvent::StyleChange || e->type() == QEvent::Show)
{
setFlow(flow());
}
return ImportCategorizedView::event(e);
}
QModelIndex ImportThumbnailBar::nextIndex(const QModelIndex& index) const
{
return importFilterModel()->index(index.row() + 1, 0);
}
QModelIndex ImportThumbnailBar::previousIndex(const QModelIndex& index) const
{
return importFilterModel()->index(index.row() - 1, 0);
}
QModelIndex ImportThumbnailBar::firstIndex() const
{
return importFilterModel()->index(0, 0);
}
QModelIndex ImportThumbnailBar::lastIndex() const
{
return importFilterModel()->index(importFilterModel()->rowCount() - 1, 0);
}
} // namespace Digikam
| gpl-2.0 |
eventum/eventum | src/Controller/MailQueueController.php | 1736 | <?php
/*
* This file is part of the Eventum (Issue Tracking System) package.
*
* @copyright (c) Eventum Team
* @license GNU General Public License, version 2 or later (GPL-2+)
*
* For the full copyright and license information,
* please see the COPYING and AUTHORS files
* that were distributed with this source code.
*/
namespace Eventum\Controller;
use Auth;
use Issue;
use Mail_Queue;
use User;
class MailQueueController extends BaseController
{
/** @var string */
protected $tpl_name = 'mail_queue.tpl.html';
/** @var int */
private $issue_id;
/**
* {@inheritdoc}
*/
protected function configure(): void
{
$request = $this->getRequest();
$this->issue_id = $request->query->getInt('iss_id');
}
/**
* {@inheritdoc}
*/
protected function canAccess(): bool
{
Auth::checkAuthentication();
$role_id = Auth::getCurrentRole();
if ($role_id < User::ROLE_DEVELOPER) {
return false;
}
$prj_id = Auth::getCurrentProject();
if (Issue::getProjectID($this->issue_id) != $prj_id) {
return false;
// use generic error
// TODO, cleanup template from 'denied' cause
//$this->tpl->assign('denied', 1);
}
return true;
}
/**
* {@inheritdoc}
*/
protected function defaultAction(): void
{
}
/**
* {@inheritdoc}
*/
protected function prepareTemplate(): void
{
$data = Mail_Queue::getListByIssueID($this->issue_id);
$this->tpl->assign(
[
'data' => $data,
'issue_id' => $this->issue_id,
]
);
}
}
| gpl-2.0 |
manhhung86it/builder-site | wp-content/themes/origin/widgets/Testimonial.php | 3854 | <?php
class WP_Testimonial extends WP_Widget {
var $image_bg_field = 'image_bg'; // the image field ID
public function __construct() {
parent::__construct(
'WP_Testimonial', // Base ID
'Home Testimonial', // Name
array('description' => 'Show list testimonial on home page')
);
}
public function widget($args, $instance) {
extract($args);
$image_id = $instance[$this->image_bg_field];
$image = new WidgetImageField($this, $image_id);
$tmp = $image->get_image_src('full');
$style = 'style="background: url(\''.$tmp.'\') no-repeat center center; -webkit-background-size: 100%; -moz-background-size: 100%; -o-background-size: 100%;"';
$posts = get_posts(array(
'posts_per_page' => $instance['number'],
'post_type' => 'testimonial',
'meta_key' => 'show_on_homepage',
'meta_value' => 1
));
if ($posts) {
$list_testimonial = '<div class="testimonials-box" '.$style.'>'
. '<div class="mainslider">'
. '<ul class="slides group">';
foreach ($posts as $post) {
$list_testimonial .='<li>'
. get_the_post_thumbnail($post->ID, 'thumbnail')
. '<div class="slider-content">'
. '<div class="slider-title">' . $post->customer_name . '</div>';
if (strlen($post->post_content) >= 200) {
$list_testimonial .= '<span>' . substr( strip_tags($post->post_content), 0, 200) . '</span>';
$list_testimonial .= '<a class=\'more-link\' href="'.get_site_url().'/testimonials">...read more</a>';
} else {
$list_testimonial .= '<span>' . $post->post_content . '</span>';
}
$list_testimonial .= '</div>'
. '</li>';
}
$list_testimonial .='</ul>'
. '</div>'
. '</div>';
echo $list_testimonial;
}
}
public function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = $new_instance['title'];
$instance[$this->image_bg_field] = intval(strip_tags($new_instance[$this->image_bg_field]));
$instance['number'] = $new_instance['number'];
return $instance;
}
public function form($instance) {
if (empty($instance['title'])) {
$title = '';
} else {
$title = $instance['title'];
}
$image_bg_id = esc_attr(isset($instance[$this->image_bg_field]) ? $instance[$this->image_bg_field] : 0 );
$image_bg = new WidgetImageField($this, $image_bg_id);
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" />
</p>
<div id="div_background_image">
<label><?php _e('Background Image:'); ?></label>
<?php echo $image_bg->get_widget_field('bg_image', 'bg'); ?>
</div>
<p id="div_number">
<label for="<?php echo $this->get_field_id('number'); ?>"><?php _e('Number of testimonials to show:'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('number'); ?>" name="<?php echo $this->get_field_name('number'); ?>" type="text" value="<?php echo esc_attr($instance['number']); ?>" />
</p>
<?php
}
}
add_action('widgets_init', create_function('', 'register_widget( "WP_Testimonial" );'));
| gpl-2.0 |
lilith645/Return-Void | src/Namespaces/Highscore.cpp | 3753 | #include "../../include/Namespaces/Highscore.h"
Highscore *Highscore::m_instance = 0;
Highscore::Highscore() {
Load();
}
Highscore::~Highscore() {
Save();
}
Highscore *Highscore::init() {
if(!Highscore::m_instance) {
Highscore::m_instance = new Highscore;
} else {
printf(("WARNING: Highscore::init() has already been called.\n"));
exit(-1);
}
return Highscore::m_instance;
}
Highscore *Highscore::instance() {
if(!Highscore::m_instance) {
return Highscore::init();
} else
return Highscore::m_instance;
}
void Highscore::destroy() {
delete Highscore::m_instance;
Highscore::m_instance = 0;
}
void Highscore::Load() {
// check whether application directory in the home diretory exists, if not create it
# ifdef __linux__
home = getenv("HOME");
if (*home.rbegin() != '/') home += '/';
mkdir((home + ".returnvoid/").c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
# endif
# ifdef __WIN32__
TCHAR szAppData[MAX_PATH];
SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, szAppData);
home = szAppData;
CreateDirectory((home + ".returnvoid/").c_str(), NULL);
# endif
isNewHighscore = false;
if(File::check_if_file_exists((home + ".returnvoid/Highscore.bin").c_str())) {
printf("Loading Highscore\n");
ifs.open((home + ".returnvoid/Highscore.bin").c_str(), std::ios::binary);
version = File::LoadFloat(ifs);
if(version != (float)VERSION) {
ifs.close();
createNewHighscore();
} else {
for(int i = 0; i < 10; ++i) {
for(int j = 0; j < 6; ++j) {
name[i][j] = File::LoadChar(ifs);
}
}
for(int i = 0; i < 10; ++i) {
highscores[i] = File::LoadInt(ifs);
}
ifs.close();
}
} else {
createNewHighscore();
}
}
void Highscore::Save() {
printf("Saving Highscore\n");
std::ofstream ofs((home + ".returnvoid/Highscore.bin").c_str(), std::ios::binary);
File::SaveFloat(ofs, version);
for(int i = 0; i < 10; ++i) {
for(int j = 0; j < 6; ++j) {
File::SaveChar(ofs, name[i][j]);
}
}
for(int i = 0; i < 10; ++i) {
File::SaveInt(ofs, highscores[i]);
}
ofs.close();
}
void Highscore::createNewHighscore() {
printf("Creating Highscore file\n");
version = VERSION;
highscores[0] = 10000;
highscores[1] = 8000;
highscores[2] = 7500;
highscores[3] = 7000;
highscores[4] = 5000;
highscores[5] = 4000;
highscores[6] = 3500;
highscores[7] = 3000;
highscores[8] = 2000;
highscores[9] = 1000;
name[0][0] = 'A';
name[0][1] = 'k';
name[0][2] = 'u';
name[0][3] = 'm';
name[0][4] = 'a';
name[0][5] = ' ';
name[1][0] = 'S';
name[1][1] = 'a';
name[1][2] = 't';
name[1][3] = 'a';
name[1][4] = 'n';
name[1][5] = ' ';
name[2][0] = 'S';
name[2][1] = 't';
name[2][2] = 'e';
name[2][3] = 'v';
name[2][4] = 'e';
name[2][5] = 'n';
name[3][0] = 'D';
name[3][1] = 'a';
name[3][2] = 'v';
name[3][3] = 'e';
name[3][4] = ' ';
name[3][5] = ' ';
name[4][0] = 'H';
name[4][1] = 'a';
name[4][2] = 'c';
name[4][3] = 'k';
name[4][4] = 'e';
name[4][5] = 'r';
name[5][0] = '1';
name[5][1] = '3';
name[5][2] = '3';
name[5][3] = '7';
name[5][4] = ' ';
name[5][5] = ' ';
name[6][0] = 'G';
name[6][1] = 'o';
name[6][2] = 'd';
name[6][3] = ' ';
name[6][4] = ' ';
name[6][5] = ' ';
name[7][0] = 'P';
name[7][1] = 'a';
name[7][2] = 'c';
name[7][3] = 'm';
name[7][4] = 'a';
name[7][5] = 'n';
name[8][0] = 'P';
name[8][1] = 'r';
name[8][2] = 'o';
name[8][3] = ' ';
name[8][4] = ' ';
name[8][5] = ' ';
name[9][0] = 'L';
name[9][1] = 'a';
name[9][2] = 'g';
name[9][3] = ' ';
name[9][4] = ' ';
name[9][5] = ' ';
Save();
}
| gpl-2.0 |
hardvain/mono-compiler | class/Microsoft.Build.Framework/Microsoft.Build.Framework/LoadInSeparateAppDomainAttribute.cs | 1611 | //
// LoadInSeperateAppDomainAttribute.cs: Defines the metadata attribute that
// MSBuild uses to identify tasks that must be executed in their own
// application domains.
//
// Author:
// Marek Sieradzki (marek.sieradzki@gmail.com)
//
// (C) 2005 Marek Sieradzki
//
// 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;
namespace Microsoft.Build.Framework
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple=false,
Inherited = true)]
public sealed class LoadInSeparateAppDomainAttribute : Attribute
{
public LoadInSeparateAppDomainAttribute ()
{
}
}
}
| gpl-2.0 |
serghei/kde3-kdelibs | kdeui/kpassivepopup.cpp | 13639 | /*
* copyright : (C) 2001-2002 by Richard Moore
* copyright : (C) 2004-2005 by Sascha Cunz
* License : This file is released under the terms of the LGPL, version 2.
* email : rich@kde.org
* email : sascha.cunz@tiscali.de
*/
#include <kconfig.h>
#include <qapplication.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qtimer.h>
#include <qvbox.h>
#include <qpainter.h>
#include <qtooltip.h>
#include <qbitmap.h>
#include <qpointarray.h>
#include <kdebug.h>
#include <kdialog.h>
#include <kpixmap.h>
#include <kpixmapeffect.h>
#include <kglobalsettings.h>
#include "config.h"
#ifdef Q_WS_X11
#include <netwm.h>
#endif
#include "kpassivepopup.h"
#include "kpassivepopup.moc"
class KPassivePopup::Private {
public:
int popupStyle;
QPointArray surround;
QPoint anchor;
QPoint fixedPosition;
};
static const int DEFAULT_POPUP_TYPE = KPassivePopup::Boxed;
static const int DEFAULT_POPUP_TIME = 6 * 1000;
static const int POPUP_FLAGS =
Qt::WStyle_Customize | Qt::WDestructiveClose | Qt::WX11BypassWM | Qt::WStyle_StaysOnTop | Qt::WStyle_Tool | Qt::WStyle_NoBorder;
KPassivePopup::KPassivePopup(QWidget *parent, const char *name, WFlags f)
: QFrame(0, name, f ? f : POPUP_FLAGS)
, window(parent ? parent->winId() : 0L)
, msgView(0)
, topLayout(0)
, hideDelay(DEFAULT_POPUP_TIME)
, hideTimer(new QTimer(this, "hide_timer"))
, m_autoDelete(false)
{
init(DEFAULT_POPUP_TYPE);
}
KPassivePopup::KPassivePopup(WId win, const char *name, WFlags f)
: QFrame(0, name, f ? f : POPUP_FLAGS)
, window(win)
, msgView(0)
, topLayout(0)
, hideDelay(DEFAULT_POPUP_TIME)
, hideTimer(new QTimer(this, "hide_timer"))
, m_autoDelete(false)
{
init(DEFAULT_POPUP_TYPE);
}
KPassivePopup::KPassivePopup(int popupStyle, QWidget *parent, const char *name, WFlags f)
: QFrame(0, name, f ? f : POPUP_FLAGS)
, window(parent ? parent->winId() : 0L)
, msgView(0)
, topLayout(0)
, hideDelay(DEFAULT_POPUP_TIME)
, hideTimer(new QTimer(this, "hide_timer"))
, m_autoDelete(false)
{
init(popupStyle);
}
KPassivePopup::KPassivePopup(int popupStyle, WId win, const char *name, WFlags f)
: QFrame(0, name, f ? f : POPUP_FLAGS)
, window(win)
, msgView(0)
, topLayout(0)
, hideDelay(DEFAULT_POPUP_TIME)
, hideTimer(new QTimer(this, "hide_timer"))
, m_autoDelete(false)
{
init(popupStyle);
}
void KPassivePopup::init(int popupStyle)
{
d = new Private;
d->popupStyle = popupStyle;
if(popupStyle == Boxed)
{
setFrameStyle(QFrame::Box | QFrame::Plain);
setLineWidth(2);
}
else if(popupStyle == Balloon)
{
setPalette(QToolTip::palette());
setAutoMask(TRUE);
}
connect(hideTimer, SIGNAL(timeout()), SLOT(hide()));
connect(this, SIGNAL(clicked()), SLOT(hide()));
}
KPassivePopup::~KPassivePopup()
{
delete d;
}
void KPassivePopup::setView(QWidget *child)
{
delete msgView;
msgView = child;
delete topLayout;
topLayout = new QVBoxLayout(this, d->popupStyle == Balloon ? 22 : KDialog::marginHint(), KDialog::spacingHint());
topLayout->addWidget(msgView);
topLayout->activate();
}
void KPassivePopup::setView(const QString &caption, const QString &text, const QPixmap &icon)
{
// kdDebug() << "KPassivePopup::setView " << caption << ", " << text << endl;
setView(standardView(caption, text, icon, this));
}
QVBox *KPassivePopup::standardView(const QString &caption, const QString &text, const QPixmap &icon, QWidget *parent)
{
QVBox *vb = new QVBox(parent ? parent : this);
vb->setSpacing(KDialog::spacingHint());
QHBox *hb = 0;
if(!icon.isNull())
{
hb = new QHBox(vb);
hb->setMargin(0);
hb->setSpacing(KDialog::spacingHint());
ttlIcon = new QLabel(hb, "title_icon");
ttlIcon->setPixmap(icon);
ttlIcon->setAlignment(AlignLeft);
}
if(!caption.isEmpty())
{
ttl = new QLabel(caption, hb ? hb : vb, "title_label");
QFont fnt = ttl->font();
fnt.setBold(true);
ttl->setFont(fnt);
ttl->setAlignment(Qt::AlignHCenter);
if(hb)
hb->setStretchFactor(ttl, 10); // enforce centering
}
if(!text.isEmpty())
{
msg = new QLabel(text, vb, "msg_label");
msg->setAlignment(AlignLeft);
}
return vb;
}
void KPassivePopup::setView(const QString &caption, const QString &text)
{
setView(caption, text, QPixmap());
}
void KPassivePopup::setTimeout(int delay)
{
hideDelay = delay;
if(hideTimer->isActive())
{
if(delay)
{
hideTimer->changeInterval(delay);
}
else
{
hideTimer->stop();
}
}
}
void KPassivePopup::setAutoDelete(bool autoDelete)
{
m_autoDelete = autoDelete;
}
void KPassivePopup::mouseReleaseEvent(QMouseEvent *e)
{
emit clicked();
emit clicked(e->pos());
}
//
// Main Implementation
//
void KPassivePopup::show()
{
if(size() != sizeHint())
resize(sizeHint());
if(d->fixedPosition.isNull())
positionSelf();
else
{
if(d->popupStyle == Balloon)
setAnchor(d->fixedPosition);
else
move(d->fixedPosition);
}
QFrame::show();
int delay = hideDelay;
if(delay < 0)
{
delay = DEFAULT_POPUP_TIME;
}
if(delay > 0)
{
hideTimer->start(delay);
}
}
void KPassivePopup::show(const QPoint &p)
{
d->fixedPosition = p;
show();
}
void KPassivePopup::hideEvent(QHideEvent *)
{
hideTimer->stop();
if(m_autoDelete)
deleteLater();
}
QRect KPassivePopup::defaultArea() const
{
#ifdef Q_WS_X11
NETRootInfo info(qt_xdisplay(), NET::NumberOfDesktops | NET::CurrentDesktop | NET::WorkArea, -1, false);
info.activate();
NETRect workArea = info.workArea(info.currentDesktop());
QRect r;
r.setRect(workArea.pos.x, workArea.pos.y, 0, 0); // top left
#else
// FIX IT
QRect r;
r.setRect(100, 100, 200, 200); // top left
#endif
return r;
}
void KPassivePopup::positionSelf()
{
QRect target;
#ifdef Q_WS_X11
if(!window)
{
target = defaultArea();
}
else
{
NETWinInfo ni(qt_xdisplay(), window, qt_xrootwin(), NET::WMIconGeometry | NET::WMKDESystemTrayWinFor);
// Figure out where to put the popup. Note that we must handle
// windows that skip the taskbar cleanly
if(ni.kdeSystemTrayWinFor())
{
NETRect frame, win;
ni.kdeGeometry(frame, win);
target.setRect(win.pos.x, win.pos.y, win.size.width, win.size.height);
}
else if(ni.state() & NET::SkipTaskbar)
{
target = defaultArea();
}
else
{
NETRect r = ni.iconGeometry();
target.setRect(r.pos.x, r.pos.y, r.size.width, r.size.height);
if(target.isNull())
{ // bogus value, use the exact position
NETRect dummy;
ni.kdeGeometry(dummy, r);
target.setRect(r.pos.x, r.pos.y, r.size.width, r.size.height);
}
}
}
#else
target = defaultArea();
#endif
moveNear(target);
}
void KPassivePopup::moveNear(QRect target)
{
QPoint pos = target.topLeft();
int x = pos.x();
int y = pos.y();
int w = width();
int h = height();
QRect r = KGlobalSettings::desktopGeometry(QPoint(x + w / 2, y + h / 2));
if(d->popupStyle == Balloon)
{
// find a point to anchor to
if(x + w > r.width())
{
x = x + target.width();
}
if(y + h > r.height())
{
y = y + target.height();
}
}
else
{
if(x < r.center().x())
x = x + target.width();
else
x = x - w;
// It's apparently trying to go off screen, so display it ALL at the bottom.
if((y + h) > r.bottom())
y = r.bottom() - h;
if((x + w) > r.right())
x = r.right() - w;
}
if(y < r.top())
y = r.top();
if(x < r.left())
x = r.left();
if(d->popupStyle == Balloon)
setAnchor(QPoint(x, y));
else
move(x, y);
}
void KPassivePopup::setAnchor(const QPoint &anchor)
{
d->anchor = anchor;
updateMask();
}
void KPassivePopup::paintEvent(QPaintEvent *pe)
{
if(d->popupStyle == Balloon)
{
QPainter p;
p.begin(this);
p.drawPolygon(d->surround);
}
else
QFrame::paintEvent(pe);
}
void KPassivePopup::updateMask()
{
// get screen-geometry for screen our anchor is on
// (geometry can differ from screen to screen!
QRect deskRect = KGlobalSettings::desktopGeometry(d->anchor);
int xh = 70, xl = 40;
if(width() < 80)
xh = xl = 40;
else if(width() < 110)
xh = width() - 40;
bool bottom = (d->anchor.y() + height()) > ((deskRect.y() + deskRect.height() - 48));
bool right = (d->anchor.x() + width()) > ((deskRect.x() + deskRect.width() - 48));
QPoint corners[4] = {QPoint(width() - 50, 10), QPoint(10, 10), QPoint(10, height() - 50), QPoint(width() - 50, height() - 50)};
QBitmap mask(width(), height(), true);
QPainter p(&mask);
QBrush brush(Qt::white, Qt::SolidPattern);
p.setBrush(brush);
int i = 0, z = 0;
for(; i < 4; ++i)
{
QPointArray corner;
corner.makeArc(corners[i].x(), corners[i].y(), 40, 40, i * 16 * 90, 16 * 90);
d->surround.resize(z + corner.count());
for(unsigned int s = 0; s < corner.count() - 1; s++)
{
d->surround.setPoint(z++, corner[s]);
}
if(bottom && i == 2)
{
if(right)
{
d->surround.resize(z + 3);
d->surround.setPoint(z++, QPoint(width() - xh, height() - 11));
d->surround.setPoint(z++, QPoint(width() - 20, height()));
d->surround.setPoint(z++, QPoint(width() - xl, height() - 11));
}
else
{
d->surround.resize(z + 3);
d->surround.setPoint(z++, QPoint(xl, height() - 11));
d->surround.setPoint(z++, QPoint(20, height()));
d->surround.setPoint(z++, QPoint(xh, height() - 11));
}
}
else if(!bottom && i == 0)
{
if(right)
{
d->surround.resize(z + 3);
d->surround.setPoint(z++, QPoint(width() - xl, 10));
d->surround.setPoint(z++, QPoint(width() - 20, 0));
d->surround.setPoint(z++, QPoint(width() - xh, 10));
}
else
{
d->surround.resize(z + 3);
d->surround.setPoint(z++, QPoint(xh, 10));
d->surround.setPoint(z++, QPoint(20, 0));
d->surround.setPoint(z++, QPoint(xl, 10));
}
}
}
d->surround.resize(z + 1);
d->surround.setPoint(z, d->surround[0]);
p.drawPolygon(d->surround);
setMask(mask);
move(right ? d->anchor.x() - width() + 20 : (d->anchor.x() < 11 ? 11 : d->anchor.x() - 20),
bottom ? d->anchor.y() - height() : (d->anchor.y() < 11 ? 11 : d->anchor.y()));
update();
}
//
// Convenience Methods
//
KPassivePopup *KPassivePopup::message(const QString &caption, const QString &text, const QPixmap &icon, QWidget *parent, const char *name,
int timeout)
{
return message(DEFAULT_POPUP_TYPE, caption, text, icon, parent, name, timeout);
}
KPassivePopup *KPassivePopup::message(const QString &text, QWidget *parent, const char *name)
{
return message(DEFAULT_POPUP_TYPE, QString::null, text, QPixmap(), parent, name);
}
KPassivePopup *KPassivePopup::message(const QString &caption, const QString &text, QWidget *parent, const char *name)
{
return message(DEFAULT_POPUP_TYPE, caption, text, QPixmap(), parent, name);
}
KPassivePopup *KPassivePopup::message(const QString &caption, const QString &text, const QPixmap &icon, WId parent, const char *name, int timeout)
{
return message(DEFAULT_POPUP_TYPE, caption, text, icon, parent, name, timeout);
}
KPassivePopup *KPassivePopup::message(int popupStyle, const QString &caption, const QString &text, const QPixmap &icon, QWidget *parent,
const char *name, int timeout)
{
KPassivePopup *pop = new KPassivePopup(popupStyle, parent, name);
pop->setAutoDelete(true);
pop->setView(caption, text, icon);
pop->hideDelay = timeout;
pop->show();
return pop;
}
KPassivePopup *KPassivePopup::message(int popupStyle, const QString &text, QWidget *parent, const char *name)
{
return message(popupStyle, QString::null, text, QPixmap(), parent, name);
}
KPassivePopup *KPassivePopup::message(int popupStyle, const QString &caption, const QString &text, QWidget *parent, const char *name)
{
return message(popupStyle, caption, text, QPixmap(), parent, name);
}
KPassivePopup *KPassivePopup::message(int popupStyle, const QString &caption, const QString &text, const QPixmap &icon, WId parent, const char *name,
int timeout)
{
KPassivePopup *pop = new KPassivePopup(popupStyle, parent, name);
pop->setAutoDelete(true);
pop->setView(caption, text, icon);
pop->hideDelay = timeout;
pop->show();
return pop;
}
// Local Variables:
// c-basic-offset: 4
// End:
| gpl-2.0 |
agomusic/ardour3 | libs/ardour/automation_list.cc | 9680 | /*
Copyright (C) 2002 Paul Davis
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 <set>
#include <climits>
#include <float.h>
#include <cmath>
#include <sstream>
#include <algorithm>
#include <sigc++/bind.h>
#include <ardour/automation_list.h>
#include <ardour/event_type_map.h>
#include <evoral/Curve.hpp>
#include <pbd/stacktrace.h>
#include <pbd/enumwriter.h>
#include "i18n.h"
using namespace std;
using namespace ARDOUR;
using namespace sigc;
using namespace PBD;
sigc::signal<void,AutomationList *> AutomationList::AutomationListCreated;
#if 0
static void dumpit (const AutomationList& al, string prefix = "")
{
cerr << prefix << &al << endl;
for (AutomationList::const_iterator i = al.const_begin(); i != al.const_end(); ++i) {
cerr << prefix << '\t' << (*i)->when << ',' << (*i)->value << endl;
}
cerr << "\n";
}
#endif
/* XXX: min_val max_val redundant? (param.min() param.max()) */
AutomationList::AutomationList (Evoral::Parameter id)
: ControlList(id)
{
_state = Off;
_style = Absolute;
_touching = false;
assert(_parameter.type() != NullAutomation);
AutomationListCreated(this);
}
AutomationList::AutomationList (const AutomationList& other)
: ControlList(other)
{
_state = other._state;
_touching = other._touching;
assert(_parameter.type() != NullAutomation);
AutomationListCreated(this);
}
AutomationList::AutomationList (const AutomationList& other, double start, double end)
: ControlList(other, start, end)
{
_style = other._style;
_state = other._state;
_touching = other._touching;
assert(_parameter.type() != NullAutomation);
AutomationListCreated(this);
}
/** \a id is used for legacy sessions where the type is not present
* in or below the <AutomationList> node. It is used if \a id is non-null.
*/
AutomationList::AutomationList (const XMLNode& node, Evoral::Parameter id)
: ControlList(id)
{
_touching = false;
_state = Off;
_style = Absolute;
set_state (node);
if (id)
_parameter = id;
assert(_parameter.type() != NullAutomation);
AutomationListCreated(this);
}
AutomationList::~AutomationList()
{
GoingAway ();
}
boost::shared_ptr<Evoral::ControlList>
AutomationList::create(Evoral::Parameter id)
{
return boost::shared_ptr<Evoral::ControlList>(new AutomationList(id));
}
bool
AutomationList::operator== (const AutomationList& other)
{
return _events == other._events;
}
AutomationList&
AutomationList::operator= (const AutomationList& other)
{
if (this != &other) {
_events.clear ();
for (const_iterator i = other._events.begin(); i != other._events.end(); ++i) {
_events.push_back (new Evoral::ControlEvent (**i));
}
_min_yval = other._min_yval;
_max_yval = other._max_yval;
_max_xval = other._max_xval;
_default_value = other._default_value;
mark_dirty ();
maybe_signal_changed ();
}
return *this;
}
void
AutomationList::maybe_signal_changed ()
{
ControlList::maybe_signal_changed ();
if (!_frozen) {
StateChanged (); /* EMIT SIGNAL */
}
}
void
AutomationList::set_automation_state (AutoState s)
{
if (s != _state) {
_state = s;
automation_state_changed (); /* EMIT SIGNAL */
}
}
void
AutomationList::set_automation_style (AutoStyle s)
{
if (s != _style) {
_style = s;
automation_style_changed (); /* EMIT SIGNAL */
}
}
void
AutomationList::start_touch ()
{
_touching = true;
_new_value = true;
}
void
AutomationList::stop_touch ()
{
_touching = false;
_new_value = false;
}
void
AutomationList::freeze ()
{
_frozen++;
}
void
AutomationList::thaw ()
{
ControlList::thaw();
if (_changed_when_thawed) {
StateChanged(); /* EMIT SIGNAL */
}
}
void
AutomationList::mark_dirty () const
{
ControlList::mark_dirty ();
Dirty (); /* EMIT SIGNAL */
}
XMLNode&
AutomationList::get_state ()
{
return state (true);
}
XMLNode&
AutomationList::state (bool full)
{
XMLNode* root = new XMLNode (X_("AutomationList"));
char buf[64];
LocaleGuard lg (X_("POSIX"));
root->add_property ("automation-id", EventTypeMap::instance().to_symbol(_parameter));
root->add_property ("id", _id.to_s());
snprintf (buf, sizeof (buf), "%.12g", _default_value);
root->add_property ("default", buf);
snprintf (buf, sizeof (buf), "%.12g", _min_yval);
root->add_property ("min-yval", buf);
snprintf (buf, sizeof (buf), "%.12g", _max_yval);
root->add_property ("max-yval", buf);
snprintf (buf, sizeof (buf), "%.12g", _max_xval);
root->add_property ("max-xval", buf);
root->add_property ("interpolation-style", enum_2_string (_interpolation));
if (full) {
root->add_property ("state", auto_state_to_string (_state));
} else {
/* never save anything but Off for automation state to a template */
root->add_property ("state", auto_state_to_string (Off));
}
root->add_property ("style", auto_style_to_string (_style));
if (!_events.empty()) {
root->add_child_nocopy (serialize_events());
}
return *root;
}
XMLNode&
AutomationList::serialize_events ()
{
XMLNode* node = new XMLNode (X_("events"));
stringstream str;
for (iterator xx = _events.begin(); xx != _events.end(); ++xx) {
str << (double) (*xx)->when;
str << ' ';
str <<(double) (*xx)->value;
str << '\n';
}
/* XML is a bit wierd */
XMLNode* content_node = new XMLNode (X_("foo")); /* it gets renamed by libxml when we set content */
content_node->set_content (str.str());
node->add_child_nocopy (*content_node);
return *node;
}
int
AutomationList::deserialize_events (const XMLNode& node)
{
if (node.children().empty()) {
return -1;
}
XMLNode* content_node = node.children().front();
if (content_node->content().empty()) {
return -1;
}
freeze ();
clear ();
stringstream str (content_node->content());
double x;
double y;
bool ok = true;
while (str) {
str >> x;
if (!str) {
break;
}
str >> y;
if (!str) {
ok = false;
break;
}
fast_simple_add (x, y);
}
if (!ok) {
clear ();
error << _("automation list: cannot load coordinates from XML, all points ignored") << endmsg;
} else {
mark_dirty ();
reposition_for_rt_add (0);
maybe_signal_changed ();
}
thaw ();
return 0;
}
int
AutomationList::set_state (const XMLNode& node)
{
XMLNodeList nlist = node.children();
XMLNode* nsos;
XMLNodeIterator niter;
const XMLProperty* prop;
if (node.name() == X_("events")) {
/* partial state setting*/
return deserialize_events (node);
}
if (node.name() == X_("Envelope") || node.name() == X_("FadeOut") || node.name() == X_("FadeIn")) {
if ((nsos = node.child (X_("AutomationList")))) {
/* new school in old school clothing */
return set_state (*nsos);
}
/* old school */
const XMLNodeList& elist = node.children();
XMLNodeConstIterator i;
XMLProperty* prop;
nframes_t x;
double y;
freeze ();
clear ();
for (i = elist.begin(); i != elist.end(); ++i) {
if ((prop = (*i)->property ("x")) == 0) {
error << _("automation list: no x-coordinate stored for control point (point ignored)") << endmsg;
continue;
}
x = atoi (prop->value().c_str());
if ((prop = (*i)->property ("y")) == 0) {
error << _("automation list: no y-coordinate stored for control point (point ignored)") << endmsg;
continue;
}
y = atof (prop->value().c_str());
fast_simple_add (x, y);
}
thaw ();
return 0;
}
if (node.name() != X_("AutomationList") ) {
error << string_compose (_("AutomationList: passed XML node called %1, not \"AutomationList\" - ignored"), node.name()) << endmsg;
return -1;
}
if ((prop = node.property ("id")) != 0) {
_id = prop->value ();
/* update session AL list */
AutomationListCreated(this);
}
if ((prop = node.property (X_("automation-id"))) != 0){
_parameter = EventTypeMap::instance().new_parameter(prop->value());
} else {
warning << "Legacy session: automation list has no automation-id property.";
}
if ((prop = node.property (X_("interpolation-style"))) != 0) {
_interpolation = (InterpolationStyle)string_2_enum(prop->value(), _interpolation);
} else {
_interpolation = Linear;
}
if ((prop = node.property (X_("default"))) != 0){
_default_value = atof (prop->value().c_str());
} else {
_default_value = 0.0;
}
if ((prop = node.property (X_("style"))) != 0) {
_style = string_to_auto_style (prop->value());
} else {
_style = Absolute;
}
if ((prop = node.property (X_("state"))) != 0) {
_state = string_to_auto_state (prop->value());
} else {
_state = Off;
}
if ((prop = node.property (X_("min_yval"))) != 0) {
_min_yval = atof (prop->value ().c_str());
} else {
_min_yval = FLT_MIN;
}
if ((prop = node.property (X_("max_yval"))) != 0) {
_max_yval = atof (prop->value ().c_str());
} else {
_max_yval = FLT_MAX;
}
if ((prop = node.property (X_("max_xval"))) != 0) {
_max_xval = atof (prop->value ().c_str());
} else {
_max_xval = 0; // means "no limit ;
}
for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
if ((*niter)->name() == X_("events")) {
deserialize_events (*(*niter));
}
}
return 0;
}
| gpl-2.0 |
ARudik/feelpp.cln | src/float/transcendental/cl_LF_exp_aux.cc | 2544 | // cl_exp_aux().
// General includes.
#include "base/cl_sysdep.h"
// Specification.
#include "float/transcendental/cl_F_tran.h"
// Implementation.
#include "cln/lfloat.h"
#include "float/transcendental/cl_LF_tran.h"
#include "float/lfloat/cl_LF.h"
#include "cln/integer.h"
#include "cln/exception.h"
#undef floor
#include <cmath>
#define floor cln_floor
namespace cln {
const cl_LF cl_exp_aux (const cl_I& p, uintE lq, uintC len)
{
{ Mutable(cl_I,p);
var uintE lp = integer_length(p); // now |p| < 2^lp.
if (!(lp <= lq)) throw runtime_exception();
lp = lq - lp; // now |p/2^lq| < 2^-lp.
// Minimize lq (saves computation time).
{
var uintC lp2 = ord2(p);
if (lp2 > 0) {
p = p >> lp2;
lq = lq - lp2;
}
}
// Evaluate a sum(0 <= n < N, a(n)/b(n) * (p(0)...p(n))/(q(0)...q(n)))
// with appropriate N, and
// a(n) = 1, b(n) = 1, p(n) = p for n>0, q(n) = n*2^lq for n>0.
var uintC actuallen = len+1; // 1 guard digit
// How many terms do we need for M bits of precision? N terms suffice,
// provided that
// 1/(2^(N*lp)*N!) < 2^-M
// <== N*(log(N)-1)+N*lp*log(2) > M*log(2)
// First approximation:
// N0 = M will suffice, so put N<=N0.
// Second approximation:
// N1 = floor(M*log(2)/(log(N0)-1+lp*log(2))), slightly too small,
// so put N>=N1.
// Third approximation:
// N2 = ceiling(M*log(2)/(log(N1)-1+lp*log(2))), slightly too large.
// N = N2+2, two more terms for safety.
var uintC N0 = intDsize*actuallen;
var uintC N1 = (uintC)(0.693147*intDsize*actuallen/(::log((double)N0)-1.0+0.693148*lp));
var uintC N2 = (uintC)(0.693148*intDsize*actuallen/(::log((double)N1)-1.0+0.693147*lp))+1;
var uintC N = N2+2;
struct rational_series_stream : cl_pq_series_stream {
var uintC n;
var cl_I p;
var uintE lq;
static cl_pq_series_term computenext (cl_pq_series_stream& thisss)
{
var rational_series_stream& thiss = (rational_series_stream&)thisss;
var uintC n = thiss.n;
var cl_pq_series_term result;
if (n==0) {
result.p = 1;
result.q = 1;
} else {
result.p = thiss.p;
result.q = (cl_I)n << thiss.lq;
}
thiss.n = n+1;
return result;
}
rational_series_stream(const cl_I& p_, uintE lq_)
: cl_pq_series_stream (rational_series_stream::computenext),
n (0), p(p_), lq(lq_) {}
} series(p, lq);
var cl_LF fsum = eval_rational_series<true>(N,series,actuallen);
return shorten(fsum,len); // verkürzen und fertig
}}
// Bit complexity (N = len, and if p has length O(log N) and ql = O(log N)):
// O(log(N)*M(N)).
} // namespace cln
| gpl-2.0 |
brKamil/joomla-zamarte | administrator/components/com_joomlaupdate/helpers/select.php | 1093 | <?php
/**
* @package Joomla.Administrator
* @subpackage com_joomlaupdate
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access.
defined('_JEXEC') or die;
/**
* Joomla! update selection list helper.
*
* @package Joomla.Administrator
* @subpackage com_joomlaupdate
* @since 2.5.4
*/
class JoomlaupdateHelperSelect
{
/**
* Returns an HTML select element with the different extraction modes
*
* @param string $default The default value of the select element
*
* @return string
*
* @since 2.5.4
*/
public static function getMethods($default = 'direct')
{
$options = array();
$options[] = JHtml::_('select.option', 'direct', JText::_('COM_JOOMLAUPDATE_VIEW_DEFAULT_METHOD_DIRECT'));
$options[] = JHtml::_('select.option', 'ftp', JText::_('COM_JOOMLAUPDATE_VIEW_DEFAULT_METHOD_FTP'));
return JHtml::_('select.genericlist', $options, 'method', '', 'value', 'text', $default, 'extraction_method');
}
}
| gpl-2.0 |
SomeRandomPerson9/3DT | src/com/harry9137/api/render/math/Quaternion.java | 1938 | package com.harry9137.api.render.math;
public class Quaternion {
private float x;
private float y;
private float z;
private float w;
public Quaternion(float x, float y, float z, float w){
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
public float length(){
return (float)Math.sqrt(x * x + y * y + z * z + w * w);
}
public Quaternion normalize()
{
float length = length();
return new Quaternion(x / length, y / length, z / length, w / length);
}
public Quaternion conjugate()
{
return new Quaternion(-x, -y, -z, w);
}
public Quaternion mul(Quaternion r)
{
float w_ = w * r.getW() - x * r.getX() - y * r.getY() - z * r.getZ();
float x_ = x * r.getW() + w * r.getX() + y * r.getZ() - z * r.getY();
float y_ = y * r.getW() + w * r.getY() + z * r.getX() - x * r.getZ();
float z_ = z * r.getW() + w * r.getZ() + x * r.getY() - y * r.getX();
return new Quaternion(x_, y_, z_, w_);
}
public Quaternion mul(Vector3f r){
float w_ = -x * r.GetX() - y * r.GetY() - z * r.GetZ();
float x_ = w * r.GetX() + y * r.GetZ() - z * r.GetY();
float y_ = w * r.GetY() + z * r.GetX() - x * r.GetZ();
float z_ = w * r.GetZ() + x * r.GetY() - y * r.GetX();
if(w_ > Integer.MAX_VALUE){
System.out.println("ERROR");
}
return new Quaternion(x_, y_, z_, w_);
}
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public float getY() {
return y;
}
public void setY(float y) {
this.y = y;
}
public float getZ() {
return z;
}
public void setZ(float z) {
this.z = z;
}
public float getW() {
return w;
}
public void setW(float w) {
this.w = w;
}
}
| gpl-2.0 |
JHeimdal/HalIR | SpecSac/spectra.hpp | 1786 | #pragma once
#include <iostream>
#include <sstream>
#include <boost/filesystem.hpp>
#include <cstdlib>
class Spectra
{
private:
bool m_init_ok;
typedef float xydata[2];
boost::filesystem::path fpath;
std::stringstream m_sstrm;
protected:
xydata *data;
float *xdata;
float *ydata;
unsigned npts;
void SetSize(int dim) {
if (dim > 0) {
data = new xydata[dim];
xdata = new float[dim];
ydata = new float[dim];
npts=dim;
}
else
dim=0;
npts=dim;
}
void SetYData(float *data) {
memcpy(ydata,data,sizeof(float)*npts);
}
enum specForm { NS, SPCF, JCAMP };
struct cfile_msg {
bool isOk;
std::stringstream msg;
specForm format;
} m_msg;
void check_file(std::string &filepath,cfile_msg &ans,bool guess=true, bool newfil=false, specForm frm=NS);
float ymax,ymin,xmax,xmin;
std::string filename;
std::string filepath;
std::string name;
Spectra(std::string &infile, bool newfil=false);
public:
Spectra() { data=NULL;xdata=NULL;ydata=NULL; }
Spectra(int dim,const xydata* indata);
Spectra(const Spectra& spec) { };
Spectra& operator=(const Spectra& spec) {
SetSize(spec.npts);
for (int i=0;i<spec.npts;i++) {
xdata[i]=spec.xdata[i];
ydata[i]=spec.ydata[i];
}
return *this;
}
inline Spectra& operator/=(const Spectra& spec) {
// TODO: m�ste se range
for (int i=0;i<spec.npts;i++) {
data[i][1]=data[i][1]/spec.data[i][1];
}
return *this;
}
virtual ~Spectra() {
if (data==NULL) {
delete [] data;
delete [] xdata;
delete [] ydata;
}
}
bool isOK() { return m_init_ok; }
virtual void write() {}
virtual std::string GetName() {
return name;
}
};
| gpl-2.0 |
picardie-nature/clicnat-qgis | test/test_resources.py | 1039 | # coding=utf-8
"""Resources test.
.. note:: 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.
"""
__author__ = 'jean-baptiste.desbas@picardie-nature.org'
__date__ = '2020-05-20'
__copyright__ = 'Copyright 2020, JB Desbas'
import unittest
from qgis.PyQt.QtGui import QIcon
class ClicnatDialogTest(unittest.TestCase):
"""Test rerources work."""
def setUp(self):
"""Runs before each test."""
pass
def tearDown(self):
"""Runs after each test."""
pass
def test_icon_png(self):
"""Test we can click OK."""
path = ':/plugins/Clicnat/icon.png'
icon = QIcon(path)
self.assertFalse(icon.isNull())
if __name__ == "__main__":
suite = unittest.makeSuite(ClicnatResourcesTest)
runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite)
| gpl-2.0 |
cassiodeveloper/blog.cassiobp.com.br | wp-content/plugins/arscode-social-slider/fblb_options_page.php | 45340 | <?php
$GP_Languages['ar'] = 'Arabic - العربية';
$GP_Languages['bg'] = 'Bulgarian - български';
$GP_Languages['ca'] = 'Catalan - català';
$GP_Languages['zh-CN'] = 'Chinese (Simplified)';
$GP_Languages['zh-TW'] = 'Chinese (Traditional)';
$GP_Languages['hr'] = 'Croatian - hrvatski';
$GP_Languages['cs'] = 'Czech - čeština';
$GP_Languages['da'] = 'Danish - dansk';
$GP_Languages['nl'] = 'Dutch - Nederlands';
$GP_Languages['en-US'] = 'English (US) - English (US)';
$GP_Languages['en-GB'] = 'English (UK) - English (UK)';
$GP_Languages['et'] = 'Estonian - eesti';
$GP_Languages['fil'] = 'Filipino - Filipino';
$GP_Languages['fi'] = 'Finnish - suomi';
$GP_Languages['fr'] = 'French - français';
$GP_Languages['de'] = 'German - Deutsch';
$GP_Languages['el'] = 'Greek - Ελληνικά';
$GP_Languages['iw'] = 'Hebrew - עברית';
$GP_Languages['hi'] = 'Hindi';
$GP_Languages['hu'] = 'Hungarian - magyar';
$GP_Languages['id'] = 'Indonesian - Bahasa Indonesia';
$GP_Languages['it'] = 'Italian - italiano';
$GP_Languages['ja'] = 'Japanese';
$GP_Languages['ko'] = 'Korean';
$GP_Languages['lv'] = 'Latvian - latviešu';
$GP_Languages['lt'] = 'Lithuanian - lietuvių';
$GP_Languages['ms'] = 'Malay - Bahasa Melayu';
$GP_Languages['no'] = 'Norwegian - norsk';
$GP_Languages['fa'] = 'Persian - فارسی';
$GP_Languages['pl'] = 'Polish - polski';
$GP_Languages['pt-BR'] = 'Portuguese (Brazil) - português (Brasil)';
$GP_Languages['pt-PT'] = 'Portuguese (Portugal) - Português (Portugal)';
$GP_Languages['ro'] = 'Romanian - română';
$GP_Languages['ru'] = 'Russian - русский';
$GP_Languages['sr'] = 'Serbian - српски';
$GP_Languages['sv'] = 'Swedish - svenska';
$GP_Languages['sk'] = 'Slovak - slovenský';
$GP_Languages['sl'] = 'Slovenian - slovenščina';
$GP_Languages['es'] = 'Spanish - español';
$GP_Languages['es-419'] = 'Spanish (Latin America) - español (Latinoamérica y el Caribe)';
$GP_Languages['th'] = 'Thai';
$GP_Languages['tr'] = 'Turkish - Türkçe';
$GP_Languages['uk'] = 'Ukrainian - українська';
$GP_Languages['vi'] = 'Vietnamese - Tiếng Việt';
$Locale['af_ZA'] = 'Afrikaans';
$Locale['ar_AR'] = 'Arabic';
$Locale['az_AZ'] = 'Azeri';
$Locale['be_BY'] = 'Belarusian';
$Locale['bg_BG'] = 'Bulgarian';
$Locale['bn_IN'] = 'Bengali';
$Locale['bs_BA'] = 'Bosnian';
$Locale['ca_ES'] = 'Catalan';
$Locale['cs_CZ'] = 'Czech';
$Locale['cy_GB'] = 'Welsh';
$Locale['da_DK'] = 'Danish';
$Locale['de_DE'] = 'German';
$Locale['el_GR'] = 'Greek';
$Locale['en_GB'] = 'English (UK)';
$Locale['en_PI'] = 'English (Pirate)';
$Locale['en_UD'] = 'English (Upside Down)';
$Locale['en_US'] = 'English (US)';
$Locale['eo_EO'] = 'Esperanto';
$Locale['es_ES'] = 'Spanish (Spain)';
$Locale['es_LA'] = 'Spanish';
$Locale['et_EE'] = 'Estonian';
$Locale['eu_ES'] = 'Basque';
$Locale['fa_IR'] = 'Persian';
$Locale['fb_LT'] = 'Leet Speak';
$Locale['fi_FI'] = 'Finnish';
$Locale['fo_FO'] = 'Faroese';
$Locale['fr_CA'] = 'French (Canada)';
$Locale['fr_FR'] = 'French (France)';
$Locale['fy_NL'] = 'Frisian';
$Locale['ga_IE'] = 'Irish';
$Locale['gl_ES'] = 'Galician';
$Locale['he_IL'] = 'Hebrew';
$Locale['hi_IN'] = 'Hindi';
$Locale['hr_HR'] = 'Croatian';
$Locale['hu_HU'] = 'Hungarian';
$Locale['hy_AM'] = 'Armenian';
$Locale['id_ID'] = 'Indonesian';
$Locale['is_IS'] = 'Icelandic';
$Locale['it_IT'] = 'Italian';
$Locale['ja_JP'] = 'Japanese';
$Locale['ka_GE'] = 'Georgian';
$Locale['ko_KR'] = 'Korean';
$Locale['ku_TR'] = 'Kurdish';
$Locale['la_VA'] = 'Latin';
$Locale['lt_LT'] = 'Lithuanian';
$Locale['lv_LV'] = 'Latvian';
$Locale['mk_MK'] = 'Macedonian';
$Locale['ml_IN'] = 'Malayalam';
$Locale['ms_MY'] = 'Malay';
$Locale['nb_NO'] = 'Norwegian (bokmal)';
$Locale['ne_NP'] = 'Nepali';
$Locale['nl_NL'] = 'Dutch';
$Locale['nn_NO'] = 'Norwegian (nynorsk)';
$Locale['pa_IN'] = 'Punjabi';
$Locale['pl_PL'] = 'Polish';
$Locale['ps_AF'] = 'Pashto';
$Locale['pt_BR'] = 'Portuguese (Brazil)';
$Locale['pt_PT'] = 'Portuguese (Portugal)';
$Locale['ro_RO'] = 'Romanian';
$Locale['ru_RU'] = 'Russian';
$Locale['sk_SK'] = 'Slovak';
$Locale['sl_SI'] = 'Slovenian';
$Locale['sq_AL'] = 'Albanian';
$Locale['sr_RS'] = 'Serbian';
$Locale['sv_SE'] = 'Swedish';
$Locale['sw_KE'] = 'Swahili';
$Locale['ta_IN'] = 'Tamil';
$Locale['te_IN'] = 'Telugu';
$Locale['th_TH'] = 'Thai';
$Locale['tl_PH'] = 'Filipino';
$Locale['tr_TR'] = 'Turkish';
$Locale['uk_UA'] = 'Ukrainian';
$Locale['vi_VN'] = 'Vietnamese';
$Locale['zh_CN'] = 'Simplified Chinese (China)';
$Locale['zh_HK'] = 'Traditional Chinese (Hong Kong)';
$Locale['zh_TW'] = 'Traditional Chinese (Taiwan)';
if ($_POST)
{
// Facebook
if (isset($_POST['Enable']))
{
$options['Enable'] = $_POST['Enable'];
}
if (isset($_POST['FacebookPageURL']))
{
$options['FacebookPageURL'] = $_POST['FacebookPageURL'];
}
if (isset($_POST['Width']) && intval($_POST['Width']))
{
$options['Width'] = $_POST['Width'];
}
if (isset($_POST['Height']) && intval($_POST['Height']))
{
$options['Height'] = $_POST['Height'];
}
if (isset($_POST['ShowFaces']))
{
$options['ShowFaces'] = $_POST['ShowFaces'];
}
if (isset($_POST['ShowStream']))
{
$options['ShowStream'] = $_POST['ShowStream'];
}
if (isset($_POST['ShowHeader']))
{
$options['ShowHeader'] = $_POST['ShowHeader'];
}
if (isset($_POST['Position']))
{
$options['Position'] = $_POST['Position'];
}
if (isset($_POST['TabPosition']))
{
$options['TabPosition'] = $_POST['TabPosition'];
}
if (isset($_POST['TabDesign']))
{
$options['TabDesign'] = $_POST['TabDesign'];
}
if (isset($_POST['Border']) && intval($_POST['Border']))
{
$options['Border'] = $_POST['Border'];
}
if (isset($_POST['BorderColor']))
{
$options['BorderColor'] = $_POST['BorderColor'];
}
if (isset($_POST['BackgroundColor']))
{
$options['BackgroundColor'] = $_POST['BackgroundColor'];
}
if (isset($_POST['Locale']))
{
$options['Locale'] = $_POST['Locale'];
}
if (isset($_POST['ColorScheme']))
{
$options['ColorScheme'] = $_POST['ColorScheme'];
}
if (isset($_POST['VPosition']))
{
$options['VPosition'] = $_POST['VPosition'];
}
if (isset($_POST['VPositionPx']) && intval($_POST['VPositionPx']))
{
$options['VPositionPx'] = $_POST['VPositionPx'];
}
if (isset($_POST['ZIndex']) && intval($_POST['ZIndex']))
{
$options['ZIndex'] = $_POST['ZIndex'];
}
// Twitter
if (isset($_POST['TW_Enable']))
{
$options['TW_Enable'] = $_POST['TW_Enable'];
}
if (isset($_POST['TW_Username']))
{
$options['TW_Username'] = $_POST['TW_Username'];
}
if (isset($_POST['TW_Width']) && intval($_POST['TW_Width']))
{
$options['TW_Width'] = $_POST['TW_Width'];
}
if (isset($_POST['TW_Height']) && intval($_POST['TW_Height']))
{
$options['TW_Height'] = $_POST['TW_Height'];
}
if (isset($_POST['TW_Position']))
{
$options['TW_Position'] = $_POST['TW_Position'];
}
if (isset($_POST['TW_TabPosition']))
{
$options['TW_TabPosition'] = $_POST['TW_TabPosition'];
}
if (isset($_POST['TW_TabDesign']))
{
$options['TW_TabDesign'] = $_POST['TW_TabDesign'];
}
if (isset($_POST['TW_Border']) && intval($_POST['TW_Border']))
{
$options['TW_Border'] = $_POST['TW_Border'];
}
if (isset($_POST['BorderColor']))
{
$options['TW_BorderColor'] = $_POST['TW_BorderColor'];
}
if (isset($_POST['TW_ShellBackground']))
{
$options['TW_ShellBackground'] = $_POST['TW_ShellBackground'];
}
if (isset($_POST['TW_ShellText']))
{
$options['TW_ShellText'] = $_POST['TW_ShellText'];
}
if (isset($_POST['TW_TweetBackground']))
{
$options['TW_TweetBackground'] = $_POST['TW_TweetBackground'];
}
if (isset($_POST['TW_TweetText']))
{
$options['TW_TweetText'] = $_POST['TW_TweetText'];
}
if (isset($_POST['TW_Links']))
{
$options['TW_Links'] = $_POST['TW_Links'];
}
if (isset($_POST['TW_VPosition']))
{
$options['TW_VPosition'] = $_POST['TW_VPosition'];
}
if (isset($_POST['TW_VPositionPx']) && intval($_POST['TW_VPositionPx']))
{
$options['TW_VPositionPx'] = $_POST['TW_VPositionPx'];
}
if (isset($_POST['TW_ZIndex']) && intval($_POST['TW_ZIndex']))
{
$options['TW_ZIndex'] = $_POST['TW_ZIndex'];
}
if (isset($_POST['TW_live']))
{
$options['TW_live'] = $_POST['TW_live'];
}
if (isset($_POST['TW_behavior']))
{
$options['TW_behavior'] = $_POST['TW_behavior'];
}
if (isset($_POST['TW_loop']))
{
$options['TW_loop'] = $_POST['TW_loop'];
}
if (isset($_POST['TW_interval']) && intval($_POST['TW_interval']))
{
$options['TW_interval'] = $_POST['TW_interval'];
}
if (isset($_POST['TW_rpp']) && intval($_POST['TW_rpp']))
{
$options['TW_rpp'] = $_POST['TW_rpp'];
}
// Google Plus
if (isset($_POST['GP_Enable']))
{
$options['GP_Enable'] = $_POST['GP_Enable'];
}
if (isset($_POST['GP_PageID']))
{
$options['GP_PageID'] = $_POST['GP_PageID'];
}
if (isset($_POST['GP_ShowFeed']))
{
$options['GP_ShowFeed'] = $_POST['GP_ShowFeed'];
}
if (isset($_POST['GP_Width']) && intval($_POST['GP_Width']))
{
$options['GP_Width'] = $_POST['GP_Width'];
}
if (isset($_POST['GP_Height']) && intval($_POST['GP_Height']))
{
$options['GP_Height'] = $_POST['GP_Height'];
}
if (isset($_POST['GP_Position']))
{
$options['GP_Position'] = $_POST['GP_Position'];
}
if (isset($_POST['GP_TabPosition']))
{
$options['GP_TabPosition'] = $_POST['GP_TabPosition'];
}
if (isset($_POST['GP_TabDesign']))
{
$options['GP_TabDesign'] = $_POST['GP_TabDesign'];
}
if (isset($_POST['GP_Border']) && intval($_POST['GP_Border']))
{
$options['GP_Border'] = $_POST['GP_Border'];
}
if (isset($_POST['BorderColor']))
{
$options['GP_BorderColor'] = $_POST['GP_BorderColor'];
}
if (isset($_POST['GP_BackgroundColor']))
{
$options['GP_BackgroundColor'] = $_POST['GP_BackgroundColor'];
}
if (isset($_POST['GP_VPosition']))
{
$options['GP_VPosition'] = $_POST['GP_VPosition'];
}
if (isset($_POST['GP_VPositionPx']) && intval($_POST['GP_VPositionPx']))
{
$options['GP_VPositionPx'] = $_POST['GP_VPositionPx'];
}
if (isset($_POST['GP_ZIndex']) && intval($_POST['GP_ZIndex']))
{
$options['GP_ZIndex'] = $_POST['GP_ZIndex'];
}
if (isset($_POST['GP_Language']))
{
$options['GP_Language'] = $_POST['GP_Language'];
}
if ($_POST['submit'])
{
update_option('FBLB_Options', $options);
echo '
<div id="setting-error-settings_updated" class="updated settings-error">
<p><strong>Settings Saved</strong></p>
</div>';
}
}
if ($_POST['preview'])
{
global $fblb_preview_options;
$fblb_preview_options = $options;
add_action('admin_footer', 'fblb_slider');
}
else
{
$options = fblb_get_options();
}
// Facebook
if (!$options['Position'])
{
$options['Position'] = 'Left';
}
if (!$options['TabPosition'])
{
$options['TabPosition'] = 'Top';
}
if (!$options['TabDesign'])
{
$options['TabDesign'] = 7;
}
if (!$options['Width'])
{
$options['Width'] = 300;
}
if (!$options['Height'])
{
$options['Height'] = 450;
}
if (!$options['Border'])
{
$options['Border'] = 5;
}
if (!$options['BorderColor'])
{
$options['BorderColor'] = '#3b5998';
}
if (!$options['BackgroundColor'])
{
$options['BackgroundColor'] = '#ffffff';
}
if (!$options['Locale'])
{
$options['Locale'] = 'en_US';
}
if (!$options['ColorScheme'])
{
$options['ColorScheme'] = 'light';
}
if (!$options['VPosition'])
{
$options['VPosition'] = 'Middle';
}
if (!$options['ZIndex'])
{
$options['ZIndex'] = 1000;
}
// Twitter
if (!$options['TW_Position'])
{
$options['TW_Position'] = 'Left';
}
if (!$options['TW_TabPosition'])
{
$options['TW_TabPosition'] = 'Middle';
}
if (!$options['TW_TabDesign'])
{
$options['TW_TabDesign'] = 7;
}
if (!$options['TW_Width'])
{
$options['TW_Width'] = 300;
}
if (!$options['TW_Height'])
{
$options['TW_Height'] = 450;
}
if (!$options['TW_Border'])
{
$options['TW_Border'] = 5;
}
if (!$options['TW_BorderColor'])
{
$options['TW_BorderColor'] = '#33ccff';
}
if (!$options['TW_ShellBackground'])
{
$options['TW_ShellBackground'] = '#33ccff';
}
if (!$options['TW_ShellText'])
{
$options['TW_ShellText'] = '#ffffff';
}
if (!$options['TW_TweetBackground'])
{
$options['TW_TweetBackground'] = '#ffffff';
}
if (!$options['TW_TweetText'])
{
$options['TW_TweetText'] = '#000000';
}
if (!$options['TW_Links'])
{
$options['TW_Links'] = '#47a61e';
}
if (!$options['TW_VPosition'])
{
$options['TW_VPosition'] = 'Middle';
}
if (!$options['TW_ZIndex'])
{
$options['TW_ZIndex'] = 1000;
}
if (!$options['TW_behavior'])
{
$options['TW_behavior'] = 'all';
}
if (!$options['TW_interval'])
{
$options['TW_interval'] = 30;
}
if (!$options['TW_rpp'])
{
$options['TW_rpp'] = 4;
}
// Google Plus
if (!$options['GP_Position'])
{
$options['GP_Position'] = 'Left';
}
if (!$options['GP_TabPosition'])
{
$options['GP_TabPosition'] = 'Bottom';
}
if (!$options['GP_TabDesign'])
{
$options['GP_TabDesign'] = 7;
}
if (!$options['GP_Width'])
{
$options['GP_Width'] = 300;
}
if (!$options['GP_Height'])
{
$options['GP_Height'] = 450;
}
if (!$options['GP_Border'])
{
$options['GP_Border'] = 5;
}
if (!$options['GP_BorderColor'])
{
$options['GP_BorderColor'] = '#000000';
}
if (!$options['GP_BackgroundColor'])
{
$options['GP_BackgroundColor'] = '#000000';
}
if (!$options['GP_VPosition'])
{
$options['GP_VPosition'] = 'Middle';
}
if (!$options['GP_ZIndex'])
{
$options['GP_ZIndex'] = 1000;
}
if (!$options['GP_Language'])
{
$options['GP_Language'] = 'en-US';
}
?>
<div class="wrap">
<div id="icon-options-general" class="icon32"><br></div>
<h2>Social Slider</h2>
<form method="post" action="<?php echo $_SERVER["REQUEST_URI"]; ?>">
<h3>Facebook Likebox</h3>
<table class="form-table">
<tbody>
<tr valign="top">
<th scope="row">Enable</th>
<td>
<fieldset>
<legend class="screen-reader-text"><span>Enable</span></legend>
<label for="Enable">
<input name="Enable" <?= ($options['Enable'] ? 'checked' : '' ) ?> type="checkbox" id="Enable" value="1" />
</label>
</fieldset>
</td>
</tr>
<tr valign="top">
<th scope="row"><label for="FacebookPageURL">Facebook Page URL</label></th>
<td><input name="FacebookPageURL" type="text" id="FacebookPageURL" value="<?= $options['FacebookPageURL'] ?>" class="regular-text" /></td>
</tr>
<tr valign="top">
<th scope="row"><label for="Width">Width</label></th>
<td><input name="Width" type="text" id="Width" value="<?= $options['Width'] ?>" class="small-text" /> px</td>
</tr>
<tr valign="top">
<th scope="row"><label for="Height">Height</label></th>
<td><input name="Height" type="text" id="Height" value="<?= $options['Height'] ?>" class="small-text" /> px</td>
</tr>
<tr valign="top">
<th scope="row">Show faces</th>
<td>
<fieldset>
<legend class="screen-reader-text"><span>Show faces</span></legend>
<label for="ShowFaces">
<input name="ShowFaces" <?= ($options['ShowFaces'] ? 'checked' : '' ) ?> type="checkbox" id="ShowFaces" value="1" />
</label>
</fieldset>
</td>
</tr>
<tr valign="top">
<th scope="row">Show stream</th>
<td>
<fieldset>
<legend class="screen-reader-text"><span>Show stream</span></legend>
<label for="ShowStream">
<input name="ShowStream" <?= ($options['ShowStream'] ? 'checked' : '' ) ?> type="checkbox" id="ShowStream" value="1" />
</label>
</fieldset>
</td>
</tr>
<tr valign="top">
<th scope="row">Show header</th>
<td>
<fieldset>
<legend class="screen-reader-text"><span>Show header</span></legend>
<label for="ShowHeader">
<input name="ShowHeader" <?= ($options['ShowHeader'] ? 'checked' : '' ) ?> type="checkbox" id="ShowHeader" value="1" />
</label>
</fieldset>
</td>
</tr>
<tr valign="top">
<th scope="row">Position</th>
<td>
<fieldset>
<label for="PositionLeft">
<input name="Position" <?= ($options['Position'] == 'Left' ? 'checked' : '' ) ?> type="radio" id="PositionLeft" value="Left" />
left
</label>
<label for="PositionRight">
<input name="Position" <?= ($options['Position'] == 'Right' ? 'checked' : '' ) ?> type="radio" id="PositionRight" value="Right" />
right
</label>
</fieldset>
</td>
</tr>
<tr valign="top">
<th scope="row">Vertical position</th>
<td>
<fieldset>
<label for="VPositionMiddle">
<input name="VPosition" <?= ($options['VPosition'] == 'Middle' ? 'checked' : '' ) ?> type="radio" id="VPositionMiddle" value="Middle" />
middle
</label>
<label for="VPositionFixed">
<input name="VPosition" <?= ($options['VPosition'] == 'Fixed' ? 'checked' : '' ) ?> type="radio" id="VPositionFixed" value="Fixed" />
fixed:
</label>
<input name="VPositionPx" type="text" id="VPositionPx" value="<?= $options['VPositionPx'] ?>" class="small-text" /> px from top
</fieldset>
</td>
</tr>
<tr valign="top">
<th scope="row">Button position</th>
<td>
<fieldset>
<label for="TabPositionTop">
<input name="TabPosition" <?= ($options['TabPosition'] == 'Top' ? 'checked' : '' ) ?> type="radio" id="TabPositionTop" value="Top" />
top
</label>
<label for="TabPositionMiddle">
<input name="TabPosition" <?= ($options['TabPosition'] == 'Middle' ? 'checked' : '' ) ?> type="radio" id="TabPositionMiddle" value="Middle" />
middle
</label>
<label for="TabPositionBottom">
<input name="TabPosition" <?= ($options['TabPosition'] == 'Bottom' ? 'checked' : '' ) ?> type="radio" id="TabPositionBottom" value="Bottom" />
bottom
</label>
</fieldset>
</td>
</tr>
<tr valign="top">
<th scope="row">Button design</th>
<td>
<fieldset>
<label for="TabDesign1">
<input name="TabDesign" <?= ($options['TabDesign'] == 1 ? 'checked' : '' ) ?> type="radio" id="TabDesign1" value="1" />
<img src="<? echo plugins_url('/img/fb1-left.png', __FILE__) ?>" />
</label>
<label for="TabDesign2">
<input name="TabDesign" <?= ($options['TabDesign'] == 2 ? 'checked' : '' ) ?> type="radio" id="TabDesign2" value="2" />
<img src="<? echo plugins_url('/img/fb2-left.png', __FILE__) ?>" />
</label>
<label for="TabDesign3">
<input name="TabDesign" <?= ($options['TabDesign'] == 3 ? 'checked' : '' ) ?> type="radio" id="TabDesign3" value="3" />
<img src="<? echo plugins_url('/img/fb3-left.png', __FILE__) ?>" />
</label>
<label for="TabDesign4">
<input name="TabDesign" <?= ($options['TabDesign'] == 4 ? 'checked' : '' ) ?> type="radio" id="TabDesign4" value="4" />
<img src="<? echo plugins_url('/img/fb4-left.png', __FILE__) ?>" />
</label>
<label for="TabDesign5">
<input name="TabDesign" <?= ($options['TabDesign'] == 5 ? 'checked' : '' ) ?> type="radio" id="TabDesign5" value="5" />
<img src="<? echo plugins_url('/img/fb5-left.png', __FILE__) ?>" />
</label>
<label for="TabDesign6">
<input name="TabDesign" <?= ($options['TabDesign'] == 6 ? 'checked' : '' ) ?> type="radio" id="TabDesign6" value="6" />
<img src="<? echo plugins_url('/img/fb6-left.png', __FILE__) ?>" />
</label>
<label for="TabDesign7">
<input name="TabDesign" <?= ($options['TabDesign'] == 7 ? 'checked' : '' ) ?> type="radio" id="TabDesign7" value="7" />
<img src="<? echo plugins_url('/img/fb7-left.png', __FILE__) ?>" />
</label>
<label for="TabDesign8">
<input name="TabDesign" <?= ($options['TabDesign'] == 8 ? 'checked' : '' ) ?> type="radio" id="TabDesign8" value="8" />
<img src="<? echo plugins_url('/img/fb8-left.png', __FILE__) ?>" />
</label>
<label for="TabDesign9">
<input name="TabDesign" <?= ($options['TabDesign'] == 9 ? 'checked' : '' ) ?> type="radio" id="TabDesign9" value="9" />
<img src="<? echo plugins_url('/img/fb9-left.png', __FILE__) ?>" />
</label>
</fieldset>
</td>
</tr>
<tr valign="top">
<th scope="row"><label for="Border">Border width</label></th>
<td><input name="Border" type="text" id="Border" value="<?= $options['Border'] ?>" class="small-text" /> px</td>
</tr>
<tr valign="top">
<th scope="row"><label for="BorderColor">Border color</label></th>
<td>
<input maxlength="7" name="BorderColor" type="text" id="BorderColor" value="<?= $options['BorderColor'] ?>" style="float: left; width: 70px;" class="small-text" /> (default: #3b5998)
<div id="BorderColorPreview" style="background-color: <?= $options['BorderColor'] ?>;float: left; margin-top: 3px; margin-left: 5px; margin-right: 5px; width: 17px; height: 17px;"></div>
</td>
</tr>
<tr valign="top">
<th scope="row"><label for="BackgroundColor">Background color</label></th>
<td>
<input maxlength="7" name="BackgroundColor" type="text" id="BackgroundColor" value="<?= $options['BackgroundColor'] ?>" style="float: left; width: 70px;" class="small-text" /> (default: #ffffff for light color scheme, #333333 for dark color scheme)
<div id="BackgroundColorPreview" style="background-color: <?= $options['BackgroundColor'] ?>;float: left; margin-top: 3px; margin-left: 5px; margin-right: 5px; width: 17px; height: 17px;"></div>
</td>
</tr>
<tr valign="top">
<th scope="row">Color Scheme</th>
<td>
<fieldset>
<label for="ColorSchemelight">
<input name="ColorScheme" <?= ($options['ColorScheme'] == 'light' ? 'checked' : '' ) ?> type="radio" id="ColorSchemelight" value="light" />
light
</label>
<label for="ColorSchemedark">
<input name="ColorScheme" <?= ($options['ColorScheme'] == 'dark' ? 'checked' : '' ) ?> type="radio" id="ColorSchemedark" value="dark" />
dark
</label>
</fieldset>
</td>
</tr>
<tr valign="top">
<th scope="row"><label for="ZIndex">CSS z-index</label></th>
<td><input name="ZIndex" type="text" id="ZIndex" value="<?= $options['ZIndex'] ?>" class="small-text" /> (default: 1000)</td>
</tr>
<tr valign="top">
<th scope="row"><label for="Locale">Locale</label></th>
<td>
<select name="Locale" id="Locale">
<?
foreach ($Locale as $k => $v)
{
echo '<option ' . ($options['Locale'] == $k ? 'selected' : '') . ' value="' . $k . '">' . $v . '</option>';
}
?>
</select>
</td>
</tr>
</tbody>
</table>
<h3>Twitter</h3>
<table class="form-table">
<tbody>
<tr valign="top">
<th scope="row">Enable</th>
<td>
<fieldset>
<legend class="screen-reader-text"><span>Enable</span></legend>
<label for="TW_Enable">
<input name="TW_Enable" <?= ($options['TW_Enable'] ? 'checked' : '' ) ?> type="checkbox" id="TW_Enable" value="1" />
</label>
</fieldset>
</td>
</tr>
<tr valign="top">
<th scope="row"><label for="TW_Username">Username</label></th>
<td><input name="TW_Username" type="text" id="TW_Username" value="<?= $options['TW_Username'] ?>" class="regular-text" /></td>
</tr>
<tr valign="top">
<th scope="row"><label for="TW_Width">Width</label></th>
<td><input name="TW_Width" type="text" id="TW_Width" value="<?= $options['TW_Width'] ?>" class="small-text" /> px</td>
</tr>
<tr valign="top">
<th scope="row"><label for="TW_Height">Height</label></th>
<td><input name="TW_Height" type="text" id="TW_Height" value="<?= $options['TW_Height'] ?>" class="small-text" /> px</td>
</tr>
<tr valign="top">
<th scope="row">Poll for new results</th>
<td>
<fieldset>
<legend class="screen-reader-text"><span>Poll for new results</span></legend>
<label for="TW_live">
<input name="TW_live" <?= ($options['TW_live'] ? 'checked' : '' ) ?> type="checkbox" id="TW_live" value="1" />
</label>
</fieldset>
</td>
</tr>
<? /*
<tr valign="top">
<th scope="row">Include scrollbar</th>
<td>
<fieldset>
<legend class="screen-reader-text"><span>Include scrollbar</span></legend>
<label for="TW_scrollbar">
<input name="TW_scrollbar" <?= ($options['TW_scrollbar'] ? 'checked' : '' ) ?> type="checkbox" id="TW_scrollbar" value="1" />
</label>
</fieldset>
</td>
</tr>
*/ ?>
<tr valign="top">
<th scope="row">Behavior</th>
<td>
<fieldset>
<label for="TW_behaviordefaultall">
<input name="TW_behavior" <?= ($options['TW_behavior'] == 'all' ? 'checked' : '' ) ?> type="radio" id="TW_behaviordefaultall" value="all" />
Load all tweets
</label>
<br />
<label for="TW_behaviordefault">
<input name="TW_behavior" <?= ($options['TW_behavior'] == 'default' ? 'checked' : '' ) ?> type="radio" id="TW_behaviordefault" value="default" />
Timed Interval:
</label>
<div style="margin-left: 80px;">
Tweet Interval <input name="TW_interval" type="text" id="TW_interval" value="<?= $options['TW_interval'] ?>" class="small-text" />
<br />
Loop results <input name="TW_loop" <?= ($options['TW_loop'] ? 'checked' : '' ) ?> type="checkbox" id="TW_loop" value="1" />
</div>
</fieldset>
</td>
</tr>
<tr valign="top">
<th scope="row"><label for="TW_rpp">Number of Tweets</label></th>
<td><input name="TW_rpp" type="text" id="TW_rpp" value="<?= $options['TW_rpp'] ?>" class="small-text" /></td>
</tr>
<tr valign="top">
<th scope="row">Position</th>
<td>
<fieldset>
<label for="TW_PositionLeft">
<input name="TW_Position" <?= ($options['TW_Position'] == 'Left' ? 'checked' : '' ) ?> type="radio" id="TW_PositionLeft" value="Left" />
left
</label>
<label for="TW_PositionRight">
<input name="TW_Position" <?= ($options['TW_Position'] == 'Right' ? 'checked' : '' ) ?> type="radio" id="TW_PositionRight" value="Right" />
right
</label>
</fieldset>
</td>
</tr>
<tr valign="top">
<th scope="row">Vertical position</th>
<td>
<fieldset>
<label for="TW_VPositionMiddle">
<input name="TW_VPosition" <?= ($options['TW_VPosition'] == 'Middle' ? 'checked' : '' ) ?> type="radio" id="TW_VPositionMiddle" value="Middle" />
middle
</label>
<label for="TW_VPositionFixed">
<input name="TW_VPosition" <?= ($options['TW_VPosition'] == 'Fixed' ? 'checked' : '' ) ?> type="radio" id="TW_VPositionFixed" value="Fixed" />
fixed:
</label>
<input name="TW_VPositionPx" type="text" id="TW_VPositionPx" value="<?= $options['TW_VPositionPx'] ?>" class="small-text" /> px from top
</fieldset>
</td>
</tr>
<tr valign="top">
<th scope="row">Button position</th>
<td>
<fieldset>
<label for="TW_TabPositionTop">
<input name="TW_TabPosition" <?= ($options['TW_TabPosition'] == 'Top' ? 'checked' : '' ) ?> type="radio" id="TW_TabPositionTop" value="Top" />
top
</label>
<label for="TW_TabPositionMiddle">
<input name="TW_TabPosition" <?= ($options['TW_TabPosition'] == 'Middle' ? 'checked' : '' ) ?> type="radio" id="TW_TabPositionMiddle" value="Middle" />
middle
</label>
<label for="TW_TabPositionBottom">
<input name="TW_TabPosition" <?= ($options['TW_TabPosition'] == 'Bottom' ? 'checked' : '' ) ?> type="radio" id="TW_TabPositionBottom" value="Bottom" />
bottom
</label>
</fieldset>
</td>
</tr>
<tr valign="top">
<th scope="row">Button design</th>
<td>
<fieldset>
<label for="TW_TabDesign1">
<input name="TW_TabDesign" <?= ($options['TW_TabDesign'] == 1 ? 'checked' : '' ) ?> type="radio" id="TW_TabDesign1" value="1" />
<img src="<? echo plugins_url('/img/tw1-left.png', __FILE__) ?>" />
</label>
<label for="TW_TabDesign2">
<input name="TW_TabDesign" <?= ($options['TW_TabDesign'] == 2 ? 'checked' : '' ) ?> type="radio" id="TW_TabDesign2" value="2" />
<img src="<? echo plugins_url('/img/tw2-left.png', __FILE__) ?>" />
</label>
<label for="TW_TabDesign3">
<input name="TW_TabDesign" <?= ($options['TW_TabDesign'] == 3 ? 'checked' : '' ) ?> type="radio" id="TW_TabDesign3" value="3" />
<img src="<? echo plugins_url('/img/tw3-left.png', __FILE__) ?>" />
</label>
<label for="TW_TabDesign7">
<input name="TW_TabDesign" <?= ($options['TW_TabDesign'] == 7 ? 'checked' : '' ) ?> type="radio" id="TW_TabDesign7" value="7" />
<img src="<? echo plugins_url('/img/tw7-left.png', __FILE__) ?>" />
</label>
<label for="TW_TabDesign8">
<input name="TW_TabDesign" <?= ($options['TW_TabDesign'] == 8 ? 'checked' : '' ) ?> type="radio" id="TW_TabDesign8" value="8" />
<img src="<? echo plugins_url('/img/tw8-left.png', __FILE__) ?>" />
</label>
<label for="TW_TabDesign9">
<input name="TW_TabDesign" <?= ($options['TW_TabDesign'] == 9 ? 'checked' : '' ) ?> type="radio" id="TW_TabDesign9" value="9" />
<img src="<? echo plugins_url('/img/tw9-left.png', __FILE__) ?>" />
</label>
</fieldset>
</td>
</tr>
<tr valign="top">
<th scope="row"><label for="TW_Border">Border width</label></th>
<td><input name="TW_Border" type="text" id="TW_Border" value="<?= $options['TW_Border'] ?>" class="small-text" /> px</td>
</tr>
<tr valign="top">
<th scope="row"><label for="TW_BorderColor">Border color</label></th>
<td>
<input maxlength="7" name="TW_BorderColor" type="text" id="TW_BorderColor" value="<?= $options['TW_BorderColor'] ?>" style="float: left; width: 70px;" class="small-text" /> (default: #33ccff)
<div id="TW_BorderColorPreview" style="background-color: <?= $options['TW_BorderColor'] ?>;float: left; margin-top: 3px; margin-left: 5px; margin-right: 5px; width: 17px; height: 17px;"></div>
</td>
</tr>
<tr valign="top">
<th scope="row"><label for="TW_ShellBackground">Shell background</label></th>
<td>
<input maxlength="7" name="TW_ShellBackground" type="text" id="TW_ShellBackground" value="<?= $options['TW_ShellBackground'] ?>" style="float: left; width: 70px;" class="small-text" /> (default: #33ccff)
<div id="TW_ShellBackgroundPreview" style="background-color: <?= $options['TW_ShellBackground'] ?>;float: left; margin-top: 3px; margin-left: 5px; margin-right: 5px; width: 17px; height: 17px;"></div>
</td>
</tr>
<tr valign="top">
<th scope="row"><label for="TW_ShellText">Shell text</label></th>
<td>
<input maxlength="7" name="TW_ShellText" type="text" id="TW_ShellText" value="<?= $options['TW_ShellText'] ?>" style="float: left; width: 70px;" class="small-text" /> (default: #ffffff)
<div id="TW_ShellTextPreview" style="background-color: <?= $options['TW_ShellText'] ?>;float: left; margin-top: 3px; margin-left: 5px; margin-right: 5px; width: 17px; height: 17px;"></div>
</td>
</tr>
<tr valign="top">
<th scope="row"><label for="TW_TweetBackground">Tweet background</label></th>
<td>
<input maxlength="7" name="TW_TweetBackground" type="text" id="TW_TweetBackground" value="<?= $options['TW_TweetBackground'] ?>" style="float: left; width: 70px;" class="small-text" /> (default: #ffffff)
<div id="TW_TweetBackgroundPreview" style="background-color: <?= $options['TW_TweetBackground'] ?>;float: left; margin-top: 3px; margin-left: 5px; margin-right: 5px; width: 17px; height: 17px;"></div>
</td>
</tr>
<tr valign="top">
<th scope="row"><label for="TW_TweetText">Tweet text</label></th>
<td>
<input maxlength="7" name="TW_TweetText" type="text" id="TW_TweetText" value="<?= $options['TW_TweetText'] ?>" style="float: left; width: 70px;" class="small-text" /> (default: #000000)
<div id="TW_TweetTextPreview" style="background-color: <?= $options['TW_TweetText'] ?>;float: left; margin-top: 3px; margin-left: 5px; margin-right: 5px; width: 17px; height: 17px;"></div>
</td>
</tr>
<tr valign="top">
<th scope="row"><label for="TW_Links">Links</label></th>
<td>
<input maxlength="7" name="TW_Links" type="text" id="TW_Links" value="<?= $options['TW_Links'] ?>" style="float: left; width: 70px;" class="small-text" /> (default: #47a61e)
<div id="TW_LinksPreview" style="background-color: <?= $options['TW_Links'] ?>;float: left; margin-top: 3px; margin-left: 5px; margin-right: 5px; width: 17px; height: 17px;"></div>
</td>
</tr>
<tr valign="top">
<th scope="row"><label for="TW_ZIndex">CSS z-index</label></th>
<td><input name="TW_ZIndex" type="text" id="TW_ZIndex" value="<?= $options['TW_ZIndex'] ?>" class="small-text" /> (default: 1000)</td>
</tr>
</tbody>
</table>
<h3>Google Plus</h3>
<?
echo '
<div>
<p><strong>You now have a cronjob setup to run:</strong>
<a href="'.get_option('siteurl') . '/wp-content/plugins/arscode-social-slider/cron.php">'.get_option('siteurl') . '/wp-content/plugins/arscode-social-slider/cron.php</a>
</p>
</div>';
?>
<table class="form-table">
<tbody>
<tr valign="top">
<th scope="row">Enable</th>
<td>
<fieldset>
<legend class="screen-reader-text"><span>Enable</span></legend>
<label for="GP_Enable">
<input name="GP_Enable" <?= ($options['GP_Enable'] ? 'checked' : '' ) ?> type="checkbox" id="GP_Enable" value="1" />
</label>
</fieldset>
</td>
</tr>
<tr valign="top">
<th scope="row"><label for="GP_PageID">Google+ Page ID</label></th>
<td>
<input name="GP_PageID" type="text" id="GP_PageID" value="<?= $options['GP_PageID'] ?>" class="regular-text" />
<br />
(eg: 104629412415657030658; https://plus.google.com/<strong>104629412415657030658</strong>/posts)
</td>
</tr>
<tr valign="top">
<th scope="row"><label for="GP_Width">Width</label></th>
<td><input name="GP_Width" type="text" id="GP_Width" value="<?= $options['GP_Width'] ?>" class="small-text" /> px</td>
</tr>
<tr valign="top">
<th scope="row"><label for="GP_Height">Height</label></th>
<td><input name="GP_Height" type="text" id="GP_Height" value="<?= $options['GP_Height'] ?>" class="small-text" /> px</td>
</tr>
<tr valign="top">
<th scope="row">Show feed</th>
<td>
<fieldset>
<legend class="screen-reader-text"><span>Show feed</span></legend>
<label for="GP_ShowFeed">
<input name="GP_ShowFeed" <?= ($options['GP_ShowFeed'] ? 'checked' : '' ) ?> type="checkbox" id="GP_ShowFeed" value="1" />
</label>
</fieldset>
</td>
</tr>
<tr valign="top">
<th scope="row">Position</th>
<td>
<fieldset>
<label for="GP_PositionLeft">
<input name="GP_Position" <?= ($options['GP_Position'] == 'Left' ? 'checked' : '' ) ?> type="radio" id="GP_PositionLeft" value="Left" />
left
</label>
<label for="GP_PositionRight">
<input name="GP_Position" <?= ($options['GP_Position'] == 'Right' ? 'checked' : '' ) ?> type="radio" id="GP_PositionRight" value="Right" />
right
</label>
</fieldset>
</td>
</tr>
<tr valign="top">
<th scope="row">Vertical position</th>
<td>
<fieldset>
<label for="GP_VPositionMiddle">
<input name="GP_VPosition" <?= ($options['GP_VPosition'] == 'Middle' ? 'checked' : '' ) ?> type="radio" id="GP_VPositionMiddle" value="Middle" />
middle
</label>
<label for="GP_VPositionFixed">
<input name="GP_VPosition" <?= ($options['GP_VPosition'] == 'Fixed' ? 'checked' : '' ) ?> type="radio" id="GP_VPositionFixed" value="Fixed" />
fixed:
</label>
<input name="GP_VPositionPx" type="text" id="GP_VPositionPx" value="<?= $options['GP_VPositionPx'] ?>" class="small-text" /> px from top
</fieldset>
</td>
</tr>
<tr valign="top">
<th scope="row">Button position</th>
<td>
<fieldset>
<label for="GP_TabPositionTop">
<input name="GP_TabPosition" <?= ($options['GP_TabPosition'] == 'Top' ? 'checked' : '' ) ?> type="radio" id="GP_TabPositionTop" value="Top" />
top
</label>
<label for="GP_TabPositionMiddle">
<input name="GP_TabPosition" <?= ($options['GP_TabPosition'] == 'Middle' ? 'checked' : '' ) ?> type="radio" id="GP_TabPositionMiddle" value="Middle" />
middle
</label>
<label for="GP_TabPositionBottom">
<input name="GP_TabPosition" <?= ($options['GP_TabPosition'] == 'Bottom' ? 'checked' : '' ) ?> type="radio" id="GP_TabPositionBottom" value="Bottom" />
bottom
</label>
</fieldset>
</td>
</tr>
<tr valign="top">
<th scope="row">Button design</th>
<td>
<fieldset>
<label for="GP_TabDesign1">
<input name="GP_TabDesign" <?= ($options['GP_TabDesign'] == 1 ? 'checked' : '' ) ?> type="radio" id="GP_TabDesign1" value="1" />
<img src="<? echo plugins_url('/img/gp1-left.png', __FILE__) ?>" />
</label>
<label for="GP_TabDesign2">
<input name="GP_TabDesign" <?= ($options['GP_TabDesign'] == 2 ? 'checked' : '' ) ?> type="radio" id="GP_TabDesign2" value="2" />
<img src="<? echo plugins_url('/img/gp2-left.png', __FILE__) ?>" />
</label>
<label for="GP_TabDesign3">
<input name="GP_TabDesign" <?= ($options['GP_TabDesign'] == 3 ? 'checked' : '' ) ?> type="radio" id="GP_TabDesign3" value="3" />
<img src="<? echo plugins_url('/img/gp3-left.png', __FILE__) ?>" />
</label>
<label for="GP_TabDesign7">
<input name="GP_TabDesign" <?= ($options['GP_TabDesign'] == 7 ? 'checked' : '' ) ?> type="radio" id="GP_TabDesign7" value="7" />
<img src="<? echo plugins_url('/img/gp7-left.png', __FILE__) ?>" />
</label>
<label for="GP_TabDesign8">
<input name="GP_TabDesign" <?= ($options['GP_TabDesign'] == 8 ? 'checked' : '' ) ?> type="radio" id="GP_TabDesign8" value="8" />
<img src="<? echo plugins_url('/img/gp8-left.png', __FILE__) ?>" />
</label>
<label for="GP_TabDesign9">
<input name="GP_TabDesign" <?= ($options['GP_TabDesign'] == 9 ? 'checked' : '' ) ?> type="radio" id="GP_TabDesign9" value="9" />
<img src="<? echo plugins_url('/img/gp9-left.png', __FILE__) ?>" />
</label>
</fieldset>
</td>
</tr>
<tr valign="top">
<th scope="row"><label for="GP_Border">Border width</label></th>
<td><input name="GP_Border" type="text" id="GP_Border" value="<?= $options['GP_Border'] ?>" class="small-text" /> px</td>
</tr>
<tr valign="top">
<th scope="row"><label for="GP_BorderColor">Border color</label></th>
<td>
<input maxlength="7" name="GP_BorderColor" type="text" id="GP_BorderColor" value="<?= $options['GP_BorderColor'] ?>" style="float: left; width: 70px;" class="small-text" /> (default: #000000)
<div id="GP_BorderColorPreview" style="background-color: <?= $options['GP_BorderColor'] ?>;float: left; margin-top: 3px; margin-left: 5px; margin-right: 5px; width: 17px; height: 17px;"></div>
</td>
</tr>
<tr valign="top">
<th scope="row"><label for="GP_BackgroundColor">Background color</label></th>
<td>
<input maxlength="7" name="GP_BackgroundColor" type="text" id="GP_BackgroundColor" value="<?= $options['GP_BackgroundColor'] ?>" style="float: left; width: 70px;" class="small-text" /> (default: #000000)
<div id="GP_BackgroundColorPreview" style="background-color: <?= $options['GP_BackgroundColor'] ?>;float: left; margin-top: 3px; margin-left: 5px; margin-right: 5px; width: 17px; height: 17px;"></div>
</td>
</tr>
<tr valign="top">
<th scope="row"><label for="GP_ZIndex">CSS z-index</label></th>
<td><input name="GP_ZIndex" type="text" id="GP_ZIndex" value="<?= $options['GP_ZIndex'] ?>" class="small-text" /> (default: 1000)</td>
</tr>
<tr valign="top">
<th scope="row"><label for="GP_Language">Language</label></th>
<td>
<select name="GP_Language" id="GP_Language">
<?
foreach ($GP_Languages as $k => $v)
{
echo '<option ' . ($options['GP_Language'] == $k ? 'selected' : '') . ' value="' . $k . '">' . $v . '</option>';
}
?>
</select>
</td>
</tr>
</tbody>
</table>
<p class="submit">
<input type="submit" name="submit" id="submit" class="button-primary" value="Save settings" />
<input type="submit" name="preview" id="preview" value="Preview" />
</p>
</form>
</div>
<script type="text/javascript">
jQuery('#BorderColor').ColorPicker({
onSubmit: function(hsb, hex, rgb, el) {
jQuery(el).ColorPickerHide();
},
onBeforeShow: function () {
jQuery(this).ColorPickerSetColor(this.value);
},
onChange: function (hsb, hex, rgb) {
jQuery('#BorderColor').val('#' + hex);
jQuery('#BorderColorPreview').css('background-color', '#' + hex);
}
})
.bind('keyup', function(){
jQuery(this).ColorPickerSetColor(this.value);
});
jQuery('#BackgroundColor').ColorPicker({
onSubmit: function(hsb, hex, rgb, el) {
jQuery(el).ColorPickerHide();
},
onBeforeShow: function () {
jQuery(this).ColorPickerSetColor(this.value);
},
onChange: function (hsb, hex, rgb) {
jQuery('#BackgroundColor').val('#' + hex);
jQuery('#BackgroundColorPreview').css('background-color', '#' + hex);
}
})
.bind('keyup', function(){
jQuery(this).ColorPickerSetColor(this.value);
});
jQuery('#TW_BorderColor').ColorPicker({
onSubmit: function(hsb, hex, rgb, el) {
jQuery(el).ColorPickerHide();
},
onBeforeShow: function () {
jQuery(this).ColorPickerSetColor(this.value);
},
onChange: function (hsb, hex, rgb) {
jQuery('#TW_BorderColor').val('#' + hex);
jQuery('#TW_BorderColorPreview').css('background-color', '#' + hex);
}
})
.bind('keyup', function(){
jQuery(this).ColorPickerSetColor(this.value);
});
jQuery('#TW_ShellBackground').ColorPicker({
onSubmit: function(hsb, hex, rgb, el) {
jQuery(el).ColorPickerHide();
},
onBeforeShow: function () {
jQuery(this).ColorPickerSetColor(this.value);
},
onChange: function (hsb, hex, rgb) {
jQuery('#TW_ShellBackground').val('#' + hex);
jQuery('#TW_ShellBackgroundPreview').css('background-color', '#' + hex);
}
})
.bind('keyup', function(){
jQuery(this).ColorPickerSetColor(this.value);
});
jQuery('#TW_ShellText').ColorPicker({
onSubmit: function(hsb, hex, rgb, el) {
jQuery(el).ColorPickerHide();
},
onBeforeShow: function () {
jQuery(this).ColorPickerSetColor(this.value);
},
onChange: function (hsb, hex, rgb) {
jQuery('#TW_ShellText').val('#' + hex);
jQuery('#TW_ShellTextPreview').css('background-color', '#' + hex);
}
})
.bind('keyup', function(){
jQuery(this).ColorPickerSetColor(this.value);
});
jQuery('#TW_TweetBackground').ColorPicker({
onSubmit: function(hsb, hex, rgb, el) {
jQuery(el).ColorPickerHide();
},
onBeforeShow: function () {
jQuery(this).ColorPickerSetColor(this.value);
},
onChange: function (hsb, hex, rgb) {
jQuery('#TW_TweetBackground').val('#' + hex);
jQuery('#TW_TweetBackgroundPreview').css('background-color', '#' + hex);
}
})
.bind('keyup', function(){
jQuery(this).ColorPickerSetColor(this.value);
});
jQuery('#TW_TweetText').ColorPicker({
onSubmit: function(hsb, hex, rgb, el) {
jQuery(el).ColorPickerHide();
},
onBeforeShow: function () {
jQuery(this).ColorPickerSetColor(this.value);
},
onChange: function (hsb, hex, rgb) {
jQuery('#TW_TweetText').val('#' + hex);
jQuery('#TW_TweetTextPreview').css('background-color', '#' + hex);
}
})
.bind('keyup', function(){
jQuery(this).ColorPickerSetColor(this.value);
});
jQuery('#TW_Links').ColorPicker({
onSubmit: function(hsb, hex, rgb, el) {
jQuery(el).ColorPickerHide();
},
onBeforeShow: function () {
jQuery(this).ColorPickerSetColor(this.value);
},
onChange: function (hsb, hex, rgb) {
jQuery('#TW_Links').val('#' + hex);
jQuery('#TW_LinksPreview').css('background-color', '#' + hex);
}
})
.bind('keyup', function(){
jQuery(this).ColorPickerSetColor(this.value);
});
jQuery('#GP_BorderColor').ColorPicker({
onSubmit: function(hsb, hex, rgb, el) {
jQuery(el).ColorPickerHide();
},
onBeforeShow: function () {
jQuery(this).ColorPickerSetColor(this.value);
},
onChange: function (hsb, hex, rgb) {
jQuery('#GP_BorderColor').val('#' + hex);
jQuery('#GP_BorderColorPreview').css('background-color', '#' + hex);
}
})
.bind('keyup', function(){
jQuery(this).ColorPickerSetColor(this.value);
});
jQuery('#GP_BackgroundColor').ColorPicker({
onSubmit: function(hsb, hex, rgb, el) {
jQuery(el).ColorPickerHide();
},
onBeforeShow: function () {
jQuery(this).ColorPickerSetColor(this.value);
},
onChange: function (hsb, hex, rgb) {
jQuery('#GP_BackgroundColor').val('#' + hex);
jQuery('#GP_BackgroundColorPreview').css('background-color', '#' + hex);
}
})
.bind('keyup', function(){
jQuery(this).ColorPickerSetColor(this.value);
});
</script> | gpl-2.0 |
kingsdigitallab/gssn-django | gssn/settings/stg.py | 639 | from .base import * # noqa
CACHE_REDIS_DATABASE = '1'
CACHES['default']['LOCATION'] = '127.0.0.1:6379:' + CACHE_REDIS_DATABASE
INTERNAL_IPS = INTERNAL_IPS + ('', )
ALLOWED_HOSTS = ['']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'app_gssn_stg',
'USER': 'app_gssn',
'PASSWORD': '',
'HOST': ''
},
}
# -----------------------------------------------------------------------------
# Local settings
# -----------------------------------------------------------------------------
try:
from .local import * # noqa
except ImportError:
pass
| gpl-2.0 |
aman104/stockhouse | wp-config.php | 3915 | <?php
/**
* Podstawowa konfiguracja WordPressa.
*
* Ten plik zawiera konfiguracje: ustawień MySQL-a, prefiksu tabel
* w bazie danych, tajnych kluczy, używanej lokalizacji WordPressa
* i ABSPATH. Więćej informacji znajduje się na stronie
* {@link http://codex.wordpress.org/Editing_wp-config.php Editing
* wp-config.php} Kodeksu. Ustawienia MySQL-a możesz zdobyć
* od administratora Twojego serwera.
*
* Ten plik jest używany przez skrypt automatycznie tworzący plik
* wp-config.php podczas instalacji. Nie musisz korzystać z tego
* skryptu, możesz po prostu skopiować ten plik, nazwać go
* "wp-config.php" i wprowadzić do niego odpowiednie wartości.
*
* @package WordPress
*/
// ** Ustawienia MySQL-a - możesz uzyskać je od administratora Twojego serwera ** //
/** Nazwa bazy danych, której używać ma WordPress */
define('DB_NAME', 'stockhouse');
/** Nazwa użytkownika bazy danych MySQL */
define('DB_USER', 'root');
/** Hasło użytkownika bazy danych MySQL */
define('DB_PASSWORD', 'pawel12pl');
/** Nazwa hosta serwera MySQL */
define('DB_HOST', 'localhost');
/** Kodowanie bazy danych używane do stworzenia tabel w bazie danych. */
define('DB_CHARSET', 'utf8');
/** Typ porównań w bazie danych. Nie zmieniaj tego ustawienia, jeśli masz jakieś wątpliwości. */
define('DB_COLLATE', '');
/**#@+
* Unikatowe klucze uwierzytelniania i sole.
*
* Zmień każdy klucz tak, aby był inną, unikatową frazą!
* Możesz wygenerować klucze przy pomocy {@link https://api.wordpress.org/secret-key/1.1/salt/ serwisu generującego tajne klucze witryny WordPress.org}
* Klucze te mogą zostać zmienione w dowolnej chwili, aby uczynić nieważnymi wszelkie istniejące ciasteczka. Uczynienie tego zmusi wszystkich użytkowników do ponownego zalogowania się.
*
* @since 2.6.0
*/
define('AUTH_KEY', 'w?J7lanRD0h[6Rjl*s!f]J>/?YK<_&&:k+wXUGFPgK/<1Kh](OS;/hqTKi-T~66e');
define('SECURE_AUTH_KEY', 'YV<`<MPm~{N2aaRStzn|[aF,+.{6FyhY<jQcb[dv@M-@EQn;>zc?+h`:GRHCxY0e');
define('LOGGED_IN_KEY', 'DVl%&c+0W{@ .*gz<N,-6g+Y-F+AYqGQ9ZJ}g|xzwQyx}Y%M$YBlBMw@#v=fADpB');
define('NONCE_KEY', '7=0@Q.w**Cg!z~L)_/3mjh!9w-6<A|sq{3SOQX+^{e%n|v)tf5C%a5JVA,[#i+-t');
define('AUTH_SALT', '_9<H&s%-mi~d@ApzN--ZXh)gn|3gDG;GgR9p?!1[xw^wnR>^Me`RGb,q4I(l(1.K');
define('SECURE_AUTH_SALT', 'La9R<V=bs1yT3|O6&.[;rhi5[P/Il4+UW7U7O/;({Y/S|>X6-=LG7~-@ZpsB6~;<');
define('LOGGED_IN_SALT', 'C&/d12CROX,HO=muPnQ7cy<>|Qo/c,+fbb!2-xM?l{=7%Hr_0thp[sCZE-o$LD8T');
define('NONCE_SALT', 'tQl#vz7bMJ=HWO1^lRM/Hv8<1l%?|bSj2Vwo=n$S 6Gh53!p!X7+(7l!R](h6rf.');
/**#@-*/
/**
* Prefiks tabel WordPressa w bazie danych.
*
* Możesz posiadać kilka instalacji WordPressa w jednej bazie danych,
* jeżeli nadasz każdej z nich unikalny prefiks.
* Tylko cyfry, litery i znaki podkreślenia, proszę!
*/
$table_prefix = 'wp_';
/**
* Kod lokalizacji WordPressa, domyślnie: angielska.
*
* Zmień to ustawienie, aby włączyć tłumaczenie WordPressa.
* Odpowiedni plik MO z tłumaczeniem na wybrany język musi
* zostać zainstalowany do katalogu wp-content/languages.
* Na przykład: zainstaluj plik de_DE.mo do katalogu
* wp-content/languages i ustaw WPLANG na 'de_DE', aby aktywować
* obsługę języka niemieckiego.
*/
define('WPLANG', 'pl_PL');
/**
* Dla programistów: tryb debugowania WordPressa.
*
* Zmień wartość tej stałej na true, aby włączyć wyświetlanie ostrzeżeń
* podczas modyfikowania kodu WordPressa.
* Wielce zalecane jest, aby twórcy wtyczek oraz motywów używali
* WP_DEBUG w miejscach pracy nad nimi.
*/
define('WP_DEBUG', false);
/* To wszystko, zakończ edycję w tym miejscu! Miłego blogowania! */
/** Absolutna ścieżka do katalogu WordPressa. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** Ustawia zmienne WordPressa i dołączane pliki. */
require_once(ABSPATH . 'wp-settings.php');
| gpl-2.0 |
chryswoods/SireTests | unittests/SireMove/intra_dynamics.py | 1643 |
from Sire.IO import *
from Sire.Mol import *
from Sire.MM import *
from Sire.System import *
from Sire.Move import *
from Sire.Base import *
from Sire.FF import *
from Sire.Maths import *
from Sire.CAS import *
from Sire.Units import *
import os
coords = "test/io/Bound_ligand1.pdb"
ff = "test/io/ligand1.template"
name = "dana"
coords = "test/io/ethane.pdb"
ff = "test/io/ethane.ff"
name = "ethane"
ethane = PDB().readMolecule(coords)
protoms_dir = "%s/Work/ProtoMS" % os.getenv("HOME")
protoms = ProtoMS("%s/protoms2" % protoms_dir)
protoms.addParameterFile("%s/parameter/amber99.ff" % protoms_dir)
protoms.addParameterFile("%s/parameter/gaff.ff" % protoms_dir)
protoms.addParameterFile(ff)
ethane = ethane.edit().rename(name).commit()
ethane = protoms.parameterise(ethane, ProtoMS.SOLUTE)
bonds = ethane.property("bond")
angles = ethane.property("angle")
dihedrals = ethane.property("dihedral")
print(bonds.potentials())
print(angles.potentials())
print(dihedrals.potentials())
#intraff = InternalFF("intraff")
intraclj = IntraCLJFF("intraclj")
#intraff.add(ethane)
intraclj.add(ethane)
solute = MoleculeGroup("solute", ethane)
solute.add(ethane)
system = System()
#system.add(intraff)
system.add(intraclj)
system.add(solute)
md = MolecularDynamics(solute, VelocityVerlet())
# {"velocity generator" : MaxwellBoltzmann(25*celsius)})
md.setTimeStep(1*femtosecond)
PDB().write(system.molecules(), "test0000.pdb")
for i in range(1,250):
md.move(system, 1)
print(system.energy(), md.kineticEnergy(), (system.energy()+md.kineticEnergy()))
PDB().write(system.molecules(), "test%0004d.pdb" % i)
| gpl-2.0 |
villaverde/iredadmin | libs/ldaplib/user.py | 25058 | # Author: Zhang Huangbin <zhb@iredmail.org>
import ldap
import ldap.filter
import web
import settings
from libs import iredutils
from libs.ldaplib import core, domain as domainlib, attrs, ldaputils, iredldif, connUtils, decorators, deltree
session = web.config.get('_session')
class User(core.LDAPWrap):
def __del__(self):
try:
self.conn.unbind()
except:
pass
# List all users under one domain.
@decorators.require_domain_access
def listAccounts(self, domain):
self.domain = domain
self.domainDN = ldaputils.convert_keyword_to_dn(self.domain, accountType='domain')
if self.domainDN[0] is False:
return self.domainDN
try:
# Use '(!(mail=@domain.ltd))' to hide catch-all account.
self.users = self.conn.search_s(
attrs.DN_BETWEEN_USER_AND_DOMAIN + self.domainDN,
ldap.SCOPE_SUBTREE,
'(&(objectClass=mailUser)(!(mail=@%s)))' % self.domain,
attrs.USER_SEARCH_ATTRS,
)
connutils = connUtils.Utils()
connutils.updateAttrSingleValue(self.domainDN, 'domainCurrentUserNumber', len(self.users))
return (True, self.users)
except ldap.NO_SUCH_OBJECT:
#self.conn.add_s(
# attrs.DN_BETWEEN_USER_AND_DOMAIN + self.domainDN,
# iredldif.ldif_group(attrs.GROUP_USERS),
# )
return (False, 'NO_SUCH_OBJECT')
except ldap.SIZELIMIT_EXCEEDED:
return (False, 'EXCEEDED_LDAP_SERVER_SIZELIMIT')
except Exception, e:
return (False, ldaputils.getExceptionDesc(e))
# Get values of user or domain catch-all account.
# accountType in ['user', 'catchall',]
@decorators.require_domain_access
def profile(self, domain, mail, accountType='user'):
self.mail = web.safestr(mail)
self.domain = self.mail.split('@', 1)[-1]
if self.domain != domain:
raise web.seeother('/domains?msg=PERMISSION_DENIED')
self.filter = '(&(objectClass=mailUser)(mail=%s))' % (self.mail,)
if accountType == 'catchall':
self.filter = '(&(objectClass=mailUser)(mail=@%s))' % (self.mail,)
else:
if not self.mail.endswith('@' + self.domain):
raise web.seeother('/domains?msg=PERMISSION_DENIED')
if attrs.RDN_USER == 'mail':
self.searchdn = ldaputils.convert_keyword_to_dn(self.mail, accountType=accountType)
self.scope = ldap.SCOPE_BASE
if self.searchdn[0] is False:
return self.searchdn
else:
domain_dn = ldaputils.convert_keyword_to_dn(self.domain, accountType='domain')
if domain_dn[0] is False:
return domain_dn
self.searchdn = attrs.DN_BETWEEN_USER_AND_DOMAIN + domain_dn
self.scope = ldap.SCOPE_SUBTREE
try:
self.user_profile = self.conn.search_s(
self.searchdn,
self.scope,
self.filter,
attrs.USER_ATTRS_ALL,
)
return (True, self.user_profile)
except Exception, e:
return (False, ldaputils.getExceptionDesc(e))
@decorators.require_domain_access
def add(self, domain, data):
# Get domain name, username, cn.
self.domain = web.safestr(data.get('domainName')).strip().lower()
self.username = web.safestr(data.get('username')).strip().lower()
self.mail = self.username + '@' + self.domain
self.groups = data.get('groups', [])
if not iredutils.is_domain(self.domain) or not iredutils.is_email(self.mail):
return (False, 'MISSING_DOMAIN_OR_USERNAME')
# Check account existing.
connutils = connUtils.Utils()
if connutils.isAccountExists(domain=self.domain, mail=self.mail,):
return (False, 'ALREADY_EXISTS')
# Get @domainAccountSetting.
domainLib = domainlib.Domain()
result_domain_profile = domainLib.profile(domain=self.domain)
# Initial parameters.
domainAccountSetting = {}
self.aliasDomains = []
if result_domain_profile[0] is not True:
return (False, result_domain_profile[1])
domainProfile = result_domain_profile[1]
domainAccountSetting = ldaputils.getAccountSettingFromLdapQueryResult(domainProfile, key='domainName').get(self.domain, {})
self.aliasDomains = domainProfile[0][1].get('domainAliasName', [])
# Check account number limit.
numberOfAccounts = domainAccountSetting.get('numberOfUsers')
if numberOfAccounts == '-1':
return (False, 'NOT_ALLOWED')
# Check password.
self.newpw = web.safestr(data.get('newpw'))
self.confirmpw = web.safestr(data.get('confirmpw'))
result = iredutils.verify_new_password(self.newpw, self.confirmpw,
min_passwd_length=domainAccountSetting.get('minPasswordLength', '0'),
max_passwd_length=domainAccountSetting.get('maxPasswordLength', '0'),
)
if result[0] is True:
if 'storePasswordInPlainText' in data and settings.STORE_PASSWORD_IN_PLAIN_TEXT:
self.passwd = iredutils.generate_password_hash(result[1], pwscheme='PLAIN')
else:
self.passwd = iredutils.generate_password_hash(result[1])
else:
return result
# Get display name.
self.cn = data.get('cn')
# Get user quota. Unit is MB.
# 0 or empty is not allowed if domain quota is set, set to
# @defaultUserQuota or @domainSpareQuotaSize
# Initial final mailbox quota.
self.quota = 0
# Get mail quota from web form.
defaultUserQuota = domainLib.getDomainDefaultUserQuota(self.domain, domainAccountSetting)
self.mailQuota = str(data.get('mailQuota')).strip()
if self.mailQuota.isdigit():
self.mailQuota = int(self.mailQuota)
else:
self.mailQuota = defaultUserQuota
# 0 means unlimited.
domainQuotaSize, domainQuotaUnit = domainAccountSetting.get('domainQuota', '0:GB').split(':')
if int(domainQuotaSize) == 0:
# Unlimited.
self.quota = self.mailQuota
else:
# Get domain quota, convert to MB.
if domainQuotaUnit == 'TB':
domainQuota = int(domainQuotaSize) * 1024 * 1024 # TB
elif domainQuotaUnit == 'GB':
domainQuota = int(domainQuotaSize) * 1024 # GB
else:
domainQuota = int(domainQuotaSize) # MB
result = connutils.getDomainCurrentQuotaSizeFromLDAP(domain=self.domain)
if result[0] is True:
domainCurrentQuotaSize = result[1]
else:
domainCurrentQuotaSize = 0
# Spare quota.
domainSpareQuotaSize = domainQuota - domainCurrentQuotaSize / (1024 * 1024)
if domainSpareQuotaSize <= 0:
return (False, 'EXCEEDED_DOMAIN_QUOTA_SIZE')
# Get FINAL mailbox quota.
if self.mailQuota == 0:
self.quota = domainSpareQuotaSize
else:
if domainSpareQuotaSize > self.mailQuota:
self.quota = self.mailQuota
else:
self.quota = domainSpareQuotaSize
# Get default groups.
self.groups = [web.safestr(v)
for v in domainAccountSetting.get('defaultList', '').split(',')
if iredutils.is_email(v)
]
self.defaultStorageBaseDirectory = domainAccountSetting.get('defaultStorageBaseDirectory', None)
# Get default mail lists which set in domain accountSetting.
ldif = iredldif.ldif_mailuser(
domain=self.domain,
aliasDomains=self.aliasDomains,
username=self.username,
cn=self.cn,
passwd=self.passwd,
quota=self.quota,
groups=self.groups,
storageBaseDirectory=self.defaultStorageBaseDirectory,
)
domain_dn = ldaputils.convert_keyword_to_dn(self.domain, accountType='domain')
if domain_dn[0] is False:
return domain_dn
if attrs.RDN_USER == 'mail':
self.dn = ldaputils.convert_keyword_to_dn(self.mail, accountType='user')
if self.dn[0] is False:
return self.dn
elif attrs.RDN_USER == 'cn':
self.dn = 'cn=' + self.cn + ',' + attrs.DN_BETWEEN_USER_AND_DOMAIN + domain_dn
elif attrs.RDN_USER == 'uid':
self.dn = 'uid=' + self.username + ',' + attrs.DN_BETWEEN_USER_AND_DOMAIN + domain_dn
else:
return (False, 'UNSUPPORTED_USER_RDN')
try:
self.conn.add_s(ldap.filter.escape_filter_chars(self.dn), ldif,)
web.logger(msg="Create user: %s." % (self.mail), domain=self.domain, event='create',)
return (True,)
except ldap.ALREADY_EXISTS:
return (False, 'ALREADY_EXISTS')
except Exception, e:
return (False, ldaputils.getExceptionDesc(e))
def getFilterOfDeleteUserFromGroups(self, mail):
# Get valid emails as list.
if isinstance(mail, list):
self.mails = [web.safestr(v).lower() for v in mail if iredutils.is_email(str(v))]
else:
# Single email.
self.mails = [web.safestr(mail).lower()]
filterUserAndAlias = '(&(|(objectClass=mailAlias)(objectClass=mailUser))(|'
filterExternalUser = '(&(objectClass=mailExternalUser)(|'
for mail in self.mails:
filterUserAndAlias += '(mailForwardingAddress=%s)' % mail
filterExternalUser += '(mail=%s)' % mail
# Close filter string.
filterUserAndAlias += '))'
filterExternalUser += '))'
filter = '(|' + filterUserAndAlias + filterExternalUser + ')'
return filter
# Delete single user from mail list, alias, user forwarding addresses.
def deleteSingleUserFromGroups(self, mail):
self.mail = web.safestr(mail)
if not iredutils.is_email(self.mail):
return (False, 'INVALID_MAIL')
# Get domain name of this account.
self.domain = self.mail.split('@')[-1]
# Get dn of mail user and domain.
self.dnUser = ldaputils.convert_keyword_to_dn(self.mail, accountType='user')
self.dnDomain = ldaputils.convert_keyword_to_dn(self.domain, accountType='domain')
if self.dnUser[0] is False:
return self.dnUser
if self.dnDomain[0] is False:
return self.dnDomain
try:
# Get accounts which contains destination email.
objsHasUser = self.conn.search_s(
self.dnDomain,
ldap.SCOPE_SUBTREE,
self.getFilterOfDeleteUserFromGroups(self.mail),
['dn'],
)
if len(objsHasUser) >= 1:
connutils = connUtils.Utils()
for obj in objsHasUser:
if obj[0].endswith(attrs.DN_BETWEEN_ALIAS_AND_DOMAIN + self.dnDomain) or \
obj[0].endswith(attrs.DN_BETWEEN_USER_AND_DOMAIN + self.dnDomain):
# Remove address from alias and user.
connutils.addOrDelAttrValue(
dn=obj[0],
attr='mailForwardingAddress',
value=self.mail,
action='delete',
)
elif obj[0].endswith('ou=Externals,' + self.domaindn):
# Remove address from external member list.
connutils.addOrDelAttrValue(
dn=obj[0],
attr='mail',
value=self.mail,
action='delete',
)
else:
pass
else:
pass
return (True,)
except Exception, e:
return (False, ldaputils.getExceptionDesc(e))
# Delete single user.
def deleteSingleUser(self, mail, deleteFromGroups=True,):
self.mail = web.safestr(mail)
if not iredutils.is_email(self.mail):
return (False, 'INVALID_MAIL')
# Get domain name of this account.
self.domain = self.mail.split('@')[-1]
# Get dn of mail user and domain.
self.dnUser = ldaputils.convert_keyword_to_dn(self.mail, accountType='user')
if self.dnUser[0] is False:
return self.dnUser
# Delete user object.
try:
# Delete single object.
#self.conn.delete_s(self.dnUser)
# Delete object and its subtree.
deltree.DelTree(self.conn, self.dnUser, ldap.SCOPE_SUBTREE)
if deleteFromGroups:
self.deleteSingleUserFromGroups(self.mail)
# Delete record from SQL database: real-time used quota.
try:
connUtils.deleteAccountFromUsedQuota([self.mail])
except Exception, e:
pass
# Log delete action.
web.logger(
msg="Delete user: %s." % (self.mail),
domain=self.domain,
event='delete',
)
return (True,)
except ldap.LDAPError, e:
return (False, ldaputils.getExceptionDesc(e))
# Delete mail users in same domain.
@decorators.require_domain_access
def delete(self, domain, mails=[]):
if mails is None or len(mails) == 0:
return (False, 'NO_ACCOUNT_SELECTED')
self.domain = web.safestr(domain)
self.mails = [str(v) for v in mails if iredutils.is_email(v) and str(v).endswith('@' + self.domain)]
if not len(self.mails) > 0:
return (False, 'INVALID_MAIL')
self.domaindn = ldaputils.convert_keyword_to_dn(self.domain, accountType='domain')
if self.domaindn[0] is False:
return self.domaindn
if not iredutils.is_domain(self.domain):
return (False, 'INVALID_DOMAIN_NAME')
result = {}
for mail in self.mails:
self.mail = web.safestr(mail)
try:
# Delete user object (ldap.SCOPE_BASE).
self.deleteSingleUser(self.mail,)
# Delete user object and whole sub-tree.
# Get dn of mail user and domain.
"""
self.userdn = ldaputils.convert_keyword_to_dn(self.mail, accountType='user')
deltree.DelTree(self.conn, self.userdn, ldap.SCOPE_SUBTREE)
# Log delete action.
web.logger(
msg="Delete user: %s." % (self.mail),
domain=self.mail.split('@')[1],
event='delete',
)
"""
except ldap.LDAPError, e:
result[self.mail] = ldaputils.getExceptionDesc(e)
if result == {}:
return (True,)
else:
return (False, str(result))
@decorators.require_domain_access
def enableOrDisableAccount(self, domain, mails, action, attr='accountStatus',):
if mails is None or len(mails) == 0:
return (False, 'NO_ACCOUNT_SELECTED')
self.mails = [str(v)
for v in mails
if iredutils.is_email(v)
and str(v).endswith('@' + str(domain))
]
result = {}
connutils = connUtils.Utils()
for mail in self.mails:
self.mail = web.safestr(mail)
if not iredutils.is_email(self.mail):
continue
self.domain = self.mail.split('@')[-1]
self.dn = ldaputils.convert_keyword_to_dn(self.mail, accountType='user')
if self.dn[0] is False:
result[self.mail] = self.dn[1]
continue
try:
connutils.enableOrDisableAccount(
domain=self.domain,
account=self.mail,
dn=self.dn,
action=web.safestr(action).strip().lower(),
accountTypeInLogger='user',
)
except ldap.LDAPError, e:
result[self.mail] = str(e)
if result == {}:
return (True,)
else:
return (False, str(result))
@decorators.require_domain_access
def update(self, profile_type, mail, data):
self.profile_type = web.safestr(profile_type)
self.mail = str(mail).lower()
self.username, self.domain = self.mail.split('@', 1)
domainAccountSetting = {}
connutils = connUtils.Utils()
domainLib = domainlib.Domain()
# Get account dn.
self.dn = connutils.getDnWithKeyword(self.mail, accountType='user')
try:
result = domainLib.getDomainAccountSetting(domain=self.domain)
if result[0] is True:
domainAccountSetting = result[1]
except Exception, e:
pass
mod_attrs = []
if self.profile_type == 'general':
# Update domainGlobalAdmin=yes
if session.get('domainGlobalAdmin') is True:
# Update domainGlobalAdmin=yes
if 'domainGlobalAdmin' in data:
mod_attrs = [(ldap.MOD_REPLACE, 'domainGlobalAdmin', 'yes')]
# Update enabledService=domainadmin
connutils.addOrDelAttrValue(
dn=self.dn,
attr='enabledService',
value='domainadmin',
action='add',
)
else:
mod_attrs = [(ldap.MOD_REPLACE, 'domainGlobalAdmin', None)]
# Remove enabledService=domainadmin
connutils.addOrDelAttrValue(
dn=self.dn,
attr='enabledService',
value='domainadmin',
action='delete',
)
# Get display name.
cn = data.get('cn', None)
mod_attrs += ldaputils.getSingleModAttr(attr='cn',
value=cn,
default=self.username)
first_name = data.get('first_name', '')
mod_attrs += ldaputils.getSingleModAttr(attr='givenName',
value=first_name,
default=self.username)
last_name = data.get('last_name', '')
mod_attrs += ldaputils.getSingleModAttr(attr='sn',
value=last_name,
default=self.username)
# Get preferred language: short lang code. e.g. en_US, de_DE.
preferred_lang = web.safestr(data.get('preferredLanguage', 'en_US'))
# Must be equal to or less than 5 characters.
if len(preferred_lang) > 5:
preferred_lang = preferred_lang[:5]
mod_attrs += [(ldap.MOD_REPLACE, 'preferredLanguage', preferred_lang)]
# Update language immediately.
if session.get('username') == self.mail and \
session.get('lang', 'en_US') != preferred_lang:
session['lang'] = preferred_lang
# Update employeeNumber, mobile, title.
for tmp_attr in ['employeeNumber', 'mobile', 'title', ]:
mod_attrs += ldaputils.getSingleModAttr(attr=tmp_attr, value=data.get(tmp_attr), default=None)
############
# Get quota
# Get mail quota from web form.
quota = web.safestr(data.get('mailQuota', '')).strip()
oldquota = web.safestr(data.get('oldMailQuota', '')).strip()
if not oldquota.isdigit():
oldquota = 0
else:
oldquota = int(oldquota)
if quota == '' or not quota.isdigit():
# Don't touch it, keep original value.
pass
else:
#mod_attrs += [( ldap.MOD_REPLACE, 'mailQuota', str(int(mailQuota) * 1024 * 1024) )]
# Assign quota which got from web form.
mailQuota = int(quota)
# If mailQuota > domainSpareQuotaSize, use domainSpareQuotaSize.
# if mailQuota < domainSpareQuotaSize, use mailQuota
# 0 means unlimited.
domainQuotaSize, domainQuotaUnit = domainAccountSetting.get('domainQuota', '0:GB').split(':')
if int(domainQuotaSize) == 0:
# Unlimited. Keep quota which got from web form.
mod_attrs += [(ldap.MOD_REPLACE, 'mailQuota', str(mailQuota * 1024 * 1024))]
else:
# Get domain quota.
if domainQuotaUnit == 'TB':
domainQuota = int(domainQuotaSize) * 1024 * 1024 # TB
elif domainQuotaUnit == 'GB':
domainQuota = int(domainQuotaSize) * 1024 # GB
else:
domainQuota = int(domainQuotaSize) # MB
# Query LDAP and get current domain quota size.
result = connutils.getDomainCurrentQuotaSizeFromLDAP(domain=self.domain)
if result[0] is True:
domainCurrentQuotaSizeInBytes = result[1]
else:
domainCurrentQuotaSizeInBytes = 0
# Spare quota.
domainSpareQuotaSize = (domainQuota + oldquota) - (domainCurrentQuotaSizeInBytes / (1024 * 1024))
if domainSpareQuotaSize <= 0:
# Don't update quota if already exceed domain quota size.
#return (False, 'EXCEEDED_DOMAIN_QUOTA_SIZE')
# Set to 1MB. don't exceed domain quota size.
mod_attrs += [(ldap.MOD_REPLACE, 'mailQuota', str(1024 * 1024))]
else:
# Get FINAL mailbox quota.
if mailQuota >= domainSpareQuotaSize:
mailQuota = domainSpareQuotaSize
mod_attrs += [(ldap.MOD_REPLACE, 'mailQuota', str(mailQuota * 1024 * 1024))]
# End quota
############
# Get telephoneNumber.
telephoneNumber = data.get('telephoneNumber', [])
nums = [str(num) for num in telephoneNumber if len(num) > 0]
mod_attrs += [(ldap.MOD_REPLACE, 'telephoneNumber', nums)]
# Get accountStatus.
if 'accountStatus' in data.keys():
accountStatus = 'active'
else:
accountStatus = 'disabled'
mod_attrs += [(ldap.MOD_REPLACE, 'accountStatus', accountStatus)]
elif self.profile_type == 'password':
# Get password length from @domainAccountSetting.
minPasswordLength = domainAccountSetting.get('minPasswordLength', settings.min_passwd_length)
maxPasswordLength = domainAccountSetting.get('maxPasswordLength', settings.max_passwd_length)
# Get new passwords from user input.
self.newpw = str(data.get('newpw', None))
self.confirmpw = str(data.get('confirmpw', None))
result = iredutils.verify_new_password(
newpw=self.newpw,
confirmpw=self.confirmpw,
min_passwd_length=minPasswordLength,
max_passwd_length=maxPasswordLength,
)
if result[0] is True:
if 'storePasswordInPlainText' in data and settings.STORE_PASSWORD_IN_PLAIN_TEXT:
self.passwd = iredutils.generate_password_hash(result[1], pwscheme='PLAIN')
else:
self.passwd = iredutils.generate_password_hash(result[1])
mod_attrs += [(ldap.MOD_REPLACE, 'userPassword', self.passwd)]
mod_attrs += [(ldap.MOD_REPLACE, 'shadowLastChange', str(ldaputils.getDaysOfShadowLastChange()))]
else:
return result
try:
self.conn.modify_s(self.dn, mod_attrs)
return (True,)
except Exception, e:
return (False, ldaputils.getExceptionDesc(e))
| gpl-2.0 |
iprem/Hackerrank | CountingSort3/src/CountingSort3.java | 585 | import java.util.Scanner;
public class CountingSort3 {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[100];
String[] s = new String[100];
for(int i = 0; i< n; i++){
int num = sc.nextInt();
a[num]++;
s[num] = sc.next();
}
for(int i =0; i< 100; i++){
int sum = 0;
for(int j =0; j<=i; j++)
sum+=a[j];
System.out.print(sum + " ");
}
}
}
| gpl-2.0 |
callakrsos/Gargoyle | VisualFxVoEditor/src/test/java/external/jshint/report/JSHintReportExecutor.java | 3617 | /********************************
* 프로젝트 : VisualFxVoEditor
* 패키지 : external.jshint.report
* 작성일 : 2017. 12. 11.
* 작성자 : KYJ
*******************************/
package external.jshint.report;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import org.junit.Before;
import org.junit.Test;
import com.kyj.fx.voeditor.visual.util.RuntimeClassUtil;
import com.kyj.fx.voeditor.visual.util.ValueUtil;
/**
* @author KYJ
*
*/
public class JSHintReportExecutor {
ExecutorService newFixedThreadPool;
@Before
public void before() throws InterruptedException {
newFixedThreadPool = Executors.newFixedThreadPool(8);
}
@Test
public void test() throws Exception {
String target = "C:\\SVN_WORKSPACE\\wwwroot";
BiConsumer<Integer, String> messageReceiver = (idx, str) -> {
System.out.println(str);
};
// messageReceiver = null;
String userHome = System.getProperty("user.home");
System.out.println(userHome);
File file = new File(target);
ArrayList<Callable<Integer>> list = new ArrayList<>();
File[] listFiles = file.listFiles();
for (File f : listFiles) {
if (f.isDirectory()) {
// if (!"MaterialMovement".equals(f.getName()))
// continue;
Callable<Integer> task = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println(f.getName() + " job Start.");
String simpleOutputName = f.getName() + "-report.html";
File file2 = new File(file.getParentFile(), simpleOutputName);
System.out.println(file2.getAbsolutePath());
// String outputFileName = f.getName() + "-report.html";
if (file2.exists())
return 0;
RuntimeClassUtil.exeSynch(Arrays.asList(
/* command location */
userHome + "\\node_modules\\.bin\\jshint.cmd"
/**/
, f.getAbsolutePath()
/* exclude */
// ,"--exclude-path", ".jshintignore"
,"--exclude" , "**/bootstrap*.js,**/*.min.js, **/jquery.min.js, jquery*.js , **/knockout*.js, "
/* config */
// ,"--config" , "C:\\SVN_WORKSPACE\\jshintconfig.json",
/* report template. */
, "--reporter", userHome + "\\node_modules\\jshint-html-reporter\\reporter.js"
// , "-verbose"
// /* redirect */
, ">", file2.getAbsolutePath()
), "EUC-KR",
new Consumer<ProcessBuilder>() {
@Override
public void accept(ProcessBuilder pb) {
pb.directory(new File(target));
System.out.println(ValueUtil.toString(pb.environment()));
}
}, messageReceiver, err -> {
System.err.println(err);
System.exit(-1);
});
if (file2.exists() && file2.length() == 12288) {
System.out.println(file2 + " " + file2.length());
file2.delete();
// System.out.println(file.length());
}
System.out.println(f.getName() + " job Complete.");
return 1;
}
};
list.add(task);
} else {
System.out.println("skip : " + f + " is not dir. ");
}
}
System.out.println("start invoke");
List<Future<Integer>> invokeAll = newFixedThreadPool.invokeAll(list);
System.out.println("end invoke");
invokeAll.forEach(System.out::println);
// newFixedThreadPool.awaitTermination(120, TimeUnit.SECONDS);
// Thread.sleep(30000);
}
}
| gpl-2.0 |
libresoft/CVSAnaly-ALERT-branch | pycvsanaly2/AsyncQueue.py | 4512 | # Copyright (C) 2008 Libresoft
#
# 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.
#
# Authors: Carlos Garcia Campos <carlosgc@gsyc.escet.urjc.es>
import threading
from time import time as _time
from collections import deque
class TimeOut (Exception):
pass
class AsyncQueue:
def __init__ (self, maxsize = 0):
self._init (maxsize)
self.mutex = threading.Lock ()
self.empty_cond = threading.Condition (self.mutex)
self.full_cond = threading.Condition (self.mutex)
self.finish = threading.Condition (self.mutex)
self.pending_items = 0
def done (self):
self.finish.acquire ()
try:
pending = self.pending_items - 1
if pending < 0:
raise ValueError ('done() called too many times')
elif pending == 0:
self.finish.notifyAll ()
self.pending_items = pending
finally:
self.finish.release ()
def join (self):
self.finish.acquire ()
try:
while self.pending_items:
self.finish.wait ()
finally:
self.finish.release ()
def empty (self):
self.mutex.acquire ()
retval = self._empty ()
self.mutex.release ()
return retval
def empty_unlocked (self):
return self._empty ()
def put (self, item, timeout = None):
self.full_cond.acquire ()
try:
if timeout is None:
while self._full ():
self.full_cond.wait ()
else:
if timeout < 0:
raise ValueError ("'timeout' must be a positive number")
endtime = _time () + timeout
while self._full ():
remaining = endtime - _time ()
if remaining <= 0.0:
raise TimeOut
self.full_cond.wait (remaining)
self._put (item)
self.pending_items += 1
self.empty_cond.notify ()
finally:
self.full_cond.release ()
def put_unlocked (self, item):
self._put (item)
def get (self, timeout = None):
self.empty_cond.acquire ()
try:
if timeout is None:
while self._empty ():
self.empty_cond.wait ()
else:
if timeout < 0:
raise ValueError ("'timeout' must be a positive number")
endtime = _time () + timeout
while self._empty ():
remaining = endtime - _time ()
if remaining <= 0.0:
raise TimeOut
self.empty_cond.wait (remaining)
item = self._get ()
self.full_cond.notify ()
return item
finally:
self.empty_cond.release ()
def get_unlocked (self):
return self._get ()
# Queue implementation
def _init (self, maxsize):
self.maxsize = maxsize
self.queue = deque ()
def _empty (self):
return not self.queue
def _full (self):
return self.maxsize > 0 and len (self.queue) == self.maxsize
def _put (self, item):
self.queue.append (item)
def _get (self):
return self.queue.popleft ()
if __name__ == '__main__':
def worker (q):
while True:
item = q.get ()
print "Got item ", item
q.done ()
q = AsyncQueue ()
for i in range (5):
t = threading.Thread (target=worker, args=(q,))
t.setDaemon (True)
t.start ()
for item in ['foo', 'bar', 1, 2, {'a' : 'b'}, [5,6,7]]:
q.put (item)
q.join ()
try:
q.get (5)
except TimeOut:
print "Queue empty! bye bye!"
| gpl-2.0 |
FranklinCoop/IS4C | pos/is4c-nf/install/db/Creator.php | 16692 | <?php
namespace COREPOS\pos\install\db;
use COREPOS\pos\lib\CoreState;
class Creator
{
private static $op_models = array(
'\\COREPOS\\pos\\lib\\models\\op\\AutoCouponsModel',
'\\COREPOS\\pos\\lib\\models\\op\\CouponCodesModel',
'\\COREPOS\\pos\\lib\\models\\op\\CustdataModel',
'\\COREPOS\\pos\\lib\\models\\op\\CustomerNotificationsModel',
'\\COREPOS\\pos\\lib\\models\\op\\CustPreferencesModel',
'\\COREPOS\\pos\\lib\\models\\op\\CustReceiptMessageModel',
'\\COREPOS\\pos\\lib\\models\\op\\CustomReceiptModel',
'\\COREPOS\\pos\\lib\\models\\op\\DateRestrictModel',
'\\COREPOS\\pos\\lib\\models\\op\\DepartmentsModel',
'\\COREPOS\\pos\\lib\\models\\op\\DisableCouponModel',
'\\COREPOS\\pos\\lib\\models\\op\\DrawerOwnerModel',
'\\COREPOS\\pos\\lib\\models\\op\\EmployeesModel',
'\\COREPOS\\pos\\lib\\models\\op\\GlobalValuesModel',
'\\COREPOS\\pos\\lib\\models\\op\\HouseCouponsModel',
'\\COREPOS\\pos\\lib\\models\\op\\HouseCouponItemsModel',
'\\COREPOS\\pos\\lib\\models\\op\\HouseVirtualCouponsModel',
'\\COREPOS\\pos\\lib\\models\\op\\IgnoredBarcodesModel',
'\\COREPOS\\pos\\lib\\models\\op\\MasterSuperDeptsModel',
'\\COREPOS\\pos\\lib\\models\\op\\MemberCardsModel',
'\\COREPOS\\pos\\lib\\models\\op\\MemtypeModel',
'\\COREPOS\\pos\\lib\\models\\op\\ParametersModel',
'\\COREPOS\\pos\\lib\\models\\op\\ProductsModel',
'\\COREPOS\\pos\\lib\\models\\op\\ShrinkReasonsModel',
'\\COREPOS\\pos\\lib\\models\\op\\SpecialDeptMapModel',
'\\COREPOS\\pos\\lib\\models\\op\\SubDeptsModel',
'\\COREPOS\\pos\\lib\\models\\op\\TendersModel',
'\\COREPOS\\pos\\lib\\models\\op\\UnpaidArTodayModel',
// depends on custdata
'\\COREPOS\\pos\\lib\\models\\op\\MemberCardsViewModel',
);
/**
Create opdata tables and views
@param $db [SQLManager] database connection
@param $name [string] database name
@return [array] of error messages
*/
public static function createOpDBs($db, $name)
{
$errors = array();
if (\CoreLocal::get('laneno') == 0) {
$errors[] = array(
'struct' => 'No structures created for lane #0',
'query' => 'None',
'details' => 'Zero is reserved for server',
);
return $errors;
}
foreach (self::$op_models as $class) {
$obj = new $class($db);
$errors[] = $obj->createIfNeeded($name);
}
$sample_data = array(
'couponcodes',
'customReceipt',
'globalvalues',
'parameters',
'tenders',
);
foreach ($sample_data as $table) {
$chk = $db->query('SELECT * FROM ' . $table, $name);
if ($db->numRows($chk) === 0) {
$loaded = \COREPOS\pos\install\data\Loader::loadSampleData($db, $table, true);
if (!$loaded) {
$errors[] = array(
'struct' => $table,
'query' => 'None',
'details' => 'Failed loading sample data',
);
}
} else {
$db->endQuery($chk);
}
}
$chk = $db->query('SELECT drawer_no FROM drawerowner', $name);
if ($db->num_rows($chk) == 0){
$db->query('INSERT INTO drawerowner (drawer_no) VALUES (1)', $name);
$db->query('INSERT INTO drawerowner (drawer_no) VALUES (2)', $name);
}
CoreState::loadParams();
return $errors;
}
private static $trans_models = array(
'\\COREPOS\\pos\\lib\\models\\trans\\DTransactionsModel',
'\\COREPOS\\pos\\lib\\models\\trans\\LocalTransModel',
'\\COREPOS\\pos\\lib\\models\\trans\\LocalTransArchiveModel',
'\\COREPOS\\pos\\lib\\models\\trans\\LocalTransTodayModel',
'\\COREPOS\\pos\\lib\\models\\trans\\LocalTempTransModel',
'\\COREPOS\\pos\\lib\\models\\trans\\SuspendedModel',
'\\COREPOS\\pos\\lib\\models\\trans\\TaxRatesModel',
'\\COREPOS\\pos\\lib\\models\\trans\\CouponAppliedModel',
'\\COREPOS\\pos\\lib\\models\\trans\\PaycardTransactionsModel',
'\\COREPOS\\pos\\lib\\models\\trans\\CapturedSignatureModel',
'\\COREPOS\\pos\\lib\\models\\trans\\EmvReceiptModel',
// placeholder,
'__LTT__',
// Views
'\\COREPOS\\pos\\lib\\models\\trans\\MemDiscountAddModel',
'\\COREPOS\\pos\\lib\\models\\trans\\MemDiscountRemoveModel',
'\\COREPOS\\pos\\lib\\models\\trans\\StaffDiscountAddModel',
'\\COREPOS\\pos\\lib\\models\\trans\\StaffDiscountRemoveModel',
'\\COREPOS\\pos\\lib\\models\\trans\\ScreenDisplayModel',
'\\COREPOS\\pos\\lib\\models\\trans\\TaxViewModel',
);
/**
Create translog tables and views
@param $db [SQLManager] database connection
@param $name [string] database name
@return [array] of error messages
*/
public static function createTransDBs($db, $name)
{
$errors = array();
$type = $db->dbmsName();
if (\CoreLocal::get('laneno') == 0) {
$errors[] = array(
'struct' => 'No structures created for lane #0',
'query' => 'None',
'details' => 'Zero is reserved for server',
);
return $errors;
}
/* lttsummary, lttsubtotals, and subtotals
* always get rebuilt to account for tax rate
* changes */
if (!function_exists('buildLTTViews')) {
include(__DIR__ . '/../buildLTTViews.php');
}
foreach (self::$trans_models as $class) {
if ($class == '__LTT__') {
$errors = buildLTTViews($db,$type,$errors);
continue;
}
$obj = new $class($db);
$errors[] = $obj->createIfNeeded($name);
}
/**
Not using models for receipt views. Hopefully many of these
can go away as deprecated.
*/
$lttR = "CREATE view rp_ltt_receipt as
select
l.description as description,
case
when voided = 5
then 'Discount'
when trans_status = 'M'
then 'Mbr special'
when trans_status = 'S'
then 'Staff special'
when unitPrice = 0.01
then ''
when scale <> 0 and quantity <> 0
then ".$db->concat('quantity', "' @ '", 'unitPrice','')."
when abs(itemQtty) > 1 and abs(itemQtty) > abs(quantity) and discounttype <> 3 and quantity = 1
then ".$db->concat('volume', "' / '", 'unitPrice','')."
when abs(itemQtty) > 1 and abs(itemQtty) > abs(quantity) and discounttype <> 3 and quantity <> 1
then ".$db->concat('quantity', "' @ '", 'volume', "' /'", 'unitPrice','')."
when abs(itemQtty) > 1 and discounttype = 3
then ".$db->concat('ItemQtty', "' / '", 'unitPrice','')."
when abs(itemQtty) > 1
then ".$db->concat('quantity', "' @ '", 'unitPrice','')."
when matched > 0
then '1 w/ vol adj'
else ''
end
as comment,
total,
case
when trans_status = 'V'
then 'VD'
when trans_status = 'R'
then 'RF'
when tax = 1 and foodstamp <> 0
then 'TF'
when tax = 1 and foodstamp = 0
then 'T'
when tax = 0 and foodstamp <> 0
then 'F'
WHEN (tax > 1 and foodstamp <> 0)
THEN ".$db->concat('SUBSTR(t.description,1,1)',"'F'",'')."
WHEN (tax > 1 and foodstamp = 0)
THEN SUBSTR(t.description,1,1)
when tax = 0 and foodstamp = 0
then ''
end
as Status,
trans_type,
unitPrice,
voided,
CASE
WHEN upc = 'DISCOUNT' THEN (
SELECT MAX(trans_id) FROM localtemptrans WHERE voided=3
)-1
WHEN trans_type = 'T' THEN trans_id+99999
ELSE trans_id
END AS trans_id,
l.emp_no,
l.register_no,
l.trans_no
from localtranstoday as l
left join taxrates as t
on l.tax = t.id
where voided <> 5 and UPC <> 'TAX'
AND trans_type <> 'L'";
self::dbStructureModify($db,'rp_ltt_receipt','DROP VIEW rp_ltt_receipt',$errors);
if(!$db->tableExists('rp_ltt_receipt',$name)){
self::dbStructureModify($db,'rp_ltt_receipt',$lttR,$errors);
}
$receiptV = "CREATE VIEW rp_receipt AS
select
case
when trans_type = 'T'
then ".$db->concat( "SUBSTR(".$db->concat('UPPER(TRIM(description))','space(44)','').", 1, 44)"
, "right(".$db->concat( 'space(8)', 'FORMAT(-1 * total, 2)','').", 8)"
, "right(".$db->concat( 'space(4)', 'status','').", 4)",'')."
when voided = 3
then ".$db->concat("SUBSTR(".$db->concat('description', 'space(30)','').", 1, 30)"
, 'space(9)'
, "'TOTAL'"
, 'right('.$db->concat( 'space(8)', 'FORMAT(unitPrice, 2)','').', 8)','')."
when voided = 2
then description
when voided = 4
then description
when voided = 6
then description
when voided = 7 or voided = 17
then ".$db->concat("SUBSTR(".$db->concat('description', 'space(30)','').", 1, 30)"
, 'space(14)'
, 'right('.$db->concat( 'space(8)', 'FORMAT(unitPrice, 2)','').', 8)'
, 'right('.$db->concat( 'space(4)', 'status','').', 4)','')."
else
".$db->concat("SUBSTR(".$db->concat('description', 'space(30)','').", 1, 30)"
, "' '"
, "SUBSTR(".$db->concat('comment', 'space(13)','').", 1, 13)"
, 'right('.$db->concat('space(8)', 'FORMAT(total, 2)','').', 8)'
, 'right('.$db->concat('space(4)', 'status','').', 4)','')."
end
as linetoprint,
emp_no,
register_no,
trans_no,
trans_id
from rp_ltt_receipt
order by trans_id";
if ($type == 'mssql') {
$receiptV = "CREATE VIEW rp_receipt AS
select top 100 percent
case
when trans_type = 'T'
then right((space(44) + upper(rtrim(Description))), 44)
+ right((space(8) + convert(varchar, (-1 * Total))), 8)
+ right((space(4) + status), 4)
when voided = 3
then left(Description + space(30), 30)
+ space(9)
+ 'TOTAL'
+ right(space(8) + convert(varchar, UnitPrice), 8)
when voided = 2
then description
when voided = 4
then description
when voided = 6
then description
when voided = 7 or voided = 17
then left(Description + space(30), 30)
+ space(14)
+ right(space(8) + convert(varchar, UnitPrice), 8)
+ right(space(4) + status, 4)
when sequence < 1000
then description
else
left(Description + space(30), 30)
+ ' '
+ left(Comment + space(13), 13)
+ right(space(8) + convert(varchar, Total), 8)
+ right(space(4) + status, 4)
end
as linetoprint,
sequence,
emp_no,
register_no,
trans_no,
trans_id
from rp_ltt_receipt
order by sequence";
} elseif($type == 'pdolite'){
$receiptV = str_replace('right(','str_right(',$receiptV);
$receiptV = str_replace('FORMAT(','ROUND(',$receiptV);
}
self::dbStructureModify($db,'rp_receipt','DROP VIEW rp_receipt',$errors);
if(!$db->tableExists('rp_receipt',$name)){
self::dbStructureModify($db,'rp_receipt',$receiptV,$errors);
}
return $errors;
}
public static function createMinServer($db, $name)
{
$errors = array();
$type = $db->dbmsName();
if (\CoreLocal::get('laneno') == 0) {
$errors[] = array(
'struct' => 'No structures created for lane #0',
'query' => 'None',
'details' => 'Zero is reserved for server',
);
return $errors;
}
$models = array(
'\COREPOS\pos\lib\models\trans\DTransactionsModel',
'\COREPOS\pos\lib\models\trans\SuspendedModel',
'\COREPOS\pos\lib\models\trans\PaycardTransactionsModel',
'\COREPOS\pos\lib\models\trans\CapturedSignatureModel',
);
foreach ($models as $class) {
$obj = new $class($db);
$errors[] = $obj->createIfNeeded($name);
}
$errors = self::createDlog($db, $name, $errors);
return $errors;
}
private static function createDlog($db, $name, $errors)
{
$dlogQ = "CREATE VIEW dlog AS
SELECT datetime AS tdate,
register_no,
emp_no,
trans_no,
upc,
CASE
WHEN trans_subtype IN ('CP','IC') OR upc LIKE '%000000052' THEN 'T'
WHEN upc = 'DISCOUNT' THEN 'S'
ELSE trans_type
END AS trans_type,
CASE
WHEN upc = 'MAD Coupon' THEN 'MA'
WHEN upc LIKE '%00000000052' THEN 'RR'
ELSE trans_subtype
END AS trans_subtype,
trans_status,
department,
quantity,
unitPrice,
total,
tax,
foodstamp,
ItemQtty,
memType,
staff,
numflag,
charflag,
card_no,
trans_id, "
. $db->concat(
$db->convert('emp_no','char'),"'-'",
$db->convert('register_no','char'),"'-'",
$db->convert('trans_no','char'),
'') . " AS trans_num
FROM dtransactions
WHERE trans_status NOT IN ('D','X','Z')
AND emp_no <> 9999
AND register_no <> 99";
if (!$db->table_exists("dlog",$name)) {
$errors = self::dbStructureModify($db,'dlog',$dlogQ,$errors);
}
return $errors;
}
public static function dbStructureModify($sql, $struct_name, $queries, &$errors=array())
{
if (!is_array($queries)) {
$queries = array($queries);
}
$error = array(
'struct' => $struct_name,
'error' => 0,
'query' => '',
'details' => '',
);
foreach ($queries as $query) {
$try = $sql->query($query);
if ($try === false){
$error['query'] .= $query . '; ';
// failing to drop a view is fine
if (!(stristr($query, "DROP ") && stristr($query,"VIEW "))) {
$error['error'] = 1;
$error['details'] = $sql->error() . '; ';
$error['important'] = true;
}
}
}
$errors[] = $error;
return $errors;
}
}
| gpl-2.0 |
thankgodr/schooldemo | NamesList.php | 14970 | <?php
#**************************************************************************
# openSIS is a free student information system for public and non-public
# schools from Open Solutions for Education, Inc. web: www.os4ed.com
#
# openSIS is web-based, open source, and comes packed with features that
# include student demographic info, scheduling, grade book, attendance,
# report cards, eligibility, transcripts, parent portal,
# student portal and more.
#
# Visit the openSIS web site at http://www.opensis.com to learn more.
# If you have question regarding this system or the license, please send
# an email to info@os4ed.com.
#
# This program is released under the terms of the GNU General Public License as
# published by the Free Software Foundation, version 2 of the License.
# See license.txt.
#
# 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/>.
#
#***************************************************************************************
error_reporting(0);
include("Data.php");
include("Warehouse.php");
$keyword = $_REQUEST['str'];
$block_id = $_REQUEST['block_id'];
if(User('PROFILE')=='student')
$user_id=UserStudentID();
else
$user_id=UserID();
$username_user=DBGet(DBQuery('SELECT USERNAME FROM login_authentication WHERE USER_ID='.$user_id.' AND PROFILE_ID='.User('PROFILE_ID')));
$username_user=$username_user[1]['USERNAME'];
if(User('PROFILE_ID')==0)
{
$tmp_q='';
$tmp_a=array();
$tmp_stu_arr=array();
$tmp_stf_arr=array();
$tmp_p_arr=array();
$tmp_q=DBGet(DBQuery('SELECT STUDENT_ID FROM students'));
foreach($tmp_q as $tmp_a)
{
$tmp_stu_arr[]=$tmp_a['STUDENT_ID'];
}
$tmp_q='';
$tmp_a=array();
$tmp_q=DBGet(DBQuery('SELECT STAFF_ID FROM staff'));
foreach($tmp_q as $tmp_a)
{
$tmp_stf_arr[]=$tmp_a['STAFF_ID'];
}
$tmp_q='';
$tmp_a=array();
$tmp_q=DBGet(DBQuery('SELECT STAFF_ID FROM people'));
foreach($tmp_q as $tmp_a)
{
$tmp_p_arr[]=$tmp_a['STAFF_ID'];
}
}
elseif(User('PROFILE_ID')!=0 && User('PROFILE')=='admin')
{
$schools=DBGet(DBQuery('SELECT GROUP_CONCAT(SCHOOL_ID) as SCHOOL_ID FROM staff_school_relationship WHERE STAFF_ID='.$user_id.' AND (START_DATE=\'0000-00-00\' OR START_DATE<=\''.date('Y-m-d').'\') AND (END_DATE=\'0000-00-00\' OR END_DATE IS NULL OR END_DATE>=\''.date('Y-m-d').'\') '));
$schools=$schools[1]['SCHOOL_ID'];
$tmp_q='';
$tmp_a=array();
$tmp_stu_arr=array();
$tmp_stf_arr=array();
$tmp_p_arr=array();
$tmp_q=DBGet(DBQuery('SELECT DISTINCT STUDENT_ID FROM student_enrollment WHERE SCHOOL_ID IN ('.$schools.') AND (START_DATE=\'0000-00-00\' OR START_DATE<=\''.date('Y-m-d').'\') AND (END_DATE=\'0000-00-00\' OR END_DATE IS NULL OR END_DATE>=\''.date('Y-m-d').'\') '));
foreach($tmp_q as $tmp_a)
{
$tmp_stu_arr[]=$tmp_a['STUDENT_ID'];
}
$tmp_q='';
$tmp_a=array();
$tmp_q=DBGet(DBQuery('SELECT DISTINCT STAFF_ID FROM staff_school_relationship WHERE SCHOOL_ID IN ('.$schools.') AND (START_DATE=\'0000-00-00\' OR START_DATE<=\''.date('Y-m-d').'\') AND (END_DATE=\'0000-00-00\' OR END_DATE IS NULL OR END_DATE>=\''.date('Y-m-d').'\') '));
foreach($tmp_q as $tmp_a)
{
$tmp_stf_arr[]=$tmp_a['STAFF_ID'];
}
$tmp_q='';
$tmp_a=array();
$tmp_q=DBGet(DBQuery('SELECT DISTINCT sjp.PERSON_ID FROM student_enrollment se,students_join_people sjp WHERE se.SCHOOL_ID IN ('.$schools.') AND (se.START_DATE=\'0000-00-00\' OR se.START_DATE<=\''.date('Y-m-d').'\') AND (se.END_DATE=\'0000-00-00\' OR se.END_DATE IS NULL OR se.END_DATE>=\''.date('Y-m-d').'\') AND se.STUDENT_ID=sjp.STUDENT_ID '));
foreach($tmp_q as $tmp_a)
{
$tmp_p_arr[]=$tmp_a['PERSON_ID'];
}
}
elseif(User('PROFILE')=='parent' || User('PROFILE')=='student')
{
$course_periods=DBGet(DBQuery('SELECT GROUP_CONCAT(course_period_id) as COURSE_PERIOD_ID FROM schedule WHERE STUDENT_ID='.UserStudentID()));
$course_periods=$course_periods[1]['COURSE_PERIOD_ID'];
$tmp_q='';
$tmp_a=array();
$tmp_stu_arr=array();
$tmp_stf_arr=array();
$tmp_p_arr=array();
if(User('PROFILE')=='parent')
{
$tmp_q=DBGet(DBQuery('SELECT DISTINCT se.STUDENT_ID FROM student_enrollment se,students_join_people sjp WHERE (se.START_DATE=\'0000-00-00\' OR se.START_DATE<=\''.date('Y-m-d').'\') AND (se.END_DATE=\'0000-00-00\' OR se.END_DATE IS NULL OR se.END_DATE>=\''.date('Y-m-d').'\') AND se.STUDENT_ID=sjp.STUDENT_ID AND sjp.PERSON_ID='.$user_id));
foreach($tmp_q as $tmp_a)
{
$tmp_stu_arr[]=$tmp_a['STUDENT_ID'];
}
}
if(User('PROFILE')=='student')
{
$tmp_q=DBGet(DBQuery('SELECT DISTINCT sjp.PERSON_ID FROM student_enrollment se,students_join_people sjp WHERE (se.START_DATE=\'0000-00-00\' OR se.START_DATE<=\''.date('Y-m-d').'\') AND (se.END_DATE=\'0000-00-00\' OR se.END_DATE IS NULL OR se.END_DATE>=\''.date('Y-m-d').'\') AND se.STUDENT_ID=sjp.STUDENT_ID AND sjp.STUDENT_ID='.$user_id));
foreach($tmp_q as $tmp_a)
{
$tmp_p_arr[]=$tmp_a['PERSON_ID'];
}
}
if($course_periods!='')
{
$tmp_q='';
$tmp_a=array();
$tmp_q=DBGet(DBQuery('SELECT TEACHER_ID,SECONDARY_TEACHER_ID FROM course_periods WHERE COURSE_PERIOD_ID IN ('.$course_periods.') '));
foreach($tmp_q as $tmp_a)
{
$tmp_stf_arr[]=$tmp_a['TEACHER_ID'];
if($tmp_a['SECONDARY_TEACHER_ID']!='')
$tmp_stf_arr[]=$tmp_a['SECONDARY_TEACHER_ID'];
}
}
$tmp_q='';
$tmp_a=array();
$tmp_q=DBGet(DBQuery('SELECT s.STAFF_ID FROM staff s,staff_school_relationship ssr WHERE PROFILE=\'admin\' AND ssr.STAFF_ID=s.STAFF_ID AND (ssr.START_DATE=\'0000-00-00\' OR ssr.START_DATE<=\''.date('Y-m-d').'\') AND (ssr.END_DATE=\'0000-00-00\' OR ssr.END_DATE IS NULL OR ssr.END_DATE>=\''.date('Y-m-d').'\') AND ssr.SCHOOL_ID='.UserSchool()));
foreach($tmp_q as $tmp_a)
{
$tmp_stf_arr[]=$tmp_a['STAFF_ID'];
}
}
elseif(User('PROFILE')=='teacher')
{
$schools=DBGet(DBQuery('SELECT GROUP_CONCAT(SCHOOL_ID) as SCHOOL_ID FROM staff_school_relationship WHERE STAFF_ID='.$user_id.' AND (START_DATE=\'0000-00-00\' OR START_DATE<=\''.date('Y-m-d').'\') AND (END_DATE=\'0000-00-00\' OR END_DATE IS NULL OR END_DATE>=\''.date('Y-m-d').'\') '));
$schools=$schools[1]['SCHOOL_ID'];
$course_periods=DBGet(DBQuery('SELECT GROUP_CONCAT(course_period_id) as COURSE_PERIOD_ID FROM course_periods WHERE TEACHER_ID='.$user_id.' OR SECONDARY_TEACHER_ID='.$user_id));
$course_periods=$course_periods[1]['COURSE_PERIOD_ID'];
$tmp_q='';
$tmp_a=array();
$tmp_stu_arr=array();
$tmp_stf_arr=array();
$tmp_p_arr=array();
if($course_periods!='')
{
$tmp_q=DBGet(DBQuery('SELECT DISTINCT se.STUDENT_ID FROM student_enrollment se,schedule s WHERE (se.START_DATE=\'0000-00-00\' OR se.START_DATE<=\''.date('Y-m-d').'\') AND (se.END_DATE=\'0000-00-00\' OR se.END_DATE IS NULL OR se.END_DATE>=\''.date('Y-m-d').'\') AND se.STUDENT_ID=s.STUDENT_ID AND s.COURSE_PERIOD_ID IN ('.$course_periods.')'));
foreach($tmp_q as $tmp_a)
{
$tmp_stu_arr[]=$tmp_a['STUDENT_ID'];
$tmp_qa=DBGet(DBQuery('SELECT DISTINCT PERSON_ID FROM students_join_people WHERE STUDENT_ID='.$tmp_a['STUDENT_ID']));
foreach($tmp_qa as $tmp_aa)
{
$tmp_p_arr[]=$tmp_aa['PERSON_ID'];
}
}
}
$tmp_q='';
$tmp_a=array();
$tmp_q=DBGet(DBQuery('SELECT s.STAFF_ID FROM staff s,staff_school_relationship ssr WHERE PROFILE=\'admin\' AND ssr.STAFF_ID=s.STAFF_ID AND (ssr.START_DATE=\'0000-00-00\' OR ssr.START_DATE<=\''.date('Y-m-d').'\') AND (ssr.END_DATE=\'0000-00-00\' OR ssr.END_DATE IS NULL OR ssr.END_DATE>=\''.date('Y-m-d').'\') AND ssr.SCHOOL_ID IN ('.$schools.')'));
foreach($tmp_q as $tmp_a)
{
$tmp_stf_arr[]=$tmp_a['STAFF_ID'];
}
}
if($keyword=="")
echo "";
else
{
$sql_staff="SELECT * FROM login_authentication,staff WHERE login_authentication.user_id=staff.staff_id and first_name LIKE '$keyword%' and username IS NOT NULL and login_authentication.profile_id NOT IN(3,4) AND staff.staff_id in (".implode(',',$tmp_stf_arr).") ORDER BY last_name";
$sql_student="SELECT * FROM login_authentication,students WHERE login_authentication.user_id=students.student_id and first_name LIKE '$keyword%' and username IS NOT NULL and login_authentication.profile_id=3 ".(count($tmp_stu_arr)>0?" AND students.student_id IN (".implode(',',$tmp_stu_arr).")":"")." ORDER BY last_name";
$sql_people="SELECT * FROM login_authentication,people WHERE login_authentication.user_id=people.staff_id and first_name LIKE '$keyword%' and username IS NOT NULL and login_authentication.profile_id=4 ".(count($tmp_p_arr)>0?" AND people.staff_id IN (".implode(',',$tmp_p_arr).")":"")." ORDER BY last_name";
$result_staff = DBGet(DBQuery($sql_staff));
$result_student = DBGet(DBQuery($sql_student));
$result_people = DBGet(DBQuery($sql_people));
if(count($result_staff)>0)
{
foreach($result_staff as $row)
{
$str = strtolower($row['LAST_NAME'].' '.$row['FIRST_NAME'].','.$row['USERNAME']);
if(trim($row['USERNAME']!=""))
echo '<a id="search'.$row['STAFF_ID'].'" onclick="a(\''.$row['USERNAME'].'\',\''.$block_id.'\')">'.$str.'</a><br>';
}
}
else
echo "";
if(count($result_student)>0 && count($tmp_stu_arr)>0)
{
foreach($result_student as $row_student)
{
$str = strtolower($row_student['LAST_NAME'].' '.$row_student['FIRST_NAME'].','.$row_student['USERNAME']);
if(trim($row_student['USERNAME']!=""))
echo '<a id="search'.$row_student['STUDENT_ID'].'" onclick="a(\''.$row_student['USERNAME'].'\',\''.$block_id.'\')">'.$str.'</a><br>';
}
}
else
echo "";
if(count($result_people)>0 && count($tmp_p_arr)>0)
{
foreach($result_people as $row_people)
{
$str = strtolower($row_people['LAST_NAME'].' '.$row_people['FIRST_NAME'].','.$row_people['USERNAME']);
if(trim($row_people['USERNAME']!=""))
echo '<a id="search'.$row_people['STAFF_ID'].'" onclick="a(\''.$row_people['USERNAME'].'\',\''.$block_id.'\')">'.$str.'</a><br>';
}
}
else
echo "";
}
$pos=strpos($keyword,',');
$lastpos=strrpos($keyword,',');
$str1=substr($keyword,$pos+1,strlen($keyword));
$str2=substr($keyword,$lastpos+1,strlen($keyword));
if($str2!="")
{
if($pos!=0 || $lastpos!=0)
{
$sql_staff="SELECT * FROM login_authentication,staff WHERE login_authentication.user_id=staff.staff_id and (first_name LIKE '$str1%' or first_name LIKE '$str2%') and username IS NOT NULL and login_authentication.profile_id NOT IN(3,4) AND staff.staff_id in (".implode(',',$tmp_stf_arr).") ORDER BY last_name";
$sql_student="SELECT * FROM login_authentication,students WHERE login_authentication.user_id=students.student_id and (first_name LIKE '$str1%' or first_name LIKE '$str2%') and username IS NOT NULL and login_authentication.profile_id=3 ".(count($tmp_stu_arr)>0?" AND students.student_id IN (".implode(',',$tmp_stu_arr).")":"")." ORDER BY last_name";
$sql_people="SELECT * FROM login_authentication,people WHERE login_authentication.user_id=people.staff_id and (first_name LIKE '$str1%' or first_name LIKE '$str2%') and username IS NOT NULL and login_authentication.profile_id=4 ".(count($tmp_p_arr)>0?" AND people.staff_id IN (".implode(',',$tmp_p_arr).")":"")." ORDER BY last_name";
$result_staff = DBGet(DBQuery($sql_staff));
$result_student = DBGet(DBQuery($sql_student));
$result_people = DBGet(DBQuery($sql_people));
if(count($result_staff)>0)
{
foreach($result_staff as $row)
{
$str = strtolower($row['LAST_NAME'].' '.$row['FIRST_NAME'].','.$row['USERNAME']);
$newpos=$lastpos+1;
if(trim($row['USERNAME']!=""))
echo '<a id="search'.$row['STAFF_ID'].'" onclick="b(\''.$newpos.'\',\''.$row['USERNAME'].'\',\''.$block_id.'\');">'.$str.'</a><br>';
}
}
else
echo "";
if(count($result_student)>0 && count($tmp_stu_arr)>0)
{
foreach($result_student as $row_student)
{
$str = strtolower($row_student['LAST_NAME'].' '.$row_student['FIRST_NAME'].','.$row_student['USERNAME']);
$newpos=$lastpos+1;
if(trim($row_student['USERNAME']!=""))
echo '<a id="search'.$row_student['STUDENT_ID'].'" onclick="b(\''.$newpos.'\',\''.$row_student['USERNAME'].'\',\''.$block_id.'\')">'.$str.'</a><br>';
}
}
else
echo "";
if(count($result_people)>0 && count($tmp_p_arr)>0)
{
foreach($result_people as $row_people)
{
$str = strtolower($row_people['LAST_NAME'].' '.$row_people['FIRST_NAME'].','.$row_people['USERNAME']);
$newpos=$lastpos+1;
if(trim($row_people['USERNAME']!=""))
echo '<a id="search'.$row_people['STUDENT_ID'].'" onclick="b(\''.$newpos.'\',\''.$row_people['USERNAME'].'\',\''.$block_id.'\')">'.$str.'</a><br>';
}
}
else
echo "";
}
}
else
echo "";
$group_id=DBGet(DBQuery("select distinct group_id,group_name from mail_group where group_name LIKE '$keyword%' AND user_name='".$username_user."' "));
if(count($group_id)>0)
{
foreach($group_id as $row)
{
$str=strtolower($row['GROUP_NAME']);
$id=$row['GROUP_ID'];
$group=DBGet(DBQuery("select * from mail_groupmembers where group_id=$id"));
foreach($group as $r)
{
$name[]=$r['USER_NAME'];
}
if(!empty($name) && count($name)>0)
$username=implode(',',$name);
echo '<a id="search'.$row['GROUP_ID'].'" onclick="a(\''.$str.'\',\''.$block_id.'\')">'.$str.'</a><br>';
}
}
else {
echo "";
}
?>
| gpl-2.0 |
samanthavandapuye/lostfit | wp-content/plugins/groups-woocommerce/lib/admin/class-groups-ws-admin.php | 7843 | <?php
/**
* class-groups-ws-admin.php
*
* Copyright (c) "kento" Karim Rahimpur www.itthinx.com
*
* This code is provided subject to the license granted.
* Unauthorized use and distribution is prohibited.
* See COPYRIGHT.txt and LICENSE.txt
*
* 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.
*
* This header and all notices must be kept intact.
*
* @author Karim Rahimpur
* @package groups-woocommerce
* @since groups-woocommerce 1.2.0
*/
/**
* Admin section for Groups integration.
*/
class Groups_WS_Admin {
const NONCE = 'groups-woocommerce-admin-nonce';
const MEMBERSHIP_ORDER_STATUS = GROUPS_WS_MEMBERSHIP_ORDER_STATUS;
const SHOW_DURATION = GROUPS_WS_SHOW_DURATION;
const FORCE_REGISTRATION = GROUPS_WS_FORCE_REGISTRATION;
const SHOW_IN_USER_PROFILE = GROUPS_WS_SHOW_IN_USER_PROFILE;
const SHOW_IN_EDIT_PROFILE = GROUPS_WS_SHOW_IN_EDIT_PROFILE;
/**
* Admin setup.
*/
public static function init() {
add_action( 'admin_menu', array( __CLASS__, 'admin_menu' ), 40 );
}
/**
* Adds the admin section.
*/
public static function admin_menu() {
$admin_page = add_submenu_page(
'woocommerce',
__( 'Groups' ),
__( 'Groups' ),
GROUPS_ADMINISTER_OPTIONS,
'groups_woocommerce',
array( __CLASS__, 'groups_woocommerce' )
);
// add_action( 'admin_print_scripts-' . $admin_page, array( __CLASS__, 'admin_print_scripts' ) );
// add_action( 'admin_print_styles-' . $admin_page, array( __CLASS__, 'admin_print_styles' ) );
}
/**
* Renders the admin section.
*/
public static function groups_woocommerce() {
if ( !current_user_can( GROUPS_ADMINISTER_OPTIONS ) ) {
wp_die( __( 'Access denied.', GROUPS_WS_PLUGIN_DOMAIN ) );
}
$options = get_option( 'groups-woocommerce', null );
if ( $options === null ) {
if ( add_option( 'groups-woocommerce', array(), null, 'no' ) ) {
$options = get_option( 'groups-woocommerce' );
}
}
if ( isset( $_POST['submit'] ) ) {
if ( wp_verify_nonce( $_POST[self::NONCE], 'set' ) ) {
$order_status = isset( $_POST[self::MEMBERSHIP_ORDER_STATUS] ) ? $_POST[self::MEMBERSHIP_ORDER_STATUS] : 'completed';
switch ( $order_status ) {
case 'completed' :
case 'processing' :
break;
default :
$order_status = GROUPS_WS_DEFAULT_MEMBERSHIP_ORDER_STATUS;
}
$options[self::MEMBERSHIP_ORDER_STATUS] = $order_status;
$options[GROUPS_WS_REMOVE_ON_HOLD] = isset( $_POST[GROUPS_WS_REMOVE_ON_HOLD] );
$options[self::SHOW_DURATION] = isset( $_POST[self::SHOW_DURATION] );
$options[self::FORCE_REGISTRATION] = isset( $_POST[self::FORCE_REGISTRATION] );
$options[self::SHOW_IN_USER_PROFILE] = isset( $_POST[self::SHOW_IN_USER_PROFILE] );
$options[self::SHOW_IN_EDIT_PROFILE] = isset( $_POST[self::SHOW_IN_EDIT_PROFILE] );
update_option( 'groups-woocommerce', $options );
}
}
$order_status = isset( $options[self::MEMBERSHIP_ORDER_STATUS] ) ? $options[self::MEMBERSHIP_ORDER_STATUS] : GROUPS_WS_DEFAULT_MEMBERSHIP_ORDER_STATUS;
$remove_on_hold = isset( $options[GROUPS_WS_REMOVE_ON_HOLD] ) ? $options[GROUPS_WS_REMOVE_ON_HOLD] : GROUPS_WS_DEFAULT_REMOVE_ON_HOLD;
$show_duration = isset( $options[self::SHOW_DURATION] ) ? $options[self::SHOW_DURATION] : GROUPS_WS_DEFAULT_SHOW_DURATION;
$force_registration = isset( $options[self::FORCE_REGISTRATION] ) ? $options[self::FORCE_REGISTRATION] : GROUPS_WS_DEFAULT_FORCE_REGISTRATION;
$show_in_user_profile = isset( $options[self::SHOW_IN_USER_PROFILE] ) ? $options[self::SHOW_IN_USER_PROFILE] : GROUPS_WS_DEFAULT_SHOW_IN_USER_PROFILE;
$show_in_edit_profile = isset( $options[self::SHOW_IN_EDIT_PROFILE] ) ? $options[self::SHOW_IN_EDIT_PROFILE] : GROUPS_WS_DEFAULT_SHOW_IN_EDIT_PROFILE;
echo '<div class="groups-woocommerce">';
echo '<h2>' . __( 'Groups', GROUPS_PLUGIN_DOMAIN ) . '</h2>';
echo
'<form action="" name="options" method="post">' .
'<div>' .
'<h3>' . __( 'Group membership', GROUPS_WS_PLUGIN_DOMAIN ) . '</h3>' .
'<h4>' . __( 'Order Status', GROUPS_WS_PLUGIN_DOMAIN ) . '</h4>' .
'<p>' .
'<label>' . __( 'Add users to or remove from groups as early as the order is ...', GROUPS_WS_PLUGIN_DOMAIN ) .
'<select name="' . self::MEMBERSHIP_ORDER_STATUS . '">' .
'<option value="completed" ' . ( $order_status == 'completed' ? ' selected="selected" ' : '' ) . '>' . __( 'Completed', GROUPS_WS_PLUGIN_DOMAIN ) . '</option>' .
'<option value="processing" ' . ( $order_status == 'processing' ? ' selected="selected" ' : '' ) . '>' . __( 'Processing', GROUPS_WS_PLUGIN_DOMAIN ) . '</option>' .
'</select>' .
'</label>' .
'</p>' .
'<p class="description">' . __( 'Note that users will always be added to or removed from groups when an order is completed.', GROUPS_WS_PLUGIN_DOMAIN ) . '</p>' .
'<p class="description">' . __( 'This setting does not apply to subscriptions.', GROUPS_WS_PLUGIN_DOMAIN ) . '</p>' .
'<h4>' . __( 'Subscription Status', GROUPS_WS_PLUGIN_DOMAIN ) . '</h4>' .
'<p>' .
'<label>' .
sprintf( '<input name="%s" type="checkbox" %s />', GROUPS_WS_REMOVE_ON_HOLD, $remove_on_hold ? ' checked="checked" ' : '' ) .
' ' .
__( 'Remove users from groups when a subscription is on hold; add them back when a subscription is reactivated.', GROUPS_WS_PLUGIN_DOMAIN ) .
'</label>' .
'</p>' .
'<p class="description">' . __( 'This setting only applies to subscriptions.', GROUPS_WS_PLUGIN_DOMAIN ) . '</p>' .
'<h3>' . __( 'Durations', GROUPS_WS_PLUGIN_DOMAIN ) . '</h3>' .
'<p>' .
'<label>' .
sprintf( '<input name="show_duration" type="checkbox" %s />', $show_duration ? ' checked="checked" ' : '' ) .
' ' .
__( 'Show durations', GROUPS_WS_PLUGIN_DOMAIN ) .
'</label>' .
'</p>' .
'<p class="description">' . __( 'Modifies the way product prices are displayed to show durations.', GROUPS_WS_PLUGIN_DOMAIN ) . '</p>' .
'<h3>' . __( 'Force registration', GROUPS_WS_PLUGIN_DOMAIN ) . '</h3>' .
'<p>' .
'<label>' .
'<input type="checkbox" ' . ( $force_registration ? ' checked="checked" ' : '' ) . ' name="' . GROUPS_WS_FORCE_REGISTRATION . '" />' .
' ' .
__( 'Force registration on checkout', GROUPS_WS_PLUGIN_DOMAIN ) .
'</label>' .
'</p>' .
'<p class="description">' .
__( 'Force registration on checkout when a subscription or a product which relates to groups is in the cart. The login form will also be shown to allow existing users to log in.', GROUPS_WS_PLUGIN_DOMAIN ) .
'</p>' .
'<h3>' . __( 'User profiles', GROUPS_WS_PLUGIN_DOMAIN ) . '</h3>' .
'<p>' .
'<label>' .
'<input type="checkbox" ' . ( $show_in_user_profile ? ' checked="checked" ' : '' ) . ' name="' . self::SHOW_IN_USER_PROFILE . '" />' .
' ' .
__( 'Show membership info in user profiles', GROUPS_WS_PLUGIN_DOMAIN ) .
'</label>' .
'</p>' .
'<p>' .
'<label>' .
'<input type="checkbox" ' . ( $show_in_edit_profile ? ' checked="checked" ' : '' ) . ' name="' . self::SHOW_IN_EDIT_PROFILE . '" />' .
' ' .
__( 'Show membership info when editing user profiles', GROUPS_WS_PLUGIN_DOMAIN ) .
'</label>' .
'</p>' .
'<p>' .
wp_nonce_field( 'set', self::NONCE, true, false ) .
'<input class="button" type="submit" name="submit" value="' . __( 'Save', GROUPS_WS_PLUGIN_DOMAIN ) . '"/>' .
'</p>' .
'</div>' .
'</form>';
echo '</div>'; // .groups-woocommerce
if ( GROUPS_WS_LOG ) {
$crons = _get_cron_array();
echo '<h2>Cron</h2>';
echo '<pre>';
echo var_export( $crons, true );
echo '</pre>';
}
}
}
Groups_WS_Admin::init();
| gpl-2.0 |
RaphaelFreire/java | src/model/VarArgs2.java | 654 | package model;
/**
* @author raphaelmachadofreire
* Detalhe sobre métodos e classes
* Utilizando varargs com argumentos padrão.
* Capítulo 7 - Página 157
*/
public class VarArgs2 {
//Aqui, msg é um parâmetro normal e v é um parâmetro varargs.
static void vaTest(String msg, int...v){
System.out.print(msg + v.length + " Conteúdo; ");
for(int x:v)
System.out.print(x + " ");
System.out.println();
}
public static void main(String[] args){
vaTest("Um varargs: ", 10);
vaTest("Três varargs: ", 1, 2, 3);
vaTest("Nenhum varargs: ");
}
}
| gpl-2.0 |
glemaitre/protoclass | protoclass/preprocessing/tests/test_rician_normalization.py | 20072 | """Test the Rician normalization."""
import os
import numpy as np
from numpy.testing import assert_raises
from numpy.testing import assert_equal
from numpy.testing import assert_warns
from numpy.testing import assert_almost_equal
from numpy.testing import assert_array_equal
from numpy.testing import assert_array_almost_equal
from protoclass.data_management import DCEModality
from protoclass.data_management import T2WModality
from protoclass.data_management import GTModality
from protoclass.preprocessing import RicianNormalization
DECIMAL_PRECISON = 5
def test_rn_init_wrong_base_modality():
""" Test either if an error is raised when a wrong base modality
is given. """
# Check that an error is raised with incompatible type of
# base modality
assert_raises(ValueError, RicianNormalization, DCEModality())
def test_rn_init_wrong_type_params():
""" Test either if an error is raised when the type of params
is wrong. """
# Check that an error is raised with incompatible type of
# params
assert_raises(ValueError, RicianNormalization, T2WModality(), 1)
def test_rn_init_string_unknown():
""" Test either if an error is raised when the string in the params
is unknown. """
# Force the params parameter to be unknown with a string type
assert_raises(ValueError, RicianNormalization, T2WModality(), 'None')
def test_rn_init_dict_wrong_dict():
""" Test either if an error is raised when mu and sigma are not
present in the dictionary. """
# Create a dictionary with unknown variable
params = {'None': 1., 'Stupid': 2.}
assert_raises(ValueError, RicianNormalization, T2WModality(), params)
def test_rn_init_dict_not_float():
""" Test either if an error is raised if mu and sigma are not of
type float. """
# Create a dictionary with unknown variable
params = {'b': 'cccc', 'off': 'bbbb', 'sigma': 'aaaa'}
assert_raises(ValueError, RicianNormalization, T2WModality(), params)
def test_rn_init_dict_extra_param():
""" Test either if an error is raised when an unknown key is given
additionaly inside the dictionary. """
# Create a dictionary with unknown variable
params = {'b': 10., 'off': 1., 'sigma': 3., 'None': 1.}
assert_raises(ValueError, RicianNormalization, T2WModality(), params)
def test_rn_init_auto():
""" Test the constructor with params equal to 'auto'. """
# Create the object
params = 'auto'
obj = RicianNormalization(T2WModality(), params)
# Check some members variable from the object
assert_equal(obj.is_fitted_, False)
assert_equal(obj.params, params)
assert_equal(obj.fit_params_, None)
def test_rn_init_dict():
""" Test the constructor with params equal to a given dict. """
# Create the object
params = {'b': .1, 'off': 1., 'sigma': 3.}
obj = RicianNormalization(T2WModality(), params)
# Check some members variable from the object
assert_equal(obj.is_fitted_, False)
assert_equal(cmp(obj.fit_params_, params), 0)
def test_rn_fit_wrong_modality():
""" Test either if an error is raised in case that a wrong
modality is provided for fitting. """
# Create a DCEModality object
currdir = os.path.dirname(os.path.abspath(__file__))
path_data_dce = os.path.join(currdir, 'data', 'dce')
dce_mod = DCEModality()
dce_mod.read_data_from_path(path_data=path_data_dce)
# Create the Rician normalization object
rician_norm = RicianNormalization(T2WModality())
# Try to make the fitting with another based modality
assert_raises(ValueError, rician_norm.fit, dce_mod)
def test_rn_fit_modality_not_read():
""" Test either if an error is raised when the data from the
modality where not read. """
# Create a T2WModality object
currdir = os.path.dirname(os.path.abspath(__file__))
path_data_t2w = os.path.join(currdir, 'data', 't2w')
t2w_mod = T2WModality(path_data_t2w)
# Create the Rician normalization object
rician_norm = RicianNormalization(T2WModality())
# Call the fitting before to have read the data
assert_raises(ValueError, rician_norm.fit, t2w_mod)
def test_rn_fit_no_gt_1_cat():
""" Test either if a warning is raised to inform that no
ground-truth has been provided. """
# Create a T2WModality object
currdir = os.path.dirname(os.path.abspath(__file__))
path_data_t2w = os.path.join(currdir, 'data', 't2w')
t2w_mod = T2WModality(path_data_t2w)
t2w_mod.read_data_from_path()
# Create the Rician normalization object
rician_norm = RicianNormalization(T2WModality())
# Call the fitting before to have read the data
assert_warns(UserWarning, rician_norm.fit, t2w_mod, None, 'prostate')
assert_almost_equal(rician_norm.fit_params_['b'], 0.17064341621605977,
decimal=DECIMAL_PRECISON)
assert_almost_equal(rician_norm.fit_params_['off'], 0.0,
decimal=DECIMAL_PRECISON)
assert_almost_equal(rician_norm.fit_params_['sigma'], 0.15609648503515802,
decimal=DECIMAL_PRECISON)
def test_rn_fit_no_cat():
""" Test either if an error is raised when the category of the
ground-truth is not provided and ground-truth is. """
# Create a T2WModality object
currdir = os.path.dirname(os.path.abspath(__file__))
path_data_t2w = os.path.join(currdir, 'data', 't2w')
t2w_mod = T2WModality(path_data_t2w)
t2w_mod.read_data_from_path()
# Create the GTModality object
path_data_gt = os.path.join(currdir, 'data', 'gt_folders')
path_data_gt_list = [os.path.join(path_data_gt, 'prostate'),
os.path.join(path_data_gt, 'pz'),
os.path.join(path_data_gt, 'cg'),
os.path.join(path_data_gt, 'cap')]
label_gt = ['prostate', 'pz', 'cg', 'cap']
gt_mod = GTModality()
gt_mod.read_data_from_path(cat_gt=label_gt, path_data=path_data_gt_list)
# Try to normalize without saying which label to use
rician_norm = RicianNormalization(T2WModality())
assert_raises(ValueError, rician_norm.fit, t2w_mod, gt_mod)
def test_rn_fit_gt_not_read():
""" Test either if the ground-truth is read or not. """
# Create a T2WModality object
currdir = os.path.dirname(os.path.abspath(__file__))
path_data_t2w = os.path.join(currdir, 'data', 't2w')
t2w_mod = T2WModality(path_data_t2w)
t2w_mod.read_data_from_path()
# Create the GTModality object
path_data_gt = os.path.join(currdir, 'data', 'gt_folders')
path_data_gt_list = [os.path.join(path_data_gt, 'prostate'),
os.path.join(path_data_gt, 'pz'),
os.path.join(path_data_gt, 'cg'),
os.path.join(path_data_gt, 'cap')]
label_gt = ['prostate', 'pz', 'cg', 'cap']
gt_mod = GTModality()
# Try to normalize without saying which label to use
rician_norm = RicianNormalization(T2WModality())
assert_raises(ValueError, rician_norm.fit, t2w_mod, gt_mod, label_gt[0])
def test_rn_fit_wrong_gt():
""" Test either if an error is raised when the wrong class is provided for
the ground-truth. """
# Create a T2WModality object
currdir = os.path.dirname(os.path.abspath(__file__))
path_data_t2w = os.path.join(currdir, 'data', 't2w')
t2w_mod = T2WModality(path_data_t2w)
t2w_mod.read_data_from_path()
# Create the GTModality object
path_data_gt = os.path.join(currdir, 'data', 'gt_folders')
path_data_gt_list = [os.path.join(path_data_gt, 'prostate'),
os.path.join(path_data_gt, 'pz'),
os.path.join(path_data_gt, 'cg'),
os.path.join(path_data_gt, 'cap')]
label_gt = ['prostate', 'pz', 'cg', 'cap']
gt_mod = GTModality()
gt_mod.read_data_from_path(cat_gt=label_gt, path_data=path_data_gt_list)
rician_norm = RicianNormalization(T2WModality())
assert_raises(ValueError, rician_norm.fit, t2w_mod, t2w_mod, label_gt[0])
def test_rn_wrong_label_gt():
""" Test either if an error is raised when the category label asked was
not load by the GTModality. """
# Create a T2WModality object
currdir = os.path.dirname(os.path.abspath(__file__))
path_data_t2w = os.path.join(currdir, 'data', 't2w')
t2w_mod = T2WModality(path_data_t2w)
t2w_mod.read_data_from_path()
# Create the GTModality object
path_data_gt = os.path.join(currdir, 'data', 'gt_folders')
path_data_gt_list = [os.path.join(path_data_gt, 'prostate'),
os.path.join(path_data_gt, 'pz'),
os.path.join(path_data_gt, 'cg'),
os.path.join(path_data_gt, 'cap')]
label_gt = ['prostate', 'pz', 'cg', 'cap']
gt_mod = GTModality()
gt_mod.read_data_from_path(cat_gt=label_gt, path_data=path_data_gt_list)
rician_norm = RicianNormalization(T2WModality())
assert_raises(ValueError, rician_norm.fit, t2w_mod, gt_mod, 'None')
def test_rn_wrong_size_gt():
""" Test either if an error is raised when the size of the ground-truth
is different from the size of the base modality. """
# Create a T2WModality object
currdir = os.path.dirname(os.path.abspath(__file__))
path_data_t2w = os.path.join(currdir, 'data', 't2w')
t2w_mod = T2WModality(path_data_t2w)
t2w_mod.read_data_from_path()
# Create the GTModality object
path_data_gt = os.path.join(currdir, 'data', 'gt_folders')
path_data_gt_list = [os.path.join(path_data_gt, 'prostate'),
os.path.join(path_data_gt, 'pz'),
os.path.join(path_data_gt, 'cg'),
os.path.join(path_data_gt, 'cap')]
label_gt = ['prostate', 'pz', 'cg', 'cap']
gt_mod = GTModality()
gt_mod.read_data_from_path(cat_gt=label_gt, path_data=path_data_gt_list)
# Change the size of the data of the modality
t2w_mod.data_ = t2w_mod.data_[:-1, :, :]
rician_norm = RicianNormalization(T2WModality())
assert_raises(ValueError, rician_norm.fit, t2w_mod, gt_mod, label_gt[0])
def test_rn_fit_wrong_params():
""" Test either if an error is raised when the params change just before
fitting. """
# Create a T2WModality object
currdir = os.path.dirname(os.path.abspath(__file__))
path_data_t2w = os.path.join(currdir, 'data', 't2w')
t2w_mod = T2WModality(path_data_t2w)
t2w_mod.read_data_from_path()
# Create the GTModality object
path_data_gt = os.path.join(currdir, 'data', 'gt_folders')
path_data_gt_list = [os.path.join(path_data_gt, 'prostate'),
os.path.join(path_data_gt, 'pz'),
os.path.join(path_data_gt, 'cg'),
os.path.join(path_data_gt, 'cap')]
label_gt = ['prostate', 'pz', 'cg', 'cap']
gt_mod = GTModality()
gt_mod.read_data_from_path(cat_gt=label_gt, path_data=path_data_gt_list)
rician_norm = RicianNormalization(T2WModality())
rician_norm.params = 'None'
assert_raises(ValueError, rician_norm.fit, t2w_mod, gt_mod, label_gt[0])
def test_rn_fit_wt_gt():
""" Test the fitting routine without ground-truth. """
# Create a T2WModality object
currdir = os.path.dirname(os.path.abspath(__file__))
path_data_t2w = os.path.join(currdir, 'data', 't2w')
t2w_mod = T2WModality(path_data_t2w)
t2w_mod.read_data_from_path()
rician_norm = RicianNormalization(T2WModality())
rician_norm.fit(t2w_mod)
assert_almost_equal(rician_norm.fit_params_['b'], 0.17064341621605977,
decimal=DECIMAL_PRECISON)
assert_almost_equal(rician_norm.fit_params_['off'], 0.0,
decimal=DECIMAL_PRECISON)
assert_almost_equal(rician_norm.fit_params_['sigma'], 0.15609648503515802,
decimal=DECIMAL_PRECISON)
def test_rn_fit_auto():
""" Test the fitting routine with auto parameters. """
# Create a T2WModality object
currdir = os.path.dirname(os.path.abspath(__file__))
path_data_t2w = os.path.join(currdir, 'data', 't2w')
t2w_mod = T2WModality(path_data_t2w)
t2w_mod.read_data_from_path()
# Create the GTModality object
path_data_gt = os.path.join(currdir, 'data', 'gt_folders')
path_data_gt_list = [os.path.join(path_data_gt, 'prostate'),
os.path.join(path_data_gt, 'pz'),
os.path.join(path_data_gt, 'cg'),
os.path.join(path_data_gt, 'cap')]
label_gt = ['prostate', 'pz', 'cg', 'cap']
gt_mod = GTModality()
gt_mod.read_data_from_path(cat_gt=label_gt, path_data=path_data_gt_list)
rician_norm = RicianNormalization(T2WModality())
rician_norm.fit(t2w_mod, gt_mod, label_gt[0])
assert_almost_equal(rician_norm.fit_params_['b'], 1.4463929678319398,
decimal=DECIMAL_PRECISON)
assert_almost_equal(rician_norm.fit_params_['off'], 0.12668917318976813,
decimal=DECIMAL_PRECISON)
assert_almost_equal(rician_norm.fit_params_['sigma'], 0.10331905081688209,
decimal=DECIMAL_PRECISON)
def test_rn_fit_fix_params():
""" Test the fitting routine with fixed parameters. """
# Create a T2WModality object
currdir = os.path.dirname(os.path.abspath(__file__))
path_data_t2w = os.path.join(currdir, 'data', 't2w')
t2w_mod = T2WModality(path_data_t2w)
t2w_mod.read_data_from_path()
# Create the GTModality object
path_data_gt = os.path.join(currdir, 'data', 'gt_folders')
path_data_gt_list = [os.path.join(path_data_gt, 'prostate'),
os.path.join(path_data_gt, 'pz'),
os.path.join(path_data_gt, 'cg'),
os.path.join(path_data_gt, 'cap')]
label_gt = ['prostate', 'pz', 'cg', 'cap']
gt_mod = GTModality()
gt_mod.read_data_from_path(cat_gt=label_gt, path_data=path_data_gt_list)
params = {'b': 200., 'off': 7., 'sigma': 80.}
rician_norm = RicianNormalization(T2WModality(), params=params)
rician_norm.fit(t2w_mod, gt_mod, label_gt[0])
assert_almost_equal(rician_norm.fit_params_['b'], 1.4463929678319398,
decimal=DECIMAL_PRECISON)
assert_almost_equal(rician_norm.fit_params_['off'], 0.12668917318976813,
decimal=DECIMAL_PRECISON)
assert_almost_equal(rician_norm.fit_params_['sigma'], 0.10331905081688209,
decimal=DECIMAL_PRECISON)
def test_rn_normalize():
""" Test the normalize function. """
# Create a T2WModality object
currdir = os.path.dirname(os.path.abspath(__file__))
path_data_t2w = os.path.join(currdir, 'data', 't2w')
t2w_mod = T2WModality(path_data_t2w)
t2w_mod.read_data_from_path()
# Create the GTModality object
path_data_gt = os.path.join(currdir, 'data', 'gt_folders')
path_data_gt_list = [os.path.join(path_data_gt, 'prostate'),
os.path.join(path_data_gt, 'pz'),
os.path.join(path_data_gt, 'cg'),
os.path.join(path_data_gt, 'cap')]
label_gt = ['prostate', 'pz', 'cg', 'cap']
gt_mod = GTModality()
gt_mod.read_data_from_path(cat_gt=label_gt, path_data=path_data_gt_list)
# Store the data before the normalization
pdf_copy = t2w_mod.pdf_.copy()
data_copy = t2w_mod.data_.copy()
# Normalize the data
rician_norm = RicianNormalization(T2WModality())
rician_norm.fit(t2w_mod, gt_mod, 'prostate')
t2w_mod = rician_norm.normalize(t2w_mod)
# Check that the data are equal to what they should be
assert_array_almost_equal(t2w_mod.data_,
(data_copy - 253.284554765) / 70.2569459323,
decimal=DECIMAL_PRECISON)
# Denormalize the data
t2w_mod = rician_norm.denormalize(t2w_mod)
# Check that the data are equal to the original data
data = np.load(os.path.join(currdir, 'data',
'data_rician_denormalize.npy'))
assert_array_equal(t2w_mod.data_, data)
data = np.load(os.path.join(currdir, 'data', 'pdf_rician_denormalize.npy'))
assert_array_equal(t2w_mod.pdf_, data)
def test_normalize_wt_fitting():
"""Test either an error is raised if the data are not fitted first."""
# Create a T2WModality object
currdir = os.path.dirname(os.path.abspath(__file__))
path_data_t2w = os.path.join(currdir, 'data', 't2w')
t2w_mod = T2WModality(path_data_t2w)
t2w_mod.read_data_from_path()
# Create the GTModality object
path_data_gt = os.path.join(currdir, 'data', 'gt_folders')
path_data_gt_list = [os.path.join(path_data_gt, 'prostate'),
os.path.join(path_data_gt, 'pz'),
os.path.join(path_data_gt, 'cg'),
os.path.join(path_data_gt, 'cap')]
label_gt = ['prostate', 'pz', 'cg', 'cap']
gt_mod = GTModality()
gt_mod.read_data_from_path(cat_gt=label_gt, path_data=path_data_gt_list)
# Store the data before the normalization
pdf_copy = t2w_mod.pdf_.copy()
data_copy = t2w_mod.data_.copy()
# Normalize the data
rician_norm = RicianNormalization(T2WModality())
assert_raises(ValueError, rician_norm.normalize, t2w_mod)
def test_denormalize_wt_fitting():
"""Test either an error is raised if the data are not fitted first."""
# Create a T2WModality object
currdir = os.path.dirname(os.path.abspath(__file__))
path_data_t2w = os.path.join(currdir, 'data', 't2w')
t2w_mod = T2WModality(path_data_t2w)
t2w_mod.read_data_from_path()
# Create the GTModality object
path_data_gt = os.path.join(currdir, 'data', 'gt_folders')
path_data_gt_list = [os.path.join(path_data_gt, 'prostate'),
os.path.join(path_data_gt, 'pz'),
os.path.join(path_data_gt, 'cg'),
os.path.join(path_data_gt, 'cap')]
label_gt = ['prostate', 'pz', 'cg', 'cap']
gt_mod = GTModality()
gt_mod.read_data_from_path(cat_gt=label_gt, path_data=path_data_gt_list)
# Store the data before the normalization
pdf_copy = t2w_mod.pdf_.copy()
data_copy = t2w_mod.data_.copy()
# Normalize the data
rician_norm = RicianNormalization(T2WModality())
assert_raises(ValueError, rician_norm.denormalize, t2w_mod)
def test_rn_save_load():
""" Test the save and load function. """
# Create a T2WModality object
currdir = os.path.dirname(os.path.abspath(__file__))
path_data_t2w = os.path.join(currdir, 'data', 't2w')
t2w_mod = T2WModality(path_data_t2w)
t2w_mod.read_data_from_path()
# Create the GTModality object
path_data_gt = os.path.join(currdir, 'data', 'gt_folders')
path_data_gt_list = [os.path.join(path_data_gt, 'prostate'),
os.path.join(path_data_gt, 'pz'),
os.path.join(path_data_gt, 'cg'),
os.path.join(path_data_gt, 'cap')]
label_gt = ['prostate', 'pz', 'cg', 'cap']
gt_mod = GTModality()
gt_mod.read_data_from_path(cat_gt=label_gt, path_data=path_data_gt_list)
# Normalize the data
rician_norm = RicianNormalization(T2WModality())
rician_norm.fit(t2w_mod, gt_mod, 'prostate')
# Store the normalization object
filename = os.path.join(currdir, 'data', 'rn_obj.p')
rician_norm.save_to_pickles(filename)
# Load the object
rn_2 = RicianNormalization.load_from_pickles(filename)
# Check that the different variables are the same
assert_equal(type(rn_2.base_modality_), type(rician_norm.base_modality_))
assert_equal(rn_2.fit_params_['b'], rician_norm.fit_params_['b'])
assert_equal(rn_2.fit_params_['off'], rician_norm.fit_params_['off'])
assert_equal(rn_2.fit_params_['sigma'], rician_norm.fit_params_['sigma'])
assert_equal(rn_2.is_fitted_, rician_norm.is_fitted_)
assert_array_equal(rn_2.roi_data_, rician_norm.roi_data_)
| gpl-2.0 |
martinkuik/PHP-Websocket-AdminControl | client.php | 2415 | <?php
/** Client
*
* PHP version 5
*
* @category PHP
* @package Martin
* @author Martin Kuik <martinn_@outlook.com>
* @copyright 2014 Martin Kuik
* @license https://gnu.org/licenses/gpl.html GPL v3 License
* @link https://github.com/martin.kuik
*/
/**
* Gets Server address
*
* @return a string with the address.
*/
function addr()
{
$a = $_SERVER['SERVER_ADDR'];
if ($a == "::1") {
$a = "localhost";
}
return $a;
}
/**
* Checks if your the localhost or an other user are
*
* @return the title.
*/
function title()
{
$a = $_SERVER['SERVER_ADDR'];
if ($a == "::1") {
$a = "<b>Admin</b>";
}
return $a;
}
?>
<html>
<head><title>Messenger API</title>
<style type="text/css">
html,body {
font-family:verdana;
font-size:15px;
}
#log {
width:600px;
height:300px;
border:1px solid #7F9DB9;
overflow:auto;
}
#msg {
width:400px;
}
</style>
<script type="text/javascript">
var socket;
var server_ip = "<?php echo addr(); ?>";
function init() {
var host = "ws://" + server_ip + ":9000/echobot";
try {
socket = new WebSocket(host);
log('WebSocket - status '+socket.readyState);
socket.onopen = function(msg) {
log("Welcome - status "+this.readyState);
};
socket.onmessage = function(msg) {
log("Received: "+msg.data);
};
socket.onclose = function(msg) {
log("Disconnected - status "+this.readyState);
};
}
catch(ex){
log(ex);
}
$("msg").focus();
}
function send(){
var txt,msg;
txt = $("msg");
msg = txt.value;
if(!msg) {
alert("Message can not be empty");
return;
}
txt.value="";
txt.focus();
try {
socket.send(msg);
log('Sent: '+msg);
} catch(ex) {
log(ex);
}
}
function quit(){
if (socket != null) {
log("Goodbye!");
socket.close();
socket=null;
}
}
function reconnect() {
quit();
init();
}
function $(id){ return document.getElementById(id); }
function log(msg){ $("log").innerHTML+="<br>"+msg; }
function onkey(event){ if(event.keyCode==13){ send(); } }
</script>
</head>
<body onload="init()">
<h3>Your ip :
<?php
error_reporting(E_STRICT);
echo title(); ?>
</h3>
<div id="log"></div>
<input id="msg" type="textbox" onkeypress="onkey(event)"/>
<button onclick="send()">Send
</button>
<button onclick="quit()">Quit</button>
<button onclick="reconnect()">Reconnect</button>
</body>
</html>
| gpl-2.0 |
ryanhellyer/wppaintbrush | footer.php | 134 | <?php
/**
* @package WordPress
* @subpackage WP Paintbrush
* @since WP Paintbrush 0.1
*/
?>
<?php wp_footer(); ?>
</body>
</html> | gpl-2.0 |
blakearchive/archive | blakearchive/static/controllers/work/work.controller.js | 355 | angular.module('blake').controller("WorkController", function($rootScope,$routeParams,BlakeDataService){
var vm = this;
vm.bds = BlakeDataService;
$rootScope.showOverlay = false;
$rootScope.help = 'work';
vm.bds.setSelectedWork($routeParams.workId);
$rootScope.worksNavState = false;
$rootScope.showWorkTitle = 'work';
});
| gpl-2.0 |
longersoft/nextcms | modules/menu/controllers/MenuController.php | 6208 | <?php
/**
* NextCMS
*
* @author Nguyen Huu Phuoc <thenextcms@gmail.com>
* @copyright Copyright (c) 2011 - 2012, Nguyen Huu Phuoc
* @license http://nextcms.org/license.txt (GNU GPL version 2 or later)
* @link http://nextcms.org
* @category modules
* @package menu
* @subpackage controllers
* @since 1.0
* @version 2012-03-10
*/
defined('APP_VALID_REQUEST') || die('You cannot access the script directly.');
class Menu_MenuController extends Zend_Controller_Action
{
////////// BACKEND ACTIONS //////////
/**
* Adds new menu
*
* @return void
*/
public function addAction()
{
Core_Services_Db::connect('master');
$request = $this->getRequest();
$menuat = $request->getParam('format');
switch ($menuat) {
case 'json':
$menu = new Menu_Models_Menu(array(
'title' => $request->getPost('title'),
'description' => $request->getPost('description'),
'created_user' => Zend_Auth::getInstance()->getIdentity()->user_id,
'created_date' => date('Y-m-d H:i:s'),
'items' => Zend_Json::decode($request->getPost('items')),
'language' => $request->getPost('language'),
'translations' => $request->getPost('translations'),
));
$menuId = Menu_Services_Menu::add($menu);
$result = true;
$this->_helper->json(array(
'result' => $result ? 'APP_RESULT_OK' : 'APP_RESULT_ERROR',
));
break;
default:
$sourceId = $request->getParam('source_id');
$source = $sourceId ? Menu_Services_Menu::getById($sourceId) : null;
$this->view->assign(array(
'source' => $source,
'sourceItems' => $source ? Zend_Json::encode(Menu_Services_Menu::getItemsTreeData($source)) : null,
'language' => $request->getParam('language', Core_Services_Config::get('core', 'localization_default_language', 'en_US')),
'languages' => Zend_Json::decode(Core_Services_Config::get('core', 'localization_languages', '{"en_US":"English"}')),
));
break;
}
}
/**
* Deletes menu
*
* @return void
*/
public function deleteAction()
{
Core_Services_Db::connect('master');
$request = $this->getRequest();
$format = $request->getParam('format');
$menuId = $request->getParam('menu_id');
$menu = Menu_Services_Menu::getById($menuId);
switch ($format) {
case 'json':
$result = Menu_Services_Menu::delete($menu);
$this->_helper->json(array(
'result' => $result ? 'APP_RESULT_OK' : 'APP_RESULT_ERROR',
));
break;
default:
$this->view->assign('menu', $menu);
break;
}
}
/**
* Edits menu
*
* @return void
*/
public function editAction()
{
Core_Services_Db::connect('master');
$request = $this->getRequest();
$format = $request->getParam('format');
$menuId = $request->getParam('menu_id');
$menu = Menu_Services_Menu::getById($menuId);
switch ($format) {
case 'json':
$result = false;
if ($menu) {
$menu->title = $request->getPost('title');
$menu->description = $request->getPost('description');
$menu->items = Zend_Json::decode($request->getPost('items'));
// Update translation
$menu->new_translations = $request->getPost('translations');
if (!$menu->new_translations) {
$menu->new_translations = Zend_Json::encode(array(
$menu->language => (string) $menu->menu_id,
));
}
$result = Menu_Services_Menu::update($menu);
}
$this->_helper->json(array(
'result' => $result ? 'APP_RESULT_OK' : 'APP_RESULT_ERROR',
));
break;
default:
// Get the translations of the menu
$translations = null;
if ($menu) {
$languages = Zend_Json::decode($menu->translations);
unset($languages[$menu->language]);
$translations = array();
foreach ($languages as $locale => $id) {
$translations[] = Menu_Services_Menu::getById($id);
}
}
$this->view->assign(array(
'menu' => $menu,
'menuId' => $menuId,
'items' => $menu ? Zend_Json::encode(Menu_Services_Menu::getItemsTreeData($menu)) : null,
'languages' => Zend_Json::decode(Core_Services_Config::get('core', 'localization_languages', '{"en_US":"English"}')),
'translations' => $translations,
));
break;
}
}
/**
* Lists menus
*
* @return void
*/
public function listAction()
{
Core_Services_Db::connect('master');
$request = $this->getRequest();
$format = $request->getParam('format');
$q = $request->getParam('q');
$default = array(
'page' => 1,
'keyword' => null,
'per_page' => 20,
'language' => null,
);
$criteria = $q ? Zend_Json::decode(base64_decode(rawurldecode($q))) : array();
$criteria = array_merge($default, $criteria);
switch ($format) {
case 'json':
$offset = ($criteria['page'] > 0) ? ($criteria['page'] - 1) * $criteria['per_page'] : 0;
$menus = Menu_Services_Menu::find($criteria, $offset, $criteria['per_page']);
$total = Menu_Services_Menu::count($criteria);
// Build data for the grid
$items = array();
$fields = array('menu_id', 'title', 'created_date', 'language', 'translations');
foreach ($menus as $menu) {
$item = array();
foreach ($fields as $field) {
$item[$field] = $menu->$field;
}
$items[] = $item;
}
// Paginator
$paginator = new Zend_Paginator(new Core_Base_Paginator_Adapter($menus, $total));
$paginator->setCurrentPageNumber($criteria['page'])
->setItemCountPerPage($criteria['per_page']);
$data = array(
// Data for the grid
'data' => array(
'identifier' => 'menu_id',
'items' => $items,
),
// Paginator
'paginator' => $this->view->paginator('slidingToolbar')->render($paginator, "javascript: dojo.publish('/app/menu/menu/list/onGotoPage', [__PAGE__]);"),
);
$this->_helper->json($data);
break;
default:
$this->view->assign('criteria', $criteria);
break;
}
}
}
| gpl-2.0 |
feliperodriguesprado/tcc_repository | software/source/smom/user/view/br.com.smom.user.login.view/src/main/java/br/com/smom/user/login/view/resources/ApplicationConfig.java | 1375 | /*
* Smom - Software Module Management.
*
* 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 br.com.smom.user.login.view.resources;
import java.util.Set;
import javax.ws.rs.core.Application;
@javax.ws.rs.ApplicationPath("resources")
public class ApplicationConfig extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<>();
addRestResourceClasses(resources);
return resources;
}
/**
* Do not modify addRestResourceClasses() method. It is automatically
* populated with all resources defined in the project. If required, comment
* out calling this method in getClasses().
*/
private void addRestResourceClasses(Set<Class<?>> resources) {
resources.add(br.com.smom.user.login.view.resources.UserResource.class);
}
}
| gpl-2.0 |
s20121035/rk3288_android5.1_repo | external/proguard/src/proguard/obfuscate/NameFactoryResetter.java | 1706 | /*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
*
* 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
*/
package proguard.obfuscate;
import proguard.classfile.*;
import proguard.classfile.visitor.ClassVisitor;
/**
* This ClassVisitor resets a given name factory whenever it visits a class
* file.
*
* @author Eric Lafortune
*/
public class NameFactoryResetter implements ClassVisitor
{
private final NameFactory nameFactory;
/**
* Creates a new NameFactoryResetter.
* @param nameFactory the name factory to be reset.
*/
public NameFactoryResetter(NameFactory nameFactory)
{
this.nameFactory = nameFactory;
}
// Implementations for ClassVisitor.
public void visitProgramClass(ProgramClass programClass)
{
nameFactory.reset();
}
public void visitLibraryClass(LibraryClass libraryClass)
{
nameFactory.reset();
}
}
| gpl-3.0 |
thomashoegg/GU-DSL | Core/src/Processing/Project/ProjectExecutor.qt.cpp | 7256 | /***********************************************************************************
* Copyright (c) 2013-2015 "Thomas Hoegg et al."
* [http://gu-dsl.org]; information about commercial use mail at info@gu-dsl.org
*
* This file is part of GU-DSL.
*
* GU-DSLis free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**********************************************************************************/
#include "Processing/Project/ProjectExecutor.qt.h"
#include "Processing/Project/Project.qt.h"
#include "Processing/Component/ComponentDiagram.qt.h"
#include <QApplication>
#include "Processing/Object/Class.qt.h"
#include "Processing/Interfaces/ISupport2DRendering.h"
#include "Processing/Interfaces/ISupportMultiple2DRendering.h"
#include "Processing/Interfaces/ISupport3DRendering.h"
#include "Processing/Interfaces/ISupportMultiple3DRendering.h"
namespace Core
{
namespace Processing
{
namespace Project
{
ProjectExecutor& ProjectExecutor::instance()
{
static ProjectExecutor instance;
return instance;
}
ProjectExecutor::ProjectExecutor()
:_project(nullptr)
{
}
ProjectExecutor::~ProjectExecutor()
{
stopProject();
cleanup();
}
void ProjectExecutor::setProject( Core::Processing::Project::ProjectPtr project )
{
if(project != _project)
{
stopComponentDiagrams();
_project = project;
QList<Core::Processing::Component::ConstComponentDiagramPtr> diagrams = _project->getDiagrams();
for(Core::Processing::Component::ConstComponentDiagramPtr diagram: diagrams)
{
installComponentDiagram(diagram);
runComponentDiagram(diagram->templateUid());
}
}
}
Core::Processing::Project::ProjectPtr ProjectExecutor::runProject()
{
runComponentDiagrams();
return _project;
}
void ProjectExecutor::stopProject()
{
stopComponentDiagrams();
}
void ProjectExecutor::cleanup()
{
for(int i = 0; i < _runningComponentDiagrams.count(); i++ )
{
QList<Core::Processing::Interfaces::IObjectPtr> objects = _runningComponentDiagrams[i]->getObjects();
for(int o = 0; o < objects.count(); o++)
{
cleanupObject(objects[o]);
}
}
}
Core::Processing::Project::ProjectPtr ProjectExecutor::getProject()
{
return _project;
}
void ProjectExecutor::installComponentDiagrams( QList<Core::Processing::Interfaces::ConstIObjectPtr> diagrams )
{
if(diagrams.length() > 0)
{
for(Core::Processing::Interfaces::ConstIObjectPtr diagram : diagrams)
{
installComponentDiagram(diagram);
}
}
else
{
installComponentDiagram(Core::Processing::Component::ComponentDiagramPtr(new Core::Processing::Component::ComponentDiagram()));
}
}
void ProjectExecutor::installComponentDiagram( Core::Processing::Interfaces::ConstIObjectPtr diagram )
{
if(_project == nullptr)
{
_project = Core::Processing::Project::ProjectPtr(new Core::Processing::Project::Project());
}
_project->AddDiagram(diagram);
}
Core::Processing::Component::ComponentDiagramPtr ProjectExecutor::runComponentDiagram(const QString& uid)
{
return runComponentDiagram(_project->findDiagramByUid(uid));
}
Core::Processing::Component::ComponentDiagramPtr ProjectExecutor::runComponentDiagram(Core::Processing::Component::ConstComponentDiagramPtr componentDiagram)
{
Core::Processing::Component::ComponentDiagramPtr newDiagram;
if(componentDiagram)
{
newDiagram = boost::dynamic_pointer_cast<Core::Processing::Component::ComponentDiagram>(componentDiagram->create());
_runningComponentDiagrams.append(newDiagram);
}
return newDiagram;
}
QList<Core::Processing::Component::ComponentDiagramPtr> ProjectExecutor::runComponentDiagrams()
{
QList<Core::Processing::Component::ComponentDiagramPtr> runningDiagrams;
for(Core::Processing::Component::ConstComponentDiagramPtr diagram : _project->getDiagrams())
{
runningDiagrams.push_back(runComponentDiagram(diagram));
}
return runningDiagrams;
}
QList<Core::Processing::Component::ComponentDiagramPtr> ProjectExecutor::getRunningComponentDiagrams()
{
return _runningComponentDiagrams;
}
void ProjectExecutor::stopComponentDiagrams()
{
for(int i = _runningComponentDiagrams.count() -1 ; i >= 0 ; i-- )
{
stopComponentDiagram(_runningComponentDiagrams[i]);
}
_runningComponentDiagrams.clear();
}
void ProjectExecutor::stopComponentDiagram( const QString& uid )
{
if(Core::Processing::Component::ComponentDiagramPtr diagram = findRunningDiagramByUid(uid))
{
stopComponentDiagram(diagram);
}
}
void ProjectExecutor::stopComponentDiagram( Core::Processing::Component::ComponentDiagramPtr runningDiagram )
{
QList<Core::Processing::Interfaces::IObjectPtr> objects = runningDiagram->getObjects();
for(int o = 0; o < objects.count(); o++)
{
cleanupObject(objects[o]);
}
runningDiagram->stop();
}
Core::Processing::Component::ComponentDiagramPtr ProjectExecutor::findRunningDiagramByUid( const QString& uid )
{
Core::Processing::Component::ComponentDiagramPtr returnValue;
for(Core::Processing::Component::ComponentDiagramPtr runningDiagram : _runningComponentDiagrams)
{
if(runningDiagram->uid() == uid)
{
returnValue = runningDiagram;
break;
}
}
return returnValue;
}
void ProjectExecutor::cleanupObject( Core::Processing::Interfaces::IObjectPtr object)
{
Core::Processing::Object::ClassPtr classObject = boost::dynamic_pointer_cast<Core::Processing::Object::Class>(object);
if(classObject != nullptr)
{
classObject->stop();
}
Core::Processing::Interfaces::ISupport2DRendering* supportRendering2D = dynamic_cast<Core::Processing::Interfaces::ISupport2DRendering*>(object.get());
Core::Processing::Interfaces::ISupportMultiple2DRendering* supportMultipleRendering2D = dynamic_cast<Core::Processing::Interfaces::ISupportMultiple2DRendering*>(object.get());
if(supportMultipleRendering2D != nullptr)
{
supportMultipleRendering2D->setRenderWindows(std::vector<Viewer::Viewer2DPtr>());
}
else if(supportRendering2D != nullptr)
{
supportRendering2D->setRenderWindow(nullptr);
}
Core::Processing::Interfaces::ISupport3DRendering* supportRendering3D = dynamic_cast<Core::Processing::Interfaces::ISupport3DRendering*>(object.get());
Core::Processing::Interfaces::ISupportMultiple3DRendering* supportMultipleRendering3D = dynamic_cast<Core::Processing::Interfaces::ISupportMultiple3DRendering*>(object.get());
if(supportMultipleRendering3D != nullptr)
{
supportMultipleRendering3D->setRenderWindows(std::vector<Viewer::Viewer3DPtr>());
}
else if(supportRendering3D != nullptr)
{
supportRendering3D->setRenderWindow(nullptr);
}
}
}; // namespace Project
}; // namespace Processing
}; //namespace Core
| gpl-3.0 |
ongbe/OpenFOAM-Dev | src/finiteVolume/cfdTools/general/MRF/MRFZone.C | 13521 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011-2012 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "MRFZone.H"
#include "fvMesh.H"
#include "volFields.H"
#include "surfaceFields.H"
#include "fvMatrices.H"
#include "syncTools.H"
#include "faceSet.H"
#include "geometricOneField.H"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
defineTypeNameAndDebug(Foam::MRFZone, 0);
// * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * //
void Foam::MRFZone::setMRFFaces()
{
const polyBoundaryMesh& patches = mesh_.boundaryMesh();
// Type per face:
// 0:not in zone
// 1:moving with frame
// 2:other
labelList faceType(mesh_.nFaces(), 0);
// Determine faces in cell zone
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// (without constructing cells)
const labelList& own = mesh_.faceOwner();
const labelList& nei = mesh_.faceNeighbour();
// Cells in zone
boolList zoneCell(mesh_.nCells(), false);
if (cellZoneID_ != -1)
{
const labelList& cellLabels = mesh_.cellZones()[cellZoneID_];
forAll(cellLabels, i)
{
zoneCell[cellLabels[i]] = true;
}
}
label nZoneFaces = 0;
for (label faceI = 0; faceI < mesh_.nInternalFaces(); faceI++)
{
if (zoneCell[own[faceI]] || zoneCell[nei[faceI]])
{
faceType[faceI] = 1;
nZoneFaces++;
}
}
labelHashSet excludedPatches(excludedPatchLabels_);
forAll(patches, patchI)
{
const polyPatch& pp = patches[patchI];
if (pp.coupled() || excludedPatches.found(patchI))
{
forAll(pp, i)
{
label faceI = pp.start()+i;
if (zoneCell[own[faceI]])
{
faceType[faceI] = 2;
nZoneFaces++;
}
}
}
else if (!isA<emptyPolyPatch>(pp))
{
forAll(pp, i)
{
label faceI = pp.start()+i;
if (zoneCell[own[faceI]])
{
faceType[faceI] = 1;
nZoneFaces++;
}
}
}
}
// Now we have for faceType:
// 0 : face not in cellZone
// 1 : internal face or normal patch face
// 2 : coupled patch face or excluded patch face
// Sort into lists per patch.
internalFaces_.setSize(mesh_.nFaces());
label nInternal = 0;
for (label faceI = 0; faceI < mesh_.nInternalFaces(); faceI++)
{
if (faceType[faceI] == 1)
{
internalFaces_[nInternal++] = faceI;
}
}
internalFaces_.setSize(nInternal);
labelList nIncludedFaces(patches.size(), 0);
labelList nExcludedFaces(patches.size(), 0);
forAll(patches, patchi)
{
const polyPatch& pp = patches[patchi];
forAll(pp, patchFacei)
{
label faceI = pp.start()+patchFacei;
if (faceType[faceI] == 1)
{
nIncludedFaces[patchi]++;
}
else if (faceType[faceI] == 2)
{
nExcludedFaces[patchi]++;
}
}
}
includedFaces_.setSize(patches.size());
excludedFaces_.setSize(patches.size());
forAll(nIncludedFaces, patchi)
{
includedFaces_[patchi].setSize(nIncludedFaces[patchi]);
excludedFaces_[patchi].setSize(nExcludedFaces[patchi]);
}
nIncludedFaces = 0;
nExcludedFaces = 0;
forAll(patches, patchi)
{
const polyPatch& pp = patches[patchi];
forAll(pp, patchFacei)
{
label faceI = pp.start()+patchFacei;
if (faceType[faceI] == 1)
{
includedFaces_[patchi][nIncludedFaces[patchi]++] = patchFacei;
}
else if (faceType[faceI] == 2)
{
excludedFaces_[patchi][nExcludedFaces[patchi]++] = patchFacei;
}
}
}
if (debug)
{
faceSet internalFaces(mesh_, "internalFaces", internalFaces_);
Pout<< "Writing " << internalFaces.size()
<< " internal faces in MRF zone to faceSet "
<< internalFaces.name() << endl;
internalFaces.write();
faceSet MRFFaces(mesh_, "includedFaces", 100);
forAll(includedFaces_, patchi)
{
forAll(includedFaces_[patchi], i)
{
label patchFacei = includedFaces_[patchi][i];
MRFFaces.insert(patches[patchi].start()+patchFacei);
}
}
Pout<< "Writing " << MRFFaces.size()
<< " patch faces in MRF zone to faceSet "
<< MRFFaces.name() << endl;
MRFFaces.write();
faceSet excludedFaces(mesh_, "excludedFaces", 100);
forAll(excludedFaces_, patchi)
{
forAll(excludedFaces_[patchi], i)
{
label patchFacei = excludedFaces_[patchi][i];
excludedFaces.insert(patches[patchi].start()+patchFacei);
}
}
Pout<< "Writing " << excludedFaces.size()
<< " faces in MRF zone with special handling to faceSet "
<< excludedFaces.name() << endl;
excludedFaces.write();
}
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
Foam::MRFZone::MRFZone(const fvMesh& mesh, Istream& is)
:
mesh_(mesh),
name_(is),
dict_(is),
cellZoneID_(mesh_.cellZones().findZoneID(name_)),
excludedPatchNames_
(
dict_.lookupOrDefault("nonRotatingPatches", wordList(0))
),
origin_(dict_.lookup("origin")),
axis_(dict_.lookup("axis")),
omega_(dict_.lookup("omega")),
Omega_("Omega", omega_*axis_)
{
if (dict_.found("patches"))
{
WarningIn("MRFZone(const fvMesh&, Istream&)")
<< "Ignoring entry 'patches'\n"
<< " By default all patches within the rotating region rotate.\n"
<< " Optionally supply excluded patches "
<< "using 'nonRotatingPatches'."
<< endl;
}
const polyBoundaryMesh& patches = mesh_.boundaryMesh();
axis_ = axis_/mag(axis_);
Omega_ = omega_*axis_;
excludedPatchLabels_.setSize(excludedPatchNames_.size());
forAll(excludedPatchNames_, i)
{
excludedPatchLabels_[i] = patches.findPatchID(excludedPatchNames_[i]);
if (excludedPatchLabels_[i] == -1)
{
FatalErrorIn
(
"Foam::MRFZone::MRFZone(const fvMesh&, Istream&)"
) << "cannot find MRF patch " << excludedPatchNames_[i]
<< exit(FatalError);
}
}
bool cellZoneFound = (cellZoneID_ != -1);
reduce(cellZoneFound, orOp<bool>());
if (!cellZoneFound)
{
FatalErrorIn
(
"Foam::MRFZone::MRFZone(const fvMesh&, Istream&)"
) << "cannot find MRF cellZone " << name_
<< exit(FatalError);
}
setMRFFaces();
}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
void Foam::MRFZone::addCoriolis
(
const volVectorField& U,
volVectorField& ddtU
) const
{
if (cellZoneID_ == -1)
{
return;
}
const labelList& cells = mesh_.cellZones()[cellZoneID_];
const scalarField& V = mesh_.V();
vectorField& ddtUc = ddtU.internalField();
const vectorField& Uc = U.internalField();
const vector& Omega = Omega_.value();
forAll(cells, i)
{
label celli = cells[i];
ddtUc[celli] += V[celli]*(Omega ^ Uc[celli]);
}
}
void Foam::MRFZone::addCoriolis(fvVectorMatrix& UEqn) const
{
if (cellZoneID_ == -1)
{
return;
}
const labelList& cells = mesh_.cellZones()[cellZoneID_];
const scalarField& V = mesh_.V();
vectorField& Usource = UEqn.source();
const vectorField& U = UEqn.psi();
const vector& Omega = Omega_.value();
forAll(cells, i)
{
label celli = cells[i];
Usource[celli] -= V[celli]*(Omega ^ U[celli]);
}
}
void Foam::MRFZone::addCoriolis
(
const volScalarField& rho,
fvVectorMatrix& UEqn
) const
{
if (cellZoneID_ == -1)
{
return;
}
const labelList& cells = mesh_.cellZones()[cellZoneID_];
const scalarField& V = mesh_.V();
vectorField& Usource = UEqn.source();
const vectorField& U = UEqn.psi();
const vector& Omega = Omega_.value();
forAll(cells, i)
{
label celli = cells[i];
Usource[celli] -= V[celli]*rho[celli]*(Omega ^ U[celli]);
}
}
void Foam::MRFZone::relativeVelocity(volVectorField& U) const
{
const volVectorField& C = mesh_.C();
const vector& origin = origin_.value();
const vector& Omega = Omega_.value();
const labelList& cells = mesh_.cellZones()[cellZoneID_];
forAll(cells, i)
{
label celli = cells[i];
U[celli] -= (Omega ^ (C[celli] - origin));
}
// Included patches
forAll(includedFaces_, patchi)
{
forAll(includedFaces_[patchi], i)
{
label patchFacei = includedFaces_[patchi][i];
U.boundaryField()[patchi][patchFacei] = vector::zero;
}
}
// Excluded patches
forAll(excludedFaces_, patchi)
{
forAll(excludedFaces_[patchi], i)
{
label patchFacei = excludedFaces_[patchi][i];
U.boundaryField()[patchi][patchFacei] -=
(Omega ^ (C.boundaryField()[patchi][patchFacei] - origin));
}
}
}
void Foam::MRFZone::absoluteVelocity(volVectorField& U) const
{
const volVectorField& C = mesh_.C();
const vector& origin = origin_.value();
const vector& Omega = Omega_.value();
const labelList& cells = mesh_.cellZones()[cellZoneID_];
forAll(cells, i)
{
label celli = cells[i];
U[celli] += (Omega ^ (C[celli] - origin));
}
// Included patches
forAll(includedFaces_, patchi)
{
forAll(includedFaces_[patchi], i)
{
label patchFacei = includedFaces_[patchi][i];
U.boundaryField()[patchi][patchFacei] =
(Omega ^ (C.boundaryField()[patchi][patchFacei] - origin));
}
}
// Excluded patches
forAll(excludedFaces_, patchi)
{
forAll(excludedFaces_[patchi], i)
{
label patchFacei = excludedFaces_[patchi][i];
U.boundaryField()[patchi][patchFacei] +=
(Omega ^ (C.boundaryField()[patchi][patchFacei] - origin));
}
}
}
void Foam::MRFZone::relativeFlux(surfaceScalarField& phi) const
{
relativeRhoFlux(geometricOneField(), phi);
}
void Foam::MRFZone::relativeFlux
(
const surfaceScalarField& rho,
surfaceScalarField& phi
) const
{
relativeRhoFlux(rho, phi);
}
void Foam::MRFZone::absoluteFlux(surfaceScalarField& phi) const
{
absoluteRhoFlux(geometricOneField(), phi);
}
void Foam::MRFZone::absoluteFlux
(
const surfaceScalarField& rho,
surfaceScalarField& phi
) const
{
absoluteRhoFlux(rho, phi);
}
void Foam::MRFZone::correctBoundaryVelocity(volVectorField& U) const
{
const vector& origin = origin_.value();
const vector& Omega = Omega_.value();
// Included patches
forAll(includedFaces_, patchi)
{
const vectorField& patchC = mesh_.Cf().boundaryField()[patchi];
vectorField pfld(U.boundaryField()[patchi]);
forAll(includedFaces_[patchi], i)
{
label patchFacei = includedFaces_[patchi][i];
pfld[patchFacei] = (Omega ^ (patchC[patchFacei] - origin));
}
U.boundaryField()[patchi] == pfld;
}
}
Foam::Ostream& Foam::operator<<(Ostream& os, const MRFZone& MRF)
{
os << indent << nl;
os.write(MRF.name_) << nl;
os << token::BEGIN_BLOCK << incrIndent << nl;
os.writeKeyword("origin") << MRF.origin_ << token::END_STATEMENT << nl;
os.writeKeyword("axis") << MRF.axis_ << token::END_STATEMENT << nl;
os.writeKeyword("omega") << MRF.omega_ << token::END_STATEMENT << nl;
if (MRF.excludedPatchNames_.size())
{
os.writeKeyword("nonRotatingPatches") << MRF.excludedPatchNames_
<< token::END_STATEMENT << nl;
}
os << decrIndent << token::END_BLOCK << nl;
return os;
}
// ************************************************************************* //
| gpl-3.0 |
rowinggolfer/openmolar2 | src/lib_openmolar/client/db_orm/patient_model.py | 9399 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
## ##
## Copyright 2010-2012, Neil Wallace <neil@openmolar.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 3 of the License, or ##
## (at your option) any later version. ##
## ##
## This program is distributed in the hope that it will be useful, ##
## but WITHOUT ANY WARRANTY; without even the implied warranty of ##
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ##
## GNU General Public License for more details. ##
## ##
## You should have received a copy of the GNU General Public License ##
## along with this program. If not, see <http://www.gnu.org/licenses/>. ##
## ##
###############################################################################
'''
This module provides the PatientModel Class, which pulls together
functionality from all the ORM classes as and when required.
'''
from PyQt4 import QtCore, QtSql
from lib_openmolar.client.db_orm import *
class PatientModel(object):
'''
This very important class represents the full patient record.
The behaviour of this object is very much like a dictionary.
'''
_dict = {}
_notes_summary_html = None
def __init__(self, patient_id):
self["patient"] = PatientDB(patient_id)
self["addresses"] = AddressObjects(patient_id)
self["telephone"] = TelephoneDB(patient_id)
self["teeth_present"] = TeethPresentDB(patient_id)
self["static_fills"] = StaticFillsDB(patient_id)
self["static_crowns"] = StaticCrownsDB(patient_id)
self["static_roots"] = StaticRootsDB(patient_id)
self["static_comments"] = StaticCommentsDB(patient_id)
self["memo_clinical"] = MemoClinicalDB(patient_id)
self["memo_clerical"] = MemoClericalDB(patient_id)
self["treatment_model"] = SETTINGS.treatment_model
SETTINGS.treatment_model.load_patient(patient_id)
self["notes_model"] = NotesModel(patient_id)
self["perio_bpe"] = PerioBpeDB(patient_id)
self["perio_pocketing"] = PerioPocketingDB(patient_id)
self["contracted_practitioners"] = ContractedPractitionerDB(patient_id)
self.patient_id = patient_id
@property
def is_dirty(self):
'''
A Boolean.
If True, then the record differs from the database state
'''
dirty = False
for att in ("patient", "addresses", "teeth_present",
"static_fills", 'static_crowns', 'static_roots', 'static_comments',
'memo_clinical', 'memo_clerical', 'treatment_model', 'notes_model'):
if self[att].is_dirty:
dirty = True
break
return dirty
def what_has_changed(self):
'''
returns a stringlist of what has changed.
TODO could be much improved
'''
changes = self['notes_model'].what_has_changed()
for att in ("patient", "addresses", "teeth_present",
"static_fills", 'static_crowns', 'static_roots', 'static_comments',
'memo_clinical', 'memo_clerical', 'treatment_model'):
if self[att].is_dirty:
changes.append(att)
return changes
def commit_changes(self):
'''
commits any user edits to the database
'''
for att in ("patient", "addresses", "teeth_present",
"static_fills", 'static_crowns', 'static_roots', 'static_comments',
'memo_clinical', 'memo_clerical', 'treatment_model'):
self[att].commit_changes()
@property
def current_contracted_dentist(self):
return self["contracted_practitioners"].current_contracted_dentist
@property
def static_chart_records(self):
'''
returns all data needed about teeth in the static chart
see also ..func::`dent_key`
'''
for record in self['static_fills'].records:
yield (record, 'fill')
for record in self['static_crowns'].records:
yield (record, 'crown')
for record in self['static_roots'].records:
yield (record, 'root')
for record in self['static_comments'].records:
yield (record, 'comment')
@property
def perio_data(self):
'''
A convenience function to access perio data.
TODO only pocketing data is returned at the moment
'''
for record in self['perio_pocketing'].records:
yield (record, 'pocket')
@property
def dent_key(self):
'''
this property is an integer, which represents which teeth are present
'''
dk, result = self['teeth_present'].value('dent_key').toLongLong()
if not result:
pass
print "no dent-key"
return dk
def set_dent_key(self, key):
'''
sets the ..func::`dent_key` for this patient
'''
self["teeth_present"].setValue("patient_id", self.patient_id)
self["teeth_present"].setValue("dent_key", key)
self["teeth_present"].setValue("checked_date",
QtCore.QDate.currentDate())
self["teeth_present"].setValue("checked_by", SETTINGS.user)
def details_html(self):
'''
an html representation of the patient
this is a combination of html data from several tables
'''
html = u'''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Patient Details</title>
<link rel="stylesheet" type="text/css" href="%s">
</head>
<body>
'''% SETTINGS.DETAILS_CSS
html += self["patient"].details_html()
html += "<br />"
html += self["contracted_practitioners"].details_html()
html += "<br />"
html += self["addresses"].details_html()
html += "<br />"
html += self["telephone"].details_html()
html += '''<hr /><div class='center'>
<b>%s</b><a href='edit_memo'>%s</a>
<br />%s'''% (_("MEMO"), SETTINGS.PENCIL, self.clerical_memo)
return html + "</body>"
@property
def age_years(self):
'''
returns an integer of the patient's age in years
'''
return self["patient"].age_tuple()[0]
@property
def full_name(self):
'''
the patient's full name
'''
return self["patient"].full_name
@property
def treatment_summary_html(self):
'''
returns an html summary of the treatment plan
TODO - this is a placeholder function
'''
return "Treatment Plan for %s"% self.full_name
@property
def clinical_memo(self):
'''
returns the clinical memo for this patient
displayed under the chart on the *summary* page
'''
return self["memo_clinical"].memo
@property
def clerical_memo(self):
'''
returns the clerical memo for this patient
displayed prominently on the *reception* page
'''
return self["memo_clerical"].memo
def refresh_bpe(self):
'''
reloads bpe data from the database
this function should be called if a BPE dialog
is raised and accepted
'''
self["perio_bpe"] = PerioBpeDB(self.patient_id)
@property
def current_bpe(self):
'''
a patient will potentially have many bpes recorded.
this is the most recent one
'''
return self["perio_bpe"].current_bpe
@property
def treatment_model(self):
'''
the :doc:`TreatmentModel` for this patient
'''
return SETTINGS.treatment_model
@property
def notes(self):
'''
the :doc:`NotesModel` for this patient
'''
return self["notes_model"]
def get(self, key, fallback=None):
'''
PatientModel.get(self, key, fallback=None)
'''
try:
return self._dict[key]
except KeyError:
return fallback
def __setitem__(self, key, val):
self._dict[key] = val
def __getitem__(self, key):
return self._dict[key]
if __name__ == "__main__":
from lib_openmolar.client.connect import DemoClientConnection
cc = DemoClientConnection()
cc.connect()
obj = PatientModel(1)
print obj.details_html()
print "DENT KEY", obj.dent_key
print "ROOTS", obj["static_roots"].records
print "BPE", obj["perio_bpe"].records
print "contracted practitioners", obj["contracted_practitioners"].records
print "Perio Data", obj.perio_data
print "Age Years", obj.age_years
print obj.notes
| gpl-3.0 |
SpleefLeague/SuperSpleef | src/main/java/com/spleefleague/superspleef/game/team/TeamSpleefBattle.java | 20223 | /*
* 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.
*/
package com.spleefleague.superspleef.game.team;
import com.google.common.collect.Lists;
import com.spleefleague.core.SpleefLeague;
import com.spleefleague.core.chat.ChatManager;
import com.spleefleague.core.chat.Theme;
import com.spleefleague.gameapi.events.BattleEndEvent;
import com.spleefleague.gameapi.events.BattleEndEvent.EndReason;
import com.spleefleague.core.player.SLPlayer;
import com.spleefleague.gameapi.queue.Battle;
import com.spleefleague.superspleef.SuperSpleef;
import com.spleefleague.superspleef.game.GameHistory;
import com.spleefleague.superspleef.game.GameHistoryPlayerData;
import com.spleefleague.superspleef.game.RemoveReason;
import com.spleefleague.superspleef.game.SpleefBattle;
import com.spleefleague.superspleef.player.SpleefPlayer;
import org.bukkit.*;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.scoreboard.DisplaySlot;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Scoreboard;
import java.util.*;
import java.util.Map.Entry;
import org.bukkit.craftbukkit.libs.org.apache.commons.lang3.time.DurationFormatUtils;
/**
* @author Jonas
*/
public class TeamSpleefBattle extends SpleefBattle<TeamSpleefArena> {
private static final Color[] colors = {
Color.BLUE,
Color.RED,
Color.YELLOW,
Color.GREEN,
Color.PURPLE,
Color.ORANGE
};
public static final ItemStack[] teamBlocks = {
new ItemStack(Material.BLUE_WOOL),
new ItemStack(Material.RED_WOOL),
new ItemStack(Material.YELLOW_WOOL),
new ItemStack(Material.GREEN_WOOL),
new ItemStack(Material.PURPLE_WOOL),
new ItemStack(Material.ORANGE_WOOL)
};
private static final ChatColor[] chatColors = {
ChatColor.BLUE,
ChatColor.RED,
ChatColor.YELLOW,
ChatColor.GREEN,
ChatColor.LIGHT_PURPLE,
ChatColor.GOLD
};
private static final ChatColor[] chatHighlightColors = {
ChatColor.DARK_BLUE,
ChatColor.DARK_RED,
ChatColor.GOLD,
ChatColor.DARK_GREEN,
ChatColor.DARK_PURPLE,
ChatColor.WHITE
};
public static final String[] names = {"Blue", "Red", "Yellow", "Green", "Purple", "Gold"};
private Team[] teams;
private Map<SpleefPlayer, Team> playerTeams;
protected TeamSpleefBattle(TeamSpleefArena arena, List<SpleefPlayer> players) {
super(arena, players);
}
@Override
public void removePlayer(SpleefPlayer sp, RemoveReason reason) {
if (reason == RemoveReason.QUIT) {
for (SpleefPlayer pl : getActivePlayers()) {
pl.sendMessage(
getSpleefMode().getChatPrefix() + " " + Theme.ERROR.buildTheme(false) + sp.getName() +
" has left the game!");
}
for (SpleefPlayer pl : getSpectators()) {
pl.sendMessage(
getSpleefMode().getChatPrefix() + " " + Theme.ERROR.buildTheme(false) + sp.getName() +
" has left the game!");
}
}
resetTeamColor(sp);
handlePlayerDeath(sp, true);
playerTeams.remove(sp);
resetPlayer(sp);
List<SpleefPlayer> activePlayers = getActivePlayers();
if (activePlayers.size() == 1) {
end(activePlayers.get(0), EndReason.valueOf(reason.name()));
}else
getPlayers().remove(sp);
}
@Override
protected void addToBattleManager() {
SuperSpleef.getInstance().getTeamSpleefBattleManager().add(this);
}
@Override
protected void removeFromBattleManager() {
SuperSpleef.getInstance().getTeamSpleefBattleManager().remove(this);
}
@Override
protected void onStart() {
playerTeams = new HashMap<>();
int pid = 0;
teams = new Team[getArena().getTeamSizes().length];
for (int teamID = 0; teamID < getArena().getTeamSizes().length; teamID++) {
Team team = new Team(teamID);
teams[teamID] = team;
for (int i = 0; i < getArena().getTeamSizes()[teamID]; i++, pid++) {
SpleefPlayer p = getPlayers().get(pid);
team.addPlayer(p);
playerTeams.put(p, team);
applyTeamColor(p, team, true);
}
}
Scoreboard scoreboard = Bukkit.getScoreboardManager().getNewScoreboard();
org.bukkit.scoreboard.Team scoreboardTeam = scoreboard.registerNewTeam("NO_COLLISION");
scoreboardTeam.setOption(org.bukkit.scoreboard.Team.Option.COLLISION_RULE, org.bukkit.scoreboard.Team.OptionStatus.NEVER);
Objective objective = scoreboard.registerNewObjective("rounds", "dummy");
objective.setDisplaySlot(DisplaySlot.SIDEBAR);
objective.setDisplayName(ChatColor.GRAY + "00:00:00 | " + ChatColor.RED + "Score:");
for (Team team : teams) {
scoreboard.getObjective("rounds").getScore(team.getName()).setScore(0);
for (SpleefPlayer sp : team.getAlivePlayers()) {
sp.setScoreboard(scoreboard);
scoreboardTeam.addEntry(sp.getName());
}
}
objective.getScore(getPlayToString()).setScore(getPlayTo());
setScoreboard(scoreboard);
scoreboard.getTeams().forEach(t -> t.setOption(org.bukkit.scoreboard.Team.Option.COLLISION_RULE, org.bukkit.scoreboard.Team.OptionStatus.NEVER));
}
private String getPlayToString() {
return ChatColor.GOLD + "Playing to: ";
}
@Override
public void onScoreboardUpdate() {
reInitScoreboard();
}
private void reInitScoreboard() {
getScoreboard().getObjective("rounds").unregister();
Objective objective = getScoreboard().registerNewObjective("rounds", "dummy");
String s = DurationFormatUtils.formatDuration(getTicksPassed() * 50, "HH:mm:ss", true);
objective.setDisplayName(ChatColor.GRAY.toString() + s + " | " + ChatColor.RED + "Score:");
objective.setDisplaySlot(DisplaySlot.SIDEBAR);
objective.getScore(getPlayToString()).setScore(getPlayTo());
Set<String> requestingReset = new HashSet();
Set<String> requestingEnd = new HashSet();
for (SpleefPlayer sp : this.getPlayers()) {
Team t = this.playerTeams.get(sp);
if (sp.isRequestingReset()) {
requestingReset.add(t.getChatColor() + sp.getName());
}
if (sp.isRequestingEndgame()) {
requestingEnd.add(t.getChatColor() + sp.getName());
}
getScoreboard().getObjective("rounds").getScore(t.getName()).setScore(t.getPoints());
}
if (!requestingEnd.isEmpty() || !requestingReset.isEmpty()) {
objective.getScore(ChatColor.BLACK + "-----------").setScore(-1);
}
if (!requestingReset.isEmpty()) {
objective.getScore(ChatColor.GOLD + "Reset requested").setScore(-2);
for (String name : requestingReset) {
objective.getScore("> " + name).setScore(-3);
}
}
if (!requestingEnd.isEmpty()) {
objective.getScore(ChatColor.RED + "End requested").setScore(-4);
for (String name : requestingEnd) {
objective.getScore("* " + name).setScore(-5);
}
}
}
@Override
public ArrayList<SpleefPlayer> getAlivePlayers() {
ArrayList<SpleefPlayer> pls = new ArrayList();
for (Team t : this.teams) {
pls.addAll(t.getAlivePlayers());
}
return pls;
}
@Override
public void end(SpleefPlayer winner, EndReason reason) {
end((Team) null, reason);
}
private void end(Team winner, EndReason reason) {
SpleefPlayer winnerPlayer = playerTeams
.entrySet()
.stream()
.filter(e -> e.getValue() == winner)
.map(Entry::getKey)
.findAny()
.orElse(null);
saveGameHistory(winnerPlayer, reason);
if (reason == EndReason.CANCEL) {
ChatManager.sendMessage(
getSpleefMode().getChatPrefix(),
Theme.INCOGNITO.buildTheme(false) + "The battle has been cancelled by a moderator.",
getGameChannel()
);
} else if (reason != EndReason.ENDGAME) {
ChatManager.sendMessage(
getSpleefMode().getChatPrefix(),
Theme.INFO.buildTheme(false) + "Team " + winner.getName() + " has won the match.", getGameChannel()
);
}
Lists.newArrayList(getSpectators()).forEach(this::resetPlayer);
Lists.newArrayList(getActivePlayers()).forEach((p) -> {
resetPlayer(p);
resetTeamColor(p);
p.invalidatePlayToRequest();
});
Bukkit.getPluginManager().callEvent(new BattleEndEvent(this, reason));
String playerNames = "";
List<SpleefPlayer> alivePlayers = getAllInTeam(winner);
for (int i = 0; i < alivePlayers.size(); i++) {
SpleefPlayer sp = alivePlayers.get(i);
if (i == 0) {
playerNames = ChatColor.RED + sp.getName();
} else if (i == alivePlayers.size() - 1) {
playerNames += ChatColor.GREEN + " and " + ChatColor.RED + sp.getName();
} else {
playerNames += ChatColor.GREEN + ", " + ChatColor.RED + sp.getName();
}
}
String wStr = playerNames + ChatColor.GREEN + " have won!";
if (winner == null) {
wStr = "";
}
ChatManager.sendMessage(
getSpleefMode().getChatPrefix(),
ChatColor.GREEN + "Game in arena " + ChatColor.WHITE + getArena().getName() + ChatColor.GREEN +
" is over. " + wStr, SuperSpleef.getInstance().getEndMessageChannel()
);
if(reason == EndReason.NORMAL) {
applyRatingChange(winner);
}
cleanup();
}
@Override
protected GameHistory modifyGameHistory(GameHistory history) {
Optional<Team> winner = Arrays
.stream(history.getPlayers())
.filter(ghpd -> ghpd.isWinner())
.map(ghpd -> ghpd.getPlayer())
.findAny()
.map(sp -> playerTeams.get(sp));
if(winner.isPresent()) {
Team team = winner.get();
for(GameHistoryPlayerData ghpd : history.getPlayers()) {
if(playerTeams.get(ghpd.getPlayer()) == team) {
ghpd.setWinner(true);
}
}
}
return history;
}
@Override
public void onArenaLeave(SpleefPlayer player) {
handlePlayerDeath(player, false);
}
private void handlePlayerDeath(SpleefPlayer player, boolean leftGame) {
if (!leftGame && isInCountdown()) {
player.teleport(getData(player).getSpawn());
} else {
Team team = playerTeams.get(player);
if (!playerTeams.get(player).getAlivePlayers().contains(player)) {
return;
}
playerTeams.get(player).getAlivePlayers().remove(player);
if (team.getAlivePlayerCount() >= 1) {
if (!leftGame) {
giveTempSpectator(player);
applyTeamColor(player, team, false);
}
} else {
Team winner = null;
for (Team t : teams) {
if (team != t) {
if (t.isAlive()) {
if (winner == null) {
winner = t;
} else {
winner = null;
break;
}
}
}
}
if (winner != null) {
winner.increasePoints();
for (Entry<SpleefPlayer, Team> e : this.playerTeams.entrySet()) {
if (e.getValue() == winner) {
getData(e.getKey()).increasePoints();
}
}
getScoreboard().getObjective("rounds").getScore(winner.getName()).setScore(winner.getPoints());
if (winner.getPoints() < getPlayTo()) {
setRound(getRound() + 1);
ChatManager.sendMessage(
getSpleefMode().getChatPrefix(),
Theme.INFO.buildTheme(false) + "Team " + winner.getName() + ChatColor.YELLOW +
" has won round " + getRound(), getGameChannel()
);
startRound();
} else {
end(winner, EndReason.NORMAL);
}
} else {
if (!leftGame) {
giveTempSpectator(player);
}
ChatManager.sendMessage(
getSpleefMode().getChatPrefix(),
Theme.INFO.buildTheme(false) + "Team " + team.getName() + ChatColor.YELLOW + " died.",
getGameChannel()
);
}
}
}
reInitScoreboard();
}
@Override
public void startRound() {
for (Entry<SpleefPlayer, Team> entry : playerTeams.entrySet()) {
SpleefPlayer sp = entry.getKey();
entry.getValue().addPlayer(sp);
sp.setDead(false);
sp.setGameMode(GameMode.ADVENTURE);
sp.getInventory().setArmorContents(entry.getValue().getArmor());
applyTeamColor(sp, playerTeams.get(sp), true);
}
super.startRound();
}
@Override
protected void updateScoreboardTime() {
if (getScoreboard() == null) {
return;
}
Objective objective = getScoreboard().getObjective("rounds");
if (objective != null) {
String s = DurationFormatUtils.formatDuration(getTicksPassed() * 50, "HH:mm:ss", true);
objective.setDisplayName(ChatColor.GRAY.toString() + s + " | " + ChatColor.RED + "Score:");
}
}
public List<SpleefPlayer> getAllInTeam(Team team) {
ArrayList<SpleefPlayer> result = new ArrayList<>();
playerTeams.forEach((SpleefPlayer slPlayer, Team slTeam) -> {
if (slTeam.equals(team)) {
result.add(slPlayer);
}
});
return result;
}
public void resetTeamColor(SpleefPlayer p) {
SLPlayer sp = SpleefLeague.getInstance().getPlayerManager().get(p);
if (sp == null) {
return;
}
sp.setTabName(null);
sp.resetChatArrowColor();
}
public void applyTeamColor(SpleefPlayer p, Team t, boolean alive) {
SLPlayer sp = SpleefLeague.getInstance().getPlayerManager().get(p);
if (sp != null) {
if (alive) {
sp.setTabName(
t.getChatHighlightColor() + "[+ " +
t.getChatColor() + p.getName() +
t.getChatHighlightColor() + " +]"
);
} else {
sp.setTabName(
t.getChatHighlightColor() + ChatColor.ITALIC.toString() + "[- " +
t.getChatColor() + ChatColor.ITALIC.toString() + p.getName() +
t.getChatHighlightColor() + ChatColor.ITALIC.toString() + " -]"
);
}
sp.setChatArrowColor(t.getChatColor());
}
}
@Override
protected void applyRatingChange(SpleefPlayer winner) {
applyRatingChange(playerTeams.get(winner));
}
private void applyRatingChange(Team winner) {
double[] teamElo = new double[teams.length];
for (int i = 0; i < teams.length; i++) {
Team team = teams[i];
teamElo[i] = playerTeams.entrySet()
.stream()
.filter(e -> e.getValue() == team)
.mapToInt(e -> e.getKey().getRating(this.getSpleefMode()))
.average()
.getAsDouble();
}
double[] teamRatingChanges = new double[teams.length];
for (int i = 0; i < teamElo.length; i++) {
for (int j = i + 1; j < teamElo.length; j++) {
double t1 = teamElo[i];
double t2 = teamElo[j];
int compare = Integer.compare(teams[j].points, teams[i].points);
double ratingChange = Battle.calculateEloRatingChange(t1, t2, compare);
teamRatingChanges[i] += ratingChange;
teamRatingChanges[j] -= ratingChange;
}
}
for (int i = 0; i < teams.length; i++) {
teamRatingChanges[i] /= teamRatingChanges.length;
Team team = teams[i];
int ratingChange = (int)Math.ceil(teamRatingChanges[i]);
playerTeams
.entrySet()
.stream()
.filter(e -> e.getValue() == team)
.map(e -> e.getKey())
.forEach(sp -> {
sp.setRating(getSpleefMode(), sp.getRating(getSpleefMode()) + ratingChange);
sp.sendMessage(getSpleefMode().getChatPrefix() + ChatColor.GREEN + " You got " + ChatColor.WHITE + ratingChange + " points.");
});
}
}
private class Team {
private final Color color;
private final ChatColor chatColor;
private final ChatColor chatHighlightColor;
private final Set<SpleefPlayer> alivePlayers;
private final String name;
private int points = 0;
public Team(int id) {
this.color = colors[id];
this.chatColor = chatColors[id];
this.chatHighlightColor = chatHighlightColors[id];
this.alivePlayers = new HashSet<>();
this.name = chatColor + names[id];
}
public Color getColor() {
return color;
}
public ChatColor getChatColor() {
return chatColor;
}
public ChatColor getChatHighlightColor() {
return chatHighlightColor;
}
public Set<SpleefPlayer> getAlivePlayers() {
return alivePlayers;
}
public void addPlayer(SpleefPlayer sp) {
alivePlayers.add(sp);
}
public boolean isAlive() {
return !alivePlayers.isEmpty();
}
public int getAlivePlayerCount() {
return alivePlayers.size();
}
public String getName() {
return name;
}
public int getPoints() {
return points;
}
public void increasePoints() {
this.points++;
}
public ItemStack[] getArmor() {
ItemStack i1 = new ItemStack(Material.LEATHER_BOOTS);
LeatherArmorMeta meta = (LeatherArmorMeta) i1.getItemMeta();
meta.setColor(color);
i1.setItemMeta(meta);
ItemStack i2 = new ItemStack(Material.LEATHER_LEGGINGS);
meta = (LeatherArmorMeta) i2.getItemMeta();
meta.setColor(color);
i2.setItemMeta(meta);
ItemStack i3 = new ItemStack(Material.LEATHER_CHESTPLATE);
meta = (LeatherArmorMeta) i3.getItemMeta();
meta.setColor(color);
i3.setItemMeta(meta);
return new ItemStack[]{i1, i2, i3, null};
}
}
}
| gpl-3.0 |
kenoph/grub-tunes | src/main.js | 370 | // The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import 'bootstrap-loader';
import 'font-awesome/css/font-awesome.css'
Vue.use(require('vue-resource'));
/* eslint-disable no-new */
new Vue({
el: '#app',
render: h => h(App)
})
| gpl-3.0 |
ualegre/m2nusmv | m2nusmv/src/main/java/edu/casetools/dcase/m2nusmv/data/MData.java | 4201 | /*
* This file is part of M2NuSMV.
*
* M2NuSMV 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.
*
* M2NuSMV 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 M2NuSMV. If not, see <http://www.gnu.org/licenses/>.
*
*/
package edu.casetools.dcase.m2nusmv.data;
import java.util.ArrayList;
import java.util.List;
import edu.casetools.dcase.m2nusmv.data.elements.BoundedOperator;
import edu.casetools.dcase.m2nusmv.data.elements.Rule;
import edu.casetools.dcase.m2nusmv.data.elements.Specification;
import edu.casetools.dcase.m2nusmv.data.elements.State;
public class MData {
private int maxIteration;
private String filePath;
private List<State> states;
private List<State> independentStates;
private List<Rule> strs;
private List<Rule> ntrs;
private List<BoundedOperator> bops;
private List<Specification> specs;
public MData() {
initialiseLists();
}
private void initialiseLists() {
states = new ArrayList<>();
strs = new ArrayList<>();
ntrs = new ArrayList<>();
bops = new ArrayList<>();
specs = new ArrayList<>();
}
public int getMaxIteration() {
return maxIteration;
}
public void setMaxIteration(int maxIteration) {
this.maxIteration = maxIteration;
}
public void setIndependentStates(List<State> independentStates) {
this.independentStates = independentStates;
}
public List<State> getIndependentStates() {
independentStates = new ArrayList<>();
for (int i = 0; i < states.size(); i++) {
if (states.get(i).isIndependent()) {
independentStates.add(states.get(i));
}
}
return independentStates;
}
public List<State> getStates() {
return states;
}
public void setStates(List<State> states) {
this.states = states;
}
public List<Rule> getStrs() {
return strs;
}
public void setStrs(List<Rule> strs) {
this.strs = strs;
}
public List<Rule> getNtrs() {
return ntrs;
}
public void setNtrs(List<Rule> ntrs) {
this.ntrs = ntrs;
}
public List<BoundedOperator> getBops() {
return bops;
}
public List<BoundedOperator> getBops(BoundedOperator.BOP_TYPE type) {
List<BoundedOperator> list = new ArrayList<>();
for (int i = 0; i < bops.size(); i++) {
if (bops.get(i).getType() == type)
list.add(bops.get(i));
}
return list;
}
public void setBops(List<BoundedOperator> bops) {
this.bops = bops;
}
public int getBopNumber(BoundedOperator.BOP_TYPE type) {
int result = 0;
for (int i = 0; i < bops.size(); i++) {
if (bops.get(i).getType() == type)
result++;
}
return result;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public List<Specification> getSpecifications() {
return this.specs;
}
public void groupStrs() {
List<Rule> toRemove = new ArrayList<>();
int limit = 0;
if (!strs.isEmpty())
limit = 1;
for (Rule rule : strs) {
for (int j = limit; j < strs.size(); j++) {
if (rule.getConsequent().getName().equals(strs.get(j).getConsequent().getName())) {
rule.getSameConsequentRules().add(strs.get(j));
toRemove.add(strs.get(j));
}
}
limit++;
}
for (Rule rule : toRemove) {
strs.remove(rule);
}
}
public void groupNtrs() {
List<Rule> toRemove = new ArrayList<>();
int limit = 0;
if (!ntrs.isEmpty())
limit = 1;
for (Rule rule : ntrs) {
for (int j = limit; j < ntrs.size(); j++) {
if (rule.getConsequent().getName().equals(ntrs.get(j).getConsequent().getName())) {
rule.getSameConsequentRules().add(ntrs.get(j));
toRemove.add(ntrs.get(j));
}
}
limit++;
}
for (Rule rule : toRemove) {
ntrs.remove(rule);
}
}
}
| gpl-3.0 |
darthlukan/lynea | main.go | 4559 | package main
import (
"bufio"
// "errors"
"fmt"
"os"
"os/exec"
"os/signal"
"strings"
"syscall"
)
var (
ProcessStack []Process
sigChan = make(chan os.Signal, 1)
)
const (
DELAY = 10
// initSocket = "/run/lynea/init"
initSocket = "/home/darthlukan/tmp/lynea"
confDir = "/etc/init"
)
type Process struct {
Pid int
Cli string
}
type Command struct {
Type, Arg string
}
func (c Command) IsEmpty() bool {
if len(c.Type) == 0 && len(c.Arg) == 0 {
return true
}
return false
}
func RouteCommand(cmd Command) error {
// Which command are we?
var err error
var process Process
switch strings.ToLower(cmd.Type) {
case "enable":
// Set service to start with system (copy service.json to /etc/init/services/
case "disable":
// remove service.json from /etc/init/services/
case "start":
// process, err = Start()
case "restart":
// process, err = Restart()
case "stop":
// process, err = Stop()
default:
// err = errors.New("Nothing to do, is this really an error?")
}
if err == nil {
ProcessStack = append(ProcessStack, process)
}
return err
}
func Fork(command string) error {
var err error
prog := exec.Command(command)
go prog.Start()
return err
}
func Reboot() {
// Reboot system
// /sbin/reboot
}
func Shutdown() {
// Shutdown system
// /sbin/halt
}
func Poweroff() {
// Poweroff system
// /sbin/poweroff
}
func Start() {
// Start Process
}
func Restart() {
// Restart Process
}
func Stop() {
// Stop Process
}
func GetBaseServices() {
// Services required to have a minimally running system
// Defined in /etc/lynea/services/base
}
func DesiredServices() {
// Read from /etc/lynea/services/user_defined
// and Fork
}
func StartupSystem() {
// PID 1
// Socket dir /run
// Mount virtual filesystems
// Mount real filesystems
// Set $HOSTNAME (/proc/sys/kernel/hostname)
// Create tmpfiles
// Spawn TTYs
// Exec (Fork) base services
}
func MkNamedPipe() error {
return syscall.Mkfifo(initSocket, syscall.S_IFIFO|0666)
}
func ReadFromPipe() (string, error) {
recvData := make([]byte, 100)
np, err := os.Open(initSocket)
if err != nil {
fmt.Printf("ReadFromPipe open: %v\n", err)
}
defer np.Close()
count, err := np.Read(recvData)
if err != nil {
fmt.Printf("ReadFromPipe read: %v\n", err)
}
data := string(recvData[:count])
return data, err
}
func ParsePipeData(data string) Command {
// data is the content of initSocket, make sure to only read the last line sent in
// should be of structure: <command> <arg>
splitData := strings.Split(data, " ")
var cmd Command
if len(splitData) == 2 {
cmd.Type = splitData[0]
cmd.Arg = splitData[1]
fmt.Printf("returning cmd: %v\n", cmd)
}
return cmd
}
func PIDOneCheck() bool {
// Are we PID 1?
// look in /proc/1/status => Name (first line of file: "Name: $NAME")
// $NAME == "lynea" => true || false
pfile, err := os.Open("/proc/1/status")
if err != nil {
fmt.Printf("PIDOneCheck caught error: %v\n", err)
return false
}
defer pfile.Close()
var lines []string
scanner := bufio.NewScanner(pfile)
lineCounter := 0
for scanner.Scan() {
lines = append(lines, scanner.Text())
if lineCounter++; lineCounter >= 1 {
break
}
}
if strings.Contains(lines[0], "lynea") {
return true
}
return false
}
func init() {
fmt.Printf("Lynea initializing...\n")
err := MkNamedPipe()
if err != nil && err.Error() != "file exists" {
fmt.Printf("Init panic: %v\n", err) // TODO: Don't actually panic, try to drop to a shell or something
}
if pid1 := PIDOneCheck(); pid1 == true {
// execute bootup, base services, etc
fmt.Printf("Booting the system...\n")
StartupSystem() // TODO: Fill this out
}
}
func main() {
signal.Notify(sigChan, syscall.SIGINT)
signal.Notify(sigChan, syscall.SIGTERM)
signal.Notify(sigChan, syscall.SIGKILL)
go func() {
sig := <-sigChan
fmt.Printf("Received signal: %v\n", sig)
if sig == syscall.SIGINT || sig == syscall.SIGTERM {
os.Exit(1)
}
}()
fmt.Printf("Running...\n")
for {
// TODO: Determine if this can be handled safely by a goroutine, also, profile to see how performant it's not.
data, err := ReadFromPipe()
if err != nil {
if err.Error() != "EOF" && len(data) == 0 {
// We'll get EOF as a normal occurrence but we only care if data is not populated.
fmt.Printf("Received error: '%v' and data: '%v'\n", err, data)
}
}
if len(data) > 0 {
fmt.Printf("Received data: %v\n", data)
cmd := ParsePipeData(data)
if !cmd.IsEmpty() {
// route
}
}
// continue listening
}
}
| gpl-3.0 |
bigswitch/snac-nox | src/lib/vlog.cc | 13153 | /* Copyright 2008 (C) Nicira, Inc.
*
* This file is part of NOX.
*
* NOX 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.
*
* NOX 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 NOX. If not, see <http://www.gnu.org/licenses/>.
*/
#include "vlog.hh"
#include <algorithm>
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>
#include <errno.h>
#include <string>
#include <syslog.h>
#include <vector>
#include "hash_map.hh"
#include "string.hh"
namespace vigil {
static const int LOG_BUFFER_LEN = 2048;
static const char* level_names[Vlog::N_LEVELS] = {
"EMER",
"ERR",
"WARN",
"INFO",
"DBG"
};
const char*
Vlog::get_level_name(Level level)
{
assert(level < N_LEVELS);
return level_names[level];
}
Vlog::Level
Vlog::get_level_val(const char *name)
{
for (Level level = (Level) 0; level < N_LEVELS; level = level + 1) {
if (!strcasecmp(level_names[level], name)) {
return level;
}
}
return (Level) -1;
}
static const char* facility_names[Vlog::N_LEVELS] = {
"syslog",
"console",
};
const char*
Vlog::get_facility_name(Facility facility)
{
assert(facility >= 0 && facility < N_FACILITIES);
return facility_names[facility];
}
Vlog::Facility
Vlog::get_facility_val(const char* name)
{
for (Facility facility = 0; facility < N_FACILITIES; ++facility) {
if (!strcasecmp(facility_names[facility], name)) {
return facility;
}
}
return -1;
}
Vlog&
vlog()
{
static Vlog* the_vlog = new Vlog();
return *the_vlog;
}
typedef hash_map<std::string, Vlog::Module> Name_to_module;
typedef hash_map<Vlog::Level*, Vlog::Module> Cache_map;
struct Vlog_impl
{
int msg_num;
/* Module names. */
Name_to_module name_to_module;
std::vector<std::string> module_to_name;
size_t n_modules() { return module_to_name.size(); }
/* levels[facility][module] is the log level for 'module' on 'facility'. */
std::vector<Vlog::Level> levels[Vlog::N_FACILITIES];
Vlog::Level min_loggable_level(Vlog::Module);
/* default_levels[facility] is the log level for new modules on
* 'facility' */
Vlog::Level default_levels[Vlog::N_FACILITIES];
/* Map to a module, from a cached value for the minimum level needed to log
* that module. (The level pointer is unique but the module need not be,
* hence the "backward" mapping.) */
Cache_map min_level_caches;
void revalidate_cache_entry(const Cache_map::value_type&);
void revalidate_cache();
};
/* Returns the minimum logging level necessary for a message to the given
* 'module' to yield output on any logging facility. */
Vlog::Level
Vlog_impl::min_loggable_level(Vlog::Module module)
{
assert(module < n_modules());
Vlog::Level min_level = Vlog::LEVEL_EMER;
for (Vlog::Facility facility = 0; facility < Vlog::N_FACILITIES;
++facility) {
min_level = std::max(min_level, levels[facility][module]);
}
return min_level;
}
/* Re-validates the minimum logging level for the given cache 'entry'. */
void
Vlog_impl::revalidate_cache_entry(const Cache_map::value_type& entry)
{
Vlog::Level* cached_min_level = entry.first;
Vlog::Module module = entry.second;
*cached_min_level = min_loggable_level(module);
}
/* Re-validates the minimum logging level for every cached entry. */
void
Vlog_impl::revalidate_cache()
{
BOOST_FOREACH (const Cache_map::value_type& entry, min_level_caches) {
revalidate_cache_entry(entry);
}
}
const char*
Vlog::get_module_name(Module module)
{
assert(module < pimpl->module_to_name.size());
return pimpl->module_to_name[module].c_str();
}
Vlog::Module
Vlog::get_module_val(const char* name, bool create)
{
Name_to_module::iterator i = pimpl->name_to_module.find(name);
if (i == pimpl->name_to_module.end()) {
if (!create) {
return -1;
}
/* Create new module. */
Module module = pimpl->module_to_name.size();
pimpl->module_to_name.push_back(std::string(name));
Name_to_module::value_type value(name, module);
i = pimpl->name_to_module.insert(value).first;
/* Set log levels. */
for (Facility facility = 0; facility < N_FACILITIES; ++facility) {
pimpl->levels[facility].push_back(pimpl->default_levels[facility]);
}
}
return i->second;
}
static void
set_facility_level(Vlog_impl* pimpl,
Vlog::Facility facility, Vlog::Module module,
Vlog::Level level)
{
assert(facility < Vlog::N_FACILITIES);
assert(level < Vlog::N_LEVELS);
if (module == Vlog::ANY_MODULE) {
Vlog::Level& default_level = pimpl->default_levels[facility];
default_level = level;
pimpl->levels[facility].assign(pimpl->n_modules(), default_level);
} else {
pimpl->levels[facility][module] = level;
}
}
void
Vlog::set_levels(Facility facility, Module module, Level level)
{
assert(facility < N_FACILITIES || facility == ANY_FACILITY);
if (facility == ANY_FACILITY) {
for (Facility facility = 0; facility < N_FACILITIES; ++facility) {
set_facility_level(pimpl, facility, module, level);
}
} else {
set_facility_level(pimpl, facility, module, level);
}
pimpl->revalidate_cache();
}
bool
Vlog::is_loggable(Module module, Level level)
{
assert(module < pimpl->n_modules());
for (Facility facility = 0; facility < N_FACILITIES; ++facility) {
if (level <= pimpl->levels[facility][module]) {
return true;
}
}
return false;
}
/* Returns the minimum logging level necessary for a message to the given
* 'module' to yield output on any logging facility. */
Vlog::Level
Vlog::min_loggable_level(Module module)
{
return pimpl->min_loggable_level(module);
}
Vlog::Vlog()
: pimpl(new Vlog_impl)
{
/* This only need to be done once per program, but doing it more than once
* shouldn't hurt. */
::openlog("snac", LOG_NDELAY, 0);
pimpl->msg_num = 0;
for (Facility facility = 0; facility < N_FACILITIES; ++facility) {
pimpl->default_levels[facility] = LEVEL_WARN;
}
/* Create an initial module with value 0 so that no real module has that
* value. If any messages are logged by a statically defined Vlog_module
* before the Vlog_module's constructor is called, then its 'module' will
* be 0, so that its module name will be logged as "uninitialized". */
get_module_val("uninitialized");
}
Vlog::~Vlog()
{
delete pimpl;
}
void
Vlog::log(Module module, Level level, const char *format, ...)
{
if (!is_loggable(module, level)) {
return;
}
va_list arg;
char logMsg[LOG_BUFFER_LEN];
::va_start(arg, format);
::vsnprintf(logMsg, sizeof logMsg, format, arg);
::va_end(arg);
output(module, level, logMsg);
}
template <typename T, typename I>
static
void
iter_inc_throw_on_end(const T& t, I& i, const std::string& str, bool end)
{
++i;
if (end != (i == t.end())){
throw std::runtime_error(str);
}
}
//-----------------------------------------------------------------------------
// Set debugging levels:
//
// mod:facility:level mod2:facility:level
std::string
Vlog::set_levels_from_string(const std::string& str)
{
using namespace std;
using namespace boost;
char_separator<char> sepwhite(" \t");
char_separator<char> sepcol(":");
typedef tokenizer<char_separator<char> > charseptok;
charseptok tok(str,sepwhite);
for(charseptok::iterator beg = tok.begin(); beg != tok.end(); ++beg) {
charseptok curmod(*beg, sepcol);
/* Parse module. */
charseptok::iterator moditer = curmod.begin();
Module module;
if (*moditer == "ANY") {
module = ANY_MODULE;
} else {
module = get_module_val(moditer->c_str(), false);
if (module == -1) {
return "unknown module " + *moditer;
}
}
/* Parse facility. */
iter_inc_throw_on_end(curmod, moditer, "invalid token "+*beg, false);
Facility facility;
if (*moditer == "ANY") {
facility = ANY_FACILITY;
} else {
facility = get_facility_val((*moditer).c_str());
if (facility == -1) {
return "unknown facility " + *moditer;
}
}
/* Parse level. */
iter_inc_throw_on_end(curmod, moditer, "invalid token "+*beg, false);
Level level = get_level_val((*moditer).c_str());
if (level == -1) {
return "unknown level " + *moditer;
}
iter_inc_throw_on_end(curmod, moditer, "invalid token "+*beg, true);
/* Set level. */
set_levels(facility, module, level);
}
return "ack";
}
std::string
Vlog::get_levels()
{
std::string levels;
levels += " console syslog\n";
levels += " ------- ------\n";
for (size_t i=0; i < pimpl->n_modules() ; i++) {
string_printf(
levels,
"%-16s %4s %4s\n",
pimpl->module_to_name[i].c_str(),
get_level_name(pimpl->levels[FACILITY_CONSOLE][i]),
get_level_name(pimpl->levels[FACILITY_SYSLOG][i]));
}
return levels;
}
void
Vlog::output(Module module, Level level, const char* log_msg)
{
pimpl->msg_num++;
int save_errno = errno;
const char* module_name = get_module_name(module);
const char* level_name = get_level_name(level);
if (pimpl->levels[FACILITY_CONSOLE][module] >= level) {
size_t length = strlen(log_msg);
bool needs_new_line = !length || log_msg[length - 1] != '\n';
::fprintf(stderr, "%05d|%s|%s:%s%s",
pimpl->msg_num, module_name, level_name, log_msg,
needs_new_line ? "\n" : "");
}
if (pimpl->levels[FACILITY_SYSLOG][module] >= level) {
int priority
= (level == LEVEL_EMER ? LOG_EMERG
: level == LEVEL_ERR ? LOG_ERR
: level == LEVEL_WARN ? LOG_WARNING
: level == LEVEL_INFO ? LOG_INFO
: LOG_DEBUG);
::syslog(priority, "%05d|%s:%s %s",
pimpl->msg_num, module_name, level_name, log_msg);
}
/* Restore errno (it's pretty unfriendly for a log function to change
* errno). */
errno = save_errno;
}
/* Sets up '*cached_min_level' so that it will always be assigned the minimum
* logging level for output to 'module' to actually log to at least one
* facility. 'cached_min_level' must not already be in use as a level
* cache. */
void
Vlog::register_cache(Vlog::Module module, Level* cached_min_level)
{
Cache_map::value_type entry(cached_min_level, module);
bool unique = pimpl->min_level_caches.insert(entry).second;
assert(unique);
pimpl->revalidate_cache_entry(entry);
}
/* Removes 'cached_min_level' from use as a level cache. 'cached_min_level'
* must have previously been set up as a level cache with register_cache(). */
void
Vlog::unregister_cache(Level* cached_min_level)
{
bool deleted = pimpl->min_level_caches.erase(cached_min_level);
assert(deleted);
}
#define VLOG_MODULE_DO_LOG(LEVEL) \
if (is_enabled(LEVEL)) { \
int save_errno = errno; \
va_list args; \
va_start(args, format); \
char msg[LOG_BUFFER_LEN]; \
::vsnprintf(msg, sizeof msg, format, args); \
vlog().output(module, (LEVEL), msg); \
va_end(args); \
errno = save_errno; \
}
Vlog_module::Vlog_module(const char *module_name)
: module(vlog().get_module_val(module_name))
{
vlog().register_cache(module, &cached_min_level);
}
Vlog_module::~Vlog_module()
{
vlog().unregister_cache(&cached_min_level);
}
void Vlog_module::emer(const char *format, ...)
{
VLOG_MODULE_DO_LOG(Vlog::LEVEL_EMER);
}
void Vlog_module::err(const char *format, ...)
{
VLOG_MODULE_DO_LOG(Vlog::LEVEL_ERR);
}
void Vlog_module::warn(const char *format, ...)
{
VLOG_MODULE_DO_LOG(Vlog::LEVEL_WARN);
}
void Vlog_module::info(const char *format, ...)
{
VLOG_MODULE_DO_LOG(Vlog::LEVEL_INFO);
}
void Vlog_module::dbg(const char *format, ...)
{
VLOG_MODULE_DO_LOG(Vlog::LEVEL_DBG);
}
void Vlog_module::log(int level, const char *format, ...)
{
VLOG_MODULE_DO_LOG(level);
}
} // namespace vigil
| gpl-3.0 |
openDeal/openDeal | admin/controller/module/account.php | 4121 | <?php
class ControllerModuleAccount extends \Core\Controller {
private $error = array();
public function index() {
$this->language->load('module/account');
$this->document->setTitle($this->language->get('heading_title'));
$this->load->model('setting/setting');
if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
$this->model_setting_setting->editSetting('account', $this->request->post);
$this->session->data['success'] = $this->language->get('text_success');
$this->redirect($this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL'));
}
$this->data['heading_title'] = $this->language->get('heading_title');
$this->data['text_enabled'] = $this->language->get('text_enabled');
$this->data['text_disabled'] = $this->language->get('text_disabled');
$this->data['text_content_top'] = $this->language->get('text_content_top');
$this->data['text_content_bottom'] = $this->language->get('text_content_bottom');
$this->data['text_column_left'] = $this->language->get('text_column_left');
$this->data['text_column_right'] = $this->language->get('text_column_right');
$this->data['entry_layout'] = $this->language->get('entry_layout');
$this->data['entry_position'] = $this->language->get('entry_position');
$this->data['entry_status'] = $this->language->get('entry_status');
$this->data['entry_sort_order'] = $this->language->get('entry_sort_order');
$this->data['button_save'] = $this->language->get('button_save');
$this->data['button_cancel'] = $this->language->get('button_cancel');
$this->data['button_add_module'] = $this->language->get('button_add_module');
$this->data['button_remove'] = $this->language->get('button_remove');
if (isset($this->error['warning'])) {
$this->data['error_warning'] = $this->error['warning'];
} else {
$this->data['error_warning'] = '';
}
$this->data['breadcrumbs'] = array();
$this->data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
'separator' => false
);
$this->data['breadcrumbs'][] = array(
'text' => $this->language->get('text_module'),
'href' => $this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL'),
'separator' => ' :: '
);
$this->data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('module/account', 'token=' . $this->session->data['token'], 'SSL'),
'separator' => ' :: '
);
$this->data['action'] = $this->url->link('module/account', 'token=' . $this->session->data['token'], 'SSL');
$this->data['cancel'] = $this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL');
$this->data['modules'] = array();
if (isset($this->request->post['account_module'])) {
$this->data['modules'] = $this->request->post['account_module'];
} elseif ($this->config->get('account_module')) {
$this->data['modules'] = $this->config->get('account_module');
}
$this->load->model('design/layout');
$this->data['layouts'] = $this->model_design_layout->getLayouts();
$this->template = 'module/account.tpl';
$this->children = array(
'common/header',
'common/footer'
);
$this->response->setOutput($this->render());
}
protected function validate() {
if (!$this->user->hasPermission('modify', 'module/account')) {
$this->error['warning'] = $this->language->get('error_permission');
}
if (!$this->error) {
return true;
} else {
return false;
}
}
}
?> | gpl-3.0 |
lihouyu/php-micro-kernel | plugin/varhandler/var_handler.php | 3760 | <?php
/**
* Copyright 2009 HouYu Li <karadog@gmail.com>
*
* This file is part of PHP Micro Kernel.
*
* PHP Micro Kernel 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.
*
* PHP Micro Kernel 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 PHP Micro Kernel. If not, see <http://www.gnu.org/licenses/>.
*/
if (!defined('LPLUGINS')) die('Access violation error!');
/**
* Variable holder functions
*/
if (!isset($_SESSION[MYHOST]) || !is_array($_SESSION[MYHOST])) {
$_SESSION[MYHOST] = array();
}
if (!isset($_SESSION[MYHOST]['_$M']) || !is_array($_SESSION[MYHOST]['_$M'])) {
$_SESSION[MYHOST]['_$M'] = array();
}
/**
* Get HTTP or manually set variables
*
* @param string $var_name The name of the requesting variable
* @param string $scope The context of the requesting variable. One of following characters or combine of them.
* 'A': All context
* 'G': $_GET
* 'P': $_POST
* 'C': $_COOKIE
* 'F': $_FILE
* 'S': $_SESSION
* 'M': Manuals
* @param mixed $default If the requesting variable is not set or empty, this value is returned
* @return mixed
*/
function get_var($var_name, $scope = 'A', $default = false) {
if (!$scope) $scope = 'A';
if ($scope == 'A') $scope = 'SGPCFM';
$return_var = $default;
$raw_var = '';
for ($i = 0; $i < strlen($scope); $i++) {
if ($scope[$i] == 'S') {
$raw_var = _get_var($_SESSION[MYHOST], $var_name);
} else if ($scope[$i] == 'G') {
$raw_var = _get_var($_GET, $var_name);
} else if ($scope[$i] == 'P') {
$raw_var = _get_var($_POST, $var_name);
} else if ($scope[$i] == 'C') {
$raw_var = _get_var($_COOKIE, $var_name);
} else if ($scope[$i] == 'F') {
$raw_var = _get_var($_FILE, $var_name);
} else if ($scope[$i] == 'M') {
$raw_var = _get_var($_SESSION[MYHOST]['_$M'], $var_name);
}
if (is_string($raw_var) && strlen(trim($raw_var)) == 0) {
// Just for simplify the logic
} else {
$return_var = $raw_var;
break;
}
}
return $return_var;
} // get_var($var_name, $scope = 'A', $default = false)
/**
* This function should never be called directly
*/
function _get_var(&$container, $var_name) {
$return_var = '';
if (isset($container[$var_name])) {
if (is_bool($container[$var_name])) {
$return_var = $container[$var_name];
} else {
if (strlen(trim(strval($container[$var_name]))) > 0) {
$return_var = $container[$var_name];
}
}
}
return $return_var;
} // _get_var(&$container, $var_name)
/**
* Set manual variables
*
* @param string $var_name The name of the new variable
* @param string $val_val The name of the new variable
*/
function set_var($var_name, $var_val) {
$_SESSION[MYHOST]['_$M'][$var_name] = $var_val;
} // set_var($var_name, $var_val)
/**
* Set session variables
*
* @param string $var_name The name of the new variable
* @param string $val_val The name of the new variable
*/
function set_session($var_name, $var_val) {
$_SESSION[MYHOST][$var_name] = $var_val;
} // set_session($var_name, $var_val)
// Variable holder functions
| gpl-3.0 |
germanbraun/crowd-orm | web-src/coffee/views/eer/tools_eer.php | 1243 | <?php
/*
Copyright 2017 Giménez, Christian
Author: Giménez, Christian
tools_uml.php
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
?>
<div data-role="controlgroup" data-type="horizontal" data-mini="true">
<a class="ui-btn ui-mini ui-icon-plus ui-btn-icon-left ui-corner-all" id="eerclass_button">Class</a>
<a class="ui-btn ui-mini ui-icon-plus ui-btn-icon-right ui-corner-all" id="eerassoc_button">Assoc</a>
<a class="ui-btn ui-mini ui-icon-plus ui-btn-icon-right ui-corner-all" id="eerisa_button">IS-A</a>
<a class="ui-btn ui-mini ui-icon-plus ui-btn-icon-right ui-corner-all" id="eerattr_button">Attr</a>
<div>
| gpl-3.0 |
lebarde/scrapix | scraplib/fs.go | 2160 | // This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package scraplib
import (
log "github.com/Sirupsen/logrus"
"github.com/spf13/afero"
"os/user"
"runtime"
)
func getFs() afero.Fs {
return afero.NewOsFs()
}
func GetCacheLocation() string {
cacheLocation := getHomeLocation()+ ".cache/" + getName() + "/"
fs := new(afero.MemMapFs)
exists, err := afero.DirExists(fs, cacheLocation)
if err != nil {
log.Panic("Problem accessing directory " + cacheLocation)
panic(err)
}
if !exists {
log.Warn("Directory " + cacheLocation + " did not exist, creating.")
err = getFs().MkdirAll(cacheLocation, 0755)
if err != nil {
log.Panic("Problem creating directory " + cacheLocation)
panic(err)
}
}
return cacheLocation
}
func GetConfigLocation() string {
return getHomeLocation() + ".config/" + getName() + "/"
}
func getHomeLocation() string {
//var AppFs afero.Fs = afero.NewOsFs()
// Get the user's directory
usr, err := user.Current()
if err != nil {
log.Fatal("Could not get the user's directory.", err)
}
usrDir := usr.HomeDir
// The config directory depends on the system
switch os := runtime.GOOS; os {
case "darwin":
// Everything from apple
fallthrough
case "dragonfly":
fallthrough
case "freebsd":
fallthrough
case "netbsd":
fallthrough
case "openbsd":
fallthrough
case "android":
fallthrough
case "plan9":
fallthrough
case "solaris":
fallthrough
case "linux":
return usrDir + "/"
case "windows":
return usrDir + `\`
default:
return ""
}
}
func getName() string {
return "scrapix"
}
| gpl-3.0 |
tompecina/legal | legal/psj/views.py | 11889 | # -*- coding: utf-8 -*-
#
# psj/views.py
#
# Copyright (C) 2011-19 Tomáš Pecina <tomas@pecina.cz>
#
# This file is part of legal.pecina.cz, a web-based toolbox for lawyers.
#
# This application 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 application 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 datetime import date, datetime
from csv import writer as csvwriter
from json import dump
from re import compile
from locale import strxfrm
from django.shortcuts import redirect, HttpResponse
from django.views.decorators.http import require_http_methods
from django.views.decorators.gzip import gzip_page
from django.apps import apps
from django.urls import reverse
from django.http import QueryDict, Http404
from legal.common.glob import (
REGISTERS, NULL_REGISTERS, INERR, TEXT_OPTS_KEYS, ODP, EXLIM_TITLE, LOCAL_SUBDOMAIN, LOCAL_URL, DTF)
from legal.common.utils import Pager, new_xml, xml_decorate, composeref, xmlbool, LOGGER, render
from legal.psj.models import Hearing
from legal.psj.forms import MainForm
APP = __package__.rpartition('.')[2]
APPVERSION = apps.get_app_config(APP).version
BATCH = 50
EXLIM = 1000
@require_http_methods(('GET', 'POST'))
def mainpage(request):
LOGGER.debug('Main page accessed using method {}'.format(request.method), request, request.POST)
err_message = ''
page_title = apps.get_app_config(APP).verbose_name
if request.method == 'GET':
form = MainForm()
return render(
request,
'psj_mainpage.xhtml',
{'app': APP,
'page_title': page_title,
'err_message': err_message,
'form': form})
else:
form = MainForm(request.POST)
if form.is_valid():
cld = form.cleaned_data
if not cld['party']:
del cld['party_opt']
query = QueryDict(mutable=True)
for key in cld:
if cld[key]:
query[key] = cld[key]
query['start'] = 0
del query['format']
return redirect('{}?{}'.format(
reverse('{}:{}list'.format(APP, cld['format'])),
query.urlencode()))
else:
LOGGER.debug('Invalid form', request)
err_message = INERR
return render(
request,
'psj_mainpage.xhtml',
{'app': APP,
'page_title': page_title,
'err_message': err_message,
'form': form})
def g2p(reqd):
par = {}
lims = {
'senate': 0,
'number': 1,
'year': 1,
'courtroom': 1,
'judge': 1,
}
for fld in lims:
if fld in reqd:
par[fld] = npar = int(reqd[fld])
assert npar >= lims[fld]
if 'court' in reqd:
par['courtroom__court_id'] = reqd['court']
if 'register' in reqd:
assert reqd['register'] in REGISTERS
par['register'] = reqd['register']
if 'date_from' in reqd:
par['time__gte'] = datetime.strptime(reqd['date_from'], DTF).date()
if 'date_to' in reqd:
par['time__lt'] = datetime.strptime(reqd['date_to'], DTF).date() + ODP
if 'party_opt' in reqd:
assert reqd['party_opt'] in TEXT_OPTS_KEYS
if 'party' in reqd:
assert 'party_opt' in reqd
par['parties__name__' + reqd['party_opt']] = reqd['party']
return par
@require_http_methods(('GET',))
def htmllist(request):
LOGGER.debug('HTML list accessed', request, request.GET)
reqd = request.GET.copy()
try:
par = g2p(reqd)
start = int(reqd['start']) if 'start' in reqd else 0
assert start >= 0
res = Hearing.objects.filter(**par).order_by('-time', 'pk').distinct()
except:
raise Http404
total = res.count()
if total and start >= total:
start = total - 1
return render(
request,
'psj_list.xhtml',
{'app': APP,
'page_title': 'Výsledky vyhledávání',
'rows': res[start:start + BATCH],
'pager': Pager(start, total, reverse('psj:htmllist'), reqd, BATCH),
'today': date.today(),
'total': total,
'NULL_REGISTERS': NULL_REGISTERS,
'noindex': True})
@gzip_page
@require_http_methods(('GET',))
def xmllist(request):
LOGGER.debug('XML list accessed', request, request.GET)
reqd = request.GET.copy()
try:
par = g2p(reqd)
res = Hearing.objects.filter(**par).order_by('time', 'pk').distinct()
except:
raise Http404
total = res.count()
if total > EXLIM:
return render(
request,
'exlim.xhtml',
{'app': APP,
'page_title': EXLIM_TITLE,
'limit': EXLIM,
'total': total,
'back': reverse('psj:mainpage')})
dec = {
'hearings': {
'xmlns': 'http://' + LOCAL_SUBDOMAIN,
'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:schemaLocation': 'http://{} {}/static/{}-{}.xsd'
.format(LOCAL_SUBDOMAIN, LOCAL_URL, APP, APPVERSION),
'application': APP,
'version': APPVERSION,
'created': datetime.now().replace(microsecond=0).isoformat()
}
}
xml = new_xml('')
tag_hearings = xml_decorate(xml.new_tag('hearings'), dec)
xml.append(tag_hearings)
for item in res:
tag_hearing = xml.new_tag('hearing')
tag_hearings.append(tag_hearing)
tag_court = xml.new_tag('court')
tag_hearing.append(tag_court)
tag_court['id'] = item.courtroom.court_id
tag_court.append(item.courtroom.court.name)
tag_courtroom = xml.new_tag('courtroom')
tag_hearing.append(tag_courtroom)
tag_courtroom.append(item.courtroom.desc)
tag_time = xml.new_tag('time')
tag_hearing.append(tag_time)
tag_time.append(item.time.replace(microsecond=0).isoformat())
tag_ref = xml.new_tag('ref')
tag_hearing.append(tag_ref)
tag_senate = xml.new_tag('senate')
tag_senate.append(str(item.senate))
tag_ref.append(tag_senate)
tag_register = xml.new_tag('register')
tag_register.append(item.register)
tag_ref.append(tag_register)
tag_number = xml.new_tag('number')
tag_number.append(str(item.number))
tag_ref.append(tag_number)
tag_year = xml.new_tag('year')
tag_year.append(str(item.year))
tag_ref.append(tag_year)
tag_judge = xml.new_tag('judge')
tag_hearing.append(tag_judge)
tag_judge.append(item.judge.name)
tag_parties = xml.new_tag('parties')
tag_hearing.append(tag_parties)
for party in item.parties.values():
tag_party = xml.new_tag('party')
tag_parties.append(tag_party)
tag_party.append(party['name'])
tag_form = xml.new_tag('form')
tag_hearing.append(tag_form)
tag_form.append(item.form.name)
tag_closed = xml.new_tag('closed')
tag_hearing.append(tag_closed)
tag_closed.append(xmlbool(item.closed))
tag_cancelled = xml.new_tag('cancelled')
tag_hearing.append(tag_cancelled)
tag_cancelled.append(xmlbool(item.cancelled))
response = HttpResponse(
str(xml).encode('utf-8') + b'\n',
content_type='text/xml; charset=utf-8')
response['Content-Disposition'] = 'attachment; filename=Jednani.xml'
return response
@gzip_page
@require_http_methods(('GET',))
def csvlist(request):
LOGGER.debug('CSV list accessed', request, request.GET)
reqd = request.GET.copy()
try:
par = g2p(reqd)
res = Hearing.objects.filter(**par).order_by('time', 'pk').distinct()
except:
raise Http404
total = res.count()
if total > EXLIM:
return render(
request,
'exlim.xhtml',
{'app': APP,
'page_title': EXLIM_TITLE,
'limit': EXLIM,
'total': total,
'back': reverse('psj:mainpage')})
response = HttpResponse(content_type='text/csv; charset=utf-8')
response['Content-Disposition'] = 'attachment; filename=Jednani.csv'
writer = csvwriter(response)
hdr = (
'Soud',
'Jednací síň',
'Datum',
'Čas',
'Spisová značka',
'Řešitel',
'Účastníci řízení',
'Druh jednání',
'Neveřejné',
'Zrušeno',
)
writer.writerow(hdr)
for item in res:
dat = (
item.courtroom.court.name,
item.courtroom.desc,
'{:%d.%m.%Y}'.format(item.time),
'{:%H:%M}'.format(item.time),
composeref(item.senate, item.register, item.number, item.year),
item.judge.name,
';'.join([p['name'] for p in item.parties.values()]),
item.form.name,
'ano' if item.closed else 'ne',
'ano' if item.cancelled else 'ne',
)
writer.writerow(dat)
return response
@gzip_page
@require_http_methods(('GET',))
def jsonlist(request):
LOGGER.debug('JSON list accessed', request, request.GET)
reqd = request.GET.copy()
try:
par = g2p(reqd)
res = Hearing.objects.filter(**par).order_by('time', 'pk').distinct()
except:
raise Http404
total = res.count()
if total > EXLIM:
return render(
request,
'exlim.xhtml',
{'app': APP,
'page_title': EXLIM_TITLE,
'limit': EXLIM,
'total': total,
'back': reverse('psj:mainpage')})
response = HttpResponse(content_type='application/json; charset=utf-8')
response['Content-Disposition'] = 'attachment; filename=Jednani.json'
lst = []
for item in res:
court = {
'id': item.courtroom.court.id,
'name': item.courtroom.court.name,
}
lst.append({
'court': court,
'courtroom': item.courtroom.desc,
'time': item.time.isoformat(),
'ref': {
'senate': item.senate,
'register': item.register,
'number': item.number,
'year': item.year,
},
'judge': item.judge.name,
'parties': [p['name'] for p in item.parties.values()],
'form': item.form.name,
'closed': item.closed,
'cancelled': item.cancelled,
})
dump(lst, response)
return response
SJ_RE = compile(r'^(\S*\.\S*\s)*(.*)$')
def stripjudge(name):
return strxfrm(SJ_RE.match(name['judge__name']).group(2))
@require_http_methods(('GET',))
def courtinfo(request, court):
LOGGER.debug('Court information accessed, court="{}"'.format(court), request)
courtrooms = (
Hearing.objects.filter(courtroom__court_id=court).values('courtroom_id', 'courtroom__desc').distinct()
.order_by('courtroom__desc'))
judges = list(Hearing.objects.filter(courtroom__court_id=court).values('judge_id', 'judge__name').distinct())
judges.sort(key=stripjudge)
return render(
request,
'psj_court.xhtml',
{'courtrooms': courtrooms,
'judges': judges},
content_type='text/plain; charset=utf-8')
| gpl-3.0 |
onedanshow/Screen-Courter | lib/src/org/apache/http/impl/conn/AbstractPooledConnAdapter.java | 5957 | /*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.conn;
import java.io.IOException;
import org.apache.http.HttpHost;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.OperatedClientConnection;
/**
* Abstract adapter from pool {@link AbstractPoolEntry entries} to
* {@link org.apache.http.conn.ManagedClientConnection managed}
* client connections.
* The connection in the pool entry is used to initialize the base class.
* In addition, methods to establish a route are delegated to the
* pool entry. {@link #shutdown shutdown} and {@link #close close}
* will clear the tracked route in the pool entry and call the
* respective method of the wrapped connection.
*
* @since 4.0
*/
public abstract class AbstractPooledConnAdapter extends AbstractClientConnAdapter {
/** The wrapped pool entry. */
protected volatile AbstractPoolEntry poolEntry;
/**
* Creates a new connection adapter.
*
* @param manager the connection manager
* @param entry the pool entry for the connection being wrapped
*/
protected AbstractPooledConnAdapter(ClientConnectionManager manager,
AbstractPoolEntry entry) {
super(manager, entry.connection);
this.poolEntry = entry;
}
/**
* Obtains the pool entry.
*
* @return the pool entry, or <code>null</code> if detached
*/
protected AbstractPoolEntry getPoolEntry() {
return this.poolEntry;
}
/**
* Asserts that there is a valid pool entry.
*
* @throws ConnectionShutdownException if there is no pool entry
* or connection has been aborted
*
* @see #assertValid(OperatedClientConnection)
*/
protected void assertValid(final AbstractPoolEntry entry) {
if (isReleased() || entry == null) {
throw new ConnectionShutdownException();
}
}
/**
* @deprecated use {@link #assertValid(AbstractPoolEntry)}
*/
@Deprecated
protected final void assertAttached() {
if (poolEntry == null) {
throw new ConnectionShutdownException();
}
}
/**
* Detaches this adapter from the wrapped connection.
* This adapter becomes useless.
*/
@Override
protected synchronized void detach() {
poolEntry = null;
super.detach();
}
public HttpRoute getRoute() {
AbstractPoolEntry entry = getPoolEntry();
assertValid(entry);
return (entry.tracker == null) ? null : entry.tracker.toRoute();
}
public void open(HttpRoute route,
HttpContext context, HttpParams params)
throws IOException {
AbstractPoolEntry entry = getPoolEntry();
assertValid(entry);
entry.open(route, context, params);
}
public void tunnelTarget(boolean secure, HttpParams params)
throws IOException {
AbstractPoolEntry entry = getPoolEntry();
assertValid(entry);
entry.tunnelTarget(secure, params);
}
public void tunnelProxy(HttpHost next, boolean secure, HttpParams params)
throws IOException {
AbstractPoolEntry entry = getPoolEntry();
assertValid(entry);
entry.tunnelProxy(next, secure, params);
}
public void layerProtocol(HttpContext context, HttpParams params)
throws IOException {
AbstractPoolEntry entry = getPoolEntry();
assertValid(entry);
entry.layerProtocol(context, params);
}
public void close() throws IOException {
AbstractPoolEntry entry = getPoolEntry();
if (entry != null)
entry.shutdownEntry();
OperatedClientConnection conn = getWrappedConnection();
if (conn != null) {
conn.close();
}
}
public void shutdown() throws IOException {
AbstractPoolEntry entry = getPoolEntry();
if (entry != null)
entry.shutdownEntry();
OperatedClientConnection conn = getWrappedConnection();
if (conn != null) {
conn.shutdown();
}
}
public Object getState() {
AbstractPoolEntry entry = getPoolEntry();
assertValid(entry);
return entry.getState();
}
public void setState(final Object state) {
AbstractPoolEntry entry = getPoolEntry();
assertValid(entry);
entry.setState(state);
}
}
| gpl-3.0 |
gelendir/scout102 | Site/protected/views/accueil/error.php | 225 | <?php
$this->pageTitle=Yii::app()->name . ' - ' . Yii::t( 'login', 'error' );
?>
<h1>Erreur <?php echo $code; ?></h2>
<div class="alert-message error">
<p>
<?php echo CHtml::encode($message); ?>
</p>
</div>
| gpl-3.0 |
iterate-ch/cyberduck | windows/src/main/csharp/ch/cyberduck/ui/winforms/PromptForm.cs | 2445 | //
// Copyright (c) 2010-2016 Yves Langisch. All rights reserved.
// http://cyberduck.io/
//
// 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.
//
// Bug fixes, suggestions and comments should be sent to:
// feedback@cyberduck.io
//
using System;
using System.Drawing;
using System.Media;
using System.Windows.Forms;
using Ch.Cyberduck.Ui.Controller;
namespace Ch.Cyberduck.Ui.Winforms
{
public partial class PromptForm : BaseForm, IPromptView
{
public PromptForm()
{
InitializeComponent();
AutoSize = true;
FormClosing += delegate(object sender, FormClosingEventArgs args)
{
bool valid = true;
if (ValidateInput != null)
{
foreach (var d in ValidateInput.GetInvocationList())
{
valid = (bool) d.DynamicInvoke();
if (!valid)
{
break;
}
}
}
bool cancel = DialogResult != DialogResult.Cancel && !valid;
if (cancel)
{
args.Cancel = true;
SystemSounds.Beep.Play();
}
};
MinimumSize = new Size(400, 150);
}
protected override bool EnableAutoSizePosition => false;
public override string[] BundleNames => new[] {"Folder", "Cryptomator", "Keychain"};
public string InputText
{
get { return inputTextBox.Text; }
set { inputTextBox.Text = value; }
}
public Image IconView
{
set { pictureBox.Image = value; }
}
public event ValidateInputHandler ValidateInput;
private void PromptForm_Shown(object sender, EventArgs e)
{
inputTextBox.Focus();
inputTextBox.SelectAll();
}
}
}
| gpl-3.0 |
pinheadmz/LTB-Companion-Wallet | Chrome Extension/popup.js | 38786 | function getNews(){
var source_html = "https://letstalkbitcoin.com/api/v1/blog/posts?limit=5";
$("#newsStories").html("<div align='center' style='padding-top: 30px;'>Loading...</div>");
$.getJSON( source_html, function( data ) {
$("#newsStories").html("");
$.each(data.posts, function(i, item) {
var date = data.posts[i]["publishDate"];
var title = data.posts[i]["title"];
var url = data.posts[i]["url"];
var image = data.posts[i]["coverImage"];
//console.log(image);
var title_display = "<a class='newslink' href='https://letstalkbitcoin.com/blog/post/"+url+"'><div class='newsArticle' align='center'><img src='"+image+"' height='240px' width='240px'><div class='lead' style='padding: 20px 0 0 0;'>"+title+"</div><div style='padding: 5px 0 10px 0;' class='small'>Published "+date.substring(0,10)+"</div></div></a>";
//console.log(data);
$("#newsStories").append(title_display);
});
});
}
function searchLTBuser(username){
var source_html = "https://letstalkbitcoin.com/api/v1/users?search="+username;
$("#ltbDirectorySearchResults").html("<div align='center' style='padding-top: 10px;'>Loading...</div>");
$.getJSON( source_html, function( data ) {
$("#ltbDirectorySearchResults").html("");
$.each(data.users, function(i, item) {
var username = data.users[i]["username"];
var avatar = data.users[i]["avatar"];
var registered = data.users[i]["regDate"];
if (i > 0) {
$("#ltbDirectorySearchResults").append("<hr>");
}
$("#ltbDirectorySearchResults").append("<div style='display: inline-block; padding: 0 20px 10px 0;'><img src='"+avatar+"' height='64px' width='64px'></div>");
$("#ltbDirectorySearchResults").append("<div style='display: inline-block;' class='ltbDirectoryUsername'>"+username+"</div>");
$("#ltbDirectorySearchResults").append("<div class='ltbDirectoryAddress'><i>Date Registered:</i><br>"+registered.substring(0,10)+"</div>");
if(data.users[i]["profile"] == null || data.users[i]["profile"]["ltbcoin-address"] == undefined) {
$("#ltbDirectorySearchResults").append("<div class='ltbDirectoryAddress'><i>LTBCOIN Address:</i><br>No Address Listed</div>");
} else {
var ltbaddress = data.users[i]["profile"]["ltbcoin-address"]["value"];
$("#ltbDirectorySearchResults").append("<div class='ltbDirectoryAddress'><i>LTBCOIN Address:</i><br><div class='movetosend' style='display: inline-block;'>"+ltbaddress+"</div></div>");
}
});
});
}
function setEncryptedTest() {
chrome.storage.local.set(
{
'encrypted': true
}, function () {
getStorage();
});
}
function setPinBackground() {
var randomBackground = Math.floor(Math.random() * 6);
var bg_link = "url('/pin_bg/"+randomBackground+".jpg')";
$("#pinsplash").css("background-image", bg_link);
$("#pinsplash").css("background-size", "330px 350px");
}
function getStorage()
{
chrome.storage.local.get(["passphrase", "encrypted", "firstopen"], function (data)
{
if ( data.firstopen == false ) {
$(".bg").css("min-height", "200px");
$("#welcomesplash").hide();
if ( data.encrypted == false) {
existingPassphrase(data.passphrase);
} else if ( data.encrypted == true) {
$(".hideEncrypted").hide();
$("#pinsplash").show();
$("#priceBox").hide();
} else {
newPassphrase();
}
} else {
$("#welcomesplash").show();
}
});
}
function copyToClipboard(text){
var copyDiv = document.createElement('div');
copyDiv.contentEditable = true;
document.body.appendChild(copyDiv);
copyDiv.innerHTML = text;
copyDiv.unselectable = "off";
copyDiv.focus();
document.execCommand('SelectAll');
document.execCommand("Copy", false, null);
document.body.removeChild(copyDiv);
}
//function getBlockHeight(){
// var source_html = "https://insight.bitpay.com/api/sync";
//
// $.getJSON( source_html, function( data ) {
//
// var block = data.blockChainHeight;
// return block;
//
// });
//}
function showBTCtransactions(transactions) {
//$("#btcbalance").html("<div style='font-size: 12px;'>You can perform "+transactions.toFixed(0)+" transactions</div><div id='depositBTC' align='center' style='margin: 5px; cursor: pointer; text-decoration: underline; font-size: 11px; color: #999;'>Deposit bitcoin for transaction fees</div>");
if (transactions == 0) {
$("#btcbalance").html("<div style='font-size: 12px;'>Deposit bitcoin to send tokens from this address.<span id='txsAvailable' style='display: none;'>"+transactions.toFixed(0)+"</span></div>");
} else {
$("#btcbalance").html("<div style='font-size: 12px;'>You can perform <span id='txsAvailable'>"+transactions.toFixed(0)+"</span> transactions</div>");
}
//var titletext = data + " satoshis";
//$("#btcbalbox").prop('title', titletext);
$("#btcbalbox").show();
}
function qrdepositDropdown() {
var currentaddr = $("#xcpaddress").html();
$("#btcbalance").html("Deposit bitcoin for transaction fees<div style='margin: 20px 0 10px 0; font-size: 10px; font-weight: bold;'>"+currentaddr+"</div><div id='btcqr' style='margin: 10px auto 20px auto; height: 100px; width: 100px;'></div><div>Cost per transaction is 0.00015470 BTC</div></div>");
var qrcode = new QRCode(document.getElementById("btcqr"), {
text: currentaddr,
width: 100,
height: 100,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.H
});
//$("#btcbalbox").prop('title', "");
$("#btcbalbox").show();
}
function getBTCBalance(pubkey) {
//var source_html = "https://insight.bitpay.com/api/addr/"+pubkey+"/balance";
//var source_html = "https://chain.localbitcoins.com/api/addr/"+pubkey+"/balance";
//var source_html = "https://chain.so/api/v2/get_address_balance/BTC/"+pubkey;
var source_html = "http://btc.blockr.io/api/v1/address/info/"+pubkey; //blockr
$("#isbtcloading").html("true");
//$.getJSON( source_html, function( data ) { //insight
$.getJSON( source_html, function( apidata ) { //blockr
//var bitcoinparsed = parseFloat(data) / 100000000; //insight
//var bitcoinparsed = (parseFloat(data.data.confirmed_balance) + parseFloat(data.data.unconfirmed_balance)).toFixed(8); //chainso
var bitcoinparsed = parseFloat(apidata.data.balance); //blockr
$("#isbtcloading").html("false");
$("#btcbalhide").html(bitcoinparsed);
//var transactions = (parseFloat(data) / 15470) ; //insight
//var transactions = (parseFloat(data.data.confirmed_balance) + parseFloat(data.data.unconfirmed_balance))/ 0.0001547; //chainso
var transactions = (parseFloat(apidata.data.balance) / 0.0001547) ; //blockr
if (transactions < 1) {
transactions = 0;
}
showBTCtransactions(transactions);
});
}
function getPrimaryBalanceXCP(pubkey, currenttoken) {
// var source_html = "https://insight.bitpay.com/api/sync";
//
// $.getJSON( source_html, function( data ) {
//
// var block = data.blockChainHeight;
//
// });
// chrome.storage.local.get('unconfirmedtx', function (data)
// {
// if(isset(data)){
// $.each(data.tx
// }, function(){
//
// });
//console.log(pubkey);
//console.log(currenttoken);
if (currenttoken == "XCP") {
//var source_html = "http://xcp.blockscan.com/api2?module=address&action=balance&btc_address="+pubkey+"&asset="+currenttoken;
var source_html = "http://counterpartychain.io/api/address/"+pubkey;
$.getJSON( source_html, function( data ) {
//var assetbalance = parseFloat(data.data[0].balance) + parseFloat(data.data[0].unconfirmed_balance);
var assetbalance = data.xcp_balance;
if (typeof assetbalance === 'undefined') {
assetbalance = 0;
}
assetbalance = parseFloat(assetbalance).toString();
$("#isdivisible").html("yes");
$("#xcpbalance").html("<span id='currentbalance'>" + assetbalance + "</span><span class='unconfirmedbal'></span><br><div style='font-size: 22px; font-weight: bold;'><span id='currenttoken'>" + currenttoken + "</span>");
$('#assetbalhide').html(assetbalance);
getRate(assetbalance, pubkey, currenttoken);
});
} else {
var source_html = "https://counterpartychain.io/api/balances/"+pubkey;
//var source_html = "http://xcp.blockscan.com/api2?module=address&action=balance&btc_address="+pubkey+"&asset="+currenttoken;
$.getJSON( source_html, function( data ) {
$.each(data.data, function(i, item) {
var assetname = data.data[i].asset;
if(assetname == currenttoken) {
var assetbalance = data.data[i].amount;
if(assetbalance.indexOf('.') !== -1)
{
$("#isdivisible").html("yes");
} else {
$("#isdivisible").html("no");
}
assetbalance = parseFloat(assetbalance).toString();
//var assetbalance = parseFloat(data.data[0].balance) + parseFloat(data.data[0].unconfirmed_balance);
$("#xcpbalance").html("<span id='currentbalance'>" + assetbalance + "</span><span class='unconfirmedbal'></span><br><div style='font-size: 22px; font-weight: bold;'><span id='currenttoken'>" + currenttoken + "</span>");
$('#assetbalhide').html(assetbalance);
getRate(assetbalance, pubkey, currenttoken);
}
});
});
}
if (typeof assetbalance === 'undefined') {
$("#xcpbalance").html("<span id='currentbalance'>0</span><span class='unconfirmedbal'></span><br><div style='font-size: 22px; font-weight: bold;'>" + currenttoken + "</div>");
$('#assetbalhide').html(0);
getRate(0, pubkey, currenttoken);
}
}
function getPrimaryBalanceBTC(pubkey){
//var source_html = "https://blockchain.info/q/addressbalance/"+pubkey;
//var source_html = "https://chain.so/api/v2/get_address_balance/BTC/"+pubkey;
var source_html = "http://btc.blockr.io/api/v1/address/info/"+pubkey;
//var source_html = "https://insight.bitpay.com/api/addr/"+pubkey+"/balance";
//var source_html = "https://chain.localbitcoins.com/api/addr/"+pubkey+"/balance";
$.getJSON( source_html, function( apidata ) { //blockr
//$.getJSON( source_html, function( data ) { //insight
//var bitcoinparsed = parseFloat(data) / 100000000; //insight
var bitcoinparsed = parseFloat(apidata.data.balance); //blockr
//var bitcoinparsed = (parseFloat(data.data.confirmed_balance) + parseFloat(data.data.unconfirmed_balance)).toFixed(8); //chainso
$("#xcpbalance").html(bitcoinparsed + "<br><div style='font-size: 22px; font-weight: bold;'>BTC</div>");
// if (bitcoinparsed.toFixed(8) == 0) {
// $("#btcsendbox").hide();
// } else {
// $("#btcsendbox").show();
// }
getRate(bitcoinparsed, pubkey, "BTC");
});
}
function getPrimaryBalance(pubkey){
$("#btcsendbox").hide();
var currenttoken = $(".currenttoken").html();
if (currenttoken != "BTC") {
getPrimaryBalanceXCP(pubkey, currenttoken);
} else {
getPrimaryBalanceBTC(pubkey);
}
}
function getRate(assetbalance, pubkey, currenttoken){
if ($("#ltbPrice").html() == "...") {
$.getJSON( "http://www.coincap.io/front/", function( data ) {
$.each(data, function(i, item) {
var assetname = data[i].short;
if (assetname == "LTBC") {
var ltbprice = 1 / parseFloat(data[i].price);
$("#ltbPrice").html(Number(ltbprice.toFixed(0)).toLocaleString('en'));
$("#ltbPrice").data("ltbcoin", { price: ltbprice.toFixed(0) });
if (currenttoken == "LTBCOIN") {
var usdValue = parseFloat(data[i].price) * parseFloat(assetbalance);
$("#xcpfiatValue").html(usdValue.toFixed(2));
$("#switchtoxcp").hide();
$("#fiatvaluebox").show();
} else {
$("#fiatvaluebox").hide();
$("#switchtoxcp").show();
}
}
});
// $.getJSON( "http://joelooney.org/ltbcoin/ltb.php", function( data ) {
//
// var ltbprice = 1 / parseFloat(data.usd_ltb);
//
// $("#ltbPrice").html(Number(ltbprice.toFixed(0)).toLocaleString('en'));
// $("#ltbPrice").data("ltbcoin", { price: ltbprice.toFixed(0) });
//
// if (currenttoken == "LTBCOIN") {
// var usdValue = parseFloat(data.usd_ltb) * parseFloat(assetbalance);
//
// $("#xcpfiatValue").html(usdValue.toFixed(2));
// $("#switchtoxcp").hide();
// $("#fiatvaluebox").show();
// } else {
// $("#fiatvaluebox").hide();
// $("#switchtoxcp").show();
// }
//
//
});
} else {
if (currenttoken == "LTBCOIN") {
var ltbrate = $("#ltbPrice").data("ltbcoin").price;
var usdrate = 1 / parseFloat(ltbrate);
var usdValue = usdrate * parseFloat(assetbalance);
$("#xcpfiatValue").html(usdValue.toFixed(2));
$("#switchtoxcp").hide();
$("#fiatvaluebox").show();
} else if (currenttoken == "BTC") {
//var btcrate = $("#btcPrice").html();
//var usdValue = btcrate * parseFloat(assetbalance);
//$("#xcpfiatValue").html(usdValue.toFixed(2));
$("#fiatvaluebox").hide();
$("#switchtoxcp").show();
} else {
$("#fiatvaluebox").hide();
$("#switchtoxcp").show();
}
}
getBTCBalance(pubkey);
}
function convertPassphrase(m){
var HDPrivateKey = bitcore.HDPrivateKey.fromSeed(m.toHex(), bitcore.Networks.livenet);
var derived = HDPrivateKey.derive("m/0'/0/" + 0);
var address1 = new bitcore.Address(derived.publicKey, bitcore.Networks.livenet);
var pubkey = address1.toString();
$("#xcpaddressTitle").show();
$("#xcpaddress").html(pubkey);
getPrimaryBalance(pubkey);
}
function assetDropdown(m)
{
$(".addressselect").html("");
var HDPrivateKey = bitcore.HDPrivateKey.fromSeed(m.toHex(), bitcore.Networks.livenet);
chrome.storage.local.get(function(data) {
var totaladdress = data["totaladdress"];
var addresslabels = data["addressinfo"];
for (var i = 0; i < totaladdress; i++) {
var derived = HDPrivateKey.derive("m/0'/0/" + i);
var address1 = new bitcore.Address(derived.publicKey, bitcore.Networks.livenet);
var pubkey = address1.toString();
$(".addressselect").append("<option label='"+addresslabels[i].label+"' title='"+pubkey+"'>"+pubkey+"</option>");
if (i == 0) {
$(".addressselect").attr("title",pubkey);
}
//.slice(0,12)
//$(".addressselect").append("<option label='"+pubkey+"'>"+pubkey+"</option>");
}
$(".addressselect").append("<option label='--- Add New Address ---'>add</option>");
});
}
function dynamicAddressDropdown(addresslabels, type)
{
var string = $("#newpassphrase").html();
var array = string.split(" ");
m = new Mnemonic(array);
var currentsize = $('#walletaddresses option').size();
if (type == "newlabel") {
currentsize = currentsize - 1;
var addressindex = $("#walletaddresses option:selected").index();
}
$(".addressselect").html("");
var HDPrivateKey = bitcore.HDPrivateKey.fromSeed(m.toHex(), bitcore.Networks.livenet);
for (var i = 0; i < currentsize; i++) {
var derived = HDPrivateKey.derive("m/0'/0/" + i);
var address1 = new bitcore.Address(derived.publicKey, bitcore.Networks.livenet);
var pubkey = address1.toString();
//$(".addressselect").append("<option label='"+pubkey+"'>"+pubkey+"</option>");
$(".addressselect").append("<option label='"+addresslabels[i].label+"' title='"+pubkey+"'>"+pubkey+"</option>");
}
$(".addressselect").append("<option label='--- Add New Address ---'>add</option>");
if (type == "newaddress") {
getBTCBalance(pubkey);
var newaddress_position = parseInt(currentsize) - 1;
var newaddress_val = $(newaddress_select).val();
$("#xcpaddress").html(newaddress_val);
getPrimaryBalance(newaddress_val);
} else {
var newaddress_position = addressindex;
}
var newaddress_select = "#walletaddresses option:eq("+newaddress_position+")";
$(newaddress_select).attr('selected', 'selected');
}
function newPassphrase()
{
m = new Mnemonic(128);
m.toWords();
var str = m.toWords().toString();
var res = str.replace(/,/gi, " ");
var phraseList = res;
$("#newpassphrase").html(phraseList);
$("#yournewpassphrase").html(phraseList);
var addressinfo = [{label:"Address 1"},{label:"Address 2"},{label:"Address 3"},{label:"Address 4"},{label:"Address 5"}];
chrome.storage.local.set(
{
'passphrase': phraseList,
'encrypted': false,
'firstopen': false,
'addressinfo': addressinfo,
'totaladdress': 5
}, function () {
//resetFive();
$(".hideEncrypted").show();
convertPassphrase(m);
assetDropdown(m);
$('#allTabs a:first').tab('show');
});
}
function existingPassphrase(string) {
string = string.replace(/\s{2,}/g, ' ');
var array = string.split(" ");
m2 = new Mnemonic(array);
$("#newpassphrase").html(string);
convertPassphrase(m2);
assetDropdown(m2);
$('#allTabs a:first').tab('show')
}
function manualPassphrase(passphrase) {
// var string = $('#manualMnemonic').val().trim().toLowerCase();
// $('#manualMnemonic').val("");
var string = passphrase.trim().toLowerCase();
string = string.replace(/\s{2,}/g, ' ');
var array = string.split(" ");
m2 = new Mnemonic(array);
$("#newpassphrase").html(string);
chrome.storage.local.set(
{
'passphrase': string,
'encrypted': false,
'firstopen': false
}, function () {
convertPassphrase(m2);
assetDropdown(m2);
$(".hideEncrypted").show();
$("#manualPassBox").hide();
$('#allTabs a:first').tab('show')
});
}
function loadAssets(add) {
//var source_html = "http://xcp.blockscan.com/api2?module=address&action=balance&btc_address="+add;
var source_html = "https://counterpartychain.io/api/balances/"+add;
var xcp_source_html = "http://counterpartychain.io/api/address/"+add;
var btc_source_html = "https://insight.bitpay.com/api/addr/"+add+"/balance";
$( "#alltransactions" ).html("");
$.getJSON( xcp_source_html, function( data ) {
//var assetbalance = parseFloat(data.data[0].balance) + parseFloat(data.data[0].unconfirmed_balance);
var xcpbalance = parseFloat(data.xcp_balance).toFixed(8);
if (xcpbalance == 'NaN' || typeof xcpbalance === 'undefined') {
xcpbalance = 0;
}
$.getJSON( source_html, function( data ) {
$( "#allassets" ).html("<div class='btcasset row'><div class='col-xs-2' style='margin-left: -10px;'><img src='bitcoin_48x48.png'></div><div class='col-xs-10'><div class='assetname'>BTC</div><div class='movetowallet'>Send</div><div class='assetqty' id='btcassetbal'></div></div></div>");
var isbtcloading = $("#isbtcloading").html();
if (isbtcloading == "true") {
var btcbalance = "...";
$("#btcassetbal").html(btcbalance);
$.getJSON( btc_source_html, function( data_btc ) {
var bitcoinparsed = parseFloat(data_btc) / 100000000;
$("#isbtcloading").html("false");
$("#btcassetbal").html(bitcoinparsed);
});
} else {
var btcbalance = $("#btcbalhide").html();
$("#btcassetbal").html(btcbalance);
}
var xcpicon = "http://counterpartychain.io/content/images/icons/xcp.png";
if (xcpbalance != 0) {
$( "#allassets" ).append("<div class='xcpasset row'><div class='col-xs-2' style='margin-left: -10px;'><img src='"+xcpicon+"'></div><div class='col-xs-10'><div class='assetname'>XCP</div><div class='movetowallet'>Send</div><div class='assetqty'>"+xcpbalance+"</div></div></div>");
}
$.each(data.data, function(i, item) {
var assetname = data.data[i].asset;
var assetbalance = data.data[i].amount; //.balance for blockscan
if (assetbalance.indexOf(".")==-1) {var divisible = "no";} else {var divisible = "yes";}
var iconname = assetname.toLowerCase();
var iconlink = "http://counterpartychain.io/content/images/icons/"+iconname+".png";
if (assetname.charAt(0) != "A") {
var assethtml = "<div class='singleasset row'><div class='col-xs-2' style='margin-left: -10px;'><img src='"+iconlink+"'></div><div class='col-xs-10'><div class='assetname'>"+assetname+"</div><div class='movetowallet'>Send</div><div class='assetqty'>"+assetbalance+"</div><div id='assetdivisible' style='display: none;'>"+divisible+"</div></div></div>";
//<div class='tokenlink'>Hide</div> - <div class='tokenlink'>Add to Favorites</div>
// if(assetname == "LTBCOIN") {
// var assethtml = "<div class='enhancedasset'><div class='assetname'>"+assetname+"</div><div class='movetowallet'>Send</div><div class='assetqty'>Balance: "+assetbalance+"</div><div id='assetdivisible' style='display: none;'>"+divisible+"</div></div>";
// }
}
$( "#allassets" ).append( assethtml );
});
$( "#allassets" ).append("<div style='height: 20px;'></div>");
loadTransactions(add);
});
});
}
/*function updateBTC(pubkey){
var source_html = "https://blockchain.info/q/addressbalance/"+pubkey;
$.getJSON( source_html, function( data ) {
$("#xcpbalance").html(data);
});
};*/
function makedSignedMessage(msg, addr, sig)
{
var qtHdr = [
"<pre>-----BEGIN BITCOIN SIGNED MESSAGE-----",
"-----BEGIN BITCOIN SIGNATURE-----",
"-----END BITCOIN SIGNATURE-----</pre>"
];
return qtHdr[0]+'\n'+msg +'\n'+qtHdr[1]+'\nVersion: Bitcoin-qt (1.0)\nAddress: '+addr+'\n\n'+sig+'\n'+qtHdr[2];
}
function getprivkey(inputaddr, inputpassphrase){
//var inputaddr = $('#inputaddress').val();
//var string = inputpassphrase.val().trim().toLowerCase();
//string = string.replace(/\s{2,}/g, ' ');
var array = inputpassphrase.split(" ");
m2 = new Mnemonic(array);
var HDPrivateKey = bitcore.HDPrivateKey.fromSeed(m2.toHex(), bitcore.Networks.livenet);
for (var i = 0; i < 50; i++) {
var derived = HDPrivateKey.derive("m/0'/0/" + i);
var address1 = new bitcore.Address(derived.publicKey, bitcore.Networks.livenet);
var pubkey = address1.toString();
if (inputaddr == pubkey) {
var privkey = derived.privateKey.toWIF();
break;
}
}
return privkey;
}
function signwith(privkey, pubkey, message) {
//var message = "Message, message";
var p = updateAddr(privkey, pubkey);
if ( !message || !p.address ){
return;
}
message = fullTrim(message);
var sig = sign_message(p.key, message, p.compressed, p.addrtype);
sgData = {"message":message, "address":p.address, "signature":sig};
signature_final = makedSignedMessage(sgData.message, sgData.address, sgData.signature);
return signature_final;
}
function twodigits(n){
return n > 9 ? "" + n: "0" + n;
}
function timeConverter(UNIX_timestamp){
var a = new Date(UNIX_timestamp*1000);
var year = a.getFullYear();
var month = a.getMonth() + 1;
var date = a.getDate();
var hour = a.getHours();
var min = a.getMinutes();
var sec = a.getSeconds();
var time = twodigits(month) + '-' + twodigits(date) + '-' + year + ' | ' + twodigits(hour) + ':' + twodigits(min) + ':' + twodigits(sec) ;
return time;
}
function loadTransactions(add) {
//{"address":"1CWpnJVCQ2hHtehW9jhVjT2Ccj9eo5dc2E","asset":"LTBCOIN","block":348621,"quantity":"-50000.00000000","status":"valid","time":1426978699,"tx_hash":"dc34bbbf3fa02619b2e086a3cde14f096b53dc91f49f43b697aaee3fdec22e86"}
var source_html = "https://counterpartychain.io/api/transactions/"+add;
$.getJSON( source_html, function( data ) {
$.each(data.data, function(i, item) {
var assetname = data.data[i].asset;
if (assetname.charAt(0) != "A") {
var address = data.data[i].address;
var quantity = data.data[i].quantity;
var time = data.data[i].time;
var translink = "https://counterpartychain.io/transaction/"+data.data[i].tx_hash;
var addlink = "https://counterpartychain.io/address/"+address;
if (parseFloat(quantity) < 0) {
var background = "senttrans";
var transtype = "<span class='small'>Sent to </span>";
} else {
var background = "receivedtrans";
var transtype = "<span class='small'>Received from </span>";
}
var assethtml = "<div class='"+background+"'><div class='row'><div class='col-xs-6'><div class='assetnametrans'>"+assetname+"</div><div class='assetqtytrans'><span class='small'>Amount:</span><br>"+quantity+"</div></div><div class='col-xs-6'><div class='addresstrans'>"+transtype+"<br><a href='"+addlink+"' style='color: #fff;'>"+address.substring(0, 12)+"...</a></div><div class='small' style='bottom: 0;'><a href='"+translink+"' style='color: #fff;'>"+timeConverter(time)+"</a></div></div></div></div>";
$( "#alltransactions" ).append( assethtml );
}
});
$( "#alltransactions" ).append("<div style='height: 20px;'></div>");
});
}
function sendtokenaction() {
$("#sendtokenbutton").html("Sending...");
$("#sendtokenbutton").prop('disabled', true);
var assetbalance = $("#xcpbalance").html();
var array = assetbalance.split(" ");
var currentbalance = parseFloat(array[0]);
var pubkey = $("#xcpaddress").html();
var currenttoken = $(".currenttoken").html();
var sendtoaddress = $("#sendtoaddress").val();
var sendtoamount_text = $("#sendtoamount").val();
var sendtoamount = parseFloat(sendtoamount_text);
if($("#isdivisible").html() == "no"){
sendtoamount = Math.floor(sendtoamount) / 100000000;
}
console.log(sendtoamount);
var minersfee = 0.0001;
var totalsend = parseFloat(sendtoamount) + minersfee;
if (bitcore.Address.isValid(sendtoaddress)){
if (isNaN(sendtoamount) == true || sendtoamount <= 0 || $.isNumeric( sendtoamount ) == false) {
$("#sendtoamount").val("Invalid Amount");
$("#sendtokenbutton").html("Refresh to continue");
} else {
if (totalsend > currentbalance) {
$("#sendtoamount").val("Insufficient Funds");
$("#sendtokenbutton").html("Refresh to continue");
} else {
var txsAvailable = $("#txsAvailable").html();
if (currenttoken == "BTC") {
sendBTC(pubkey, sendtoaddress, sendtoamount, minersfee);
} else if (txsAvailable > 1) {
var btc_total = 0.0000547; //total btc to receiving address
var msig_total = 0.000078; //total btc to multisig output (returned to sender)
var mnemonic = $("#newpassphrase").html();
$("#sendtokenbutton").html("Sending...");
//sendXCP(pubkey, sendtoaddress, currenttoken, sendtoamount, btc_total, msig_total, minersfee, mnemonic);
sendXCP_opreturn(pubkey, sendtoaddress, currenttoken, sendtoamount, btc_total, minersfee, mnemonic);
//setUnconfirmed(pubkey, currenttoken, sendtoamount);
}
$("#sendtoaddress").prop('disabled', true);
$("#sendtoamount").prop('disabled', true);
//$("#sendtokenbutton").html("Sent! Refresh to continue...");
}
}
} else {
var success = false;
var userid = $("#sendtoaddress").val().toLowerCase();
$.getJSON( "https://letstalkbitcoin.com/api/v1/users/"+userid, function( data ) {
success = true;
$("#sendtoaddress").val(data.profile.profile["ltbcoin-address"]["value"]);
sendtokenaction();
});
setTimeout(function() {
if (!success) {
$("#sendtoaddress").val("Invalid Address");
$("#sendtokenbutton").html("Refresh to continue");
}
}, 1500);
}
}
function resetFive() {
var addressinfo = [{label:"Address 1"},{label:"Address 2"},{label:"Address 3"},{label:"Address 4"},{label:"Address 5"}];
chrome.storage.local.set(
{
'totaladdress': 5,
'addressinfo': addressinfo
}, function(){
var string = $("#newpassphrase").html();
var array = string.split(" ");
m = new Mnemonic(array);
assetDropdown(m);
$('#allTabs a:first').tab('show');
});
}
function setInitialAddressCount() {
chrome.storage.local.get(function(data) {
if(typeof(data["totaladdress"]) !== 'undefined') {
//already set
var newtotal = parseInt(data["totaladdress"]);
} else {
var newtotal = 5;
}
if(typeof(data["addressinfo"]) !== 'undefined') {
//already set
var addressinfo = data["addressinfo"];
} else {
var addressinfo = [{label:"Address 1"},{label:"Address 2"},{label:"Address 3"},{label:"Address 4"},{label:"Address 5"}];
}
chrome.storage.local.set(
{
'totaladdress': newtotal,
'addressinfo': addressinfo
}, function () {
//show new address
});
});
}
function addTotalAddress(callback) {
chrome.storage.local.get(function(data) {
var newtotal = parseInt(data["totaladdress"]) + 1;
var addressinfo = data["addressinfo"];
var newlabel = "Address "+newtotal;
addressinfo.push({label:newlabel});
chrome.storage.local.set(
{
'totaladdress': newtotal,
'addressinfo': addressinfo
}, function () {
callback(addressinfo, "newaddress");
});
});
}
function insertAddressLabel(newlabel, callback) {
chrome.storage.local.get(function(data) {
var addressinfo = data["addressinfo"];
var addressindex = $("#walletaddresses option:selected").index();
addressinfo[addressindex].label = newlabel;
chrome.storage.local.set(
{
'addressinfo': addressinfo
}, function () {
$("#addresslabeledit").toggle();
$("#pocketdropdown").toggle();
callback(addressinfo, "newlabel");
});
});
}
//function setUnconfirmed(sendaddress, sendasset, sendamount) {
//
// var currentbalance = parseFloat($("#assetbalhide").html());
// var finalbalance = currentbalance - parseFloat(sendamount);
// var unconfirmedamt = parseFloat(sendamount)*(-1);
//
//
//
// var tx = {asset: sendasset, txamount: unconfirmedamt, postbalance: finalbalance};
//
// var txfinal = {address: sendaddress, tx: tx};
//
// chrome.storage.local.get(function(data) {
// if(typeof(data["unconfirmedtx"]) !== 'undefined' && data["unconfirmedtx"] instanceof Array) {
// data["unconfirmedtx"].push(txfinal);
// } else {
// data["unconfirmedtx"] = [txfinal];
// }
//
// chrome.storage.local.set(data);
//
//
//
// });
//
//}
| gpl-3.0 |
zuloloxi/dnSpy | dnSpy/TreeNodes/Analyzer/AnalyzedAssemblyTreeNode.cs | 2454 | // Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
//
// 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 dnlib.DotNet;
using dnSpy;
using dnSpy.Images;
using dnSpy.NRefactory;
using ICSharpCode.Decompiler;
namespace ICSharpCode.ILSpy.TreeNodes.Analyzer {
internal class AnalyzedAssemblyTreeNode : AnalyzerEntityTreeNode {
private readonly ModuleDef analyzedAssembly;
public AnalyzedAssemblyTreeNode(ModuleDef analyzedAssembly) {
if (analyzedAssembly == null)
throw new ArgumentNullException("analyzedAssembly");
this.analyzedAssembly = analyzedAssembly;
//this.LazyLoading = true;
}
public override object Icon {
get { return ImageCache.Instance.GetImage("Assembly", BackgroundType.TreeNode); }
}
protected override void Write(ITextOutput output, Language language) {
var isExe = analyzedAssembly.Assembly != null &&
analyzedAssembly.IsManifestModule &&
(analyzedAssembly.Characteristics & dnlib.PE.Characteristics.Dll) == 0;
output.Write(UIUtils.CleanUpIdentifier(analyzedAssembly.Name), isExe ? TextTokenType.AssemblyExe : TextTokenType.Assembly);
}
protected override void LoadChildren() {
//this.Children.Add(new AnalyzedAssemblyReferencedByTreeNode(analyzedAssembly));
}
public override IMemberRef Member {
get { return null; }
}
public override IMDTokenProvider MDTokenProvider {
get { return analyzedAssembly; }
}
}
}
| gpl-3.0 |
e154/smart-home | system/initial/environments/default/images.go | 10230 | // This file is part of the Smart Home
// Program complex distribution https://github.com/e154/smart-home
// Copyright (C) 2016-2021, Filippov Alex
//
// This library is free software: you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 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 Lesser General Public
// License along with this library. If not, see
// <https://www.gnu.org/licenses/>.
package _default
import (
"os"
"path"
"strings"
"github.com/e154/smart-home/adaptors"
"github.com/e154/smart-home/common"
m "github.com/e154/smart-home/models"
. "github.com/e154/smart-home/system/initial/assertions"
)
// ImageManager ...
type ImageManager struct {
adaptors *adaptors.Adaptors
}
// NewImageManager ...
func NewImageManager(adaptors *adaptors.Adaptors) *ImageManager {
return &ImageManager{
adaptors: adaptors,
}
}
// Create ...
func (i ImageManager) Create() (imageList map[string]*m.Image) {
imageList = map[string]*m.Image{
"button_v1_off": {
Image: "30d2f4116a09fd14b49c266985db8109.svg",
MimeType: "text/html; charset=utf-8",
Size: 2518,
Name: "button_v1_off.svg",
},
"button_v1_refresh": {
Image: "86486ca5d086aafd5724d61251b94bba.svg",
MimeType: "text/html; charset=utf-8",
Size: 3212,
Name: "button_v1_refresh.svg",
},
"lamp_v1_r": {
Image: "2d4a761241e24a77725287180656b466.svg",
MimeType: "text/xml; charset=utf-8",
Size: 2261,
Name: "lamp_v1_r.svg",
},
"socket_v1_b": {
Image: "bef910d70c56f38b22cea0c00d92d8cc.svg",
MimeType: "text/html; charset=utf-8",
Size: 7326,
Name: "socket_v1_b.svg",
},
"button_v1_on": {
Image: "7c145f62dcaf8da2a9eb43f2b23ea2b1.svg",
MimeType: "text/html; charset=utf-8",
Size: 2398,
Name: "button_v1_on.svg",
},
"socket_v1_def": {
Image: "4c28edf0700531731df43ed055ebf56d.svg",
MimeType: "text/html; charset=utf-8",
Size: 7326,
Name: "socket_v1_def.svg",
},
"socket_v1_r": {
Image: "e91e461f7c9a800eed5a074101d3e5a5.svg",
MimeType: "text/html; charset=utf-8",
Size: 7326,
Name: "socket_v1_r.svg",
},
"lamp_v1_def": {
Image: "91e93ee7e7734654083dee0a5cbe55e9.svg",
MimeType: "text/xml; charset=utf-8",
Size: 2266,
Name: "lamp_v1_def.svg",
},
"socket_v1_g": {
Image: "4819b36056dfa786f5856fa45e9a3151.svg",
MimeType: "text/html; charset=utf-8",
Size: 7326,
Name: "socket_v1_g.svg",
},
"lamp_v1_y": {
Image: "c1c5ec4e75bb6ec33f5f8cfd87b0090e.svg",
MimeType: "text/xml; charset=utf-8",
Size: 2261,
Name: "lamp_v1_y.svg",
},
"socket_v2_b": {
Image: "c813ac54bb4dd6b99499d097eda67310.svg",
MimeType: "text/html; charset=utf-8",
Size: 3060,
Name: "socket_v2_b.svg",
},
"socket_v2_def": {
Image: "f0ea38f2b388dc2bb2566f6efc7731b0.svg",
MimeType: "text/html; charset=utf-8",
Size: 3060,
Name: "socket_v2_def.svg",
},
"socket_v2_g": {
Image: "fa6b42c81056069d03857cfbb2cf95eb.svg",
MimeType: "text/html; charset=utf-8",
Size: 3060,
Name: "socket_v2_g.svg",
},
"socket_v2_r": {
Image: "e565f191030491cfdc39ad728559c18f.svg",
MimeType: "text/html; charset=utf-8",
Size: 3060,
Name: "socket_v2_r.svg",
},
"socket_v3_b": {
Image: "297d56426098a53091fb8f91aabe3cd7.svg",
MimeType: "text/html; charset=utf-8",
Size: 2718,
Name: "socket_v3_b.svg",
},
"socket_v3_def": {
Image: "becf0f8f635061c143acb4329f744615.svg",
MimeType: "text/html; charset=utf-8",
Size: 2718,
Name: "socket_v3_def.svg",
},
"socket_v3_g": {
Image: "850bf4da00cb9de85e1442695230a127.svg",
MimeType: "text/html; charset=utf-8",
Size: 2718,
Name: "socket_v3_g.svg",
},
"socket_v3_r": {
Image: "434514389e95cab6d684b978378055d5.svg",
MimeType: "text/html; charset=utf-8",
Size: 2718,
Name: "socket_v3_r.svg",
},
"map-schematic-original": {
Image: "9384f1f6f9c2f4bf00fbc6debaae9b26.svg",
MimeType: "text/html; charset=utf-8",
Size: 195108,
Name: "map-schematic-original.svg",
},
"temp_v1_r": {
Image: "688d2d752252de21c9d62a643c37ea40.svg",
MimeType: "text/html; charset=utf-8",
Size: 3980,
Name: "temp_v1_r.svg",
},
"temp_v1_y": {
Image: "8b2f46785aa3bdf7a6a487fc89a0f99e.svg",
MimeType: "text/html; charset=utf-8",
Size: 3980,
Name: "temp_v1_y.svg",
},
"temp_v1_def": {
Image: "655d491beafaefce2117cb2012dc674a.svg",
MimeType: "text/html; charset=utf-8",
Size: 3980,
Name: "temp_v1_def.svg",
},
"temp_v1_original": {
Image: "e8dee745788685f9f86e611cf5758cab.svg",
MimeType: "text/html; charset=utf-8",
Size: 3770,
Name: "temp_v1_original.svg",
},
"fan_v1_r": {
Image: "eaf1c68959341c466fac68363f21cbbe.svg",
MimeType: "text/html; charset=utf-8",
Size: 6238,
Name: "fan_v1_r.svg",
},
"fan_v1_y": {
Image: "33a5d5e7290e0f37a4c160cdbd0b5f23.svg",
MimeType: "text/html; charset=utf-8",
Size: 6238,
Name: "fan_v1_y.svg",
},
"fan_v1_def": {
Image: "fd64ec639417d88e37b1c2cc167bcafc.svg",
MimeType: "text/html; charset=utf-8",
Size: 6238,
Name: "fan_v1_def.svg",
},
"fan_v1_original": {
Image: "b4820c5939fe6b042888c922dfd1bada.svg",
MimeType: "text/html; charset=utf-8",
Size: 5799,
Name: "fan_v1_original.svg",
},
"door_v1_closed": {
Image: "2e3e5c74775360e0274576ba6c83f044.svg",
MimeType: "text/html; charset=utf-8",
Size: 509,
Name: "door_v1_closed.svg",
},
"door_v1_closed_r": {
Image: "221f451b426188a2df987163a2ab5715.svg",
MimeType: "text/html; charset=utf-8",
Size: 508,
Name: "door_v1_closed_r.svg",
},
"door_v1_closed_def": {
Image: "dd2a735b71b2899869e36c54f140b3fa.svg",
MimeType: "text/html; charset=utf-8",
Size: 509,
Name: "door_v1_closed_def.svg",
},
"door_v1_opened1": {
Image: "74cb4de3f70bb7a7e5d651ee6a23bffc.svg",
MimeType: "text/html; charset=utf-8",
Size: 725,
Name: "door_v1_opened1.svg",
},
"door_v1_opened2": {
Image: "def90d2778eb6e4465f5808889e2a92c.svg",
MimeType: "text/html; charset=utf-8",
Size: 862,
Name: "door_v1_opened2.svg",
},
"door_v1_opened3": {
Image: "fe7c9ecdbbdedc99ab16070da52251a4.svg",
MimeType: "text/html; charset=utf-8",
Size: 1179,
Name: "door_v1_opened3.svg",
},
"md_v1_def": {
Image: "3f7482861152f6bf9de3940aa031e7bf.svg",
MimeType: "text/html; charset=utf-8",
Size: 1686,
Name: "motion_detection_v1_def.svg",
},
"md_v1_original": {
Image: "763b23acd999eb268deec7320c4b0b88.svg",
MimeType: "text/html; charset=utf-8",
Size: 1689,
Name: "motion_detection_v1_original.svg",
},
"md_v1_r": {
Image: "5d6d372b84cb75b80e6447cbc5cecb72.svg",
MimeType: "text/html; charset=utf-8",
Size: 1685,
Name: "motion_detection_v1_r.svg",
},
"md_v1_o": {
Image: "0fcdb4e0857adeb71f699b18ce22e403.svg",
MimeType: "text/html; charset=utf-8",
Size: 1711,
Name: "motion_detection_v1_o.svg",
},
"md_v1_y": {
Image: "55a011dcd81772b9752470471842d365.svg",
MimeType: "text/html; charset=utf-8",
Size: 1689,
Name: "motion_detection_v1_y.svg",
},
"md_v2_def": {
Image: "fe4fad32a33ef2448debab3cf2dc4c6f.svg",
MimeType: "text/html; charset=utf-8",
Size: 1388,
Name: "motion_detection_v2_def.svg",
},
"md_v2_original": {
Image: "73125c0ca60b84b647fe5f7bc2833432.svg",
MimeType: "text/html; charset=utf-8",
Size: 1391,
Name: "motion_detection_v2_original.svg",
},
"md_v2_r": {
Image: "82799f02881efe45f2a5211ab357e2e2.svg",
MimeType: "text/html; charset=utf-8",
Size: 1387,
Name: "motion_detection_v2_r.svg",
},
"md_v2_o": {
Image: "58b1695473e44277c0306a726a601aef.svg",
MimeType: "text/html; charset=utf-8",
Size: 1391,
Name: "motion_detection_v2_o.svg",
},
"md_v2_y": {
Image: "aab3542bb028c61a4343bfc4e8c92daf.svg",
MimeType: "text/html; charset=utf-8",
Size: 1391,
Name: "motion_detection_v2_y.svg",
},
}
_ = i.install(imageList)
return
}
func (i ImageManager) install(imageList map[string]*m.Image) (err error) {
var subDir string
for _, image := range imageList {
if _, err = i.adaptors.Image.GetByImageName(image.Image); err == nil {
continue
}
image.Id, err = i.adaptors.Image.Add(image)
So(err, ShouldBeNil)
fullPath := common.GetFullPath(image.Image)
to := path.Join(fullPath, image.Image)
if exist := common.FileExist(to); !exist {
_ = os.MkdirAll(fullPath, os.ModePerm)
switch {
case strings.Contains(image.Name, "button"):
subDir = "buttons"
case strings.Contains(image.Name, "lamp"):
subDir = "lamp"
case strings.Contains(image.Name, "socket"):
subDir = "socket"
case strings.Contains(image.Name, "temp"):
subDir = "temp"
case strings.Contains(image.Name, "fan"):
subDir = "fan"
case strings.Contains(image.Name, "map"):
subDir = "map"
case strings.Contains(image.Name, "door"):
subDir = "door"
case strings.Contains(image.Name, "motion_detection"):
subDir = "motion_detection"
}
from := path.Join("data", "icons", subDir, image.Name)
common.CopyFile(from, to)
}
}
return
}
// Upgrade ...
func (i ImageManager) Upgrade(oldVersion int) (err error) {
var imageList map[string]*m.Image
switch oldVersion {
case 0:
default:
return
}
err = i.install(imageList)
return
}
| gpl-3.0 |
bolsadoinfinito/site | wp-content/plugins/t4p-core-composer/core/shortcode/child.php | 814 | <?php
/**
* @author Theme4Press
* @package Theme4Press Page Builder
* @version 1.0.0
/*
/*
* Parent class for sub elements
*/
class T4P_Pb_Shortcode_Child extends T4P_Pb_Shortcode_Element {
/**
* Over write parent method
*
* @param string $content
* @param string $shortcode_data
* @param string $el_title
* @param int $index
* @param bool $inlude_sc_structure
* @param array $extra_params
* @return string
*/
public function element_in_pgbldr( $content = '', $shortcode_data = '', $el_title = '', $index = '', $inlude_sc_structure = true, $extra_params = array() ) {
$this->config['sub_element'] = true;
return parent::element_in_pgbldr( $content, $shortcode_data, $el_title, $index, $inlude_sc_structure, $extra_params );
}
}
| gpl-3.0 |
idega/platform2 | src/com/idega/block/trade/stockroom/data/Supplier.java | 5882 | /*
* $Id: Supplier.java,v 1.26 2005/06/18 15:59:00 gimmi Exp $
* Created on 18.6.2005
*
* Copyright (C) 2005 Idega Software hf. All Rights Reserved.
*
* This software is the proprietary information of Idega hf.
* Use is subject to license terms.
*/
package com.idega.block.trade.stockroom.data;
import java.rmi.RemoteException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.FinderException;
import com.idega.block.trade.data.CreditCardInformation;
import com.idega.core.contact.data.Email;
import com.idega.core.file.data.ICFile;
import com.idega.core.location.data.Address;
import com.idega.data.IDOAddRelationshipException;
import com.idega.data.IDOLegacyEntity;
import com.idega.data.IDORelationshipException;
import com.idega.data.IDORemoveRelationshipException;
import com.idega.user.data.Group;
/**
*
* Last modified: $Date: 2005/06/18 15:59:00 $ by $Author: gimmi $
*
* @author <a href="mailto:gimmi@idega.com">gimmi</a>
* @version $Revision: 1.26 $
*/
public interface Supplier extends IDOLegacyEntity {
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#getName
*/
public String getName();
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#setName
*/
public void setName(String name);
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#getDescription
*/
public String getDescription();
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#setDescription
*/
public void setDescription(String description);
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#setGroupId
*/
public void setGroupId(int id);
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#getGroupId
*/
public int getGroupId();
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#setIsValid
*/
public void setIsValid(boolean isValid);
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#getIsValid
*/
public boolean getIsValid();
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#getSupplierManagerID
*/
public int getSupplierManagerID();
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#getSupplierManager
*/
public Group getSupplierManager();
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#setSupplierManager
*/
public void setSupplierManager(Group group);
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#setSupplierManagerPK
*/
public void setSupplierManagerPK(Object pk);
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#getAddress
*/
public Address getAddress() throws SQLException;
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#getAddresses
*/
public List getAddresses() throws SQLException;
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#getPhones
*/
public List getPhones() throws SQLException;
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#getHomePhone
*/
public List getHomePhone() throws SQLException;
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#getFaxPhone
*/
public List getFaxPhone() throws SQLException;
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#getWorkPhone
*/
public List getWorkPhone() throws SQLException;
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#getMobilePhone
*/
public List getMobilePhone() throws SQLException;
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#getPhones
*/
public List getPhones(int PhoneTypeId) throws SQLException;
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#getEmail
*/
public Email getEmail() throws SQLException;
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#getEmails
*/
public List getEmails() throws SQLException;
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#getTPosMerchantId
*/
public int getTPosMerchantId();
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#getSettings
*/
public Settings getSettings() throws FinderException, RemoteException, CreateException;
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#setCreditCardInformation
*/
public void setCreditCardInformation(Collection pks) throws IDORemoveRelationshipException,
IDOAddRelationshipException, EJBException;
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#addCreditCardInformationPK
*/
public void addCreditCardInformationPK(Object pk) throws IDOAddRelationshipException;
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#addCreditCardInformation
*/
public void addCreditCardInformation(CreditCardInformation info) throws IDOAddRelationshipException, EJBException;
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#getCreditCardInformation
*/
public Collection getCreditCardInformation() throws IDORelationshipException;
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#getProductCategories
*/
public Collection getProductCategories() throws IDORelationshipException;
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#getOrganizationID
*/
public String getOrganizationID();
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#setOrganizationID
*/
public void setOrganizationID(String organizationId);
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#getICFile
*/
public ICFile getICFile();
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#setICFile
*/
public void setICFile(int fileID);
/**
* @see com.idega.block.trade.stockroom.data.SupplierBMPBean#setICFile
*/
public void setICFile(ICFile file);
}
| gpl-3.0 |
mrRosset/Engemu | Scripts/Export_all_Dlls.py | 315 | from os import listdir, system
from os.path import isfile, join
import sys
Dllpath = sys.argv[1]
Exportspath = sys.argv[2]
onlyfiles = [f for f in listdir(Dllpath) if isfile(join(Dllpath, f))]
for file in onlyfiles:
system("ListExports.exe " + join(Dllpath, file) + " > " + join(Exportspath, file) + ".exports") | gpl-3.0 |
fnurl/alot | setup.py | 1221 | #!/usr/bin/env python
from setuptools import setup, find_packages
import alot
setup(name='alot',
version=alot.__version__,
description=alot.__description__,
author=alot.__author__,
author_email=alot.__author_email__,
url=alot.__url__,
license=alot.__copyright__,
packages=find_packages(exclude=['tests*']),
package_data={'alot': [
'defaults/alot.rc.spec',
'defaults/notmuch.rc.spec',
'defaults/abook_contacts.spec',
'defaults/default.theme',
'defaults/default.bindings',
'defaults/config.stub',
'defaults/theme.spec',
]},
entry_points={
'console_scripts':
['alot = alot.__main__:main'],
},
install_requires=[
'notmuch>=0.13',
'urwid>=1.1.0',
'urwidtrees>=1.0',
'twisted>=10.2.0',
'python-magic',
'configobj>=4.7.0',
'pygpgme>=0.2'],
tests_require=[
'mock',
],
provides=['alot'],
test_suite="tests",
)
| gpl-3.0 |
daviddavis/foretello_api_v21 | app/controllers/api/v21/architectures_controller.rb | 364 | module Api
module V21
class ArchitecturesController < V2::ArchitecturesController
include Api::Version21
def index
super
render :json => @architectures, :each_serializer => ArchitectureSerializer
end
def show
render :json => @architecture, :serializer => ArchitectureSerializer
end
end
end
end
| gpl-3.0 |
frasmarco/webGui | src/app/shared/voice-control/commands-help.component.ts | 522 | import {Component, OnInit, Inject, ViewContainerRef, ViewChild} from '@angular/core';
import {VoiceControlService} from './voice-control.service';
@Component({
selector: 'sa-commands-help',
templateUrl: './commands-help.component.html',
styles: [],
})
export class CommandsHelpComponent implements OnInit {
@ViewChild('seeCommandsModal') seeCommandsModal;
constructor() {}
ngOnInit() {
}
public show() {
this.seeCommandsModal.show();
}
public hide() {
this.seeCommandsModal.hide();
}
}
| gpl-3.0 |
ksmith0/pixie_scan | src/core/ReadBuffData.RevF.cpp | 8123 | /** \file ReadBuffData.RevD.cpp
* \brief retrieve data from raw buffer array ibuf
*/
/*----------------------------------------------------------------------
* Copyright (c) 2005, XIA LLC
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
* * Neither the name of XIA LLC nor the names of its
* contributors may be used to endorse or promote
* products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*----------------------------------------------------------------------*/
#include <iostream>
#include <iomanip>
#include <vector>
#include <cmath>
// data related to pixie packet structure
#include "pixie16app_defs.h"
// our event structure
#include "DetectorLibrary.hpp"
#include "Globals.hpp"
#include "ChanEvent.hpp"
#include "Trace.hpp"
#include "StatsData.hpp"
using pixie::word_t;
using pixie::halfword_t;
using std::cout;
using std::endl;
using std::cerr;
using std::vector;
extern StatsData stats;
/*! \brief extract channel information from raw data
ReadBuffData extracts channel information from the raw data arrays
and places it into a structure called evt. A pointer to each
of the evt objects is placed in the eventlist vector for later time
sorting.
\param [in] buf : the buffer to process
\param [in] bufLen : the length of the buffer
\param [in] eventList : the event list to add the extracted buffer to
\return An unused integer
*/
int ReadBuffDataF(word_t *buf, unsigned long *bufLen,
vector<ChanEvent*> &eventList) {
// multiplier for high bits of 48-bit time
static const double HIGH_MULT = pow(2., 32.);
word_t modNum;
unsigned long numEvents = 0;
word_t *bufStart = buf;
/* Determine the number of words in the buffer */
*bufLen = *buf++;
/* Read the module number */
modNum = *buf++;
ChanEvent *lastVirtualChannel = NULL;
if(*bufLen > 0) { // check if the buffer has data
if(*bufLen == 2) {
// this is an empty channel
return 0;
}
do {
ChanEvent *currentEvt = new ChanEvent;
// decoding event data... see pixie16app.c
// buf points to the start of channel data
//Decode the first header word
word_t chanNum = (buf[0] & 0x0000000F);
word_t slotNum = (buf[0] & 0x000000F0) >> 4;
word_t crateNum = (buf[0] & 0x00000F00) >> 8;
word_t headerLength = (buf[0] & 0x0001F000) >> 12;
word_t eventLength = (buf[0] & 0x7FFE0000) >> 17;
currentEvt->pileupBit = (buf[0] & 0x80000000) != 0;
// Sanity check
if(headerLength == stats.headerLength) {
// this is a manual statistics block inserted poll
stats.DoStatisticsBlock(&buf[1], modNum);
buf += eventLength;
numEvents = readbuff::STATS;
continue;
}
//Decode the second header word
word_t lowTime = buf[1];
//Decode the third header word
word_t highTime = buf[2] & 0x0000FFFF;
word_t cfdTime = (buf[2] & 0x3FFF0000) >> 16;
currentEvt->cfdTrigSource = ((buf[2] & 0x40000000) != 0);
currentEvt->cfdForceTrig = ((buf[2] & 0x80000000) != 0);
//Decode the foruth header word
word_t energy = buf[3] & 0x0000FFFF;
word_t traceLength = (buf[3] & 0x7FFF0000) >> 16;
currentEvt->saturatedBit = ((buf[3] & 0x80000000) != 0);
int offset = headerLength - 8;
switch(headerLength) {
case 4:
case 6:
case 8:
case 10:
break;
case 12:
case 14:
case 16:
case 18:
for(int i=0; i < currentEvt->numQdcs; i++)
currentEvt->qdcValue[i] = buf[offset + i];
break;
default:
cerr << " Unexpected header length: " << headerLength << endl;
cerr << " Buffer " << modNum << " of length " << *bufLen << endl;
cerr << " CHAN:SLOT:CRATE "
<< chanNum << ":" << slotNum << ":" << crateNum << endl;
return readbuff::ERROR;
break;
}
// one last sanity check
if(traceLength / 2 + headerLength != eventLength) {
cerr << " Bad event length (" << eventLength
<< ") does not correspond with length of header ("
<< headerLength << ") and length of trace ("
<< traceLength << ")" << endl;
buf += eventLength;
continue;
}
// handle multiple crates
modNum += 100 * crateNum;
currentEvt->chanNum = chanNum;
currentEvt->modNum = modNum;
if(currentEvt->virtualChannel) {
DetectorLibrary* modChan = DetectorLibrary::get();
currentEvt->modNum += modChan->GetPhysicalModules();
if(modChan->at(modNum, chanNum).HasTag("construct_trace")) {
lastVirtualChannel = currentEvt;
}
}
currentEvt->energy = energy;
if(currentEvt->saturatedBit)
currentEvt->energy = 16383;
currentEvt->trigTime = lowTime;
currentEvt->cfdTime = cfdTime;
currentEvt->eventTimeHi = highTime;
currentEvt->eventTimeLo = lowTime;
currentEvt->time = highTime * HIGH_MULT + lowTime;
buf += headerLength;
/* Check if trace data follows the channel header */
if(traceLength > 0) {
// sbuf points to the beginning of trace data
halfword_t *sbuf = (halfword_t *)buf;
currentEvt->trace.reserve(traceLength);
if(currentEvt->saturatedBit)
currentEvt->trace.SetValue("saturation", 1);
if(lastVirtualChannel != NULL && lastVirtualChannel->trace.empty()) {
lastVirtualChannel->trace.assign(traceLength, 0);
}
// Read the trace data (2-bytes per sample, i.e. 2 samples per word)
for(unsigned int k = 0; k < traceLength; k ++) {
currentEvt->trace.push_back(sbuf[k]);
if(lastVirtualChannel != NULL) {
lastVirtualChannel->trace[k] += sbuf[k];
}
}
buf += traceLength / 2;
}
eventList.push_back(currentEvt);
numEvents++;
} while(buf < bufStart + *bufLen);
} else { // if buffer has data
cout << "ERROR BufNData " << *bufLen << endl;
cout << "ERROR IN ReadBuffData" << endl;
cout << "LIST UNKNOWN" << endl;
return readbuff::ERROR;
}
return numEvents;
}
| gpl-3.0 |
digitarald/redracer | vendor/agavi/translation/data/timezones/America_47_Montreal.php | 15122 | <?php
/**
* Data file for America/Montreal timezone, compiled from the olson data.
*
* Auto-generated by the phing olson task on 11/04/2008 09:20:40
*
* @package agavi
* @subpackage translation
*
* @copyright Authors
* @copyright The Agavi Project
*
* @since 0.11.0
*
* @version $Id: America_47_Montreal.php 3274 2008-11-04 10:10:58Z david $
*/
return array (
'types' =>
array (
0 =>
array (
'rawOffset' => -18000,
'dstOffset' => 0,
'name' => 'ET',
),
1 =>
array (
'rawOffset' => -18000,
'dstOffset' => 3600,
'name' => 'EDT',
),
2 =>
array (
'rawOffset' => -18000,
'dstOffset' => 0,
'name' => 'EST',
),
3 =>
array (
'rawOffset' => -18000,
'dstOffset' => 3600,
'name' => 'EWT',
),
4 =>
array (
'rawOffset' => -18000,
'dstOffset' => 3600,
'name' => 'EPT',
),
),
'rules' =>
array (
0 =>
array (
'time' => -2713892744,
'type' => 0,
),
1 =>
array (
'time' => -1665334800,
'type' => 1,
),
2 =>
array (
'time' => -1662753600,
'type' => 2,
),
3 =>
array (
'time' => -1640977200,
'type' => 0,
),
4 =>
array (
'time' => -1632070800,
'type' => 1,
),
5 =>
array (
'time' => -1614794400,
'type' => 2,
),
6 =>
array (
'time' => -1609441200,
'type' => 2,
),
7 =>
array (
'time' => -1601742600,
'type' => 1,
),
8 =>
array (
'time' => -1583775000,
'type' => 2,
),
9 =>
array (
'time' => -1567355400,
'type' => 1,
),
10 =>
array (
'time' => -1554053400,
'type' => 2,
),
11 =>
array (
'time' => -1535907600,
'type' => 1,
),
12 =>
array (
'time' => -1522605600,
'type' => 2,
),
13 =>
array (
'time' => -1504458000,
'type' => 1,
),
14 =>
array (
'time' => -1491156000,
'type' => 2,
),
15 =>
array (
'time' => -1439830800,
'type' => 1,
),
16 =>
array (
'time' => -1428255000,
'type' => 2,
),
17 =>
array (
'time' => -1409504400,
'type' => 1,
),
18 =>
array (
'time' => -1396807200,
'type' => 2,
),
19 =>
array (
'time' => -1378054800,
'type' => 1,
),
20 =>
array (
'time' => -1365357600,
'type' => 2,
),
21 =>
array (
'time' => -1346612400,
'type' => 1,
),
22 =>
array (
'time' => -1333915200,
'type' => 2,
),
23 =>
array (
'time' => -1315162800,
'type' => 1,
),
24 =>
array (
'time' => -1301860800,
'type' => 2,
),
25 =>
array (
'time' => -1283713200,
'type' => 1,
),
26 =>
array (
'time' => -1270411200,
'type' => 2,
),
27 =>
array (
'time' => -1252263600,
'type' => 1,
),
28 =>
array (
'time' => -1238961600,
'type' => 2,
),
29 =>
array (
'time' => -1220814000,
'type' => 1,
),
30 =>
array (
'time' => -1207512000,
'type' => 2,
),
31 =>
array (
'time' => -1188759600,
'type' => 1,
),
32 =>
array (
'time' => -1176062400,
'type' => 2,
),
33 =>
array (
'time' => -1157310000,
'type' => 1,
),
34 =>
array (
'time' => -1144008000,
'type' => 2,
),
35 =>
array (
'time' => -1125860400,
'type' => 1,
),
36 =>
array (
'time' => -1112558400,
'type' => 2,
),
37 =>
array (
'time' => -1094410800,
'type' => 1,
),
38 =>
array (
'time' => -1081108800,
'type' => 2,
),
39 =>
array (
'time' => -1062961200,
'type' => 1,
),
40 =>
array (
'time' => -1049659200,
'type' => 2,
),
41 =>
array (
'time' => -1031511600,
'type' => 1,
),
42 =>
array (
'time' => -1018209600,
'type' => 2,
),
43 =>
array (
'time' => -1000062000,
'type' => 1,
),
44 =>
array (
'time' => -986760000,
'type' => 2,
),
45 =>
array (
'time' => -968007600,
'type' => 1,
),
46 =>
array (
'time' => -955310400,
'type' => 2,
),
47 =>
array (
'time' => -936558000,
'type' => 1,
),
48 =>
array (
'time' => -880218000,
'type' => 3,
),
49 =>
array (
'time' => -769395600,
'type' => 4,
),
50 =>
array (
'time' => -765396000,
'type' => 2,
),
51 =>
array (
'time' => -757364400,
'type' => 2,
),
52 =>
array (
'time' => -747248400,
'type' => 1,
),
53 =>
array (
'time' => -733946400,
'type' => 2,
),
54 =>
array (
'time' => -715798800,
'type' => 1,
),
55 =>
array (
'time' => -702496800,
'type' => 2,
),
56 =>
array (
'time' => -684349200,
'type' => 1,
),
57 =>
array (
'time' => -671047200,
'type' => 2,
),
58 =>
array (
'time' => -652899600,
'type' => 1,
),
59 =>
array (
'time' => -636573600,
'type' => 2,
),
60 =>
array (
'time' => -620845200,
'type' => 1,
),
61 =>
array (
'time' => -605124000,
'type' => 2,
),
62 =>
array (
'time' => -589395600,
'type' => 1,
),
63 =>
array (
'time' => -576093600,
'type' => 2,
),
64 =>
array (
'time' => -557946000,
'type' => 1,
),
65 =>
array (
'time' => -544644000,
'type' => 2,
),
66 =>
array (
'time' => -526496400,
'type' => 1,
),
67 =>
array (
'time' => -513194400,
'type' => 2,
),
68 =>
array (
'time' => -495046800,
'type' => 1,
),
69 =>
array (
'time' => -481744800,
'type' => 2,
),
70 =>
array (
'time' => -463597200,
'type' => 1,
),
71 =>
array (
'time' => -450295200,
'type' => 2,
),
72 =>
array (
'time' => -431542800,
'type' => 1,
),
73 =>
array (
'time' => -418240800,
'type' => 2,
),
74 =>
array (
'time' => -400093200,
'type' => 1,
),
75 =>
array (
'time' => -384372000,
'type' => 2,
),
76 =>
array (
'time' => -368643600,
'type' => 1,
),
77 =>
array (
'time' => -352922400,
'type' => 2,
),
78 =>
array (
'time' => -337194000,
'type' => 1,
),
79 =>
array (
'time' => -321472800,
'type' => 2,
),
80 =>
array (
'time' => -305744400,
'type' => 1,
),
81 =>
array (
'time' => -289418400,
'type' => 2,
),
82 =>
array (
'time' => -273690000,
'type' => 1,
),
83 =>
array (
'time' => -257968800,
'type' => 2,
),
84 =>
array (
'time' => -242240400,
'type' => 1,
),
85 =>
array (
'time' => -226519200,
'type' => 2,
),
86 =>
array (
'time' => -210790800,
'type' => 1,
),
87 =>
array (
'time' => -195069600,
'type' => 2,
),
88 =>
array (
'time' => -179341200,
'type' => 1,
),
89 =>
array (
'time' => -163620000,
'type' => 2,
),
90 =>
array (
'time' => -147891600,
'type' => 1,
),
91 =>
array (
'time' => -131565600,
'type' => 2,
),
92 =>
array (
'time' => -116442000,
'type' => 1,
),
93 =>
array (
'time' => -100116000,
'type' => 2,
),
94 =>
array (
'time' => -84387600,
'type' => 1,
),
95 =>
array (
'time' => -68666400,
'type' => 2,
),
96 =>
array (
'time' => -52938000,
'type' => 1,
),
97 =>
array (
'time' => -37216800,
'type' => 2,
),
98 =>
array (
'time' => -21488400,
'type' => 1,
),
99 =>
array (
'time' => -5767200,
'type' => 2,
),
100 =>
array (
'time' => 9961200,
'type' => 1,
),
101 =>
array (
'time' => 25682400,
'type' => 2,
),
102 =>
array (
'time' => 41410800,
'type' => 1,
),
103 =>
array (
'time' => 57736800,
'type' => 2,
),
104 =>
array (
'time' => 73465200,
'type' => 1,
),
105 =>
array (
'time' => 89186400,
'type' => 2,
),
106 =>
array (
'time' => 104914800,
'type' => 1,
),
107 =>
array (
'time' => 120636000,
'type' => 2,
),
108 =>
array (
'time' => 126248400,
'type' => 2,
),
109 =>
array (
'time' => 136364400,
'type' => 1,
),
110 =>
array (
'time' => 152085600,
'type' => 2,
),
111 =>
array (
'time' => 167814000,
'type' => 1,
),
112 =>
array (
'time' => 183535200,
'type' => 2,
),
113 =>
array (
'time' => 199263600,
'type' => 1,
),
114 =>
array (
'time' => 215589600,
'type' => 2,
),
115 =>
array (
'time' => 230713200,
'type' => 1,
),
116 =>
array (
'time' => 247039200,
'type' => 2,
),
117 =>
array (
'time' => 262767600,
'type' => 1,
),
118 =>
array (
'time' => 278488800,
'type' => 2,
),
119 =>
array (
'time' => 294217200,
'type' => 1,
),
120 =>
array (
'time' => 309938400,
'type' => 2,
),
121 =>
array (
'time' => 325666800,
'type' => 1,
),
122 =>
array (
'time' => 341388000,
'type' => 2,
),
123 =>
array (
'time' => 357116400,
'type' => 1,
),
124 =>
array (
'time' => 372837600,
'type' => 2,
),
125 =>
array (
'time' => 388566000,
'type' => 1,
),
126 =>
array (
'time' => 404892000,
'type' => 2,
),
127 =>
array (
'time' => 420015600,
'type' => 1,
),
128 =>
array (
'time' => 436341600,
'type' => 2,
),
129 =>
array (
'time' => 452070000,
'type' => 1,
),
130 =>
array (
'time' => 467791200,
'type' => 2,
),
131 =>
array (
'time' => 483519600,
'type' => 1,
),
132 =>
array (
'time' => 499240800,
'type' => 2,
),
133 =>
array (
'time' => 514969200,
'type' => 1,
),
134 =>
array (
'time' => 530690400,
'type' => 2,
),
135 =>
array (
'time' => 544604400,
'type' => 1,
),
136 =>
array (
'time' => 562140000,
'type' => 2,
),
137 =>
array (
'time' => 576054000,
'type' => 1,
),
138 =>
array (
'time' => 594194400,
'type' => 2,
),
139 =>
array (
'time' => 607503600,
'type' => 1,
),
140 =>
array (
'time' => 625644000,
'type' => 2,
),
141 =>
array (
'time' => 638953200,
'type' => 1,
),
142 =>
array (
'time' => 657093600,
'type' => 2,
),
143 =>
array (
'time' => 671007600,
'type' => 1,
),
144 =>
array (
'time' => 688543200,
'type' => 2,
),
145 =>
array (
'time' => 702457200,
'type' => 1,
),
146 =>
array (
'time' => 719992800,
'type' => 2,
),
147 =>
array (
'time' => 733906800,
'type' => 1,
),
148 =>
array (
'time' => 752047200,
'type' => 2,
),
149 =>
array (
'time' => 765356400,
'type' => 1,
),
150 =>
array (
'time' => 783496800,
'type' => 2,
),
151 =>
array (
'time' => 796806000,
'type' => 1,
),
152 =>
array (
'time' => 814946400,
'type' => 2,
),
153 =>
array (
'time' => 828860400,
'type' => 1,
),
154 =>
array (
'time' => 846396000,
'type' => 2,
),
155 =>
array (
'time' => 860310000,
'type' => 1,
),
156 =>
array (
'time' => 877845600,
'type' => 2,
),
157 =>
array (
'time' => 891759600,
'type' => 1,
),
158 =>
array (
'time' => 909295200,
'type' => 2,
),
159 =>
array (
'time' => 923209200,
'type' => 1,
),
160 =>
array (
'time' => 941349600,
'type' => 2,
),
161 =>
array (
'time' => 954658800,
'type' => 1,
),
162 =>
array (
'time' => 972799200,
'type' => 2,
),
163 =>
array (
'time' => 986108400,
'type' => 1,
),
164 =>
array (
'time' => 1004248800,
'type' => 2,
),
165 =>
array (
'time' => 1018162800,
'type' => 1,
),
166 =>
array (
'time' => 1035698400,
'type' => 2,
),
167 =>
array (
'time' => 1049612400,
'type' => 1,
),
168 =>
array (
'time' => 1067148000,
'type' => 2,
),
169 =>
array (
'time' => 1081062000,
'type' => 1,
),
170 =>
array (
'time' => 1099202400,
'type' => 2,
),
171 =>
array (
'time' => 1112511600,
'type' => 1,
),
172 =>
array (
'time' => 1130652000,
'type' => 2,
),
173 =>
array (
'time' => 1143961200,
'type' => 1,
),
174 =>
array (
'time' => 1162101600,
'type' => 2,
),
175 =>
array (
'time' => 1173596400,
'type' => 1,
),
176 =>
array (
'time' => 1194156000,
'type' => 2,
),
),
'finalRule' =>
array (
'type' => 'dynamic',
'offset' => -18000,
'name' => 'E%sT',
'save' => 3600,
'start' =>
array (
'month' => 2,
'date' => '8',
'day_of_week' => -1,
'time' => 7200000,
'type' => 0,
),
'end' =>
array (
'month' => 10,
'date' => '1',
'day_of_week' => -1,
'time' => 7200000,
'type' => 0,
),
'startYear' => 2007,
),
'name' => 'America/Montreal',
);
?> | gpl-3.0 |