repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
mwin007/WP-Tania-Site | wp-content/themes/forumengine/page-following.php | 3333 | <?php
/**
* Template Name: Following Threads Page
*/
get_header();
global $wp_query, $wp_rewrite, $post,$user_ID;
et_get_user_following_threads();
$data = et_get_unread_follow();
?>
<div class="header-bottom header-filter">
<div class="main-center">
<?php fe_navigations(); ?>
</div>
<div class="mo-menu-toggle visible-sm visible-xs">
<a class="icon-menu-tablet" href="#"><?php _e('open',ET_DOMAIN) ?></a>
</div>
</div>
<!--end header Bottom-->
<div class="container main-center">
<div class="row">
<div class="col-md-9 marginTop30">
<ul class="list-post" id="main_list_post">
<?php
/**
* Display threads
*/
$follows = get_user_meta( $user_ID, 'et_following_threads',true);
$posts_in = ($follows) ? $follows : array(0);
$args = array(
'post_type' => 'thread',
'post_status' => array('publish','pending','closed'),
'paged' => get_query_var('paged'),
'post__in' => $posts_in
);
add_filter( 'posts_join', 'ET_ForumFront::_thread_join' );
add_filter( 'posts_orderby', 'ET_ForumFront::_thread_orderby');
$following = new WP_Query($args);
if ($following->have_posts()){
while ($following->have_posts()){
$following->the_post();
get_template_part( 'template/thread', 'loop' );
} // end while
} else { ?>
<div class="notice-noresult">
<span class="icon" data-icon="!"></span><?php _e('You are not following any thread yet.', ET_DOMAIN) ?>
</div>
<?php
} // end if
remove_filter('posts_join' , 'ET_ForumFront::_thread_join');
remove_filter('posts_orderby' , 'ET_ForumFront::_thread_orderby');
?>
</ul>
<?php
$page = get_query_var('paged') ? get_query_var('paged') : 1;
if(!get_option( 'et_infinite_scroll' )){
?>
<!-- Normal Paginations -->
<div class="pagination pagination-centered" id="main_pagination">
<?php
echo paginate_links( array(
'base' => str_replace('99999', '%#%', esc_url(get_pagenum_link( 99999 ))),
'format' => $wp_rewrite->using_permalinks() ? 'page/%#%' : '?paged=%#%',
'current' => max(1, $page),
'total' => $following->max_num_pages,
'prev_text' => '<',
'next_text' => '>',
'type' => 'list'
) );
?>
</div>
<!-- Normal Paginations -->
<?php } else { ?>
<!-- Infinite Scroll -->
<?php
$fetch = ($page < $following->max_num_pages) ? 1 : 0 ;
$check = floor((int) 10 / (int) get_option( 'posts_per_page' ));
?>
<div id="loading" class="hide" data-fetch="<?php echo $fetch ?>" data-check="<?php echo $check ?>" data-status="scroll-follow">
<div class="bubblingG">
<span id="bubblingG_1">
</span>
<span id="bubblingG_2">
</span>
<span id="bubblingG_3">
</span>
</div>
<?php _e( 'Loading more threads', ET_DOMAIN ); ?>
<input type="hidden" value="<?php echo $page ?>" id="current_page">
<input type="hidden" value="<?php echo $following->max_num_pages ?>" id="max_page">
</div>
<!-- Infinite Scroll -->
<?php } ?>
</div>
<div class="col-md-3 hidden-sm hidden-xs">
<?php get_sidebar( ) ?>
<!-- end widget -->
</div>
</div>
</div>
<?php get_footer(); ?>
| gpl-2.0 |
rex-xxx/mt6572_x201 | frameworks/compile/mclinker/lib/Support/RealPath.cpp | 1194 | //===- RealPath.cpp -------------------------------------------------------===//
//
// The MCLinker Project
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "mcld/Support/RealPath.h"
#include "mcld/Support/FileSystem.h"
using namespace mcld::sys::fs;
//==========================
// RealPath
RealPath::RealPath()
: Path() {
}
RealPath::RealPath(const RealPath::ValueType* s )
: Path(s) {
initialize();
}
RealPath::RealPath(const RealPath::StringType &s )
: Path(s) {
initialize();
}
RealPath::RealPath(const Path& pPath)
: Path(pPath) {
initialize();
}
RealPath::~RealPath()
{
}
RealPath& RealPath::assign(const Path& pPath)
{
Path::m_PathName.assign(pPath.native());
return (*this);
}
void RealPath::initialize()
{
if (isFromRoot()) {
detail::canonicalize(m_PathName);
}
else if (isFromPWD()) {
std::string path_name;
detail::get_pwd(path_name);
path_name += '/';
path_name += m_PathName;
detail::canonicalize(path_name);
m_PathName = path_name;
}
}
| gpl-2.0 |
lengagne/GestionEDT | src/Comment.cpp | 1278 | // Comment.h
// Copyright (C) 2012 lengagne (lengagne@gmail.com)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 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 program was developped in the following labs:
// 2009-2011: Joint robotics Laboratory - CNRS/AIST,Tsukuba, Japan.
// 2011-2012: Karlsruhe Institute fur Technologie, Karlsruhe, Germany
// 2012-2013: IUT de Beziers/ LIRMM, Beziers, France
// from 2013: Université Blaise Pascal / axis : ISPR / theme MACCS
#ifndef __Comment__
#define __Comment__
#include <string>
#include <iostream>
#include "Comment.h"
Comment::Comment()
{
}
Comment::Comment()
{
}
#endif | gpl-2.0 |
alexwais/redmine_workflow_hidden_fields | lib/redmine_workflow_hidden_fields/query_patch.rb | 2111 | module RedmineWorkflowHiddenFields
module QueryPatch
def available_and_visible_columns
available_columns.reject{|col| col.respond_to?(:custom_field) ? completely_hidden_fields.include?(col.custom_field.id.to_s) : completely_hidden_fields.include?(col.name)}
end
# Returns an array of columns that can be used to group the results
def groupable_columns
available_and_visible_columns.select {|c| c.groupable}
end
# Returns a Hash of columns and the key for sorting
def sortable_columns
available_and_visible_columns.inject({}) {|h, column|
h[column.name.to_s] = column.sortable
h
}
end
def available_inline_columns
available_and_visible_columns.select(&:inline?)
end
def available_block_columns
available_and_visible_columns.reject(&:inline?)
end
def columns
super.reject{|col| col.respond_to?(:custom_field) ? completely_hidden_fields.include?(col.custom_field.id.to_s) : completely_hidden_fields.include?(col.name)}
end
def available_filters
unless @available_filters
super
completely_hidden_fields.each {|field|
@available_filters.delete field
}
end
@available_filters
end
def completely_hidden_fields
unless @completely_hidden_fields
if project != nil
@completely_hidden_fields = project.completely_hidden_attribute_names
else
@completely_hidden_fields = []
usr = User.current;
first = true
all_projects.each { |prj|
if usr.roles_for_project(prj).count > 0
if first
@completely_hidden_fields = prj.completely_hidden_attribute_names(usr)
else
@completely_hidden_fields &= prj.completely_hidden_attribute_names(usr)
end
return @completely_hidden_fields if @completely_hidden_fields.empty?
first = false
end
}
end
end
return @completely_hidden_fields
end
# Adds a filter for the given custom field
def add_custom_field_filter(field, assoc=nil)
unless completely_hidden_fields.include?(field.id.to_s)
super
end
end
end
end
| gpl-2.0 |
hubzero/hubzero-cms | core/components/com_projects/site/views/projects/tmpl/_menu.php | 3916 | <?php
/**
* @package hubzero-cms
* @copyright Copyright (c) 2005-2020 The Regents of the University of California.
* @license http://opensource.org/licenses/MIT MIT
*/
// No direct access
defined('_HZEXEC_') or die();
$assetTabs = array();
// Sort tabs so that asset tabs are together
foreach ($this->tabs as $tab)
{
if ($tab['submenu'] == 'Assets')
{
$assetTabs[] = $tab;
}
}
$a = 0;
$counts = $this->model->get('counts');
?>
<ul class="projecttools">
<?php
foreach ($this->tabs as $tab)
{
if (!isset($tab['icon']))
{
$tab['icon'] = 'f009';
}
/*if (isset($tab['submenu']) && $tab['submenu'] == 'Assets' && count($assetTabs) > 0)
{
// counter for asset tabs
$a++;
// Header tab
if ($a == 1)
{
?>
<li class="assets">
<span class="tab-assets" data-icon=""><?php echo Lang::txt('COM_PROJECTS_TAB_ASSETS'); ?></span>
<ul class="assetlist">
<?php foreach ($assetTabs as $aTab) { ?>
<li<?php if ($aTab['name'] == $this->active) { echo ' class="active"'; } ?>>
<a class="tab-<?php echo $aTab['name']; ?>" data-icon="&#x<?php echo $aTab['icon']; ?>" href="<?php echo Route::url('index.php?option=' . $this->option . '&alias=' . $this->model->get('alias') . '&active=' . $aTab['name']); ?>" title="<?php echo Lang::txt('COM_PROJECTS_VIEW') . ' ' . strtolower(Lang::txt('COM_PROJECTS_PROJECT')) . ' ' . strtolower($aTab['title']); ?>">
<span><?php echo $aTab['title']; ?></span>
<?php if (isset($counts[$aTab['name']]) && $counts[$aTab['name']] != 0) { ?>
<span class="mini" id="c-<?php echo $aTab['name']; ?>"><span id="c-<?php echo $aTab['name']; ?>-num"><?php echo $counts[$aTab['name']]; ?></span></span>
<?php } ?>
</a>
<?php if (isset($aTab['children']) && count($aTab['children']) > 0) { ?>
<ul>
<?php foreach ($aTab['children'] as $item) { ?>
<li<?php if ($item['class']) { echo ' class="' . $item['class'] . '"'; } ?>>
<a class="tab-<?php echo $aTab['name']; ?>" data-icon="&#x<?php echo $item['icon']; ?>" href="<?php echo Route::url($item['url']); ?>">
<span><?php echo $item['title']; ?></span>
</a>
</li>
<?php } ?>
</ul>
<?php } ?>
</li>
<?php } ?>
</ul>
</li>
<?php
}
continue;
}*/
?>
<li<?php if ($tab['name'] == $this->active) { echo ' class="active"'; } ?>>
<a class="tab-<?php echo $tab['name']; ?>" data-icon="&#x<?php echo $tab['icon']; ?>" href="<?php echo Route::url('index.php?option=' . $this->option . '&alias=' . $this->model->get('alias') . '&active=' . $tab['name']); ?>" title="<?php echo Lang::txt('COM_PROJECTS_VIEW') . ' ' . strtolower(Lang::txt('COM_PROJECTS_PROJECT')) . ' ' . strtolower($tab['title']); ?>">
<span><?php echo $tab['title']; ?></span>
<?php if (isset($counts[$tab['name']]) && $counts[$tab['name']] != 0) { ?>
<span class="mini" id="c-<?php echo $tab['name']; ?>"><span id="c-<?php echo $tab['name']; ?>-num"><?php echo $counts[$tab['name']]; ?></span></span>
<?php } ?>
</a>
<?php if (isset($tab['children']) && count($tab['children']) > 0) { ?>
<ul>
<?php foreach ($tab['children'] as $item) { ?>
<li<?php if ($item['class']) { echo ' class="' . $item['class'] . '"'; } ?>>
<a class="tab-<?php echo $item['name']; ?>" data-icon="&#x<?php echo $item['icon']; ?>" href="<?php echo Route::url($item['url']); ?>">
<span><?php echo $item['title']; ?></span>
</a>
</li>
<?php } ?>
</ul>
<?php } ?>
</li>
<?php
}
?>
</ul>
<ul>
<?php
$integrations = Event::trigger('projects.onProjectIntegrationList', array($this->model));
$integrations = array_filter($integrations);
?>
<?php foreach ($integrations as $integration): ?>
<li><?php echo $integration; ?></li>
<?php endforeach; ?>
</ul>
| gpl-2.0 |
hholzgra/osm2pgsql | geometry-builder.cpp | 27692 | /*
#-----------------------------------------------------------------------------
# Part of osm2pgsql utility
#-----------------------------------------------------------------------------
# By Artem Pavlenko, Copyright 2007
#
# 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.
#-----------------------------------------------------------------------------
*/
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <sstream>
#include <stdexcept>
#include <memory>
#include <new>
#include <numeric>
#if defined(__CYGWIN__)
#define GEOS_INLINE
#endif
#include <geos/geom/prep/PreparedGeometry.h>
#include <geos/geom/prep/PreparedGeometryFactory.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/Coordinate.h>
#include <geos/geom/CoordinateSequence.h>
#include <geos/geom/CoordinateSequenceFactory.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/GeometryCollection.h>
#include <geos/geom/LineString.h>
#include <geos/geom/LinearRing.h>
#include <geos/geom/MultiLineString.h>
#include <geos/geom/Polygon.h>
#include <geos/geom/MultiPolygon.h>
#include <geos/io/WKBReader.h>
#include <geos/io/WKBWriter.h>
#include <geos/util/GEOSException.h>
#include <geos/opLinemerge.h>
using namespace geos::geom;
using namespace geos::util;
using namespace geos::operation::linemerge;
#include "geometry-builder.hpp"
#include "reprojection.hpp"
typedef std::unique_ptr<Geometry> geom_ptr;
typedef std::unique_ptr<CoordinateSequence> coord_ptr;
namespace {
void coords2nodes(CoordinateSequence * coords, nodelist_t &nodes)
{
size_t num_coords = coords->getSize();
nodes.reserve(num_coords);
for (size_t i = 0; i < num_coords; i++) {
Coordinate coord = coords->getAt(i);
nodes.push_back(osmNode(coord.x, coord.y));
}
}
coord_ptr nodes2coords(GeometryFactory &gf, const nodelist_t &nodes)
{
coord_ptr coords(gf.getCoordinateSequenceFactory()->create(size_t(0), size_t(2)));
for (const auto& nd: nodes) {
coords->add(Coordinate(nd.lon, nd.lat), 0);
}
return coords;
}
geom_ptr create_multi_line(GeometryFactory &gf, const multinodelist_t &xnodes)
{
// XXX leaks memory if an exception is thrown
std::unique_ptr<std::vector<Geometry*> > lines(new std::vector<Geometry*>);
lines->reserve(xnodes.size());
for (const auto& nodes: xnodes) {
auto coords = nodes2coords(gf, nodes);
if (coords->getSize() > 1) {
lines->push_back(gf.createLineString(coords.release()));
}
}
return geom_ptr(gf.createMultiLineString(lines.release()));
}
bool is_polygon_line(CoordinateSequence * coords)
{
return (coords->getSize() >= 4)
&& (coords->getAt(coords->getSize() - 1).equals2D(coords->getAt(0)));
}
/**
* Reprojects given Linear Ring from target projection to spherical mercator.
* Caller takes ownership of return value.
*/
LinearRing* reproject_linearring(const LineString *ls, const reprojection *proj)
{
auto *gf = ls->getFactory();
coord_ptr coords(gf->getCoordinateSequenceFactory()->create(size_t(0), size_t(2)));
for (auto i : *(ls->getCoordinatesRO()->toVector())) {
Coordinate c(i.x, i.y);
proj->target_to_tile(&c.y, &c.x);
coords->add(c);
}
return gf->createLinearRing(coords.release());
}
/**
* Computes area of given polygonal geometry.
* \return the area in projected units, or in EPSG 3857 if area reprojection is enabled
*/
double get_area(const geos::geom::Geometry *geom, reprojection *proj)
{
// reprojection is not necessary, or has not been asked for.
if (!proj) {
return geom->getArea();
}
// MultiPolygon - return sum of individual areas
if (const auto *multi = dynamic_cast<const MultiPolygon *>(geom)) {
return std::accumulate(multi->begin(), multi->end(), 0.0,
[=](double a, const Geometry *g) {
return a + get_area(g, proj);
});
}
const auto *poly = dynamic_cast<const geos::geom::Polygon *>(geom);
if (!poly) {
return 0.0;
}
// standard polygon - reproject rings individually, then assemble polygon and
// compute area.
const auto *ext = poly->getExteriorRing();
std::unique_ptr<LinearRing> projectedExt(reproject_linearring(ext, proj));
auto nholes = poly->getNumInteriorRing();
std::unique_ptr<std::vector<Geometry *> > projectedHoles(new std::vector<Geometry *>);
for (std::size_t i=0; i < nholes; i++) {
auto* hole = poly->getInteriorRingN(i);
projectedHoles->push_back(reproject_linearring(hole, proj));
}
const geom_ptr projectedPoly(poly->getFactory()->createPolygon(projectedExt.release(), projectedHoles.release()));
return projectedPoly->getArea();
}
struct polygondata
{
std::unique_ptr<Polygon> polygon;
std::unique_ptr<LinearRing> ring;
double area;
bool iscontained;
unsigned containedbyid;
polygondata(std::unique_ptr<Polygon> p, LinearRing* r, double a)
: polygon(std::move(p)), ring(r), area(a),
iscontained(false), containedbyid(0)
{}
};
struct polygondata_comparearea {
bool operator()(const polygondata& lhs, const polygondata& rhs) {
return lhs.area > rhs.area;
}
};
} // anonymous namespace
void geometry_builder::pg_geom_t::set(const geos::geom::Geometry *g, bool poly,
reprojection *p)
{
geos::io::WKBWriter writer(2, getMachineByteOrder(), true);
std::stringstream stream(std::ios_base::out);
writer.writeHEX(*g, stream);
geom = stream.str();
if (valid()) {
area = poly ? get_area(g, p) : 0;
polygon = poly;
}
}
geom_ptr geometry_builder::create_simple_poly(GeometryFactory &gf,
std::unique_ptr<CoordinateSequence> coords) const
{
std::unique_ptr<LinearRing> shell(gf.createLinearRing(coords.release()));
std::unique_ptr<std::vector<Geometry *> > empty(new std::vector<Geometry *>);
geom_ptr geom(gf.createPolygon(shell.release(), empty.release()));
if (!geom->isValid()) {
if (excludepoly) {
throw std::runtime_error("Excluding broken polygon.");
} else {
geom = geom_ptr(geom->buffer(0));
}
}
geom->normalize(); // Fix direction of ring
return geom;
}
geometry_builder::pg_geom_t geometry_builder::get_wkb_simple(const nodelist_t &nodes, int polygon) const
{
pg_geom_t wkb;
try
{
GeometryFactory gf;
auto coords = nodes2coords(gf, nodes);
if (polygon && is_polygon_line(coords.get())) {
auto geom = create_simple_poly(gf, std::move(coords));
wkb.set(geom.get(), true, projection);
} else {
if (coords->getSize() < 2)
throw std::runtime_error("Excluding degenerate line.");
geom_ptr geom(gf.createLineString(coords.release()));
wkb.set(geom.get(), false);
}
}
catch (const std::bad_alloc&)
{
std::cerr << std::endl << "Exception caught processing way. You are likelly running out of memory." << std::endl;
std::cerr << "Try in slim mode, using -s parameter." << std::endl;
}
catch (const std::runtime_error& e)
{
//std::cerr << std::endl << "Exception caught processing way: " << e.what() << std::endl;
}
catch (...)
{
std::cerr << std::endl << "Exception caught processing way" << std::endl;
}
return wkb;
}
geometry_builder::pg_geoms_t geometry_builder::get_wkb_split(const nodelist_t &nodes, int polygon, double split_at) const
{
//TODO: use count to get some kind of hint of how much we should reserve?
pg_geoms_t wkbs;
try
{
GeometryFactory gf;
auto coords = nodes2coords(gf, nodes);
if (polygon && is_polygon_line(coords.get())) {
auto geom = create_simple_poly(gf, std::move(coords));
wkbs.emplace_back(geom.get(), true, projection);
} else {
if (coords->getSize() < 2)
throw std::runtime_error("Excluding degenerate line.");
double distance = 0;
std::unique_ptr<CoordinateSequence> segment(gf.getCoordinateSequenceFactory()->create((size_t)0, (size_t)2));
segment->add(coords->getAt(0));
for(size_t i=1; i<coords->getSize(); i++) {
const Coordinate this_pt = coords->getAt(i);
const Coordinate prev_pt = coords->getAt(i-1);
const double delta = this_pt.distance(prev_pt);
assert(!std::isnan(delta));
// figure out if the addition of this point would take the total
// length of the line in `segment` over the `split_at` distance.
if (distance + delta > split_at) {
const size_t splits = (size_t) std::floor((distance + delta) / split_at);
// use the splitting distance to split the current segment up
// into as many parts as necessary to keep each part below
// the `split_at` distance.
for (size_t j = 0; j < splits; ++j) {
double frac = (double(j + 1) * split_at - distance) / delta;
const Coordinate interpolated(frac * (this_pt.x - prev_pt.x) + prev_pt.x,
frac * (this_pt.y - prev_pt.y) + prev_pt.y);
segment->add(interpolated);
geom_ptr geom(gf.createLineString(segment.release()));
wkbs.emplace_back(geom.get(), false);
segment.reset(gf.getCoordinateSequenceFactory()->create((size_t)0, (size_t)2));
segment->add(interpolated);
}
// reset the distance based on the final splitting point for
// the next iteration.
distance = segment->getAt(0).distance(this_pt);
} else {
// if not split then just push this point onto the sequence
// being saved up.
distance += delta;
}
// always add this point
segment->add(this_pt);
// on the last iteration, close out the line.
if (i == coords->getSize()-1) {
geom_ptr geom(gf.createLineString(segment.release()));
wkbs.emplace_back(geom.get(), false);
}
}
}
}
catch (const std::bad_alloc&)
{
std::cerr << std::endl << "Exception caught processing way. You are likely running out of memory." << std::endl;
std::cerr << "Try in slim mode, using -s parameter." << std::endl;
}
catch (const std::runtime_error& e)
{
//std::cerr << std::endl << "Exception caught processing way: " << e.what() << std::endl;
}
catch (...)
{
std::cerr << std::endl << "Exception caught processing way" << std::endl;
}
return wkbs;
}
int geometry_builder::parse_wkb(const char* wkb, multinodelist_t &nodes, bool *polygon) {
GeometryFactory gf;
geos::io::WKBReader reader(gf);
*polygon = false;
std::stringstream stream(wkb, std::ios_base::in);
geom_ptr geometry(reader.readHEX(stream));
switch (geometry->getGeometryTypeId()) {
// Single geometries
case GEOS_POLYGON:
// Drop through
case GEOS_LINEARRING:
*polygon = true;
// Drop through
case GEOS_POINT:
// Drop through
case GEOS_LINESTRING:
{
nodes.push_back(nodelist_t());
coord_ptr coords(geometry->getCoordinates());
coords2nodes(coords.get(), nodes.back());
break;
}
// Geometry collections
case GEOS_MULTIPOLYGON:
*polygon = true;
// Drop through
case GEOS_MULTIPOINT:
// Drop through
case GEOS_MULTILINESTRING:
{
auto gc = dynamic_cast<GeometryCollection *>(geometry.get());
size_t num_geometries = gc->getNumGeometries();
nodes.assign(num_geometries, nodelist_t());
for (size_t i = 0; i < num_geometries; i++) {
const Geometry *subgeometry = gc->getGeometryN(i);
coord_ptr coords(subgeometry->getCoordinates());
coords2nodes(coords.get(), nodes[i]);
}
break;
}
default:
std::cerr << std::endl << "unexpected object type while processing PostGIS data" << std::endl;
return -1;
}
return 0;
}
geometry_builder::pg_geoms_t geometry_builder::build_polygons(const multinodelist_t &xnodes,
bool enable_multi, osmid_t osm_id) const
{
pg_geoms_t wkbs;
try
{
GeometryFactory gf;
geom_ptr mline = create_multi_line(gf, xnodes);
//geom_ptr noded (segment->Union(mline.get()));
LineMerger merger;
//merger.add(noded.get());
merger.add(mline.get());
std::unique_ptr<std::vector<LineString *>> merged(merger.getMergedLineStrings());
// Procces ways into lines or simple polygon list
std::vector<polygondata> polys;
polys.reserve(merged->size());
for (auto *line: *merged) {
// stuff into unique pointer for auto-destruct
std::unique_ptr<LineString> pline(line);
if (pline->getNumPoints() > 3 && pline->isClosed()) {
std::unique_ptr<Polygon> poly(gf.createPolygon(gf.createLinearRing(pline->getCoordinates()),0));
double area = get_area(poly.get(), projection);
if (area > 0.0) {
polys.emplace_back(std::move(poly),
gf.createLinearRing(pline->getCoordinates()),
area);
}
}
}
if (!polys.empty())
{
std::sort(polys.begin(), polys.end(), polygondata_comparearea());
unsigned toplevelpolygons = 0;
int istoplevelafterall;
size_t totalpolys = polys.size();
geos::geom::prep::PreparedGeometryFactory pgf;
for (unsigned i=0 ;i < totalpolys; ++i)
{
if (polys[i].iscontained) continue;
toplevelpolygons++;
const geos::geom::prep::PreparedGeometry* preparedtoplevelpolygon = pgf.create(polys[i].polygon.get());
for (unsigned j=i+1; j < totalpolys; ++j)
{
// Does preparedtoplevelpolygon contain the smaller polygon[j]?
if (polys[j].containedbyid == 0 && preparedtoplevelpolygon->contains(polys[j].polygon.get()))
{
// are we in a [i] contains [k] contains [j] situation
// which would actually make j top level
istoplevelafterall = 0;
for (unsigned k=i+1; k < j; ++k)
{
if (polys[k].iscontained && polys[k].containedbyid == i && polys[k].polygon->contains(polys[j].polygon.get()))
{
istoplevelafterall = 1;
break;
}
}
if (istoplevelafterall == 0)
{
polys[j].iscontained = true;
polys[j].containedbyid = i;
}
}
}
pgf.destroy(preparedtoplevelpolygon);
}
// polys now is a list of polygons tagged with which ones are inside each other
// List of polygons for multipolygon
std::unique_ptr<std::vector<Geometry*>> polygons(new std::vector<Geometry*>);
// For each top level polygon create a new polygon including any holes
for (unsigned i=0 ;i < totalpolys; ++i)
{
if (polys[i].iscontained) continue;
// List of holes for this top level polygon
std::unique_ptr<std::vector<Geometry*> > interior(new std::vector<Geometry*>);
for (unsigned j=i+1; j < totalpolys; ++j)
{
if (polys[j].iscontained && polys[j].containedbyid == i)
{
interior->push_back(polys[j].ring.release());
}
}
Polygon* poly(gf.createPolygon(polys[i].ring.release(), interior.release()));
poly->normalize();
polygons->push_back(poly);
}
// Make a multipolygon if required
if ((toplevelpolygons > 1) && enable_multi)
{
geom_ptr multipoly(gf.createMultiPolygon(polygons.release()));
if (!multipoly->isValid() && !excludepoly) {
multipoly = geom_ptr(multipoly->buffer(0));
}
multipoly->normalize();
if ((excludepoly == 0) || (multipoly->isValid())) {
wkbs.emplace_back(multipoly.get(), true, projection);
}
}
else
{
for(unsigned i=0; i<toplevelpolygons; i++) {
geom_ptr poly(polygons->at(i));
if (!poly->isValid() && !excludepoly) {
poly = geom_ptr(poly->buffer(0));
poly->normalize();
}
if ((excludepoly == 0) || (poly->isValid())) {
wkbs.emplace_back(poly.get(), true, projection);
}
}
}
}
}//TODO: don't show in message id when osm_id == -1
catch (const std::exception& e)
{
std::cerr << std::endl << "Standard exception processing relation_id="<< osm_id << ": " << e.what() << std::endl;
}
catch (...)
{
std::cerr << std::endl << "Exception caught processing relation id=" << osm_id << std::endl;
}
return wkbs;
}
geometry_builder::pg_geom_t geometry_builder::build_multilines(const multinodelist_t &xnodes, osmid_t osm_id) const
{
pg_geom_t wkb;
try
{
GeometryFactory gf;
geom_ptr mline = create_multi_line(gf, xnodes);
wkb.set(mline.get(), false);
}//TODO: don't show in message id when osm_id == -1
catch (const std::exception& e)
{
std::cerr << std::endl << "Standard exception processing relation_id="<< osm_id << ": " << e.what() << std::endl;
}
catch (...)
{
std::cerr << std::endl << "Exception caught processing relation id=" << osm_id << std::endl;
}
return wkb;
}
geometry_builder::pg_geoms_t geometry_builder::build_both(const multinodelist_t &xnodes,
int make_polygon, int enable_multi,
double split_at, osmid_t osm_id) const
{
pg_geoms_t wkbs;
try
{
GeometryFactory gf;
geom_ptr mline = create_multi_line(gf, xnodes);
//geom_ptr noded (segment->Union(mline.get()));
LineMerger merger;
//merger.add(noded.get());
merger.add(mline.get());
std::unique_ptr<std::vector<LineString *> > merged(merger.getMergedLineStrings());
// Procces ways into lines or simple polygon list
std::vector<polygondata> polys;
polys.reserve(merged->size());
for (auto *line: *merged) {
// stuff into unique pointer to ensure auto-destruct
std::unique_ptr<LineString> pline(line);
if (make_polygon && pline->getNumPoints() > 3 && pline->isClosed()) {
std::unique_ptr<Polygon> poly(gf.createPolygon(gf.createLinearRing(pline->getCoordinates()),0));
double area = get_area(poly.get(), projection);
if (area > 0.0) {
polys.emplace_back(std::move(poly),
gf.createLinearRing(pline->getCoordinates()),
area);
}
} else {
double distance = 0;
std::unique_ptr<CoordinateSequence> segment;
segment = std::unique_ptr<CoordinateSequence>(gf.getCoordinateSequenceFactory()->create((size_t)0, (size_t)2));
segment->add(pline->getCoordinateN(0));
for(int j=1; j<(int)pline->getNumPoints(); ++j) {
segment->add(pline->getCoordinateN(j));
distance += pline->getCoordinateN(j).distance(pline->getCoordinateN(j-1));
if ((distance >= split_at) || (j == (int)pline->getNumPoints()-1)) {
geom_ptr geom = geom_ptr(gf.createLineString(segment.release()));
wkbs.emplace_back(geom.get(), false);
segment.reset(gf.getCoordinateSequenceFactory()->create((size_t)0, (size_t)2));
distance=0;
segment->add(pline->getCoordinateN(j));
}
}
}
}
if (!polys.empty())
{
std::sort(polys.begin(), polys.end(), polygondata_comparearea());
unsigned toplevelpolygons = 0;
int istoplevelafterall;
size_t totalpolys = polys.size();
geos::geom::prep::PreparedGeometryFactory pgf;
for (unsigned i=0 ;i < totalpolys; ++i)
{
if (polys[i].iscontained) continue;
toplevelpolygons++;
const geos::geom::prep::PreparedGeometry* preparedtoplevelpolygon = pgf.create(polys[i].polygon.get());
for (unsigned j=i+1; j < totalpolys; ++j)
{
// Does preparedtoplevelpolygon contain the smaller polygon[j]?
if (polys[j].containedbyid == 0 && preparedtoplevelpolygon->contains(polys[j].polygon.get()))
{
// are we in a [i] contains [k] contains [j] situation
// which would actually make j top level
istoplevelafterall = 0;
for (unsigned k=i+1; k < j; ++k)
{
if (polys[k].iscontained && polys[k].containedbyid == i && polys[k].polygon->contains(polys[j].polygon.get()))
{
istoplevelafterall = 1;
break;
}
#if 0
else if (polys[k].polygon->intersects(polys[j].polygon) || polys[k].polygon->touches(polys[j].polygon))
{
// FIXME: This code does not work as intended
// It should be setting the polys[k].ring in order to update this object
// but the value of polys[k].polygon calculated is normally NULL
// Add polygon this polygon (j) to k since they intersect
// Mark ourselfs to be dropped (2), delete the original k
Geometry* polyunion = polys[k].polygon->Union(polys[j].polygon);
delete(polys[k].polygon);
polys[k].polygon = dynamic_cast<Polygon*>(polyunion);
polys[j].iscontained = 2; // Drop
istoplevelafterall = 2;
break;
}
#endif
}
if (istoplevelafterall == 0)
{
polys[j].iscontained = true;
polys[j].containedbyid = i;
}
}
}
pgf.destroy(preparedtoplevelpolygon);
}
// polys now is a list of polygons tagged with which ones are inside each other
// List of polygons for multipolygon
std::unique_ptr<std::vector<Geometry*> > polygons(new std::vector<Geometry*>);
// For each top level polygon create a new polygon including any holes
for (unsigned i=0 ;i < totalpolys; ++i)
{
if (polys[i].iscontained) continue;
// List of holes for this top level polygon
std::unique_ptr<std::vector<Geometry*> > interior(new std::vector<Geometry*>);
for (unsigned j=i+1; j < totalpolys; ++j)
{
if (polys[j].iscontained && polys[j].containedbyid == i)
{
interior->push_back(polys[j].ring.release());
}
}
Polygon* poly(gf.createPolygon(polys[i].ring.release(), interior.release()));
poly->normalize();
polygons->push_back(poly);
}
// Make a multipolygon if required
if ((toplevelpolygons > 1) && enable_multi)
{
geom_ptr multipoly(gf.createMultiPolygon(polygons.release()));
if (!multipoly->isValid() && !excludepoly) {
multipoly = geom_ptr(multipoly->buffer(0));
}
multipoly->normalize();
if ((excludepoly == 0) || (multipoly->isValid())) {
wkbs.emplace_back(multipoly.get(), true, projection);
}
}
else
{
for(unsigned i=0; i<toplevelpolygons; i++)
{
geom_ptr poly(polygons->at(i));
if (!poly->isValid() && !excludepoly) {
poly = geom_ptr(poly->buffer(0));
poly->normalize();
}
if (!excludepoly || (poly->isValid())) {
wkbs.emplace_back(poly.get(), true, projection);
}
}
}
}
}//TODO: don't show in message id when osm_id == -1
catch (const std::exception& e)
{
std::cerr << std::endl << "Standard exception processing relation id="<< osm_id << ": " << e.what() << std::endl;
}
catch (...)
{
std::cerr << std::endl << "Exception caught processing relation id=" << osm_id << std::endl;
}
return wkbs;
}
| gpl-2.0 |
TUD-OS/M3 | src/libs/m3/stream/Standard.cc | 1057 | /*
* Copyright (C) 2016, Nils Asmussen <nils@os.inf.tu-dresden.de>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* M3 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.
*/
#include <base/Common.h>
#include <base/Init.h>
#include <m3/stream/Standard.h>
namespace m3 {
// create them after VPE::self() has finished, because otherwise the file objects are not available
INIT_PRIO_STREAM FStream cerr(STDERR_FD, FILE_W, 256, FStream::FL_LINE_BUF);
INIT_PRIO_STREAM FStream cout(STDOUT_FD, FILE_W, 256, FStream::FL_LINE_BUF);
INIT_PRIO_STREAM FStream cin(STDIN_FD, FILE_R, 128);
}
| gpl-2.0 |
rollinm/xbmc | xbmc/XBDateTime.cpp | 33795 | /*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include <cstdlib>
#include "XBDateTime.h"
#include "LangInfo.h"
#include "guilib/LocalizeStrings.h"
#include "utils/log.h"
#include "utils/StringUtils.h"
#include "utils/Archive.h"
#ifdef TARGET_POSIX
#include "XTimeUtils.h"
#include "XFileUtils.h"
#else
#include <Windows.h>
#endif
#define SECONDS_PER_DAY 86400UL
#define SECONDS_PER_HOUR 3600UL
#define SECONDS_PER_MINUTE 60UL
#define SECONDS_TO_FILETIME 10000000UL
static const char *DAY_NAMES[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
static const char *MONTH_NAMES[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
/////////////////////////////////////////////////
//
// CDateTimeSpan
//
CDateTimeSpan::CDateTimeSpan()
{
m_timeSpan.dwHighDateTime=0;
m_timeSpan.dwLowDateTime=0;
}
CDateTimeSpan::CDateTimeSpan(const CDateTimeSpan& span)
{
m_timeSpan.dwHighDateTime=span.m_timeSpan.dwHighDateTime;
m_timeSpan.dwLowDateTime=span.m_timeSpan.dwLowDateTime;
}
CDateTimeSpan::CDateTimeSpan(int day, int hour, int minute, int second)
{
SetDateTimeSpan(day, hour, minute, second);
}
bool CDateTimeSpan::operator >(const CDateTimeSpan& right) const
{
return CompareFileTime(&m_timeSpan, &right.m_timeSpan)>0;
}
bool CDateTimeSpan::operator >=(const CDateTimeSpan& right) const
{
return operator >(right) || operator ==(right);
}
bool CDateTimeSpan::operator <(const CDateTimeSpan& right) const
{
return CompareFileTime(&m_timeSpan, &right.m_timeSpan)<0;
}
bool CDateTimeSpan::operator <=(const CDateTimeSpan& right) const
{
return operator <(right) || operator ==(right);
}
bool CDateTimeSpan::operator ==(const CDateTimeSpan& right) const
{
return CompareFileTime(&m_timeSpan, &right.m_timeSpan)==0;
}
bool CDateTimeSpan::operator !=(const CDateTimeSpan& right) const
{
return !operator ==(right);
}
CDateTimeSpan CDateTimeSpan::operator +(const CDateTimeSpan& right) const
{
CDateTimeSpan left(*this);
ULARGE_INTEGER timeLeft;
left.ToULargeInt(timeLeft);
ULARGE_INTEGER timeRight;
right.ToULargeInt(timeRight);
timeLeft.QuadPart+=timeRight.QuadPart;
left.FromULargeInt(timeLeft);
return left;
}
CDateTimeSpan CDateTimeSpan::operator -(const CDateTimeSpan& right) const
{
CDateTimeSpan left(*this);
ULARGE_INTEGER timeLeft;
left.ToULargeInt(timeLeft);
ULARGE_INTEGER timeRight;
right.ToULargeInt(timeRight);
timeLeft.QuadPart-=timeRight.QuadPart;
left.FromULargeInt(timeLeft);
return left;
}
const CDateTimeSpan& CDateTimeSpan::operator +=(const CDateTimeSpan& right)
{
ULARGE_INTEGER timeThis;
ToULargeInt(timeThis);
ULARGE_INTEGER timeRight;
right.ToULargeInt(timeRight);
timeThis.QuadPart+=timeRight.QuadPart;
FromULargeInt(timeThis);
return *this;
}
const CDateTimeSpan& CDateTimeSpan::operator -=(const CDateTimeSpan& right)
{
ULARGE_INTEGER timeThis;
ToULargeInt(timeThis);
ULARGE_INTEGER timeRight;
right.ToULargeInt(timeRight);
timeThis.QuadPart-=timeRight.QuadPart;
FromULargeInt(timeThis);
return *this;
}
void CDateTimeSpan::ToULargeInt(ULARGE_INTEGER& time) const
{
time.u.HighPart=m_timeSpan.dwHighDateTime;
time.u.LowPart=m_timeSpan.dwLowDateTime;
}
void CDateTimeSpan::FromULargeInt(const ULARGE_INTEGER& time)
{
m_timeSpan.dwHighDateTime=time.u.HighPart;
m_timeSpan.dwLowDateTime=time.u.LowPart;
}
void CDateTimeSpan::SetDateTimeSpan(int day, int hour, int minute, int second)
{
ULARGE_INTEGER time;
ToULargeInt(time);
time.QuadPart=(LONGLONG)day*SECONDS_PER_DAY*SECONDS_TO_FILETIME;
time.QuadPart+=(LONGLONG)hour*SECONDS_PER_HOUR*SECONDS_TO_FILETIME;
time.QuadPart+=(LONGLONG)minute*SECONDS_PER_MINUTE*SECONDS_TO_FILETIME;
time.QuadPart+=(LONGLONG)second*SECONDS_TO_FILETIME;
FromULargeInt(time);
}
void CDateTimeSpan::SetFromTimeString(const std::string& time) // hh:mm
{
if (time.size() >= 5 && time[2] == ':')
{
int hour = atoi(time.substr(0, 2).c_str());
int minutes = atoi(time.substr(3, 2).c_str());
SetDateTimeSpan(0,hour,minutes,0);
}
}
int CDateTimeSpan::GetDays() const
{
ULARGE_INTEGER time;
ToULargeInt(time);
return (int)(time.QuadPart/SECONDS_TO_FILETIME)/SECONDS_PER_DAY;
}
int CDateTimeSpan::GetHours() const
{
ULARGE_INTEGER time;
ToULargeInt(time);
return (int)((time.QuadPart/SECONDS_TO_FILETIME)%SECONDS_PER_DAY)/SECONDS_PER_HOUR;
}
int CDateTimeSpan::GetMinutes() const
{
ULARGE_INTEGER time;
ToULargeInt(time);
return (int)((time.QuadPart/SECONDS_TO_FILETIME%SECONDS_PER_DAY)%SECONDS_PER_HOUR)/SECONDS_PER_MINUTE;
}
int CDateTimeSpan::GetSeconds() const
{
ULARGE_INTEGER time;
ToULargeInt(time);
return (int)(((time.QuadPart/SECONDS_TO_FILETIME%SECONDS_PER_DAY)%SECONDS_PER_HOUR)%SECONDS_PER_MINUTE)%SECONDS_PER_MINUTE;
}
int CDateTimeSpan::GetSecondsTotal() const
{
ULARGE_INTEGER time;
ToULargeInt(time);
return (int)(time.QuadPart/SECONDS_TO_FILETIME);
}
void CDateTimeSpan::SetFromPeriod(const std::string &period)
{
long days = atoi(period.c_str());
// find the first non-space and non-number
size_t pos = period.find_first_not_of("0123456789 ", 0);
if (pos != std::string::npos)
{
std::string units = period.substr(pos, 3);
if (StringUtils::EqualsNoCase(units, "wee"))
days *= 7;
else if (StringUtils::EqualsNoCase(units, "mon"))
days *= 31;
}
SetDateTimeSpan(days, 0, 0, 0);
}
/////////////////////////////////////////////////
//
// CDateTime
//
CDateTime::CDateTime()
{
Reset();
}
CDateTime::CDateTime(const SYSTEMTIME &time)
{
// we store internally as a FILETIME
m_state = ToFileTime(time, m_time) ? valid : invalid;
}
CDateTime::CDateTime(const FILETIME &time)
{
m_time=time;
SetValid(true);
}
CDateTime::CDateTime(const CDateTime& time)
{
m_time=time.m_time;
m_state=time.m_state;
}
CDateTime::CDateTime(const time_t& time)
{
m_state = ToFileTime(time, m_time) ? valid : invalid;
}
CDateTime::CDateTime(const tm& time)
{
m_state = ToFileTime(time, m_time) ? valid : invalid;
}
CDateTime::CDateTime(int year, int month, int day, int hour, int minute, int second)
{
SetDateTime(year, month, day, hour, minute, second);
}
CDateTime CDateTime::GetCurrentDateTime()
{
// get the current time
SYSTEMTIME time;
GetLocalTime(&time);
return CDateTime(time);
}
CDateTime CDateTime::GetUTCDateTime()
{
CDateTime time(GetCurrentDateTime());
time += GetTimezoneBias();
return time;
}
const CDateTime& CDateTime::operator =(const SYSTEMTIME& right)
{
m_state = ToFileTime(right, m_time) ? valid : invalid;
return *this;
}
const CDateTime& CDateTime::operator =(const FILETIME& right)
{
m_time=right;
SetValid(true);
return *this;
}
const CDateTime& CDateTime::operator =(const time_t& right)
{
m_state = ToFileTime(right, m_time) ? valid : invalid;
return *this;
}
const CDateTime& CDateTime::operator =(const tm& right)
{
m_state = ToFileTime(right, m_time) ? valid : invalid;
return *this;
}
bool CDateTime::operator >(const CDateTime& right) const
{
return operator >(right.m_time);
}
bool CDateTime::operator >=(const CDateTime& right) const
{
return operator >(right) || operator ==(right);
}
bool CDateTime::operator <(const CDateTime& right) const
{
return operator <(right.m_time);
}
bool CDateTime::operator <=(const CDateTime& right) const
{
return operator <(right) || operator ==(right);
}
bool CDateTime::operator ==(const CDateTime& right) const
{
return operator ==(right.m_time);
}
bool CDateTime::operator !=(const CDateTime& right) const
{
return !operator ==(right);
}
bool CDateTime::operator >(const FILETIME& right) const
{
return CompareFileTime(&m_time, &right)>0;
}
bool CDateTime::operator >=(const FILETIME& right) const
{
return operator >(right) || operator ==(right);
}
bool CDateTime::operator <(const FILETIME& right) const
{
return CompareFileTime(&m_time, &right)<0;
}
bool CDateTime::operator <=(const FILETIME& right) const
{
return operator <(right) || operator ==(right);
}
bool CDateTime::operator ==(const FILETIME& right) const
{
return CompareFileTime(&m_time, &right)==0;
}
bool CDateTime::operator !=(const FILETIME& right) const
{
return !operator ==(right);
}
bool CDateTime::operator >(const SYSTEMTIME& right) const
{
FILETIME time;
ToFileTime(right, time);
return operator >(time);
}
bool CDateTime::operator >=(const SYSTEMTIME& right) const
{
return operator >(right) || operator ==(right);
}
bool CDateTime::operator <(const SYSTEMTIME& right) const
{
FILETIME time;
ToFileTime(right, time);
return operator <(time);
}
bool CDateTime::operator <=(const SYSTEMTIME& right) const
{
return operator <(right) || operator ==(right);
}
bool CDateTime::operator ==(const SYSTEMTIME& right) const
{
FILETIME time;
ToFileTime(right, time);
return operator ==(time);
}
bool CDateTime::operator !=(const SYSTEMTIME& right) const
{
return !operator ==(right);
}
bool CDateTime::operator >(const time_t& right) const
{
FILETIME time;
ToFileTime(right, time);
return operator >(time);
}
bool CDateTime::operator >=(const time_t& right) const
{
return operator >(right) || operator ==(right);
}
bool CDateTime::operator <(const time_t& right) const
{
FILETIME time;
ToFileTime(right, time);
return operator <(time);
}
bool CDateTime::operator <=(const time_t& right) const
{
return operator <(right) || operator ==(right);
}
bool CDateTime::operator ==(const time_t& right) const
{
FILETIME time;
ToFileTime(right, time);
return operator ==(time);
}
bool CDateTime::operator !=(const time_t& right) const
{
return !operator ==(right);
}
bool CDateTime::operator >(const tm& right) const
{
FILETIME time;
ToFileTime(right, time);
return operator >(time);
}
bool CDateTime::operator >=(const tm& right) const
{
return operator >(right) || operator ==(right);
}
bool CDateTime::operator <(const tm& right) const
{
FILETIME time;
ToFileTime(right, time);
return operator <(time);
}
bool CDateTime::operator <=(const tm& right) const
{
return operator <(right) || operator ==(right);
}
bool CDateTime::operator ==(const tm& right) const
{
FILETIME time;
ToFileTime(right, time);
return operator ==(time);
}
bool CDateTime::operator !=(const tm& right) const
{
return !operator ==(right);
}
CDateTime CDateTime::operator +(const CDateTimeSpan& right) const
{
CDateTime left(*this);
ULARGE_INTEGER timeLeft;
left.ToULargeInt(timeLeft);
ULARGE_INTEGER timeRight;
right.ToULargeInt(timeRight);
timeLeft.QuadPart+=timeRight.QuadPart;
left.FromULargeInt(timeLeft);
return left;
}
CDateTime CDateTime::operator -(const CDateTimeSpan& right) const
{
CDateTime left(*this);
ULARGE_INTEGER timeLeft;
left.ToULargeInt(timeLeft);
ULARGE_INTEGER timeRight;
right.ToULargeInt(timeRight);
timeLeft.QuadPart-=timeRight.QuadPart;
left.FromULargeInt(timeLeft);
return left;
}
const CDateTime& CDateTime::operator +=(const CDateTimeSpan& right)
{
ULARGE_INTEGER timeThis;
ToULargeInt(timeThis);
ULARGE_INTEGER timeRight;
right.ToULargeInt(timeRight);
timeThis.QuadPart+=timeRight.QuadPart;
FromULargeInt(timeThis);
return *this;
}
const CDateTime& CDateTime::operator -=(const CDateTimeSpan& right)
{
ULARGE_INTEGER timeThis;
ToULargeInt(timeThis);
ULARGE_INTEGER timeRight;
right.ToULargeInt(timeRight);
timeThis.QuadPart-=timeRight.QuadPart;
FromULargeInt(timeThis);
return *this;
}
CDateTimeSpan CDateTime::operator -(const CDateTime& right) const
{
CDateTimeSpan left;
ULARGE_INTEGER timeLeft;
left.ToULargeInt(timeLeft);
ULARGE_INTEGER timeThis;
ToULargeInt(timeThis);
ULARGE_INTEGER timeRight;
right.ToULargeInt(timeRight);
timeLeft.QuadPart=timeThis.QuadPart-timeRight.QuadPart;
left.FromULargeInt(timeLeft);
return left;
}
CDateTime::operator FILETIME() const
{
return m_time;
}
void CDateTime::Archive(CArchive& ar)
{
if (ar.IsStoring())
{
ar<<(int)m_state;
if (m_state==valid)
{
SYSTEMTIME st;
GetAsSystemTime(st);
ar<<st;
}
}
else
{
Reset();
int state;
ar >> (int &)state;
m_state = CDateTime::STATE(state);
if (m_state==valid)
{
SYSTEMTIME st;
ar>>st;
ToFileTime(st, m_time);
}
}
}
void CDateTime::Reset()
{
SetDateTime(1601, 1, 1, 0, 0, 0);
SetValid(false);
}
void CDateTime::SetValid(bool yesNo)
{
m_state=yesNo ? valid : invalid;
}
bool CDateTime::IsValid() const
{
return m_state==valid;
}
bool CDateTime::ToFileTime(const SYSTEMTIME& time, FILETIME& fileTime) const
{
return SystemTimeToFileTime(&time, &fileTime) == TRUE &&
(fileTime.dwLowDateTime > 0 || fileTime.dwHighDateTime > 0);
}
bool CDateTime::ToFileTime(const time_t& time, FILETIME& fileTime) const
{
LONGLONG ll = Int32x32To64(time, 10000000)+0x19DB1DED53E8000LL;
fileTime.dwLowDateTime = (DWORD)(ll & 0xFFFFFFFF);
fileTime.dwHighDateTime = (DWORD)(ll >> 32);
return true;
}
bool CDateTime::ToFileTime(const tm& time, FILETIME& fileTime) const
{
SYSTEMTIME st;
ZeroMemory(&st, sizeof(SYSTEMTIME));
st.wYear=time.tm_year+1900;
st.wMonth=time.tm_mon+1;
st.wDayOfWeek=time.tm_wday;
st.wDay=time.tm_mday;
st.wHour=time.tm_hour;
st.wMinute=time.tm_min;
st.wSecond=time.tm_sec;
return SystemTimeToFileTime(&st, &fileTime)==TRUE;
}
void CDateTime::ToULargeInt(ULARGE_INTEGER& time) const
{
time.u.HighPart=m_time.dwHighDateTime;
time.u.LowPart=m_time.dwLowDateTime;
}
void CDateTime::FromULargeInt(const ULARGE_INTEGER& time)
{
m_time.dwHighDateTime=time.u.HighPart;
m_time.dwLowDateTime=time.u.LowPart;
}
bool CDateTime::SetFromDateString(const std::string &date)
{
/* TODO:STRING_CLEANUP */
if (date.empty())
{
SetValid(false);
return false;
}
if (SetFromDBDate(date))
return true;
const char* months[] = {"january","february","march","april","may","june","july","august","september","october","november","december",NULL};
int j=0;
size_t iDayPos = date.find("day");
size_t iPos = date.find(' ');
if (iDayPos < iPos && iDayPos != std::string::npos)
{
iDayPos = iPos + 1;
iPos = date.find(' ', iPos+1);
}
else
iDayPos = 0;
std::string strMonth = date.substr(iDayPos, iPos - iDayPos);
if (strMonth.empty())
return false;
size_t iPos2 = date.find(",");
std::string strDay = (date.size() >= iPos) ? date.substr(iPos, iPos2-iPos) : "";
std::string strYear = date.substr(date.find(' ', iPos2) + 1);
while (months[j] && stricmp(strMonth.c_str(),months[j]) != 0)
j++;
if (!months[j])
return false;
return SetDateTime(atol(strYear.c_str()),j+1,atol(strDay.c_str()),0,0,0);
}
int CDateTime::GetDay() const
{
SYSTEMTIME st;
GetAsSystemTime(st);
return st.wDay;
}
int CDateTime::GetMonth() const
{
SYSTEMTIME st;
GetAsSystemTime(st);
return st.wMonth;
}
int CDateTime::GetYear() const
{
SYSTEMTIME st;
GetAsSystemTime(st);
return st.wYear;
}
int CDateTime::GetHour() const
{
SYSTEMTIME st;
GetAsSystemTime(st);
return st.wHour;
}
int CDateTime::GetMinute() const
{
SYSTEMTIME st;
GetAsSystemTime(st);
return st.wMinute;
}
int CDateTime::GetSecond() const
{
SYSTEMTIME st;
GetAsSystemTime(st);
return st.wSecond;
}
int CDateTime::GetDayOfWeek() const
{
SYSTEMTIME st;
GetAsSystemTime(st);
return st.wDayOfWeek;
}
int CDateTime::GetMinuteOfDay() const
{
SYSTEMTIME st;
GetAsSystemTime(st);
return st.wHour*60+st.wMinute;
}
bool CDateTime::SetDateTime(int year, int month, int day, int hour, int minute, int second)
{
SYSTEMTIME st;
ZeroMemory(&st, sizeof(SYSTEMTIME));
st.wYear=year;
st.wMonth=month;
st.wDay=day;
st.wHour=hour;
st.wMinute=minute;
st.wSecond=second;
m_state = ToFileTime(st, m_time) ? valid : invalid;
return m_state == valid;
}
bool CDateTime::SetDate(int year, int month, int day)
{
return SetDateTime(year, month, day, 0, 0, 0);
}
bool CDateTime::SetTime(int hour, int minute, int second)
{
// 01.01.1601 00:00:00 is 0 as filetime
return SetDateTime(1601, 1, 1, hour, minute, second);
}
void CDateTime::GetAsSystemTime(SYSTEMTIME& time) const
{
FileTimeToSystemTime(&m_time, &time);
}
#define UNIX_BASE_TIME 116444736000000000LL /* nanoseconds since epoch */
void CDateTime::GetAsTime(time_t& time) const
{
LONGLONG ll;
ll = ((LONGLONG)m_time.dwHighDateTime << 32) + m_time.dwLowDateTime;
time=(time_t)((ll - UNIX_BASE_TIME) / 10000000);
}
void CDateTime::GetAsTm(tm& time) const
{
SYSTEMTIME st;
GetAsSystemTime(st);
time.tm_year=st.wYear-1900;
time.tm_mon=st.wMonth-1;
time.tm_wday=st.wDayOfWeek;
time.tm_mday=st.wDay;
time.tm_hour=st.wHour;
time.tm_min=st.wMinute;
time.tm_sec=st.wSecond;
mktime(&time);
}
void CDateTime::GetAsTimeStamp(FILETIME& time) const
{
::LocalFileTimeToFileTime(&m_time, &time);
}
std::string CDateTime::GetAsDBDate() const
{
SYSTEMTIME st;
GetAsSystemTime(st);
return StringUtils::Format("%04i-%02i-%02i", st.wYear, st.wMonth, st.wDay);
}
std::string CDateTime::GetAsDBDateTime() const
{
SYSTEMTIME st;
GetAsSystemTime(st);
return StringUtils::Format("%04i-%02i-%02i %02i:%02i:%02i", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
}
std::string CDateTime::GetAsSaveString() const
{
SYSTEMTIME st;
GetAsSystemTime(st);
return StringUtils::Format("%04i%02i%02i_%02i%02i%02i", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);;
}
bool CDateTime::SetFromUTCDateTime(const CDateTime &dateTime)
{
CDateTime tmp(dateTime);
tmp -= GetTimezoneBias();
m_time = tmp.m_time;
m_state = tmp.m_state;
return m_state == valid;
}
static bool bGotTimezoneBias = false;
void CDateTime::ResetTimezoneBias(void)
{
bGotTimezoneBias = false;
}
CDateTimeSpan CDateTime::GetTimezoneBias(void)
{
static CDateTimeSpan timezoneBias;
if (!bGotTimezoneBias)
{
bGotTimezoneBias = true;
TIME_ZONE_INFORMATION tz;
switch(GetTimeZoneInformation(&tz))
{
case TIME_ZONE_ID_DAYLIGHT:
timezoneBias = CDateTimeSpan(0, 0, tz.Bias + tz.DaylightBias, 0);
break;
case TIME_ZONE_ID_STANDARD:
timezoneBias = CDateTimeSpan(0, 0, tz.Bias + tz.StandardBias, 0);
break;
case TIME_ZONE_ID_UNKNOWN:
timezoneBias = CDateTimeSpan(0, 0, tz.Bias, 0);
break;
}
}
return timezoneBias;
}
bool CDateTime::SetFromUTCDateTime(const time_t &dateTime)
{
CDateTime tmp(dateTime);
return SetFromUTCDateTime(tmp);
}
bool CDateTime::SetFromW3CDate(const std::string &dateTime)
{
std::string date;
size_t posT = dateTime.find("T");
if(posT != std::string::npos)
date = dateTime.substr(0, posT);
else
date = dateTime;
int year = 0, month = 1, day = 1;
if (date.size() >= 4)
year = atoi(date.substr(0, 4).c_str());
if (date.size() >= 10)
{
month = atoi(date.substr(5, 2).c_str());
day = atoi(date.substr(8, 2).c_str());
}
CDateTime tmpDateTime(year, month, day, 0, 0, 0);
if (tmpDateTime.IsValid())
*this = tmpDateTime;
return IsValid();
}
bool CDateTime::SetFromW3CDateTime(const std::string &dateTime, bool ignoreTimezone /* = false */)
{
std::string date, time, zone;
size_t posT = dateTime.find("T");
if(posT != std::string::npos)
{
date = dateTime.substr(0, posT);
std::string::size_type posZ = dateTime.find_first_of("+-Z", posT);
if(posZ == std::string::npos)
time = dateTime.substr(posT + 1);
else
{
time = dateTime.substr(posT + 1, posZ - posT - 1);
zone = dateTime.substr(posZ);
}
}
else
date = dateTime;
int year = 0, month = 1, day = 1, hour = 0, min = 0, sec = 0;
if (date.size() >= 4)
year = atoi(date.substr(0, 4).c_str());
if (date.size() >= 10)
{
month = atoi(date.substr(5, 2).c_str());
day = atoi(date.substr(8, 2).c_str());
}
if (time.length() >= 5)
{
hour = atoi(time.substr(0, 2).c_str());
min = atoi(time.substr(3, 2).c_str());
}
if (time.length() >= 8)
sec = atoi(time.substr(6, 2).c_str());
CDateTime tmpDateTime(year, month, day, hour, min, sec);
if (!tmpDateTime.IsValid())
return false;
if (!ignoreTimezone && !zone.empty())
{
// check if the timezone is UTC
if (StringUtils::StartsWith(zone, "Z"))
return SetFromUTCDateTime(tmpDateTime);
else
{
// retrieve the timezone offset (ignoring the + or -)
CDateTimeSpan zoneSpan; zoneSpan.SetFromTimeString(zone.substr(1));
if (zoneSpan.GetSecondsTotal() != 0)
{
if (StringUtils::StartsWith(zone, "+"))
tmpDateTime += zoneSpan;
else if (StringUtils::StartsWith(zone, "-"))
tmpDateTime -= zoneSpan;
}
}
}
*this = tmpDateTime;
return IsValid();
}
bool CDateTime::SetFromDBDateTime(const std::string &dateTime)
{
// assumes format YYYY-MM-DD HH:MM:SS
if (dateTime.size() == 19)
{
int year = atoi(dateTime.substr(0, 4).c_str());
int month = atoi(dateTime.substr(5, 2).c_str());
int day = atoi(dateTime.substr(8, 2).c_str());
int hour = atoi(dateTime.substr(11, 2).c_str());
int min = atoi(dateTime.substr(14, 2).c_str());
int sec = atoi(dateTime.substr(17, 2).c_str());
return SetDateTime(year, month, day, hour, min, sec);
}
return false;
}
bool CDateTime::SetFromDBDate(const std::string &date)
{
if (date.size() < 10)
return false;
// assumes format:
// YYYY-MM-DD or DD-MM-YYYY
const static std::string sep_chars = "-./";
int year = 0, month = 0, day = 0;
if (sep_chars.find(date[2]) != std::string::npos)
{
day = atoi(date.substr(0, 2).c_str());
month = atoi(date.substr(3, 2).c_str());
year = atoi(date.substr(6, 4).c_str());
}
else if (sep_chars.find(date[4]) != std::string::npos)
{
year = atoi(date.substr(0, 4).c_str());
month = atoi(date.substr(5, 2).c_str());
day = atoi(date.substr(8, 2).c_str());
}
return SetDate(year, month, day);
}
bool CDateTime::SetFromDBTime(const std::string &time)
{
if (time.size() < 8)
return false;
// assumes format:
// HH:MM:SS
int hour, minute, second;
hour = atoi(time.substr(0, 2).c_str());
minute = atoi(time.substr(3, 2).c_str());
second = atoi(time.substr(6, 2).c_str());
return SetTime(hour, minute, second);
}
bool CDateTime::SetFromRFC1123DateTime(const std::string &dateTime)
{
std::string date = dateTime;
StringUtils::Trim(date);
if (date.size() != 29)
return false;
int day = strtol(date.substr(5, 2).c_str(), NULL, 10);
std::string strMonth = date.substr(8, 3);
int month = 0;
for (unsigned int index = 0; index < 12; index++)
{
if (strMonth == MONTH_NAMES[index])
{
month = index + 1;
break;
}
}
if (month < 1)
return false;
int year = strtol(date.substr(12, 4).c_str(), NULL, 10);
int hour = strtol(date.substr(17, 2).c_str(), NULL, 10);
int min = strtol(date.substr(20, 2).c_str(), NULL, 10);
int sec = strtol(date.substr(23, 2).c_str(), NULL, 10);
return SetDateTime(year, month, day, hour, min, sec);
}
std::string CDateTime::GetAsLocalizedTime(const std::string &format, bool withSeconds) const
{
std::string strOut;
const std::string& strFormat = format.empty() ? g_langInfo.GetTimeFormat() : format;
SYSTEMTIME dateTime;
GetAsSystemTime(dateTime);
// Prefetch meridiem symbol
const std::string& strMeridiem = g_langInfo.GetMeridiemSymbol(dateTime.wHour > 11 ? MeridiemSymbolPM : MeridiemSymbolAM);
size_t length = strFormat.size();
for (size_t i=0; i < length; ++i)
{
char c=strFormat[i];
if (c=='\'')
{
// To be able to display a "'" in the string,
// find the last "'" that doesn't follow a "'"
size_t pos=i + 1;
while(((pos = strFormat.find(c, pos + 1)) != std::string::npos &&
pos<strFormat.size()) && strFormat[pos+1]=='\'') {}
std::string strPart;
if (pos != std::string::npos)
{
// Extract string between ' '
strPart=strFormat.substr(i + 1, pos - i - 1);
i=pos;
}
else
{
strPart=strFormat.substr(i + 1, length - i - 1);
i=length;
}
StringUtils::Replace(strPart, "''", "'");
strOut+=strPart;
}
else if (c=='h' || c=='H') // parse hour (H="24 hour clock")
{
int partLength=0;
int pos=strFormat.find_first_not_of(c,i+1);
if (pos>-1)
{
// Get length of the hour mask, eg. HH
partLength=pos-i;
i=pos-1;
}
else
{
// mask ends at the end of the string, extract it
partLength=length-i;
i=length;
}
int hour=dateTime.wHour;
if (c=='h')
{ // recalc to 12 hour clock
if (hour > 11)
hour -= (12 * (hour > 12));
else
hour += (12 * (hour < 1));
}
// Format hour string with the length of the mask
std::string str;
if (partLength==1)
str = StringUtils::Format("%d", hour);
else
str = StringUtils::Format("%02d", hour);
strOut+=str;
}
else if (c=='m') // parse minutes
{
int partLength=0;
int pos=strFormat.find_first_not_of(c,i+1);
if (pos>-1)
{
// Get length of the minute mask, eg. mm
partLength=pos-i;
i=pos-1;
}
else
{
// mask ends at the end of the string, extract it
partLength=length-i;
i=length;
}
// Format minute string with the length of the mask
std::string str;
if (partLength==1)
str = StringUtils::Format("%d", dateTime.wMinute);
else
str = StringUtils::Format("%02d", dateTime.wMinute);
strOut+=str;
}
else if (c=='s') // parse seconds
{
int partLength=0;
int pos=strFormat.find_first_not_of(c,i+1);
if (pos>-1)
{
// Get length of the seconds mask, eg. ss
partLength=pos-i;
i=pos-1;
}
else
{
// mask ends at the end of the string, extract it
partLength=length-i;
i=length;
}
if (withSeconds)
{
// Format seconds string with the length of the mask
std::string str;
if (partLength==1)
str = StringUtils::Format("%d", dateTime.wSecond);
else
str = StringUtils::Format("%02d", dateTime.wSecond);
strOut+=str;
}
else
strOut.erase(strOut.size()-1,1);
}
else if (c=='x') // add meridiem symbol
{
int pos=strFormat.find_first_not_of(c,i+1);
if (pos>-1)
{
// Get length of the meridiem mask
i=pos-1;
}
else
{
// mask ends at the end of the string, extract it
i=length;
}
strOut+=strMeridiem;
}
else // everything else pass to output
strOut+=c;
}
return strOut;
}
std::string CDateTime::GetAsLocalizedDate(bool longDate/*=false*/, bool withShortNames/*=true*/) const
{
return GetAsLocalizedDate(g_langInfo.GetDateFormat(longDate), withShortNames);
}
std::string CDateTime::GetAsLocalizedDate(const std::string &strFormat, bool withShortNames/*=true*/) const
{
std::string strOut;
SYSTEMTIME dateTime;
GetAsSystemTime(dateTime);
size_t length = strFormat.size();
for (size_t i = 0; i < length; ++i)
{
char c=strFormat[i];
if (c=='\'')
{
// To be able to display a "'" in the string,
// find the last "'" that doesn't follow a "'"
size_t pos = i + 1;
while(((pos = strFormat.find(c, pos + 1)) != std::string::npos &&
pos < strFormat.size()) &&
strFormat[pos + 1] == '\'') {}
std::string strPart;
if (pos != std::string::npos)
{
// Extract string between ' '
strPart = strFormat.substr(i + 1, pos - i - 1);
i = pos;
}
else
{
strPart = strFormat.substr(i + 1, length - i - 1);
i = length;
}
StringUtils::Replace(strPart, "''", "'");
strOut+=strPart;
}
else if (c=='D' || c=='d') // parse days
{
size_t partLength=0;
size_t pos = strFormat.find_first_not_of(c, i+1);
if (pos != std::string::npos)
{
// Get length of the day mask, eg. DDDD
partLength=pos-i;
i=pos-1;
}
else
{
// mask ends at the end of the string, extract it
partLength=length-i;
i=length;
}
// Format string with the length of the mask
std::string str;
if (partLength==1) // single-digit number
str = StringUtils::Format("%d", dateTime.wDay);
else if (partLength==2) // two-digit number
str = StringUtils::Format("%02d", dateTime.wDay);
else // Day of week string
{
int wday = dateTime.wDayOfWeek;
if (wday < 1 || wday > 7) wday = 7;
str = g_localizeStrings.Get(((withShortNames || c =='d') ? 40 : 10) + wday);
}
strOut+=str;
}
else if (c=='M' || c=='m') // parse month
{
size_t partLength=0;
size_t pos=strFormat.find_first_not_of(c,i+1);
if (pos != std::string::npos)
{
// Get length of the month mask, eg. MMMM
partLength=pos-i;
i=pos-1;
}
else
{
// mask ends at the end of the string, extract it
partLength=length-i;
i=length;
}
// Format string with the length of the mask
std::string str;
if (partLength==1) // single-digit number
str = StringUtils::Format("%d", dateTime.wMonth);
else if (partLength==2) // two-digit number
str = StringUtils::Format("%02d", dateTime.wMonth);
else // Month string
{
int wmonth = dateTime.wMonth;
if (wmonth < 1 || wmonth > 12) wmonth = 12;
str = g_localizeStrings.Get(((withShortNames || c =='m') ? 50 : 20) + wmonth);
}
strOut+=str;
}
else if (c=='Y' || c =='y') // parse year
{
size_t partLength = 0;
size_t pos = strFormat.find_first_not_of(c,i+1);
if (pos != std::string::npos)
{
// Get length of the year mask, eg. YYYY
partLength=pos-i;
i=pos-1;
}
else
{
// mask ends at the end of the string, extract it
partLength=length-i;
i=length;
}
// Format string with the length of the mask
std::string str = StringUtils::Format("%d", dateTime.wYear); // four-digit number
if (partLength <= 2)
str.erase(0, 2); // two-digit number
strOut+=str;
}
else // everything else pass to output
strOut+=c;
}
return strOut;
}
std::string CDateTime::GetAsLocalizedDateTime(bool longDate/*=false*/, bool withSeconds/*=true*/) const
{
return GetAsLocalizedDate(longDate) + ' ' + GetAsLocalizedTime("", withSeconds);
}
CDateTime CDateTime::GetAsUTCDateTime() const
{
CDateTime time(m_time);
time += GetTimezoneBias();
return time;
}
std::string CDateTime::GetAsRFC1123DateTime() const
{
CDateTime time(GetAsUTCDateTime());
int weekDay = time.GetDayOfWeek();
if (weekDay < 0)
weekDay = 0;
else if (weekDay > 6)
weekDay = 6;
if (weekDay != time.GetDayOfWeek())
CLog::Log(LOGWARNING, "Invalid day of week %d in %s", time.GetDayOfWeek(), time.GetAsDBDateTime().c_str());
int month = time.GetMonth();
if (month < 1)
month = 1;
else if (month > 12)
month = 12;
if (month != time.GetMonth())
CLog::Log(LOGWARNING, "Invalid month %d in %s", time.GetMonth(), time.GetAsDBDateTime().c_str());
return StringUtils::Format("%s, %02i %s %04i %02i:%02i:%02i GMT", DAY_NAMES[weekDay], time.GetDay(), MONTH_NAMES[month - 1], time.GetYear(), time.GetHour(), time.GetMinute(), time.GetSecond());
}
std::string CDateTime::GetAsW3CDate() const
{
SYSTEMTIME st;
GetAsSystemTime(st);
return StringUtils::Format("%04i-%02i-%02i", st.wYear, st.wMonth, st.wDay);
}
std::string CDateTime::GetAsW3CDateTime(bool asUtc /* = false */) const
{
CDateTime w3cDate = *this;
if (asUtc)
w3cDate = GetAsUTCDateTime();
SYSTEMTIME st;
w3cDate.GetAsSystemTime(st);
std::string result = StringUtils::Format("%04i-%02i-%02iT%02i:%02i:%02i", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
if (asUtc)
return result + "Z";
CDateTimeSpan bias = GetTimezoneBias();
return result + StringUtils::Format("%c%02i:%02i", (bias.GetSecondsTotal() >= 0 ? '+' : '-'), abs(bias.GetHours()), abs(bias.GetMinutes())).c_str();
}
int CDateTime::MonthStringToMonthNum(const std::string& month)
{
const char* months[] = {"january","february","march","april","may","june","july","august","september","october","november","december"};
const char* abr_months[] = {"jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"};
int i = 0;
for (; i < 12 && !StringUtils::EqualsNoCase(month, months[i]) && !StringUtils::EqualsNoCase(month, abr_months[i]); i++);
i++;
return i;
}
| gpl-2.0 |
thundernet8/WRGameVideos-API | app/open_1_0/errors.py | 1298 | from flask import jsonify
def incorrect_grant_type(message):
response = jsonify({'error': 'grant_type_error', 'message': message})
response.status_code = 200
return response
def incorrect_response_type(message):
response = jsonify({'error': 'response_type_error', 'message': message})
response.status_code = 200
return response
def unknown_app(message):
response = jsonify({'error': 'unknown_app_error', 'message': message})
response.status_code = 200
return response
def unapproved_app(message):
response = jsonify({'error': 'unapproved_app_error', 'message': message})
response.status_code = 200
return response
def unmatched_redirect(message):
response = jsonify({'error': 'unmatched_redirect', 'message': message})
response.status_code = 200
return response
def incorrect_sign(message):
response = jsonify({'error': 'incorrect_sign', 'message': message})
response.status_code = 200
return response
def incorrect_code(message):
response = jsonify({'error': 'incorrect_code', 'message': message})
response.status_code = 200
return response
def incorrect_openid(message):
response = jsonify({'error': 'incorrect_openid', 'message': message})
response.status_code = 200
return response
| gpl-2.0 |
srisatish/openjdk | hotspot/src/share/vm/shark/sharkInliner.cpp | 16766 | /*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
* Copyright 2009 Red Hat, Inc.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "incls/_precompiled.incl"
#include "incls/_sharkInliner.cpp.incl"
using namespace llvm;
class SharkInlineBlock : public SharkBlock {
public:
SharkInlineBlock(ciMethod* target, SharkState* state)
: SharkBlock(state, target),
_outer_state(state),
_entry_state(new SharkState(this)) {
for (int i = target->max_locals() - 1; i >= 0; i--) {
SharkValue *value = NULL;
if (i < target->arg_size())
value = outer_state()->pop();
entry_state()->set_local(i, value);
}
}
private:
SharkState* _outer_state;
SharkState* _entry_state;
private:
SharkState* outer_state() {
return _outer_state;
}
SharkState* entry_state() {
return _entry_state;
}
public:
void emit_IR() {
parse_bytecode(0, target()->code_size());
}
private:
void do_return(BasicType type) {
if (type != T_VOID) {
SharkValue *result = pop_result(type);
outer_state()->push(result);
if (result->is_two_word())
outer_state()->push(NULL);
}
}
};
class SharkInlinerHelper : public StackObj {
public:
SharkInlinerHelper(ciMethod* target, SharkState* entry_state)
: _target(target),
_entry_state(entry_state),
_iter(target) {}
private:
ciBytecodeStream _iter;
SharkState* _entry_state;
ciMethod* _target;
public:
ciBytecodeStream* iter() {
return &_iter;
}
SharkState* entry_state() const {
return _entry_state;
}
ciMethod* target() const {
return _target;
}
public:
Bytecodes::Code bc() {
return iter()->cur_bc();
}
int max_locals() const {
return target()->max_locals();
}
int max_stack() const {
return target()->max_stack();
}
// Inlinability check
public:
bool is_inlinable();
private:
void initialize_for_check();
bool do_getstatic() {
return do_field_access(true, false);
}
bool do_getfield() {
return do_field_access(true, true);
}
bool do_putfield() {
return do_field_access(false, true);
}
bool do_field_access(bool is_get, bool is_field);
// Local variables for inlinability check
private:
bool* _locals;
public:
bool* local_addr(int index) const {
assert(index >= 0 && index < max_locals(), "bad local variable index");
return &_locals[index];
}
bool local(int index) const {
return *local_addr(index);
}
void set_local(int index, bool value) {
*local_addr(index) = value;
}
// Expression stack for inlinability check
private:
bool* _stack;
bool* _sp;
public:
int stack_depth() const {
return _sp - _stack;
}
bool* stack_addr(int slot) const {
assert(slot >= 0 && slot < stack_depth(), "bad stack slot");
return &_sp[-(slot + 1)];
}
void push(bool value) {
assert(stack_depth() < max_stack(), "stack overrun");
*(_sp++) = value;
}
bool pop() {
assert(stack_depth() > 0, "stack underrun");
return *(--_sp);
}
// Methods for two-word locals
public:
void push_pair_local(int index) {
push(local(index));
push(local(index + 1));
}
void pop_pair_local(int index) {
set_local(index + 1, pop());
set_local(index, pop());
}
// Code generation
public:
void do_inline() {
(new SharkInlineBlock(target(), entry_state()))->emit_IR();
}
};
// Quick checks so we can bail out before doing too much
bool SharkInliner::may_be_inlinable(ciMethod *target) {
// We can't inline native methods
if (target->is_native())
return false;
// Not much point inlining abstract ones, and in any
// case we'd need a stack frame to throw the exception
if (target->is_abstract())
return false;
// Don't inline anything huge
if (target->code_size() > SharkMaxInlineSize)
return false;
// Monitors aren't allowed without a frame to put them in
if (target->is_synchronized() || target->has_monitor_bytecodes())
return false;
// We don't do control flow
if (target->has_exception_handlers() || target->has_jsrs())
return false;
// Don't try to inline constructors, as they must
// eventually call Object.<init> which we can't inline.
// Note that this catches <clinit> too, but why would
// we be compiling that?
if (target->is_initializer())
return false;
// Mustn't inline Object.<init>
// Should be caught by the above, but just in case...
if (target->intrinsic_id() == vmIntrinsics::_Object_init)
return false;
return true;
}
// Full-on detailed check, for methods that pass the quick checks
// Inlined methods have no stack frame, so we can't do anything
// that would require one. This means no safepoints (and hence
// no loops) and no VM calls. No VM calls means, amongst other
// things, that no exceptions can be created, which means no null
// checks or divide-by-zero checks are allowed. The lack of null
// checks in particular would eliminate practically everything,
// but we can get around that restriction by relying on the zero-
// check eliminator to strip the checks. To do that, we need to
// walk through the method, tracking which values are and are not
// zero-checked.
bool SharkInlinerHelper::is_inlinable() {
ResourceMark rm;
initialize_for_check();
SharkConstant *sc;
bool a, b, c, d;
iter()->reset_to_bci(0);
while (iter()->next() != ciBytecodeStream::EOBC()) {
switch (bc()) {
case Bytecodes::_nop:
break;
case Bytecodes::_aconst_null:
push(false);
break;
case Bytecodes::_iconst_0:
push(false);
break;
case Bytecodes::_iconst_m1:
case Bytecodes::_iconst_1:
case Bytecodes::_iconst_2:
case Bytecodes::_iconst_3:
case Bytecodes::_iconst_4:
case Bytecodes::_iconst_5:
push(true);
break;
case Bytecodes::_lconst_0:
push(false);
push(false);
break;
case Bytecodes::_lconst_1:
push(true);
push(false);
break;
case Bytecodes::_fconst_0:
case Bytecodes::_fconst_1:
case Bytecodes::_fconst_2:
push(false);
break;
case Bytecodes::_dconst_0:
case Bytecodes::_dconst_1:
push(false);
push(false);
break;
case Bytecodes::_bipush:
push(iter()->get_constant_u1() != 0);
break;
case Bytecodes::_sipush:
push(iter()->get_constant_u2() != 0);
break;
case Bytecodes::_ldc:
case Bytecodes::_ldc_w:
case Bytecodes::_ldc2_w:
sc = SharkConstant::for_ldc(iter());
if (!sc->is_loaded())
return false;
push(sc->is_nonzero());
if (sc->is_two_word())
push(false);
break;
case Bytecodes::_iload_0:
case Bytecodes::_fload_0:
case Bytecodes::_aload_0:
push(local(0));
break;
case Bytecodes::_lload_0:
case Bytecodes::_dload_0:
push_pair_local(0);
break;
case Bytecodes::_iload_1:
case Bytecodes::_fload_1:
case Bytecodes::_aload_1:
push(local(1));
break;
case Bytecodes::_lload_1:
case Bytecodes::_dload_1:
push_pair_local(1);
break;
case Bytecodes::_iload_2:
case Bytecodes::_fload_2:
case Bytecodes::_aload_2:
push(local(2));
break;
case Bytecodes::_lload_2:
case Bytecodes::_dload_2:
push_pair_local(2);
break;
case Bytecodes::_iload_3:
case Bytecodes::_fload_3:
case Bytecodes::_aload_3:
push(local(3));
break;
case Bytecodes::_lload_3:
case Bytecodes::_dload_3:
push_pair_local(3);
break;
case Bytecodes::_iload:
case Bytecodes::_fload:
case Bytecodes::_aload:
push(local(iter()->get_index()));
break;
case Bytecodes::_lload:
case Bytecodes::_dload:
push_pair_local(iter()->get_index());
break;
case Bytecodes::_istore_0:
case Bytecodes::_fstore_0:
case Bytecodes::_astore_0:
set_local(0, pop());
break;
case Bytecodes::_lstore_0:
case Bytecodes::_dstore_0:
pop_pair_local(0);
break;
case Bytecodes::_istore_1:
case Bytecodes::_fstore_1:
case Bytecodes::_astore_1:
set_local(1, pop());
break;
case Bytecodes::_lstore_1:
case Bytecodes::_dstore_1:
pop_pair_local(1);
break;
case Bytecodes::_istore_2:
case Bytecodes::_fstore_2:
case Bytecodes::_astore_2:
set_local(2, pop());
break;
case Bytecodes::_lstore_2:
case Bytecodes::_dstore_2:
pop_pair_local(2);
break;
case Bytecodes::_istore_3:
case Bytecodes::_fstore_3:
case Bytecodes::_astore_3:
set_local(3, pop());
break;
case Bytecodes::_lstore_3:
case Bytecodes::_dstore_3:
pop_pair_local(3);
break;
case Bytecodes::_istore:
case Bytecodes::_fstore:
case Bytecodes::_astore:
set_local(iter()->get_index(), pop());
break;
case Bytecodes::_lstore:
case Bytecodes::_dstore:
pop_pair_local(iter()->get_index());
break;
case Bytecodes::_pop:
pop();
break;
case Bytecodes::_pop2:
pop();
pop();
break;
case Bytecodes::_swap:
a = pop();
b = pop();
push(a);
push(b);
break;
case Bytecodes::_dup:
a = pop();
push(a);
push(a);
break;
case Bytecodes::_dup_x1:
a = pop();
b = pop();
push(a);
push(b);
push(a);
break;
case Bytecodes::_dup_x2:
a = pop();
b = pop();
c = pop();
push(a);
push(c);
push(b);
push(a);
break;
case Bytecodes::_dup2:
a = pop();
b = pop();
push(b);
push(a);
push(b);
push(a);
break;
case Bytecodes::_dup2_x1:
a = pop();
b = pop();
c = pop();
push(b);
push(a);
push(c);
push(b);
push(a);
break;
case Bytecodes::_dup2_x2:
a = pop();
b = pop();
c = pop();
d = pop();
push(b);
push(a);
push(d);
push(c);
push(b);
push(a);
break;
case Bytecodes::_getfield:
if (!do_getfield())
return false;
break;
case Bytecodes::_getstatic:
if (!do_getstatic())
return false;
break;
case Bytecodes::_putfield:
if (!do_putfield())
return false;
break;
case Bytecodes::_iadd:
case Bytecodes::_isub:
case Bytecodes::_imul:
case Bytecodes::_iand:
case Bytecodes::_ixor:
case Bytecodes::_ishl:
case Bytecodes::_ishr:
case Bytecodes::_iushr:
pop();
pop();
push(false);
break;
case Bytecodes::_ior:
a = pop();
b = pop();
push(a && b);
break;
case Bytecodes::_idiv:
case Bytecodes::_irem:
if (!pop())
return false;
pop();
push(false);
break;
case Bytecodes::_ineg:
break;
case Bytecodes::_ladd:
case Bytecodes::_lsub:
case Bytecodes::_lmul:
case Bytecodes::_land:
case Bytecodes::_lxor:
pop();
pop();
pop();
pop();
push(false);
push(false);
break;
case Bytecodes::_lor:
a = pop();
b = pop();
push(a && b);
break;
case Bytecodes::_ldiv:
case Bytecodes::_lrem:
pop();
if (!pop())
return false;
pop();
pop();
push(false);
push(false);
break;
case Bytecodes::_lneg:
break;
case Bytecodes::_lshl:
case Bytecodes::_lshr:
case Bytecodes::_lushr:
pop();
pop();
pop();
push(false);
push(false);
break;
case Bytecodes::_fadd:
case Bytecodes::_fsub:
case Bytecodes::_fmul:
case Bytecodes::_fdiv:
case Bytecodes::_frem:
pop();
pop();
push(false);
break;
case Bytecodes::_fneg:
break;
case Bytecodes::_dadd:
case Bytecodes::_dsub:
case Bytecodes::_dmul:
case Bytecodes::_ddiv:
case Bytecodes::_drem:
pop();
pop();
pop();
pop();
push(false);
push(false);
break;
case Bytecodes::_dneg:
break;
case Bytecodes::_iinc:
set_local(iter()->get_index(), false);
break;
case Bytecodes::_lcmp:
pop();
pop();
pop();
pop();
push(false);
break;
case Bytecodes::_fcmpl:
case Bytecodes::_fcmpg:
pop();
pop();
push(false);
break;
case Bytecodes::_dcmpl:
case Bytecodes::_dcmpg:
pop();
pop();
pop();
pop();
push(false);
break;
case Bytecodes::_i2l:
push(false);
break;
case Bytecodes::_i2f:
pop();
push(false);
break;
case Bytecodes::_i2d:
pop();
push(false);
push(false);
break;
case Bytecodes::_l2i:
case Bytecodes::_l2f:
pop();
pop();
push(false);
break;
case Bytecodes::_l2d:
pop();
pop();
push(false);
push(false);
break;
case Bytecodes::_f2i:
pop();
push(false);
break;
case Bytecodes::_f2l:
case Bytecodes::_f2d:
pop();
push(false);
push(false);
break;
case Bytecodes::_d2i:
case Bytecodes::_d2f:
pop();
pop();
push(false);
break;
case Bytecodes::_d2l:
pop();
pop();
push(false);
push(false);
break;
case Bytecodes::_i2b:
case Bytecodes::_i2c:
case Bytecodes::_i2s:
pop();
push(false);
break;
case Bytecodes::_return:
case Bytecodes::_ireturn:
case Bytecodes::_lreturn:
case Bytecodes::_freturn:
case Bytecodes::_dreturn:
case Bytecodes::_areturn:
break;
default:
return false;
}
}
return true;
}
void SharkInlinerHelper::initialize_for_check() {
_locals = NEW_RESOURCE_ARRAY(bool, max_locals());
_stack = NEW_RESOURCE_ARRAY(bool, max_stack());
memset(_locals, 0, max_locals() * sizeof(bool));
for (int i = 0; i < target()->arg_size(); i++) {
SharkValue *arg = entry_state()->stack(target()->arg_size() - 1 - i);
if (arg && arg->zero_checked())
set_local(i, true);
}
_sp = _stack;
}
bool SharkInlinerHelper::do_field_access(bool is_get, bool is_field) {
assert(is_get || is_field, "can't inline putstatic");
// If the holder isn't linked then there isn't a lot we can do
if (!target()->holder()->is_linked())
return false;
// Get the field
bool will_link;
ciField *field = iter()->get_field(will_link);
if (!will_link)
return false;
// If the field is mismatched then an exception needs throwing
if (is_field == field->is_static())
return false;
// Pop the value off the stack if necessary
if (!is_get) {
pop();
if (field->type()->is_two_word())
pop();
}
// Pop and null-check the receiver if necessary
if (is_field) {
if (!pop())
return false;
}
// Push the result if necessary
if (is_get) {
bool result_pushed = false;
if (field->is_constant()) {
SharkConstant *sc = SharkConstant::for_field(iter());
if (sc->is_loaded()) {
push(sc->is_nonzero());
result_pushed = true;
}
}
if (!result_pushed)
push(false);
if (field->type()->is_two_word())
push(false);
}
return true;
}
bool SharkInliner::attempt_inline(ciMethod *target, SharkState *state) {
if (SharkIntrinsics::is_intrinsic(target)) {
SharkIntrinsics::inline_intrinsic(target, state);
return true;
}
if (may_be_inlinable(target)) {
SharkInlinerHelper inliner(target, state);
if (inliner.is_inlinable()) {
inliner.do_inline();
return true;
}
}
return false;
}
| gpl-2.0 |
znyang/eroid | library/src/main/java/com/zen/android/eroid/injection/DroidComponentManager.java | 598 | package com.zen.android.eroid.injection;
import com.zen.android.eroid.injection.component.DaggerIProDroidComponent;
import com.zen.android.eroid.injection.component.IDroidComponent;
/**
* DroidComponentManager
*
* @author zeny
* @version 2015.10.25
*/
public final class DroidComponentManager {
private static IDroidComponent sAppComponent;
private DroidComponentManager() {
}
public static IDroidComponent get() {
if (sAppComponent == null) {
sAppComponent = DaggerIProDroidComponent.builder().build();
}
return sAppComponent;
}
}
| gpl-2.0 |
vogel/kadu | plugins/single_window/translations/single_window_fr.ts | 1779 | <?xml version="1.0" ?><!DOCTYPE TS><TS language="fr" version="2.1">
<context>
<name>@default</name>
<message>
<source>Look</source>
<translation>Apparence</translation>
</message>
<message>
<source>SingleWindow</source>
<translation> Fenêtre unique</translation>
</message>
<message>
<source>General</source>
<translation>Général</translation>
</message>
<message>
<source>Roster position</source>
<translation>Position de Roster</translation>
</message>
<message>
<source>Choose position of roster in Single Window mode</source>
<translation>Choisir la position de roster en mode Fenêtre unique</translation>
</message>
<message>
<source>Left</source>
<translation>Gauche</translation>
</message>
<message>
<source>Right</source>
<translation>Droite</translation>
</message>
<message>
<source>Shortcuts</source>
<translation>Raccourcis</translation>
</message>
<message>
<source>Switch to previous tab</source>
<translation>Aller à l'onglet précédent</translation>
</message>
<message>
<source>Switch to next tab</source>
<translation>Aller à l'onglet suivant</translation>
</message>
<message>
<source>Show/hide roster</source>
<translation>Afficher / masquer roster</translation>
</message>
<message>
<source>Switch focus between roster and tabs</source>
<translation>Basculer le focus entre roster et les onglets</translation>
</message>
<message>
<source>Behavior</source>
<translation>Comportement</translation>
</message>
</context>
</TS> | gpl-2.0 |
Jane-Wu/zs | themes/capital/js/footer.js | 358 | /**
* @file
* Bootstrap Tooltips.
*/
var Drupal = Drupal || {};
(function ($, Drupal) {
"use strict";
/**
*/
Drupal.behaviors.autoFooter = {
attach: function (context) {
var bodyMinHeight = $(window).height() - 160;
$("div.main-container").css({"min-height": bodyMinHeight + "px"});
},
};
})(window.jQuery, window.Drupal);
| gpl-2.0 |
dipacs/Viwib | trunk/src/Viwib/src/com/eagerlogic/viwib/ui/welcome/WelcomeScreen.java | 7828 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.eagerlogic.viwib.ui.welcome;
import com.eagerlogic.viwib.Viwib;
import com.eagerlogic.viwib.config.Config;
import com.eagerlogic.viwib.ui.addtracker.AddTrackerScreen;
import com.eagerlogic.viwib.ui.login.LoginScreen;
import java.awt.EventQueue;
import java.awt.Panel;
import java.io.File;
import javafx.application.Platform;
import javafx.beans.binding.DoubleBinding;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.Group;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.effect.DropShadow;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.StrokeType;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
/**
*
* @author dipacs
*/
public class WelcomeScreen extends Parent {
public final SimpleDoubleProperty width = new SimpleDoubleProperty();
public final SimpleDoubleProperty height = new SimpleDoubleProperty();
public WelcomeScreen() {
final Group root = new Group();
root.translateXProperty().bind(new DoubleBinding() {
{
super.bind(root.boundsInLocalProperty(), width);
}
@Override
protected double computeValue() {
return (width.get() - root.getBoundsInLocal().getWidth()) / 2;
}
});
root.translateYProperty().bind(new DoubleBinding() {
{
super.bind(root.boundsInLocalProperty(), width);
}
@Override
protected double computeValue() {
return (height.get() - root.getBoundsInLocal().getHeight()) / 2;
}
});
this.getChildren().add(root);
Rectangle rect = new Rectangle();
rect.setArcWidth(10);
rect.setArcHeight(10);
rect.setFill(Color.WHITE);
rect.setStroke(Color.rgb(192, 192, 192));
rect.setStrokeWidth(1.0);
rect.setStrokeType(StrokeType.INSIDE);
DropShadow ds = new DropShadow();
ds.setRadius(20);
ds.setOffsetX(1);
ds.setOffsetY(1);
rect.setEffect(ds);
root.getChildren().add(rect);
final VBox vbox = new VBox(40);
vbox.translateXProperty().set(20);
vbox.translateYProperty().set(20);
root.getChildren().add(vbox);
Label lblTitle = new Label("Welcome");
lblTitle.getStyleClass().add("lblScreenTitle");
vbox.getChildren().add(lblTitle);
Label lblInfo = new Label("It seems that this is the first time when you start Viwib. Please choose a folder "
+ "where Viwib will store your downloaded files. If you dont know what does this mean, just "
+ "leave this on the default value.");
lblInfo.getStyleClass().add("lblScreenInfo");
lblInfo.setWrapText(true);
lblInfo.setTextAlignment(TextAlignment.CENTER);
lblInfo.setPrefWidth(500);
vbox.getChildren().add(lblInfo);
VBox vbox2 = new VBox(5);
vbox.getChildren().add(vbox2);
Label lblSaveFolder = new Label("Select Save Location:");
lblSaveFolder.getStyleClass().add("lblFieldTitle");
vbox2.getChildren().add(lblSaveFolder);
String defSaveUrl = Config.VIWIB_URL;
if (!defSaveUrl.endsWith(File.separator)) {
defSaveUrl += File.separator;
}
defSaveUrl += "Downloads" + File.separator;
final Button btnSaveLocation = new Button(defSaveUrl);
btnSaveLocation.setPrefWidth(500);
btnSaveLocation.setCursor(Cursor.HAND);
btnSaveLocation.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFileChooser jfc = new JFileChooser();
jfc.setMultiSelectionEnabled(false);
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
final String newUrl = jfc.getSelectedFile().getAbsolutePath();
Platform.runLater(new Runnable() {
@Override
public void run() {
btnSaveLocation.setText(newUrl);
}
});
}
}
});
}
});
vbox2.getChildren().add(btnSaveLocation);
Button btnSave = new Button("Save");
btnSave.getStyleClass().add("btnApprove");
btnSave.setTranslateX(400);
btnSave.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent evt) {
String saveLocation = btnSaveLocation.getText();
if (saveLocation == null) {
showErrorMessage("Invalid Save Location", "The selected save location is invalid. Please check if the selected folder is accessible and writeable.");
return;
}
File f = null;
try {
f = new File(saveLocation);
if (!f.exists()) {
if (!f.mkdirs()) {
showErrorMessage("Invalid Save Location", "The selected save location is invalid. Please check if the selected folder is accessible and writeable.");
return;
}
}
} catch (Throwable t) {
showErrorMessage("Invalid Save Location", "The selected save location is invalid. Please check if the selected folder is accessible and writeable.");
return;
}
Config.setSaveLocation(saveLocation);
Config.save();
LoginScreen loginScren = new LoginScreen();
loginScren.width.bind(Viwib.getInstance().getSlidePanel().widthProperty);
loginScren.height.bind(Viwib.getInstance().getSlidePanel().heightProperty);
Viwib.getInstance().slideLeft(loginScren);
}
});
vbox.getChildren().add(btnSave);
btnSave.setAlignment(Pos.TOP_RIGHT);
btnSave.setManaged(true);
rect.widthProperty().bind(new DoubleBinding() {
{
super.bind(vbox.boundsInLocalProperty());
}
@Override
protected double computeValue() {
return vbox.boundsInLocalProperty().get().getWidth() + 40;
}
});
rect.heightProperty().bind(new DoubleBinding() {
{
super.bind(vbox.boundsInLocalProperty());
}
@Override
protected double computeValue() {
return vbox.boundsInLocalProperty().get().getHeight() + 40;
}
});
}
private void showErrorMessage(final String title, final String message) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(null, message, title, JOptionPane.ERROR_MESSAGE);
}
});
}
}
| gpl-2.0 |
OSM-Forum/openstreetmap-forum | lang/Brazilian_Portuguese/misc.php | 4961 | <?php
// Language definitions used in various scripts
$lang_misc = array(
'Mark read redirect' => 'Todos os tópicos deste fórum foram marcados como lidos. Redirecionando …',
'Mark forum read redirect' => 'Todos os tópicos no fórum especificado foram marcados como lidos. Redirecionando …',
// Send email
'Form email disabled' => 'O usuário para o qual você deseja enviar um email desativou o formulário de email.',
'No email subject' => 'Você deve digitar um assunto.',
'No email message' => 'Você deve digitar uma mensagem.',
'Too long email message' => 'As mensagens não podem ter mais de 65535 caracteres (64 KB).',
'Email flood' => 'Ao menos %s segundos devem passar entre cada email enviado. Por favor, aguarde %s segundos e tente enviar novamente.',
'Email sent redirect' => 'Email enviado. Redirecionando …',
'Send email to' => 'Enviar email para',
'Email subject' => 'Assunto',
'Email message' => 'Mensagem',
'Email disclosure note' => 'Por favor, note que ao usar este formulário, seu endereço de email será exibido ao destinatário.',
'Write email' => 'Escreva e envie sua mensagem de email',
// Report
'No reason' => 'Você deve digitar uma razão.',
'Reason too long' => 'Sua mensagem deve ter menos de 65535 caracteres (~64kb).',
'Report flood' => 'Ao menos %s segundos devem passar entre denúncias. Por favor, aguarde %s segundos e tente novamente.',
'Report redirect' => 'Mensagem denunciada. Redirecionando …',
'Report post' => 'Denunciar mensagem',
'Reason' => 'Razão',
'Reason desc' => 'Por favor, digite brevemente a razão pela qual está denunciando esta mensagem',
// Subscriptions
'Already subscribed topic' => 'Você já inscrito neste tópico.',
'Already subscribed forum' => 'Você já está inscrito neste fórum.',
'Subscribe redirect' => 'Sua inscrição foi adicionada. Redirecionando …',
'Not subscribed topic' => 'Você não está inscrito neste tópico.',
'Not subscribed forum' => 'Você não está inscrito neste fórum.',
'Unsubscribe redirect' => 'Sua inscrição foi cancelada. Redirecionando …',
// General forum and topic moderation
'Moderate' => 'Moderar',
'Select' => 'Selecionar', // the header of a column of checkboxes
'Move' => 'Mover',
'Split' => 'Dividir',
'Delete' => 'Excluir',
'Merge' => 'Mesclar',
// Moderate forum
'Open' => 'Abrir',
'Close' => 'Fechar',
'Move topic' => 'Mover tópico',
'Move topics' => 'Mover tópicos',
'Move legend' => 'Selecione o destino',
'Move to' => 'Mover para',
'Nowhere to move' => 'Não há fóruns para onde você possa mover tópicos.',
'Leave redirect' => 'Manter tópico(s) de redirecionamento',
'Move topic redirect' => 'Tópico movido. Redirecionando …',
'Move topics redirect' => 'Tópicos movidos. Redirecionando …',
'Confirm delete legend' => 'Por favor confirme a exclusão',
'Delete topics' => 'Excluir tópicos',
'Delete topics comply' => 'Você tem certeza que deseja excluir os tópicos selecionados?',
'Delete topics redirect' => 'Tópicos excluídos. Redirecionando …',
'Open topic redirect' => 'Tópico aberto. Redirecionando …',
'Open topics redirect' => 'Tópicos abertos. Redirecionando …',
'Close topic redirect' => 'Tópico fechado. Redirecionando …',
'Close topics redirect' => 'Tópicos fechados. Redirecionando …',
'No topics selected' => 'Você deve selecionar ao menos um tópico para mover/excluir/abrir/fechar.',
'Not enough topics selected' => 'Você deve selecionar o menos dois tópicos para mesclar.',
'Stick topic redirect' => 'Tópico fixado. Redirecionando …',
'Unstick topic redirect' => 'Tópico desfixado. Redirecionando …',
'Merge topics' => 'Mesclar tópicos',
'Merge topics redirect' => 'Tópicos mesclados. Redirecionando …',
'Confirm merge legend' => 'Por favor confirme a mesclagem',
'New subject' => 'Novo assunto',
// Split multiple posts in topic
'Confirm split legend' => 'Por favor confirme a divisão das mensagens selecionadas e selecione o destino para onde movê-las.',
'Split posts' => 'Dividir mensagens',
'Split posts comply' => 'Você tem certeza que deseja dividir as mensagens selecionadas?',
'Split posts redirect' => 'Mensagens divididas. Redirecionando …',
// Delete multiple posts in topic
'Delete posts' => 'Excluir mensagens',
'Cannot select first' => 'A primeira mensagem não pode ser selecionada para divisão/exclusão.',
'Delete posts comply' => 'Você tem certeza que deseja excluir as mensagens selecionadas?',
'Delete posts redirect' => 'Mensagens excluídas. Redirecionando …',
'No posts selected' => 'Você deve selecionar ao menos uma mensagem para dividir/excluir.',
// Get host
'Host info 1' => 'O endereço IP é: %s',
'Host info 2' => 'O nome de host é: %s',
'Show more users' => 'Exibir mais usuários com este IP',
);
| gpl-2.0 |
nestoronald/sismos | modules/mod_k2_filter/helper.php | 2663 | <?php
/*
// "K2 Tools" Module by JoomlaWorks for Joomla! 1.5.x - Version 2.1
// Copyright (c) 2006 - 2009 JoomlaWorks Ltd. All rights reserved.
// Released under the GNU/GPL license: http://www.gnu.org/copyleft/gpl.html
// More info at http://www.joomlaworks.gr and http://k2.joomlaworks.gr
// Designed and developed by the JoomlaWorks team
// *** Last update: September 9th, 2009 ***
*/
/*
// mod for K2 Extra fields Filter and Search module by Piotr Konieczny
// piotr@smartwebstudio.com
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
require_once (JPATH_SITE.DS.'components'.DS.'com_k2'.DS.'helpers'.DS.'route.php');
require_once (JPATH_SITE.DS.'components'.DS.'com_k2'.DS.'helpers'.DS.'utilities.php');
class modK2FilterHelper {
function getSearchImage($button_text) {
$img = JHTML::_('image.site', 'searchButton.gif', '/images/M_images/', NULL, NULL, $button_text, null, 0);
return $img;
}
// pulls out specified information about extra fields from the database
function pull($field_id,$what) {
$query = 'SELECT t.id, t.name as name, t.value as value, t.type as type FROM #__k2_extra_fields AS t WHERE t.published = 1 AND t.id = "'.$field_id.'"';
$db =& JFactory::getDBO();
$db->setQuery($query);
$extra_fields = get_object_vars($db->loadObject());
switch ($what) {
case 'name' :
$output = $extra_fields['name']; break;
case 'type' :
$output = $extra_fields['type']; break;
case 'value' :
$output = $extra_fields['value']; break;
default:
$output = $extra_fields['value']; break;
}
return $output;
}
// pulls out extra fields of specified item from the database
function pullItem($itemID) {
$query = 'SELECT t.id, t.extra_fields FROM #__k2_items AS t WHERE t.published = 1 AND t.id = "'.$itemID.'"';
$db =& JFactory::getDBO();
$db->setQuery($query);
$extra_fields = get_object_vars($db->loadObject());
$output = $extra_fields['extra_fields'];
return $output;
}
// extracts info from JSON format
function extractExtraFields($extraFields) {
$jsonObjects = json_decode($extraFields);
if (count($jsonObjects) < 1) return NULL;
// convert objects to array
foreach ($jsonObjects as $object){
if (isset($object->name)) $objects[] = $object->name;
else if (isset($object->id)) {
$objects[$object->id] = $object->value;
}
else return;
}
return $objects;
}
// from thaderweb.com
function getExtraField($id){
$db = JFactory::getDBO();
$query = "SELECT id, name, value FROM #__k2_extra_fields WHERE id = ".$db->quote($id); // $id
$db->setQuery($query);
$rows = $db->loadObject();
return $rows;
}
}
| gpl-2.0 |
spiridonov-oa/Oxpaha | administrator/components/com_spidercontacts/toolbar.spidercontacts.html.php | 2126 | <?php
/**
* @package Spider Contacts
* @author Web-Dorado
* @copyright (C) 2012 Web-Dorado. All rights reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
**/
defined('_JEXEC') or die('Restricted access');
class TOOLBAR_spidercontacts
{
function _VIEW($controller)
{ JToolBarHelper::title('Spider Contacts View Message');
JToolBarHelper::cancel();
}
public static function _NEW($controller)
{
JToolBarHelper::title('Spider Contacts Manager');
JToolBarHelper::save();
JToolBarHelper::apply();
JToolBarHelper::cancel();
}
public static function _DEFAULT($controller)
{
JToolBarHelper::title('Spider Contacts Manager');
if ($controller == 'options')
{
JToolBarHelper::title('Spider Contacts Options','generic.png');
if (isset($_GET['op_type']))
{
JToolBarHelper::save();
JToolBarHelper::apply();
JToolBarHelper::cancel();
}
}
if ($controller=='messages')
{
JToolBarHelper::title('Spider Contacts Messages');
JToolBarHelper::deleteList();
JToolBarHelper::custom('markReaden', 'apply.png', 'apply.png', 'Mark as Readen', true, true);
JToolBarHelper::custom('markUnreaden', 'cancel.png', 'cancel.png', 'Mark as Unreaden', true, true);
}
if ($controller=='contacts')
{
JToolBarHelper::title('Spider Contacts Contacts');
JToolBarHelper::publishList();
JToolBarHelper::unpublishList();
JToolBarHelper::editList();
JToolBarHelper::deleteList();
JToolBarHelper::addNew();
}
if ($controller=='category')
{
JToolBarHelper::title('Spider Contacts Categories ');
JToolBarHelper::publishList();
JToolBarHelper::unpublishList();
JToolBarHelper::editList();
JToolBarHelper::deleteList();
JToolBarHelper::addNew();
}
}
}
?> | gpl-2.0 |
Open-Transport/synthese | legacy/server/src/39_map/MapModule.gen.cpp | 33 | synthese::map::moduleRegister();
| gpl-2.0 |
zhangweiheu/exams-system-core | src/main/java/com/online/exams/system/core/service/impl/PaperGenerateServiceImpl.java | 8173 | package com.online.exams.system.core.service.impl;
import com.online.exams.system.core.bean.MongoPaper;
import com.online.exams.system.core.bean.QuestionMap;
import com.online.exams.system.core.dao.MongoPaperDao;
import com.online.exams.system.core.dao.PaperDao;
import com.online.exams.system.core.dao.PaperGenerateDao;
import com.online.exams.system.core.model.Paper;
import com.online.exams.system.core.mybatis.enums.PaperTypeEnum;
import com.online.exams.system.core.mybatis.enums.StatusEnum;
import com.online.exams.system.core.mybatis.enums.TagEnum;
import com.online.exams.system.core.service.PaperGenerateService;
import com.online.exams.system.core.util.PaperUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
* Created by zhang on 2016/3/12.
*/
@Service
public class PaperGenerateServiceImpl implements PaperGenerateService {
private static final Logger LOGGER = LoggerFactory.getLogger(PaperGenerateServiceImpl.class);
@Autowired
private PaperGenerateDao paperGenerateDao;
@Autowired
private PaperDao paperDao;
@Autowired
private MongoPaperDao mongoPaperDao;
@Override
public HashMap<String, Object> generateSingleSelection(List<TagEnum> tagEnumList, int uid) {
List<QuestionMap> resultQuestionMap = new ArrayList<>();
List<Integer> integers = PaperUtil.getRandomNumberByTotalAndCount(20, tagEnumList.size());
for (int i = 0; i < tagEnumList.size(); i++) {
TagEnum tagEnum = tagEnumList.get(i);
List<QuestionMap> questionMapList = paperGenerateDao.generateSingleSelection(tagEnum);
questionMapList = PaperUtil.generateRandomQuestionListByCount(questionMapList, integers.get(i));
resultQuestionMap.addAll(questionMapList);
}
return convertQMap2QAndSavePaper(resultQuestionMap, PaperTypeEnum.SINGLE_SELECTION, uid);
}
@Override
public HashMap<String, Object> generateMultiSelection(List<TagEnum> tagEnumList, int uid) {
List<QuestionMap> resultQuestionMap = new ArrayList<>();
List<Integer> integers = PaperUtil.getRandomNumberByTotalAndCount(10, tagEnumList.size());
for (int i = 0; i < tagEnumList.size(); i++) {
TagEnum tagEnum = tagEnumList.get(i);
List<QuestionMap> questionMapList = paperGenerateDao.generateMultiSelection(tagEnum);
questionMapList = PaperUtil.generateRandomQuestionListByCount(questionMapList, integers.get(i));
resultQuestionMap.addAll(questionMapList);
}
return convertQMap2QAndSavePaper(resultQuestionMap, PaperTypeEnum.MULTI_SELECTION, uid);
}
@Override
public HashMap<String, Object> generateProgrammingQuestion(List<TagEnum> tagEnumList, int uid) {
List<QuestionMap> resultQuestionMap = new ArrayList<>();
for (int i = 0; i < tagEnumList.size(); i++) {
TagEnum tagEnum = tagEnumList.get(i);
List<QuestionMap> questionMapList = paperGenerateDao.generateProgrammingQuestion(tagEnum);
questionMapList = PaperUtil.generateRandomQuestionListByCount(questionMapList, 1);
resultQuestionMap.addAll(questionMapList);
}
return convertQMap2QAndSavePaper(resultQuestionMap, PaperTypeEnum.PROGRAMMING_QUESTION, uid);
}
@Override
public HashMap<String, Object> generateSingleMultiSelection(List<TagEnum> tagEnumList, int uid) {
List<QuestionMap> questionMaps = new ArrayList<>();
for (int i = 0; i < tagEnumList.size(); i++) {
TagEnum tagEnum = tagEnumList.get(i);
List<QuestionMap> questionMapList = paperGenerateDao.generateSingleSelection(tagEnum);
questionMapList = PaperUtil.generateRandomQuestionListByCount(questionMapList, 20);
questionMaps.addAll(questionMapList);
questionMapList = paperGenerateDao.generateMultiSelection(tagEnum);
questionMapList = PaperUtil.generateRandomQuestionListByCount(questionMapList, 10);
questionMaps.addAll(questionMapList);
}
return convertQMap2QAndSavePaper(questionMaps, PaperTypeEnum.SINGLE_AND_MULTI, uid);
}
@Override
public HashMap<String, Object> generateMultiProgrammingSelection(List<TagEnum> tagEnumList, int uid) {
List<QuestionMap> questionMaps = new ArrayList<>();
for (int i = 0; i < tagEnumList.size(); i++) {
TagEnum tagEnum = tagEnumList.get(i);
List<QuestionMap> questionMapList = paperGenerateDao.generateMultiSelection(tagEnum);
questionMapList = PaperUtil.generateRandomQuestionListByCount(questionMapList, 10);
questionMaps.addAll(questionMapList);
}
questionMaps.addAll(paperGenerateDao.generateProgrammingQuestion());
return convertQMap2QAndSavePaper(questionMaps, PaperTypeEnum.MULTI_AND_PROGRAMMING, uid);
}
@Override
public HashMap<String, Object> generateSingleProgrammingQuestion(List<TagEnum> tagEnumList, int uid) {
List<QuestionMap> questionMaps = new ArrayList<>();
for (int i = 0; i < tagEnumList.size(); i++) {
TagEnum tagEnum = tagEnumList.get(i);
List<QuestionMap> questionMapList = paperGenerateDao.generateSingleSelection(tagEnum);
questionMapList = PaperUtil.generateRandomQuestionListByCount(questionMapList, 10);
questionMaps.addAll(questionMapList);
}
questionMaps.addAll(paperGenerateDao.generateProgrammingQuestion());
return convertQMap2QAndSavePaper(questionMaps, PaperTypeEnum.MULTI_AND_PROGRAMMING, uid);
}
@Override
public HashMap<String, Object> generateSingleMultiProgrammingQuestion(List<TagEnum> tagEnumList, int uid) {
List<QuestionMap> questionMaps = new ArrayList<>();
for (int i = 0; i < tagEnumList.size(); i++) {
TagEnum tagEnum = tagEnumList.get(i);
List<QuestionMap> questionMapList = paperGenerateDao.generateSingleSelection(tagEnum);
questionMapList = PaperUtil.generateRandomQuestionListByCount(questionMapList, 20);
questionMaps.addAll(questionMapList);
questionMapList = paperGenerateDao.generateMultiSelection(tagEnum);
questionMapList = PaperUtil.generateRandomQuestionListByCount(questionMapList, 10);
questionMaps.addAll(questionMapList);
}
questionMaps.addAll(paperGenerateDao.generateProgrammingQuestion());
return convertQMap2QAndSavePaper(questionMaps, PaperTypeEnum.SINGLE_AND_MULTI_PROGRAMMING, uid);
}
private HashMap<String, Object> convertQMap2QAndSavePaper(List<QuestionMap> questionMaps, PaperTypeEnum paperTypeEnum, int uid) {
HashMap<String, Object> hashMap = new HashMap<>();
for (QuestionMap questionMap : questionMaps) {
questionMap.setRight(false);
questionMap.setCurrentAnswer("");
}
MongoPaper mongoPaper = new MongoPaper();
mongoPaper.setQuestionMapList(questionMaps);
mongoPaper.setUserId(uid);
mongoPaper.setCreateAt(new Date());
mongoPaper.setUpdateAt(new Date());
int mpid = mongoPaperDao.addPaper(mongoPaper).intValue();
Paper paper = new Paper();
paper.setMongoPaperId(mpid);
paper.setCreateAt(mongoPaper.getCreateAt());
paper.setUpdateAt(mongoPaper.getUpdateAt());
paper.setUserId(uid);
paper.setPaperType(paperTypeEnum);
paper.setScore(0.0);
paper.setTotalRight(0);
paper.setDifficulty(new BigDecimal(PaperUtil.calculateAverageDifficultyOfQuestionMap(questionMaps)).setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue());
paper.setStatus(StatusEnum.NORMAL);
paperDao.savePaper(paper);
hashMap.put("questions", questionMaps);
hashMap.put("pid", paper.getId());
hashMap.put("time", paper.getCreateAt());
return hashMap;
}
}
| gpl-2.0 |
andrewroldugin/art | third_party/boost/boost/mpl/aux_/begin_end_impl.hpp | 2816 |
#ifndef BOOST_MPL_AUX_BEGIN_END_IMPL_HPP_INCLUDED
#define BOOST_MPL_AUX_BEGIN_END_IMPL_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id: begin_end_impl.hpp 85945 2013-09-26 09:46:46Z skelly $
// $Date: 2013-09-26 12:46:46 +0300 (Чт, 26 сен 2013) $
// $Revision: 85945 $
#include <boost/mpl/begin_end_fwd.hpp>
#include <boost/mpl/sequence_tag_fwd.hpp>
#include <boost/mpl/void.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/aux_/has_begin.hpp>
#include <boost/mpl/aux_/na.hpp>
#include <boost/mpl/aux_/traits_lambda_spec.hpp>
namespace boost { namespace mpl {
namespace aux {
template< typename Sequence >
struct begin_type
{
typedef typename Sequence::begin type;
};
template< typename Sequence >
struct end_type
{
typedef typename Sequence::end type;
};
}
// default implementation; conrete sequences might override it by
// specializing either the 'begin_impl/end_impl' or the primary
// 'begin/end' templates
template< typename Tag >
struct begin_impl
{
template< typename Sequence > struct apply
{
typedef typename eval_if<aux::has_begin<Sequence, true_>,
aux::begin_type<Sequence>, void_>::type type;
};
};
template< typename Tag >
struct end_impl
{
template< typename Sequence > struct apply
{
typedef typename eval_if<aux::has_begin<Sequence, true_>,
aux::end_type<Sequence>, void_>::type type;
};
};
// specialize 'begin_trait/end_trait' for two pre-defined tags
# define AUX778076_IMPL_SPEC(name, tag, result) \
template<> \
struct name##_impl<tag> \
{ \
template< typename Sequence > struct apply \
{ \
typedef result type; \
}; \
}; \
/**/
// a sequence with nested 'begin/end' typedefs; just query them
AUX778076_IMPL_SPEC(begin, nested_begin_end_tag, typename Sequence::begin)
AUX778076_IMPL_SPEC(end, nested_begin_end_tag, typename Sequence::end)
// if a type 'T' does not contain 'begin/end' or 'tag' members
// and doesn't specialize either 'begin/end' or 'begin_impl/end_impl'
// templates, then we end up here
AUX778076_IMPL_SPEC(begin, non_sequence_tag, void_)
AUX778076_IMPL_SPEC(end, non_sequence_tag, void_)
AUX778076_IMPL_SPEC(begin, na, void_)
AUX778076_IMPL_SPEC(end, na, void_)
# undef AUX778076_IMPL_SPEC
BOOST_MPL_ALGORITM_TRAITS_LAMBDA_SPEC_IMPL(1,begin_impl)
BOOST_MPL_ALGORITM_TRAITS_LAMBDA_SPEC_IMPL(1,end_impl)
}}
#endif // BOOST_MPL_AUX_BEGIN_END_IMPL_HPP_INCLUDED
| gpl-2.0 |
inderpreet/Galileo-win32 | VisualStudio/WinSock2_Client/WinSock2_Client/main.cpp | 2960 | #define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"
int __cdecl main(int argc, char **argv)
{
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
char *sendbuf = "this is a test";
char recvbuf[DEFAULT_BUFLEN];
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
// Validate the parameters
if (argc != 2) {
printf("usage: %s server-name\n", argv[0]);
return 1;
}
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// Connect to server.
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
// Send an initial buffer
iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
if (iResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %ld\n", iResult);
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// Receive until the peer closes the connection
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if (iResult > 0)
printf("Bytes received: %d\n", iResult);
else if (iResult == 0)
printf("Connection closed\n");
else
printf("recv failed with error: %d\n", WSAGetLastError());
} while (iResult > 0);
// cleanup
closesocket(ConnectSocket);
WSACleanup();
return 0;
} | gpl-2.0 |
Ausm/ObjectStore | src/ObjectStore/ObjectStore.cs | 3351 | using ObjectStore.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
#if NETCOREAPP1_0
using System.Reflection;
#endif
[assembly: InternalsVisibleTo("ObjectStore.SqlClient")]
[assembly: InternalsVisibleTo("ObjectStore.Sqlite")]
namespace ObjectStore
{
public class ObjectStore : IObjectProvider
{
#region Konstruktoren
public ObjectStore()
{
_objectProviders = new Dictionary<Type, IObjectProvider>();
}
#endregion
#region Membervariablen
Dictionary<Type, IObjectProvider> _objectProviders;
#endregion
#region Funktionen
#region Öffentlich
public IObjectProvider RegisterObjectProvider(Type type, IObjectProvider objectProvider)
{
IObjectProvider returnValue = null;
if (_objectProviders.ContainsKey(type))
{
returnValue = _objectProviders[type];
}
_objectProviders[type] = objectProvider;
return returnValue;
}
public IObjectProvider RegisterObjectProvider(IObjectProvider objectProvider)
{
return RegisterObjectProvider(typeof(object), objectProvider);
}
#endregion
#region IObjectProvider Members
public IQueryable<T> GetQueryable<T>() where T : class
{
List<IObjectProvider> providers = GetProviderForType(typeof(T));
if (providers.Count == 1)
{
return providers[0].GetQueryable<T>();
}
if (providers.Count > 1)
{
IQueryable<T> queryable = null;
foreach (IObjectProvider provider in providers)
{
if (queryable == null)
{
queryable = provider.GetQueryable<T>();
}
else
{
queryable.Union(provider.GetQueryable<T>());
}
}
return queryable;
}
return new List<T>().AsQueryable();
}
public T CreateObject<T>() where T : class
{
foreach (IObjectProvider provider in GetProviderForType(typeof(T)))
{
T obj = provider.CreateObject<T>();
if (obj != null && !obj.Equals(default(T)))
return obj;
}
return default(T);
}
bool IObjectProvider.SupportsType(Type type)
{
return GetProviderForType(type).Count > 0;
}
#endregion
#region Privat
private List<IObjectProvider> GetProviderForType(Type type)
{
List<IObjectProvider> returnValue = new List<IObjectProvider>();
foreach (KeyValuePair<Type, IObjectProvider> provider in _objectProviders)
{
if ((provider.Key.IsAssignableFrom(type) ||
type.IsAssignableFrom(provider.Key)) &&
provider.Value.SupportsType(type))
{
returnValue.Add(provider.Value);
}
}
return returnValue;
}
#endregion
#endregion
}
}
| gpl-2.0 |
cala/mangos-wotlk | src/game/BattleGround/BattleGroundMgr.cpp | 98911 | /*
* This file is part of the CMaNGOS Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "Common.h"
#include "Globals/SharedDefines.h"
#include "Entities/Player.h"
#include "BattleGroundMgr.h"
#include "BattleGroundAV.h"
#include "BattleGroundAB.h"
#include "BattleGroundEY.h"
#include "BattleGroundWS.h"
#include "BattleGroundNA.h"
#include "BattleGroundBE.h"
#include "BattleGroundAA.h"
#include "BattleGroundRL.h"
#include "BattleGroundSA.h"
#include "BattleGroundDS.h"
#include "BattleGroundRV.h"
#include "BattleGroundIC.h"
#include "BattleGroundRB.h"
#include "Maps/MapManager.h"
#include "Maps/Map.h"
#include "Globals/ObjectMgr.h"
#include "ProgressBar.h"
#include "Chat/Chat.h"
#include "Arena/ArenaTeam.h"
#include "World/World.h"
#include "WorldPacket.h"
#include "GameEvents/GameEventMgr.h"
#include "Policies/Singleton.h"
INSTANTIATE_SINGLETON_1(BattleGroundMgr);
/*********************************************************/
/*** BATTLEGROUND QUEUE SYSTEM ***/
/*********************************************************/
BattleGroundQueue::BattleGroundQueue()
{
for (uint8 i = 0; i < PVP_TEAM_COUNT; ++i)
{
for (uint8 j = 0; j < MAX_BATTLEGROUND_BRACKETS; ++j)
{
m_SumOfWaitTimes[i][j] = 0;
m_WaitTimeLastPlayer[i][j] = 0;
for (uint8 k = 0; k < COUNT_OF_PLAYERS_TO_AVERAGE_WAIT_TIME; ++k)
m_WaitTimes[i][j][k] = 0;
}
}
}
BattleGroundQueue::~BattleGroundQueue()
{
m_QueuedPlayers.clear();
for (uint8 i = 0; i < MAX_BATTLEGROUND_BRACKETS; ++i)
{
for (uint8 j = 0; j < BG_QUEUE_GROUP_TYPES_COUNT; ++j)
{
for (GroupsQueueType::iterator itr = m_QueuedGroups[i][j].begin(); itr != m_QueuedGroups[i][j].end(); ++itr)
delete (*itr);
m_QueuedGroups[i][j].clear();
}
}
}
/*********************************************************/
/*** BATTLEGROUND QUEUE SELECTION POOLS ***/
/*********************************************************/
// selection pool initialization, used to clean up from prev selection
void BattleGroundQueue::SelectionPool::Init()
{
SelectedGroups.clear();
PlayerCount = 0;
}
// remove group info from selection pool
// returns true when we need to try to add new group to selection pool
// returns false when selection pool is ok or when we kicked smaller group than we need to kick
// sometimes it can be called on empty selection pool
bool BattleGroundQueue::SelectionPool::KickGroup(uint32 size)
{
// find maxgroup or LAST group with size == size and kick it
bool found = false;
GroupsQueueType::iterator groupToKick = SelectedGroups.begin();
for (GroupsQueueType::iterator itr = groupToKick; itr != SelectedGroups.end(); ++itr)
{
if (abs((int32)((*itr)->Players.size() - size)) <= 1)
{
groupToKick = itr;
found = true;
}
else if (!found && (*itr)->Players.size() >= (*groupToKick)->Players.size())
groupToKick = itr;
}
// if pool is empty, do nothing
if (GetPlayerCount())
{
// update player count
GroupQueueInfo* ginfo = (*groupToKick);
SelectedGroups.erase(groupToKick);
PlayerCount -= ginfo->Players.size();
// return false if we kicked smaller group or there are enough players in selection pool
if (ginfo->Players.size() <= size + 1)
return false;
}
return true;
}
// add group to selection pool
// used when building selection pools
// returns true if we can invite more players, or when we added group to selection pool
// returns false when selection pool is full
bool BattleGroundQueue::SelectionPool::AddGroup(GroupQueueInfo* ginfo, uint32 desiredCount)
{
// if group is larger than desired count - don't allow to add it to pool
if (!ginfo->IsInvitedToBGInstanceGUID && desiredCount >= PlayerCount + ginfo->Players.size())
{
SelectedGroups.push_back(ginfo);
// increase selected players count
PlayerCount += ginfo->Players.size();
return true;
}
if (PlayerCount < desiredCount)
return true;
return false;
}
/*********************************************************/
/*** BATTLEGROUND QUEUES ***/
/*********************************************************/
// add group or player (grp == nullptr) to bg queue with the given leader and bg specifications
GroupQueueInfo* BattleGroundQueue::AddGroup(Player* leader, Group* grp, BattleGroundTypeId BgTypeId, PvPDifficultyEntry const* bracketEntry, ArenaType arenaType, bool isRated, bool isPremade, uint32 arenaRating, uint32 arenateamid)
{
BattleGroundBracketId bracketId = bracketEntry->GetBracketId();
// create new ginfo
GroupQueueInfo* ginfo = new GroupQueueInfo;
ginfo->BgTypeId = BgTypeId;
ginfo->arenaType = arenaType;
ginfo->ArenaTeamId = arenateamid;
ginfo->IsRated = isRated;
ginfo->IsInvitedToBGInstanceGUID = 0;
ginfo->JoinTime = WorldTimer::getMSTime();
ginfo->RemoveInviteTime = 0;
ginfo->GroupTeam = leader->GetTeam();
ginfo->ArenaTeamRating = arenaRating;
ginfo->OpponentsTeamRating = 0;
ginfo->Players.clear();
// compute index (if group is premade or joined a rated match) to queues
uint32 index = 0;
if (!isRated && !isPremade)
index += PVP_TEAM_COUNT; // BG_QUEUE_PREMADE_* -> BG_QUEUE_NORMAL_*
if (ginfo->GroupTeam == HORDE)
++index; // BG_QUEUE_*_ALLIANCE -> BG_QUEUE_*_HORDE
DEBUG_LOG("Adding Group to BattleGroundQueue bgTypeId : %u, bracket_id : %u, index : %u", BgTypeId, bracketId, index);
uint32 lastOnlineTime = WorldTimer::getMSTime();
// announce world (this don't need mutex)
if (isRated && sWorld.getConfig(CONFIG_BOOL_ARENA_QUEUE_ANNOUNCER_JOIN))
{
sWorld.SendWorldText(LANG_ARENA_QUEUE_ANNOUNCE_WORLD_JOIN, ginfo->arenaType, ginfo->arenaType, ginfo->ArenaTeamRating);
}
// add players from group to ginfo
{
// std::lock_guard<std::recursive_mutex> guard(m_Lock);
if (grp)
{
for (GroupReference* itr = grp->GetFirstMember(); itr != nullptr; itr = itr->next())
{
Player* member = itr->getSource();
if (!member)
continue; // this should never happen
PlayerQueueInfo& pl_info = m_QueuedPlayers[member->GetObjectGuid()];
pl_info.LastOnlineTime = lastOnlineTime;
pl_info.GroupInfo = ginfo;
// add the pinfo to ginfo's list
ginfo->Players[member->GetObjectGuid()] = &pl_info;
}
}
else
{
PlayerQueueInfo& pl_info = m_QueuedPlayers[leader->GetObjectGuid()];
pl_info.LastOnlineTime = lastOnlineTime;
pl_info.GroupInfo = ginfo;
ginfo->Players[leader->GetObjectGuid()] = &pl_info;
}
// add GroupInfo to m_QueuedGroups
m_QueuedGroups[bracketId][index].push_back(ginfo);
// announce to world, this code needs mutex
if (arenaType == ARENA_TYPE_NONE && !isRated && !isPremade && sWorld.getConfig(CONFIG_UINT32_BATTLEGROUND_QUEUE_ANNOUNCER_JOIN))
{
if (BattleGround* bg = sBattleGroundMgr.GetBattleGroundTemplate(ginfo->BgTypeId))
{
char const* bgName = bg->GetName();
uint32 MinPlayers = bg->GetMinPlayersPerTeam();
uint32 qHorde = 0;
uint32 qAlliance = 0;
uint32 q_min_level = bracketEntry->minLevel;
uint32 q_max_level = bracketEntry->maxLevel;
GroupsQueueType::const_iterator itr;
for (itr = m_QueuedGroups[bracketId][BG_QUEUE_NORMAL_ALLIANCE].begin(); itr != m_QueuedGroups[bracketId][BG_QUEUE_NORMAL_ALLIANCE].end(); ++itr)
if (!(*itr)->IsInvitedToBGInstanceGUID)
qAlliance += (*itr)->Players.size();
for (itr = m_QueuedGroups[bracketId][BG_QUEUE_NORMAL_HORDE].begin(); itr != m_QueuedGroups[bracketId][BG_QUEUE_NORMAL_HORDE].end(); ++itr)
if (!(*itr)->IsInvitedToBGInstanceGUID)
qHorde += (*itr)->Players.size();
// Show queue status to player only (when joining queue)
if (sWorld.getConfig(CONFIG_UINT32_BATTLEGROUND_QUEUE_ANNOUNCER_JOIN) == 1)
{
ChatHandler(leader).PSendSysMessage(LANG_BG_QUEUE_ANNOUNCE_SELF, bgName, q_min_level, q_max_level,
qAlliance, (MinPlayers > qAlliance) ? MinPlayers - qAlliance : (uint32)0, qHorde, (MinPlayers > qHorde) ? MinPlayers - qHorde : (uint32)0);
}
// System message
else
{
sWorld.SendWorldText(LANG_BG_QUEUE_ANNOUNCE_WORLD, bgName, q_min_level, q_max_level,
qAlliance, (MinPlayers > qAlliance) ? MinPlayers - qAlliance : (uint32)0, qHorde, (MinPlayers > qHorde) ? MinPlayers - qHorde : (uint32)0);
}
}
}
// release mutex
}
return ginfo;
}
void BattleGroundQueue::PlayerInvitedToBGUpdateAverageWaitTime(GroupQueueInfo* ginfo, BattleGroundBracketId bracket_id)
{
uint32 timeInQueue = WorldTimer::getMSTimeDiff(ginfo->JoinTime, WorldTimer::getMSTime());
uint8 team_index = TEAM_INDEX_ALLIANCE; // default set to BG_TEAM_ALLIANCE - or non rated arenas!
if (ginfo->arenaType == ARENA_TYPE_NONE)
{
if (ginfo->GroupTeam == HORDE)
team_index = TEAM_INDEX_HORDE;
}
else
{
if (ginfo->IsRated)
team_index = TEAM_INDEX_HORDE; // for rated arenas use BG_TEAM_HORDE
}
// store pointer to arrayindex of player that was added first
uint32* lastPlayerAddedPointer = &(m_WaitTimeLastPlayer[team_index][bracket_id]);
// remove his time from sum
m_SumOfWaitTimes[team_index][bracket_id] -= m_WaitTimes[team_index][bracket_id][(*lastPlayerAddedPointer)];
// set average time to new
m_WaitTimes[team_index][bracket_id][(*lastPlayerAddedPointer)] = timeInQueue;
// add new time to sum
m_SumOfWaitTimes[team_index][bracket_id] += timeInQueue;
// set index of last player added to next one
(*lastPlayerAddedPointer)++;
(*lastPlayerAddedPointer) %= COUNT_OF_PLAYERS_TO_AVERAGE_WAIT_TIME;
}
uint32 BattleGroundQueue::GetAverageQueueWaitTime(GroupQueueInfo* ginfo, BattleGroundBracketId bracket_id)
{
uint8 team_index = TEAM_INDEX_ALLIANCE; // default set to BG_TEAM_ALLIANCE - or non rated arenas!
if (ginfo->arenaType == ARENA_TYPE_NONE)
{
if (ginfo->GroupTeam == HORDE)
team_index = TEAM_INDEX_HORDE;
}
else
{
if (ginfo->IsRated)
team_index = TEAM_INDEX_HORDE; // for rated arenas use BG_TEAM_HORDE
}
// check if there is enought values(we always add values > 0)
if (m_WaitTimes[team_index][bracket_id][COUNT_OF_PLAYERS_TO_AVERAGE_WAIT_TIME - 1])
return (m_SumOfWaitTimes[team_index][bracket_id] / COUNT_OF_PLAYERS_TO_AVERAGE_WAIT_TIME);
else
// if there aren't enough values return 0 - not available
return 0;
}
// remove player from queue and from group info, if group info is empty then remove it too
void BattleGroundQueue::RemovePlayer(ObjectGuid guid, bool decreaseInvitedCount)
{
// Player *plr = sObjectMgr.GetPlayer(guid);
// std::lock_guard<std::recursive_mutex> guard(m_Lock);
int32 bracket_id = -1; // signed for proper for-loop finish
QueuedPlayersMap::iterator itr;
// remove player from map, if he's there
itr = m_QueuedPlayers.find(guid);
if (itr == m_QueuedPlayers.end())
{
sLog.outError("BattleGroundQueue: couldn't find for remove: %s", guid.GetString().c_str());
return;
}
GroupQueueInfo* group = itr->second.GroupInfo;
GroupsQueueType::iterator group_itr, group_itr_tmp;
// mostly people with the highest levels are in battlegrounds, thats why
// we count from MAX_BATTLEGROUND_QUEUES - 1 to 0
// variable index removes useless searching in other team's queue
uint32 index = GetTeamIndexByTeamId(group->GroupTeam);
for (int8 bracket_id_tmp = MAX_BATTLEGROUND_BRACKETS - 1; bracket_id_tmp >= 0 && bracket_id == -1; --bracket_id_tmp)
{
// we must check premade and normal team's queue - because when players from premade are joining bg,
// they leave groupinfo so we can't use its players size to find out index
for (uint8 j = index; j < BG_QUEUE_GROUP_TYPES_COUNT; j += BG_QUEUE_NORMAL_ALLIANCE)
{
for (group_itr_tmp = m_QueuedGroups[bracket_id_tmp][j].begin(); group_itr_tmp != m_QueuedGroups[bracket_id_tmp][j].end(); ++group_itr_tmp)
{
if ((*group_itr_tmp) == group)
{
bracket_id = bracket_id_tmp;
group_itr = group_itr_tmp;
// we must store index to be able to erase iterator
index = j;
break;
}
}
}
}
// player can't be in queue without group, but just in case
if (bracket_id == -1)
{
sLog.outError("BattleGroundQueue: ERROR Cannot find groupinfo for %s", guid.GetString().c_str());
return;
}
DEBUG_LOG("BattleGroundQueue: Removing %s, from bracket_id %u", guid.GetString().c_str(), (uint32)bracket_id);
// ALL variables are correctly set
// We can ignore leveling up in queue - it should not cause crash
// remove player from group
// if only one player there, remove group
// remove player queue info from group queue info
GroupQueueInfoPlayers::iterator pitr = group->Players.find(guid);
if (pitr != group->Players.end())
group->Players.erase(pitr);
// if invited to bg, and should decrease invited count, then do it
if (decreaseInvitedCount && group->IsInvitedToBGInstanceGUID)
{
BattleGround* bg = sBattleGroundMgr.GetBattleGround(group->IsInvitedToBGInstanceGUID, group->BgTypeId);
if (bg)
bg->DecreaseInvitedCount(group->GroupTeam);
}
// remove player queue info
m_QueuedPlayers.erase(itr);
// announce to world if arena team left queue for rated match, show only once
if (group->arenaType != ARENA_TYPE_NONE && group->IsRated && group->Players.empty() && sWorld.getConfig(CONFIG_BOOL_ARENA_QUEUE_ANNOUNCER_EXIT))
sWorld.SendWorldText(LANG_ARENA_QUEUE_ANNOUNCE_WORLD_EXIT, group->arenaType, group->arenaType, group->ArenaTeamRating);
// if player leaves queue and he is invited to rated arena match, then he have to loose
if (group->IsInvitedToBGInstanceGUID && group->IsRated && decreaseInvitedCount)
{
ArenaTeam* at = sObjectMgr.GetArenaTeamById(group->ArenaTeamId);
if (at)
{
DEBUG_LOG("UPDATING memberLost's personal arena rating for %s by opponents rating: %u", guid.GetString().c_str(), group->OpponentsTeamRating);
Player* plr = sObjectMgr.GetPlayer(guid);
if (plr)
at->MemberLost(plr, group->OpponentsTeamRating);
else
at->OfflineMemberLost(guid, group->OpponentsTeamRating);
at->SaveToDB();
}
}
// remove group queue info if needed
if (group->Players.empty())
{
m_QueuedGroups[bracket_id][index].erase(group_itr);
delete group;
}
// if group wasn't empty, so it wasn't deleted, and player have left a rated
// queue -> everyone from the group should leave too
// don't remove recursively if already invited to bg!
else if (!group->IsInvitedToBGInstanceGUID && group->IsRated)
{
// remove next player, this is recursive
// first send removal information
if (Player* plr2 = sObjectMgr.GetPlayer(group->Players.begin()->first))
{
BattleGround* bg = sBattleGroundMgr.GetBattleGroundTemplate(group->BgTypeId);
BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(group->BgTypeId, group->arenaType);
uint32 queueSlot = plr2->GetBattleGroundQueueIndex(bgQueueTypeId);
plr2->RemoveBattleGroundQueueId(bgQueueTypeId); // must be called this way, because if you move this call to
// queue->removeplayer, it causes bugs
WorldPacket data;
sBattleGroundMgr.BuildBattleGroundStatusPacket(data, bg, queueSlot, STATUS_NONE, 0, 0, ARENA_TYPE_NONE, TEAM_NONE);
plr2->GetSession()->SendPacket(data);
}
// then actually delete, this may delete the group as well!
RemovePlayer(group->Players.begin()->first, decreaseInvitedCount);
}
}
// returns true when player pl_guid is in queue and is invited to bgInstanceGuid
bool BattleGroundQueue::IsPlayerInvited(ObjectGuid pl_guid, const uint32 bgInstanceGuid, const uint32 removeTime)
{
// std::lock_guard<std::recursive_mutex> g(m_Lock);
QueuedPlayersMap::const_iterator qItr = m_QueuedPlayers.find(pl_guid);
return (qItr != m_QueuedPlayers.end()
&& qItr->second.GroupInfo->IsInvitedToBGInstanceGUID == bgInstanceGuid
&& qItr->second.GroupInfo->RemoveInviteTime == removeTime);
}
bool BattleGroundQueue::GetPlayerGroupInfoData(ObjectGuid guid, GroupQueueInfo* ginfo)
{
// std::lock_guard<std::recursive_mutex> g(m_Lock);
QueuedPlayersMap::const_iterator qItr = m_QueuedPlayers.find(guid);
if (qItr == m_QueuedPlayers.end())
return false;
*ginfo = *(qItr->second.GroupInfo);
return true;
}
bool BattleGroundQueue::InviteGroupToBG(GroupQueueInfo* ginfo, BattleGround* bg, Team side)
{
// set side if needed
if (side)
ginfo->GroupTeam = side;
if (!ginfo->IsInvitedToBGInstanceGUID)
{
// not yet invited
// set invitation
ginfo->IsInvitedToBGInstanceGUID = bg->GetInstanceID();
BattleGroundTypeId bgTypeId = bg->GetTypeID();
BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(bgTypeId, bg->GetArenaType());
BattleGroundBracketId bracket_id = bg->GetBracketId();
// set ArenaTeamId for rated matches
if (bg->isArena() && bg->isRated())
bg->SetArenaTeamIdForTeam(ginfo->GroupTeam, ginfo->ArenaTeamId);
ginfo->RemoveInviteTime = WorldTimer::getMSTime() + INVITE_ACCEPT_WAIT_TIME;
// loop through the players
for (GroupQueueInfoPlayers::iterator itr = ginfo->Players.begin(); itr != ginfo->Players.end(); ++itr)
{
// get the player
Player* plr = sObjectMgr.GetPlayer(itr->first);
// if offline, skip him, this should not happen - player is removed from queue when he logs out
if (!plr)
continue;
// invite the player
PlayerInvitedToBGUpdateAverageWaitTime(ginfo, bracket_id);
// sBattleGroundMgr.InvitePlayer(plr, bg, ginfo->Team);
// set invited player counters
bg->IncreaseInvitedCount(ginfo->GroupTeam);
plr->SetInviteForBattleGroundQueueType(bgQueueTypeId, ginfo->IsInvitedToBGInstanceGUID);
// create remind invite events
BGQueueInviteEvent* inviteEvent = new BGQueueInviteEvent(plr->GetObjectGuid(), ginfo->IsInvitedToBGInstanceGUID, bgTypeId, ginfo->arenaType, ginfo->RemoveInviteTime);
plr->m_Events.AddEvent(inviteEvent, plr->m_Events.CalculateTime(INVITATION_REMIND_TIME));
// create automatic remove events
BGQueueRemoveEvent* removeEvent = new BGQueueRemoveEvent(plr->GetObjectGuid(), ginfo->IsInvitedToBGInstanceGUID, bgTypeId, bgQueueTypeId, ginfo->RemoveInviteTime);
plr->m_Events.AddEvent(removeEvent, plr->m_Events.CalculateTime(INVITE_ACCEPT_WAIT_TIME));
WorldPacket data;
uint32 queueSlot = plr->GetBattleGroundQueueIndex(bgQueueTypeId);
DEBUG_LOG("Battleground: invited %s to BG instance %u queueindex %u bgtype %u, I can't help it if they don't press the enter battle button.",
plr->GetGuidStr().c_str(), bg->GetInstanceID(), queueSlot, bg->GetTypeID());
// send status packet
sBattleGroundMgr.BuildBattleGroundStatusPacket(data, bg, queueSlot, STATUS_WAIT_JOIN, INVITE_ACCEPT_WAIT_TIME, 0, ginfo->arenaType, TEAM_NONE);
plr->GetSession()->SendPacket(data);
}
return true;
}
return false;
}
/*
This function is inviting players to already running battlegrounds
Invitation type is based on config file
large groups are disadvantageous, because they will be kicked first if invitation type = 1
*/
void BattleGroundQueue::FillPlayersToBG(BattleGround* bg, BattleGroundBracketId bracket_id)
{
int32 hordeFree = bg->GetFreeSlotsForTeam(HORDE);
int32 aliFree = bg->GetFreeSlotsForTeam(ALLIANCE);
// iterator for iterating through bg queue
GroupsQueueType::const_iterator Ali_itr = m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE].begin();
// count of groups in queue - used to stop cycles
uint32 aliCount = m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE].size();
// index to queue which group is current
uint32 aliIndex = 0;
for (; aliIndex < aliCount && m_SelectionPools[TEAM_INDEX_ALLIANCE].AddGroup((*Ali_itr), aliFree); ++aliIndex)
++Ali_itr;
// the same thing for horde
GroupsQueueType::const_iterator Horde_itr = m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_HORDE].begin();
uint32 hordeCount = m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_HORDE].size();
uint32 hordeIndex = 0;
for (; hordeIndex < hordeCount && m_SelectionPools[TEAM_INDEX_HORDE].AddGroup((*Horde_itr), hordeFree); ++hordeIndex)
++Horde_itr;
// if ofc like BG queue invitation is set in config, then we are happy
if (sWorld.getConfig(CONFIG_UINT32_BATTLEGROUND_INVITATION_TYPE) == 0)
return;
/*
if we reached this code, then we have to solve NP - complete problem called Subset sum problem
So one solution is to check all possible invitation subgroups, or we can use these conditions:
1. Last time when BattleGroundQueue::Update was executed we invited all possible players - so there is only small possibility
that we will invite now whole queue, because only 1 change has been made to queues from the last BattleGroundQueue::Update call
2. Other thing we should consider is group order in queue
*/
// At first we need to compare free space in bg and our selection pool
int32 diffAli = aliFree - int32(m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount());
int32 diffHorde = hordeFree - int32(m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount());
while (abs(diffAli - diffHorde) > 1 && (m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount() > 0 || m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount() > 0))
{
// each cycle execution we need to kick at least 1 group
if (diffAli < diffHorde)
{
// kick alliance group, add to pool new group if needed
if (m_SelectionPools[TEAM_INDEX_ALLIANCE].KickGroup(diffHorde - diffAli))
{
for (; aliIndex < aliCount && m_SelectionPools[TEAM_INDEX_ALLIANCE].AddGroup((*Ali_itr), (aliFree >= diffHorde) ? aliFree - diffHorde : 0); ++aliIndex)
++Ali_itr;
}
// if ali selection is already empty, then kick horde group, but if there are less horde than ali in bg - break;
if (!m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount())
{
if (aliFree <= diffHorde + 1)
break;
m_SelectionPools[TEAM_INDEX_HORDE].KickGroup(diffHorde - diffAli);
}
}
else
{
// kick horde group, add to pool new group if needed
if (m_SelectionPools[TEAM_INDEX_HORDE].KickGroup(diffAli - diffHorde))
{
for (; hordeIndex < hordeCount && m_SelectionPools[TEAM_INDEX_HORDE].AddGroup((*Horde_itr), (hordeFree >= diffAli) ? hordeFree - diffAli : 0); ++hordeIndex)
++Horde_itr;
}
if (!m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount())
{
if (hordeFree <= diffAli + 1)
break;
m_SelectionPools[TEAM_INDEX_ALLIANCE].KickGroup(diffAli - diffHorde);
}
}
// count diffs after small update
diffAli = aliFree - int32(m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount());
diffHorde = hordeFree - int32(m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount());
}
}
// this method checks if premade versus premade battleground is possible
// then after 30 mins (default) in queue it moves premade group to normal queue
// it tries to invite as much players as it can - to MaxPlayersPerTeam, because premade groups have more than MinPlayersPerTeam players
bool BattleGroundQueue::CheckPremadeMatch(BattleGroundBracketId bracket_id, uint32 MinPlayersPerTeam, uint32 MaxPlayersPerTeam)
{
// check match
if (!m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].empty() && !m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].empty())
{
// start premade match
// if groups aren't invited
GroupsQueueType::const_iterator ali_group, horde_group;
for (ali_group = m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].begin(); ali_group != m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].end(); ++ali_group)
if (!(*ali_group)->IsInvitedToBGInstanceGUID)
break;
for (horde_group = m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].begin(); horde_group != m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].end(); ++horde_group)
if (!(*horde_group)->IsInvitedToBGInstanceGUID)
break;
if (ali_group != m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].end() && horde_group != m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].end())
{
m_SelectionPools[TEAM_INDEX_ALLIANCE].AddGroup((*ali_group), MaxPlayersPerTeam);
m_SelectionPools[TEAM_INDEX_HORDE].AddGroup((*horde_group), MaxPlayersPerTeam);
// add groups/players from normal queue to size of bigger group
uint32 maxPlayers = std::max(m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount(), m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount());
GroupsQueueType::const_iterator itr;
for (uint8 i = 0; i < PVP_TEAM_COUNT; ++i)
{
for (itr = m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + i].begin(); itr != m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + i].end(); ++itr)
{
// if itr can join BG and player count is less that maxPlayers, then add group to selectionpool
if (!(*itr)->IsInvitedToBGInstanceGUID && !m_SelectionPools[i].AddGroup((*itr), maxPlayers))
break;
}
}
// premade selection pools are set
return true;
}
}
// now check if we can move group from Premade queue to normal queue (timer has expired) or group size lowered!!
// this could be 2 cycles but i'm checking only first team in queue - it can cause problem -
// if first is invited to BG and seconds timer expired, but we can ignore it, because players have only 80 seconds to click to enter bg
// and when they click or after 80 seconds the queue info is removed from queue
uint32 time_before = WorldTimer::getMSTime() - sWorld.getConfig(CONFIG_UINT32_BATTLEGROUND_PREMADE_GROUP_WAIT_FOR_MATCH);
for (uint8 i = 0; i < PVP_TEAM_COUNT; ++i)
{
if (!m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE + i].empty())
{
GroupsQueueType::iterator itr = m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE + i].begin();
if (!(*itr)->IsInvitedToBGInstanceGUID && ((*itr)->JoinTime < time_before || (*itr)->Players.size() < MinPlayersPerTeam))
{
// we must insert group to normal queue and erase pointer from premade queue
m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + i].push_front((*itr));
m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE + i].erase(itr);
}
}
}
// selection pools are not set
return false;
}
// this method tries to create battleground or arena with MinPlayersPerTeam against MinPlayersPerTeam
bool BattleGroundQueue::CheckNormalMatch(BattleGround* bg_template, BattleGroundBracketId bracket_id, uint32 minPlayers, uint32 maxPlayers)
{
GroupsQueueType::const_iterator itr_team[PVP_TEAM_COUNT];
for (uint8 i = 0; i < PVP_TEAM_COUNT; ++i)
{
itr_team[i] = m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + i].begin();
for (; itr_team[i] != m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + i].end(); ++(itr_team[i]))
{
if (!(*(itr_team[i]))->IsInvitedToBGInstanceGUID)
{
m_SelectionPools[i].AddGroup(*(itr_team[i]), maxPlayers);
if (m_SelectionPools[i].GetPlayerCount() >= minPlayers)
break;
}
}
}
// try to invite same number of players - this cycle may cause longer wait time even if there are enough players in queue, but we want ballanced bg
uint32 j = TEAM_INDEX_ALLIANCE;
if (m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount() < m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount())
j = TEAM_INDEX_HORDE;
if (sWorld.getConfig(CONFIG_UINT32_BATTLEGROUND_INVITATION_TYPE) != 0
&& m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount() >= minPlayers && m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount() >= minPlayers)
{
// we will try to invite more groups to team with less players indexed by j
++(itr_team[j]); // this will not cause a crash, because for cycle above reached break;
for (; itr_team[j] != m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + j].end(); ++(itr_team[j]))
{
if (!(*(itr_team[j]))->IsInvitedToBGInstanceGUID)
if (!m_SelectionPools[j].AddGroup(*(itr_team[j]), m_SelectionPools[(j + 1) % PVP_TEAM_COUNT].GetPlayerCount()))
break;
}
// do not allow to start bg with more than 2 players more on 1 faction
if (abs((int32)(m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount() - m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount())) > 2)
return false;
}
// allow 1v0 if debug bg
if (sBattleGroundMgr.isTesting() && bg_template->isBattleGround() && (m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount() || m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount()))
return true;
// return true if there are enough players in selection pools - enable to work .debug bg command correctly
return m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount() >= minPlayers && m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount() >= minPlayers;
}
// this method will check if we can invite players to same faction skirmish match
bool BattleGroundQueue::CheckSkirmishForSameFaction(BattleGroundBracketId bracket_id, uint32 minPlayersPerTeam)
{
if (m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount() < minPlayersPerTeam && m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount() < minPlayersPerTeam)
return false;
PvpTeamIndex teamIdx = TEAM_INDEX_ALLIANCE;
PvpTeamIndex otherTeamIdx = TEAM_INDEX_HORDE;
Team otherTeamId = HORDE;
if (m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount() == minPlayersPerTeam)
{
teamIdx = TEAM_INDEX_HORDE;
otherTeamIdx = TEAM_INDEX_ALLIANCE;
otherTeamId = ALLIANCE;
}
// clear other team's selection
m_SelectionPools[otherTeamIdx].Init();
// store last ginfo pointer
GroupQueueInfo* ginfo = m_SelectionPools[teamIdx].SelectedGroups.back();
// set itr_team to group that was added to selection pool latest
GroupsQueueType::iterator itr_team = m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + teamIdx].begin();
for (; itr_team != m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + teamIdx].end(); ++itr_team)
if (ginfo == *itr_team)
break;
if (itr_team == m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + teamIdx].end())
return false;
GroupsQueueType::iterator itr_team2 = itr_team;
++itr_team2;
// invite players to other selection pool
for (; itr_team2 != m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + teamIdx].end(); ++itr_team2)
{
// if selection pool is full then break;
if (!(*itr_team2)->IsInvitedToBGInstanceGUID && !m_SelectionPools[otherTeamIdx].AddGroup(*itr_team2, minPlayersPerTeam))
break;
}
if (m_SelectionPools[otherTeamIdx].GetPlayerCount() != minPlayersPerTeam)
return false;
// here we have correct 2 selections and we need to change one teams team and move selection pool teams to other team's queue
for (GroupsQueueType::iterator itr = m_SelectionPools[otherTeamIdx].SelectedGroups.begin(); itr != m_SelectionPools[otherTeamIdx].SelectedGroups.end(); ++itr)
{
// set correct team
(*itr)->GroupTeam = otherTeamId;
// add team to other queue
m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + otherTeamIdx].push_front(*itr);
// remove team from old queue
GroupsQueueType::iterator itr2 = itr_team;
++itr2;
for (; itr2 != m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + teamIdx].end(); ++itr2)
{
if (*itr2 == *itr)
{
m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + teamIdx].erase(itr2);
break;
}
}
}
return true;
}
/*
this method is called when group is inserted, or player / group is removed from BG Queue - there is only one player's status changed, so we don't use while(true) cycles to invite whole queue
it must be called after fully adding the members of a group to ensure group joining
should be called from BattleGround::RemovePlayer function in some cases
*/
void BattleGroundQueue::Update(BattleGroundTypeId bgTypeId, BattleGroundBracketId bracket_id, ArenaType arenaType, bool isRated, uint32 arenaRating)
{
// std::lock_guard<std::recursive_mutex> guard(m_Lock);
// if no players in queue - do nothing
if (m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].empty() &&
m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].empty() &&
m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE].empty() &&
m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_HORDE].empty())
return;
// battleground with free slot for player should be always in the beggining of the queue
// maybe it would be better to create bgfreeslotqueue for each bracket_id
BGFreeSlotQueueType::iterator itr, next;
for (itr = sBattleGroundMgr.BGFreeSlotQueue[bgTypeId].begin(); itr != sBattleGroundMgr.BGFreeSlotQueue[bgTypeId].end(); itr = next)
{
next = itr;
++next;
// DO NOT allow queue manager to invite new player to arena
if ((*itr)->isBattleGround() && (*itr)->GetTypeID() == bgTypeId && (*itr)->GetBracketId() == bracket_id &&
(*itr)->GetStatus() > STATUS_WAIT_QUEUE && (*itr)->GetStatus() < STATUS_WAIT_LEAVE)
{
BattleGround* bg = *itr; // we have to store battleground pointer here, because when battleground is full, it is removed from free queue (not yet implemented!!)
// and iterator is invalid
// clear selection pools
m_SelectionPools[TEAM_INDEX_ALLIANCE].Init();
m_SelectionPools[TEAM_INDEX_HORDE].Init();
// call a function that does the job for us
FillPlayersToBG(bg, bracket_id);
// now everything is set, invite players
for (GroupsQueueType::const_iterator citr = m_SelectionPools[TEAM_INDEX_ALLIANCE].SelectedGroups.begin(); citr != m_SelectionPools[TEAM_INDEX_ALLIANCE].SelectedGroups.end(); ++citr)
InviteGroupToBG((*citr), bg, (*citr)->GroupTeam);
for (GroupsQueueType::const_iterator citr = m_SelectionPools[TEAM_INDEX_HORDE].SelectedGroups.begin(); citr != m_SelectionPools[TEAM_INDEX_HORDE].SelectedGroups.end(); ++citr)
InviteGroupToBG((*citr), bg, (*citr)->GroupTeam);
if (!bg->HasFreeSlots())
{
// remove BG from BGFreeSlotQueue
bg->RemoveFromBGFreeSlotQueue();
}
}
}
// finished iterating through the bgs with free slots, maybe we need to create a new bg
BattleGround* bg_template = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
if (!bg_template)
{
sLog.outError("Battleground: Update: bg template not found for %u", bgTypeId);
return;
}
PvPDifficultyEntry const* bracketEntry = GetBattlegroundBracketById(bg_template->GetMapId(), bracket_id);
if (!bracketEntry)
{
sLog.outError("Battleground: Update: bg bracket entry not found for map %u bracket id %u", bg_template->GetMapId(), bracket_id);
return;
}
// get the min. players per team, properly for larger arenas as well. (must have full teams for arena matches!)
uint32 MinPlayersPerTeam = bg_template->GetMinPlayersPerTeam();
uint32 MaxPlayersPerTeam = bg_template->GetMaxPlayersPerTeam();
if (sBattleGroundMgr.isTesting())
MinPlayersPerTeam = 1;
if (bg_template->isArena())
{
if (sBattleGroundMgr.isArenaTesting())
{
MaxPlayersPerTeam = 1;
MinPlayersPerTeam = 1;
}
else
{
// this switch can be much shorter
MaxPlayersPerTeam = arenaType;
MinPlayersPerTeam = arenaType;
/*switch(arenaType)
{
case ARENA_TYPE_2v2:
MaxPlayersPerTeam = 2;
MinPlayersPerTeam = 2;
break;
case ARENA_TYPE_3v3:
MaxPlayersPerTeam = 3;
MinPlayersPerTeam = 3;
break;
case ARENA_TYPE_5v5:
MaxPlayersPerTeam = 5;
MinPlayersPerTeam = 5;
break;
}*/
}
}
m_SelectionPools[TEAM_INDEX_ALLIANCE].Init();
m_SelectionPools[TEAM_INDEX_HORDE].Init();
if (bg_template->isBattleGround())
{
// check if there is premade against premade match
if (CheckPremadeMatch(bracket_id, MinPlayersPerTeam, MaxPlayersPerTeam))
{
// create new battleground
BattleGround* bg2 = sBattleGroundMgr.CreateNewBattleGround(bgTypeId, bracketEntry, ARENA_TYPE_NONE, false);
if (!bg2)
{
sLog.outError("BattleGroundQueue::Update - Cannot create battleground: %u", bgTypeId);
return;
}
// invite those selection pools
for (uint8 i = 0; i < PVP_TEAM_COUNT; ++i)
for (GroupsQueueType::const_iterator citr = m_SelectionPools[TEAM_INDEX_ALLIANCE + i].SelectedGroups.begin(); citr != m_SelectionPools[TEAM_INDEX_ALLIANCE + i].SelectedGroups.end(); ++citr)
InviteGroupToBG((*citr), bg2, (*citr)->GroupTeam);
// start bg
bg2->StartBattleGround();
// clear structures
m_SelectionPools[TEAM_INDEX_ALLIANCE].Init();
m_SelectionPools[TEAM_INDEX_HORDE].Init();
}
}
// now check if there are in queues enough players to start new game of (normal battleground, or non-rated arena)
if (!isRated)
{
// if there are enough players in pools, start new battleground or non rated arena
if (CheckNormalMatch(bg_template, bracket_id, MinPlayersPerTeam, MaxPlayersPerTeam)
|| (bg_template->isArena() && CheckSkirmishForSameFaction(bracket_id, MinPlayersPerTeam)))
{
// we successfully created a pool
BattleGround* bg2 = sBattleGroundMgr.CreateNewBattleGround(bgTypeId, bracketEntry, arenaType, false);
if (!bg2)
{
sLog.outError("BattleGroundQueue::Update - Cannot create battleground: %u", bgTypeId);
return;
}
// invite those selection pools
for (uint8 i = 0; i < PVP_TEAM_COUNT; ++i)
for (GroupsQueueType::const_iterator citr = m_SelectionPools[TEAM_INDEX_ALLIANCE + i].SelectedGroups.begin(); citr != m_SelectionPools[TEAM_INDEX_ALLIANCE + i].SelectedGroups.end(); ++citr)
InviteGroupToBG((*citr), bg2, (*citr)->GroupTeam);
// start bg
bg2->StartBattleGround();
}
}
else if (bg_template->isArena())
{
// found out the minimum and maximum ratings the newly added team should battle against
// arenaRating is the rating of the latest joined team, or 0
// 0 is on (automatic update call) and we must set it to team's with longest wait time
if (!arenaRating)
{
GroupQueueInfo* front1 = nullptr;
GroupQueueInfo* front2 = nullptr;
if (!m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].empty())
{
front1 = m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].front();
arenaRating = front1->ArenaTeamRating;
}
if (!m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].empty())
{
front2 = m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].front();
arenaRating = front2->ArenaTeamRating;
}
if (front1 && front2)
{
if (front1->JoinTime < front2->JoinTime)
arenaRating = front1->ArenaTeamRating;
}
else if (!front1 && !front2)
return; // queues are empty
}
// set rating range
uint32 arenaMinRating = (arenaRating <= sBattleGroundMgr.GetMaxRatingDifference()) ? 0 : arenaRating - sBattleGroundMgr.GetMaxRatingDifference();
uint32 arenaMaxRating = arenaRating + sBattleGroundMgr.GetMaxRatingDifference();
// if max rating difference is set and the time past since server startup is greater than the rating discard time
// (after what time the ratings aren't taken into account when making teams) then
// the discard time is current_time - time_to_discard, teams that joined after that, will have their ratings taken into account
// else leave the discard time on 0, this way all ratings will be discarded
uint32 discardTime = WorldTimer::getMSTime() - sBattleGroundMgr.GetRatingDiscardTimer();
// we need to find 2 teams which will play next game
GroupsQueueType::iterator itr_team[PVP_TEAM_COUNT];
// optimalization : --- we dont need to use selection_pools - each update we select max 2 groups
for (uint8 i = BG_QUEUE_PREMADE_ALLIANCE; i < BG_QUEUE_NORMAL_ALLIANCE; ++i)
{
// take the group that joined first
itr_team[i] = m_QueuedGroups[bracket_id][i].begin();
for (; itr_team[i] != m_QueuedGroups[bracket_id][i].end(); ++(itr_team[i]))
{
// if group match conditions, then add it to pool
if (!(*itr_team[i])->IsInvitedToBGInstanceGUID
&& (((*itr_team[i])->ArenaTeamRating >= arenaMinRating && (*itr_team[i])->ArenaTeamRating <= arenaMaxRating)
|| (*itr_team[i])->JoinTime < discardTime))
{
m_SelectionPools[i].AddGroup((*itr_team[i]), MaxPlayersPerTeam);
// break for cycle to be able to start selecting another group from same faction queue
break;
}
}
}
// now we are done if we have 2 groups - ali vs horde!
// if we don't have, we must try to continue search in same queue
// tmp variables are correctly set
// this code isn't much userfriendly - but it is supposed to continue search for mathing group in HORDE queue
if (m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount() == 0 && m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount())
{
itr_team[TEAM_INDEX_ALLIANCE] = itr_team[TEAM_INDEX_HORDE];
++itr_team[TEAM_INDEX_ALLIANCE];
for (; itr_team[TEAM_INDEX_ALLIANCE] != m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].end(); ++(itr_team[TEAM_INDEX_ALLIANCE]))
{
if (!(*itr_team[TEAM_INDEX_ALLIANCE])->IsInvitedToBGInstanceGUID
&& (((*itr_team[TEAM_INDEX_ALLIANCE])->ArenaTeamRating >= arenaMinRating && (*itr_team[TEAM_INDEX_ALLIANCE])->ArenaTeamRating <= arenaMaxRating)
|| (*itr_team[TEAM_INDEX_ALLIANCE])->JoinTime < discardTime))
{
m_SelectionPools[TEAM_INDEX_ALLIANCE].AddGroup((*itr_team[TEAM_INDEX_ALLIANCE]), MaxPlayersPerTeam);
break;
}
}
}
// this code isn't much userfriendly - but it is supposed to continue search for mathing group in ALLIANCE queue
if (m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount() == 0 && m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount())
{
itr_team[TEAM_INDEX_HORDE] = itr_team[TEAM_INDEX_ALLIANCE];
++itr_team[TEAM_INDEX_HORDE];
for (; itr_team[TEAM_INDEX_HORDE] != m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].end(); ++(itr_team[TEAM_INDEX_HORDE]))
{
if (!(*itr_team[TEAM_INDEX_HORDE])->IsInvitedToBGInstanceGUID
&& (((*itr_team[TEAM_INDEX_HORDE])->ArenaTeamRating >= arenaMinRating && (*itr_team[TEAM_INDEX_HORDE])->ArenaTeamRating <= arenaMaxRating)
|| (*itr_team[TEAM_INDEX_HORDE])->JoinTime < discardTime))
{
m_SelectionPools[TEAM_INDEX_HORDE].AddGroup((*itr_team[TEAM_INDEX_HORDE]), MaxPlayersPerTeam);
break;
}
}
}
// if we have 2 teams, then start new arena and invite players!
if (m_SelectionPools[TEAM_INDEX_ALLIANCE].GetPlayerCount() && m_SelectionPools[TEAM_INDEX_HORDE].GetPlayerCount())
{
BattleGround* arena = sBattleGroundMgr.CreateNewBattleGround(bgTypeId, bracketEntry, arenaType, true);
if (!arena)
{
sLog.outError("BattlegroundQueue::Update couldn't create arena instance for rated arena match!");
return;
}
(*(itr_team[TEAM_INDEX_ALLIANCE]))->OpponentsTeamRating = (*(itr_team[TEAM_INDEX_HORDE]))->ArenaTeamRating;
DEBUG_LOG("setting oposite teamrating for team %u to %u", (*(itr_team[TEAM_INDEX_ALLIANCE]))->ArenaTeamId, (*(itr_team[TEAM_INDEX_ALLIANCE]))->OpponentsTeamRating);
(*(itr_team[TEAM_INDEX_HORDE]))->OpponentsTeamRating = (*(itr_team[TEAM_INDEX_ALLIANCE]))->ArenaTeamRating;
DEBUG_LOG("setting oposite teamrating for team %u to %u", (*(itr_team[TEAM_INDEX_HORDE]))->ArenaTeamId, (*(itr_team[TEAM_INDEX_HORDE]))->OpponentsTeamRating);
// now we must move team if we changed its faction to another faction queue, because then we will spam log by errors in Queue::RemovePlayer
if ((*(itr_team[TEAM_INDEX_ALLIANCE]))->GroupTeam != ALLIANCE)
{
// add to alliance queue
m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].push_front(*(itr_team[TEAM_INDEX_ALLIANCE]));
// erase from horde queue
m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].erase(itr_team[TEAM_INDEX_ALLIANCE]);
itr_team[TEAM_INDEX_ALLIANCE] = m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].begin();
}
if ((*(itr_team[TEAM_INDEX_HORDE]))->GroupTeam != HORDE)
{
m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].push_front(*(itr_team[TEAM_INDEX_HORDE]));
m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].erase(itr_team[TEAM_INDEX_HORDE]);
itr_team[TEAM_INDEX_HORDE] = m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].begin();
}
InviteGroupToBG(*(itr_team[TEAM_INDEX_ALLIANCE]), arena, ALLIANCE);
InviteGroupToBG(*(itr_team[TEAM_INDEX_HORDE]), arena, HORDE);
DEBUG_LOG("Starting rated arena match!");
arena->StartBattleGround();
}
}
}
/*********************************************************/
/*** BATTLEGROUND QUEUE EVENTS ***/
/*********************************************************/
bool BGQueueInviteEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/)
{
Player* plr = sObjectMgr.GetPlayer(m_PlayerGuid);
// player logged off (we should do nothing, he is correctly removed from queue in another procedure)
if (!plr)
return true;
BattleGround* bg = sBattleGroundMgr.GetBattleGround(m_BgInstanceGUID, m_BgTypeId);
// if battleground ended and its instance deleted - do nothing
if (!bg)
return true;
BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(bg->GetTypeID(), bg->GetArenaType());
uint32 queueSlot = plr->GetBattleGroundQueueIndex(bgQueueTypeId);
if (queueSlot < PLAYER_MAX_BATTLEGROUND_QUEUES) // player is in queue or in battleground
{
// check if player is invited to this bg
BattleGroundQueue& bgQueue = sBattleGroundMgr.m_BattleGroundQueues[bgQueueTypeId];
if (bgQueue.IsPlayerInvited(m_PlayerGuid, m_BgInstanceGUID, m_RemoveTime))
{
WorldPacket data;
// we must send remaining time in queue
sBattleGroundMgr.BuildBattleGroundStatusPacket(data, bg, queueSlot, STATUS_WAIT_JOIN, INVITE_ACCEPT_WAIT_TIME - INVITATION_REMIND_TIME, 0, m_ArenaType, TEAM_NONE);
plr->GetSession()->SendPacket(data);
}
}
return true; // event will be deleted
}
void BGQueueInviteEvent::Abort(uint64 /*e_time*/)
{
// do nothing
}
/*
this event has many possibilities when it is executed:
1. player is in battleground ( he clicked enter on invitation window )
2. player left battleground queue and he isn't there any more
3. player left battleground queue and he joined it again and IsInvitedToBGInstanceGUID = 0
4. player left queue and he joined again and he has been invited to same battleground again -> we should not remove him from queue yet
5. player is invited to bg and he didn't choose what to do and timer expired - only in this condition we should call queue::RemovePlayer
we must remove player in the 5. case even if battleground object doesn't exist!
*/
bool BGQueueRemoveEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/)
{
Player* plr = sObjectMgr.GetPlayer(m_PlayerGuid);
if (!plr)
// player logged off (we should do nothing, he is correctly removed from queue in another procedure)
return true;
BattleGround* bg = sBattleGroundMgr.GetBattleGround(m_BgInstanceGUID, m_BgTypeId);
// battleground can be deleted already when we are removing queue info
// bg pointer can be nullptr! so use it carefully!
uint32 queueSlot = plr->GetBattleGroundQueueIndex(m_BgQueueTypeId);
if (queueSlot < PLAYER_MAX_BATTLEGROUND_QUEUES) // player is in queue, or in Battleground
{
// check if player is in queue for this BG and if we are removing his invite event
BattleGroundQueue& bgQueue = sBattleGroundMgr.m_BattleGroundQueues[m_BgQueueTypeId];
if (bgQueue.IsPlayerInvited(m_PlayerGuid, m_BgInstanceGUID, m_RemoveTime))
{
DEBUG_LOG("Battleground: removing player %u from bg queue for instance %u because of not pressing enter battle in time.", plr->GetGUIDLow(), m_BgInstanceGUID);
plr->RemoveBattleGroundQueueId(m_BgQueueTypeId);
bgQueue.RemovePlayer(m_PlayerGuid, true);
// update queues if battleground isn't ended
if (bg && bg->isBattleGround() && bg->GetStatus() != STATUS_WAIT_LEAVE)
sBattleGroundMgr.ScheduleQueueUpdate(0, ARENA_TYPE_NONE, m_BgQueueTypeId, m_BgTypeId, bg->GetBracketId());
WorldPacket data;
sBattleGroundMgr.BuildBattleGroundStatusPacket(data, bg, queueSlot, STATUS_NONE, 0, 0, ARENA_TYPE_NONE, TEAM_NONE);
plr->GetSession()->SendPacket(data);
}
}
// event will be deleted
return true;
}
void BGQueueRemoveEvent::Abort(uint64 /*e_time*/)
{
// do nothing
}
/*********************************************************/
/*** BATTLEGROUND MANAGER ***/
/*********************************************************/
BattleGroundMgr::BattleGroundMgr() : m_NextAutoDistributionTime(0), m_AutoDistributionTimeChecker(0), m_ArenaTesting(false)
{
for (uint8 i = BATTLEGROUND_TYPE_NONE; i < MAX_BATTLEGROUND_TYPE_ID; ++i)
m_BattleGrounds[i].clear();
m_NextRatingDiscardUpdate = sWorld.getConfig(CONFIG_UINT32_ARENA_RATING_DISCARD_TIMER);
m_Testing = false;
}
BattleGroundMgr::~BattleGroundMgr()
{
DeleteAllBattleGrounds();
}
void BattleGroundMgr::DeleteAllBattleGrounds()
{
// will also delete template bgs:
for (uint8 i = BATTLEGROUND_TYPE_NONE; i < MAX_BATTLEGROUND_TYPE_ID; ++i)
{
for (BattleGroundSet::iterator itr = m_BattleGrounds[i].begin(); itr != m_BattleGrounds[i].end();)
{
BattleGround* bg = itr->second;
++itr; // step from invalidate iterator pos in result element remove in ~BattleGround call
delete bg;
}
}
}
// used to update running battlegrounds, and delete finished ones
void BattleGroundMgr::Update(uint32 diff)
{
// update scheduled queues
if (!m_QueueUpdateScheduler.empty())
{
std::vector<uint64> scheduled;
{
// create mutex
// std::lock_guard<std::mutex> guard(SchedulerLock);
// copy vector and clear the other
scheduled = std::vector<uint64>(m_QueueUpdateScheduler);
m_QueueUpdateScheduler.clear();
// release lock
}
for (uint8 i = 0; i < scheduled.size(); ++i)
{
uint32 arenaRating = scheduled[i] >> 32;
ArenaType arenaType = ArenaType(scheduled[i] >> 24 & 255);
BattleGroundQueueTypeId bgQueueTypeId = BattleGroundQueueTypeId(scheduled[i] >> 16 & 255);
BattleGroundTypeId bgTypeId = BattleGroundTypeId((scheduled[i] >> 8) & 255);
BattleGroundBracketId bracket_id = BattleGroundBracketId(scheduled[i] & 255);
m_BattleGroundQueues[bgQueueTypeId].Update(bgTypeId, bracket_id, arenaType, arenaRating > 0, arenaRating);
}
}
// if rating difference counts, maybe force-update queues
if (sWorld.getConfig(CONFIG_UINT32_ARENA_MAX_RATING_DIFFERENCE) && sWorld.getConfig(CONFIG_UINT32_ARENA_RATING_DISCARD_TIMER))
{
// it's time to force update
if (m_NextRatingDiscardUpdate < diff)
{
// forced update for rated arenas (scan all, but skipped non rated)
DEBUG_LOG("BattleGroundMgr: UPDATING ARENA QUEUES");
for (uint8 qtype = BATTLEGROUND_QUEUE_2v2; qtype <= BATTLEGROUND_QUEUE_5v5; ++qtype)
for (uint8 bracket = BG_BRACKET_ID_FIRST; bracket < MAX_BATTLEGROUND_BRACKETS; ++bracket)
m_BattleGroundQueues[qtype].Update(
BATTLEGROUND_AA, BattleGroundBracketId(bracket),
BattleGroundMgr::BGArenaType(BattleGroundQueueTypeId(qtype)), true, 0);
m_NextRatingDiscardUpdate = sWorld.getConfig(CONFIG_UINT32_ARENA_RATING_DISCARD_TIMER);
}
else
m_NextRatingDiscardUpdate -= diff;
}
if (sWorld.getConfig(CONFIG_BOOL_ARENA_AUTO_DISTRIBUTE_POINTS))
{
if (m_AutoDistributionTimeChecker < diff)
{
if (sWorld.GetGameTime() > m_NextAutoDistributionTime)
{
DistributeArenaPoints();
m_NextAutoDistributionTime = time_t(m_NextAutoDistributionTime + BATTLEGROUND_ARENA_POINT_DISTRIBUTION_DAY * sWorld.getConfig(CONFIG_UINT32_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS));
CharacterDatabase.PExecute("UPDATE saved_variables SET NextArenaPointDistributionTime = '" UI64FMTD "'", uint64(m_NextAutoDistributionTime));
}
m_AutoDistributionTimeChecker = 600000; // check 10 minutes
}
else
m_AutoDistributionTimeChecker -= diff;
}
}
void BattleGroundMgr::BuildBattleGroundStatusPacket(WorldPacket& data, BattleGround* bg, uint8 QueueSlot, uint8 StatusID, uint32 Time1, uint32 Time2, ArenaType arenatype, Team arenaTeam) const
{
// we can be in 2 queues in same time...
if (StatusID == 0 || !bg)
{
data.Initialize(SMSG_BATTLEFIELD_STATUS, 4 + 8);
data << uint32(QueueSlot); // queue id (0...1)
data << uint64(0);
return;
}
data.Initialize(SMSG_BATTLEFIELD_STATUS, (4 + 8 + 1 + 1 + 4 + 1 + 4 + 4 + 4));
data << uint32(QueueSlot); // queue id (0...1) - player can be in 2 queues in time
// uint64 in client
data << uint64(uint64(arenatype) | (uint64(0x0D) << 8) | (uint64(bg->GetTypeID()) << 16) | (uint64(0x1F90) << 48));
data << uint8(0); // 3.3.0, some level, only saw 80...
data << uint8(0); // 3.3.0, some level, only saw 80...
data << uint32(bg->GetClientInstanceID());
// alliance/horde for BG and skirmish/rated for Arenas
// following displays the minimap-icon 0 = faction icon 1 = arenaicon
data << uint8(bg->isRated());
data << uint32(StatusID); // status
switch (StatusID)
{
case STATUS_WAIT_QUEUE: // status_in_queue
data << uint32(Time1); // average wait time, milliseconds
data << uint32(Time2); // time in queue, updated every minute!, milliseconds
break;
case STATUS_WAIT_JOIN: // status_invite
data << uint32(bg->GetMapId()); // map id
data << uint64(0); // 3.3.5, unknown
data << uint32(Time1); // time to remove from queue, milliseconds
break;
case STATUS_IN_PROGRESS: // status_in_progress
data << uint32(bg->GetMapId()); // map id
data << uint64(0); // 3.3.5, unknown
data << uint32(Time1); // time to bg auto leave, 0 at bg start, 120000 after bg end, milliseconds
data << uint32(Time2); // time from bg start, milliseconds
data << uint8(arenaTeam == ALLIANCE ? 1 : 0); // arenaTeam (0 for horde, 1 for alliance)
break;
default:
sLog.outError("Unknown BG status!");
break;
}
}
void BattleGroundMgr::BuildPvpLogDataPacket(WorldPacket& data, BattleGround* bg) const
{
uint8 type = (bg->isArena() ? 1 : 0);
// last check on 3.0.3
data.Initialize(MSG_PVP_LOG_DATA, (1 + 1 + 4 + 40 * bg->GetPlayerScoresSize()));
data << uint8(type); // type (battleground=0/arena=1)
if (type) // arena
{
// it seems this must be according to BG_WINNER_A/H and _NOT_ BG_TEAM_A/H
for (int8 i = 1; i >= 0; --i)
{
uint32 pointsLost = bg->m_ArenaTeamRatingChanges[i] < 0 ? abs(bg->m_ArenaTeamRatingChanges[i]) : 0;
uint32 pointsGained = bg->m_ArenaTeamRatingChanges[i] > 0 ? bg->m_ArenaTeamRatingChanges[i] : 0;
data << uint32(pointsLost); // Rating Lost
data << uint32(pointsGained); // Rating gained
data << uint32(0); // Matchmaking Value
DEBUG_LOG("rating change: %d", bg->m_ArenaTeamRatingChanges[i]);
}
for (int8 i = 1; i >= 0; --i)
{
uint32 at_id = bg->m_ArenaTeamIds[i];
ArenaTeam* at = sObjectMgr.GetArenaTeamById(at_id);
if (at)
data << at->GetName();
else
data << (uint8)0;
}
}
if (bg->GetStatus() != STATUS_WAIT_LEAVE)
data << uint8(0); // bg not ended
else
{
data << uint8(1); // bg ended
data << uint8(bg->GetWinner() == ALLIANCE ? 1 : 0);// who win
}
data << (int32)(bg->GetPlayerScoresSize());
for (BattleGround::BattleGroundScoreMap::const_iterator itr = bg->GetPlayerScoresBegin(); itr != bg->GetPlayerScoresEnd(); ++itr)
{
const BattleGroundScore* score = itr->second;
data << ObjectGuid(itr->first);
data << (int32)score->KillingBlows;
if (type == 0)
{
data << (int32)score->HonorableKills;
data << (int32)score->Deaths;
data << (int32)(score->BonusHonor);
}
else
{
Team team = bg->GetPlayerTeam(itr->first);
if (!team)
if (Player* player = sObjectMgr.GetPlayer(itr->first))
team = player->GetTeam();
if (bg->GetWinner() == team && team != TEAM_NONE)
data << uint8(1);
else
data << uint8(0);
}
data << (int32)score->DamageDone; // damage done
data << (int32)score->HealingDone; // healing done
switch (bg->GetTypeID()) // battleground specific things
{
case BATTLEGROUND_AV:
data << (uint32)0x00000005; // count of next fields
data << (uint32)((BattleGroundAVScore*)score)->GraveyardsAssaulted; // GraveyardsAssaulted
data << (uint32)((BattleGroundAVScore*)score)->GraveyardsDefended; // GraveyardsDefended
data << (uint32)((BattleGroundAVScore*)score)->TowersAssaulted; // TowersAssaulted
data << (uint32)((BattleGroundAVScore*)score)->TowersDefended; // TowersDefended
data << (uint32)((BattleGroundAVScore*)score)->SecondaryObjectives; // SecondaryObjectives - free some of the Lieutnants
break;
case BATTLEGROUND_WS:
data << (uint32)0x00000002; // count of next fields
data << (uint32)((BattleGroundWGScore*)score)->FlagCaptures; // flag captures
data << (uint32)((BattleGroundWGScore*)score)->FlagReturns; // flag returns
break;
case BATTLEGROUND_AB:
data << (uint32)0x00000002; // count of next fields
data << (uint32)((BattleGroundABScore*)score)->BasesAssaulted; // bases asssulted
data << (uint32)((BattleGroundABScore*)score)->BasesDefended; // bases defended
break;
case BATTLEGROUND_EY:
data << (uint32)0x00000001; // count of next fields
data << (uint32)((BattleGroundEYScore*)score)->FlagCaptures; // flag captures
break;
case BATTLEGROUND_NA:
case BATTLEGROUND_BE:
case BATTLEGROUND_AA:
case BATTLEGROUND_RL:
case BATTLEGROUND_SA: // wotlk
case BATTLEGROUND_DS: // wotlk
case BATTLEGROUND_RV: // wotlk
case BATTLEGROUND_IC: // wotlk
case BATTLEGROUND_RB: // wotlk
data << (int32)0; // 0
break;
default:
DEBUG_LOG("Unhandled MSG_PVP_LOG_DATA for BG id %u", bg->GetTypeID());
data << (int32)0;
break;
}
}
}
void BattleGroundMgr::BuildGroupJoinedBattlegroundPacket(WorldPacket& data, GroupJoinBattlegroundResult result) const
{
data.Initialize(SMSG_GROUP_JOINED_BATTLEGROUND, 4);
data << int32(result);
if (result == ERR_BATTLEGROUND_JOIN_TIMED_OUT || result == ERR_BATTLEGROUND_JOIN_FAILED)
data << uint64(0); // player guid
}
void BattleGroundMgr::BuildUpdateWorldStatePacket(WorldPacket& data, uint32 field, uint32 value) const
{
data.Initialize(SMSG_UPDATE_WORLD_STATE, 4 + 4);
data << uint32(field);
data << uint32(value);
}
void BattleGroundMgr::BuildPlaySoundPacket(WorldPacket& data, uint32 soundid) const
{
data.Initialize(SMSG_PLAY_SOUND, 4);
data << uint32(soundid);
}
void BattleGroundMgr::BuildPlayerLeftBattleGroundPacket(WorldPacket& data, ObjectGuid guid) const
{
data.Initialize(SMSG_BATTLEGROUND_PLAYER_LEFT, 8);
data << ObjectGuid(guid);
}
void BattleGroundMgr::BuildPlayerJoinedBattleGroundPacket(WorldPacket& data, Player* plr) const
{
data.Initialize(SMSG_BATTLEGROUND_PLAYER_JOINED, 8);
data << plr->GetObjectGuid();
}
BattleGround* BattleGroundMgr::GetBattleGroundThroughClientInstance(uint32 instanceId, BattleGroundTypeId bgTypeId)
{
// cause at HandleBattleGroundJoinOpcode the clients sends the instanceid he gets from
// SMSG_BATTLEFIELD_LIST we need to find the battleground with this clientinstance-id
BattleGround* bg = GetBattleGroundTemplate(bgTypeId);
if (!bg)
return nullptr;
if (bg->isArena())
return GetBattleGround(instanceId, bgTypeId);
for (BattleGroundSet::iterator itr = m_BattleGrounds[bgTypeId].begin(); itr != m_BattleGrounds[bgTypeId].end(); ++itr)
{
if (itr->second->GetClientInstanceID() == instanceId)
return itr->second;
}
return nullptr;
}
BattleGround* BattleGroundMgr::GetBattleGround(uint32 InstanceID, BattleGroundTypeId bgTypeId)
{
// search if needed
BattleGroundSet::iterator itr;
if (bgTypeId == BATTLEGROUND_TYPE_NONE)
{
for (uint8 i = BATTLEGROUND_AV; i < MAX_BATTLEGROUND_TYPE_ID; ++i)
{
itr = m_BattleGrounds[i].find(InstanceID);
if (itr != m_BattleGrounds[i].end())
return itr->second;
}
return nullptr;
}
itr = m_BattleGrounds[bgTypeId].find(InstanceID);
return ((itr != m_BattleGrounds[bgTypeId].end()) ? itr->second : nullptr);
}
BattleGround* BattleGroundMgr::GetBattleGroundTemplate(BattleGroundTypeId bgTypeId)
{
// map is sorted and we can be sure that lowest instance id has only BG template
return m_BattleGrounds[bgTypeId].empty() ? nullptr : m_BattleGrounds[bgTypeId].begin()->second;
}
uint32 BattleGroundMgr::CreateClientVisibleInstanceId(BattleGroundTypeId bgTypeId, BattleGroundBracketId bracket_id)
{
if (IsArenaType(bgTypeId))
return 0; // arenas don't have client-instanceids
// we create here an instanceid, which is just for
// displaying this to the client and without any other use..
// the client-instanceIds are unique for each battleground-type
// the instance-id just needs to be as low as possible, beginning with 1
// the following works, because std::set is default ordered with "<"
// the optimalization would be to use as bitmask std::vector<uint32> - but that would only make code unreadable
uint32 lastId = 0;
ClientBattleGroundIdSet& ids = m_ClientBattleGroundIds[bgTypeId][bracket_id];
for (ClientBattleGroundIdSet::const_iterator itr = ids.begin(); itr != ids.end();)
{
if ((++lastId) != *itr) // if there is a gap between the ids, we will break..
break;
lastId = *itr;
}
ids.insert(lastId + 1);
return lastId + 1;
}
// create a new battleground that will really be used to play
BattleGround* BattleGroundMgr::CreateNewBattleGround(BattleGroundTypeId bgTypeId, PvPDifficultyEntry const* bracketEntry, ArenaType arenaType, bool isRated)
{
// get the template BG
BattleGround* bg_template = GetBattleGroundTemplate(bgTypeId);
if (!bg_template)
{
sLog.outError("BattleGround: CreateNewBattleGround - bg template not found for %u", bgTypeId);
return nullptr;
}
// for arenas there is random map used
if (bg_template->isArena())
{
BattleGroundTypeId arenas[] = { BATTLEGROUND_NA, BATTLEGROUND_BE, BATTLEGROUND_RL, BATTLEGROUND_DS, BATTLEGROUND_RV };
bgTypeId = arenas[urand(0, countof(arenas) - 1)];
bg_template = GetBattleGroundTemplate(bgTypeId);
if (!bg_template)
{
sLog.outError("BattleGround: CreateNewBattleGround - bg template not found for %u", bgTypeId);
return nullptr;
}
}
BattleGround* bg;
// create a copy of the BG template
switch (bgTypeId)
{
case BATTLEGROUND_AV:
bg = new BattleGroundAV(*(BattleGroundAV*)bg_template);
break;
case BATTLEGROUND_WS:
bg = new BattleGroundWS(*(BattleGroundWS*)bg_template);
break;
case BATTLEGROUND_AB:
bg = new BattleGroundAB(*(BattleGroundAB*)bg_template);
break;
case BATTLEGROUND_NA:
bg = new BattleGroundNA(*(BattleGroundNA*)bg_template);
break;
case BATTLEGROUND_BE:
bg = new BattleGroundBE(*(BattleGroundBE*)bg_template);
break;
case BATTLEGROUND_AA:
bg = new BattleGroundAA(*(BattleGroundAA*)bg_template);
break;
case BATTLEGROUND_EY:
bg = new BattleGroundEY(*(BattleGroundEY*)bg_template);
break;
case BATTLEGROUND_RL:
bg = new BattleGroundRL(*(BattleGroundRL*)bg_template);
break;
case BATTLEGROUND_SA:
bg = new BattleGroundSA(*(BattleGroundSA*)bg_template);
break;
case BATTLEGROUND_DS:
bg = new BattleGroundDS(*(BattleGroundDS*)bg_template);
break;
case BATTLEGROUND_RV:
bg = new BattleGroundRV(*(BattleGroundRV*)bg_template);
break;
case BATTLEGROUND_IC:
bg = new BattleGroundIC(*(BattleGroundIC*)bg_template);
break;
case BATTLEGROUND_RB:
bg = new BattleGroundRB(*(BattleGroundRB*)bg_template);
break;
default:
// error, but it is handled few lines above
return nullptr;
}
// set before Map creating for let use proper difficulty
bg->SetBracket(bracketEntry);
// will also set m_bgMap, instanceid
sMapMgr.CreateBgMap(bg->GetMapId(), bg);
bg->SetClientInstanceID(CreateClientVisibleInstanceId(bgTypeId, bracketEntry->GetBracketId()));
// reset the new bg (set status to status_wait_queue from status_none)
bg->Reset();
// start the joining of the bg
bg->SetStatus(STATUS_WAIT_JOIN);
bg->SetArenaType(arenaType);
bg->SetRated(isRated);
return bg;
}
// used to create the BG templates
uint32 BattleGroundMgr::CreateBattleGround(BattleGroundTypeId bgTypeId, bool IsArena, uint32 MinPlayersPerTeam, uint32 MaxPlayersPerTeam, uint32 LevelMin, uint32 LevelMax, char const* BattleGroundName, uint32 MapID, float Team1StartLocX, float Team1StartLocY, float Team1StartLocZ, float Team1StartLocO, float Team2StartLocX, float Team2StartLocY, float Team2StartLocZ, float Team2StartLocO, float StartMaxDist)
{
// Create the BG
BattleGround* bg;
switch (bgTypeId)
{
case BATTLEGROUND_AV: bg = new BattleGroundAV; break;
case BATTLEGROUND_WS: bg = new BattleGroundWS; break;
case BATTLEGROUND_AB: bg = new BattleGroundAB; break;
case BATTLEGROUND_NA: bg = new BattleGroundNA; break;
case BATTLEGROUND_BE: bg = new BattleGroundBE; break;
case BATTLEGROUND_AA: bg = new BattleGroundAA; break;
case BATTLEGROUND_EY: bg = new BattleGroundEY; break;
case BATTLEGROUND_RL: bg = new BattleGroundRL; break;
case BATTLEGROUND_SA: bg = new BattleGroundSA; break;
case BATTLEGROUND_DS: bg = new BattleGroundDS; break;
case BATTLEGROUND_RV: bg = new BattleGroundRV; break;
case BATTLEGROUND_IC: bg = new BattleGroundIC; break;
case BATTLEGROUND_RB: bg = new BattleGroundRB; break;
default: bg = new BattleGround; break; // placeholder for non implemented BG
}
bg->SetMapId(MapID);
bg->SetTypeID(bgTypeId);
bg->SetArenaorBGType(IsArena);
bg->SetMinPlayersPerTeam(MinPlayersPerTeam);
bg->SetMaxPlayersPerTeam(MaxPlayersPerTeam);
bg->SetMinPlayers(MinPlayersPerTeam * 2);
bg->SetMaxPlayers(MaxPlayersPerTeam * 2);
bg->SetName(BattleGroundName);
bg->SetTeamStartLoc(ALLIANCE, Team1StartLocX, Team1StartLocY, Team1StartLocZ, Team1StartLocO);
bg->SetTeamStartLoc(HORDE, Team2StartLocX, Team2StartLocY, Team2StartLocZ, Team2StartLocO);
bg->SetStartMaxDist(StartMaxDist);
bg->SetLevelRange(LevelMin, LevelMax);
// add bg to update list
AddBattleGround(bg->GetInstanceID(), bg->GetTypeID(), bg);
// return some not-null value, bgTypeId is good enough for me
return bgTypeId;
}
void BattleGroundMgr::CreateInitialBattleGrounds()
{
uint32 count = 0;
// 0 1 2 3 4 5 6 7
QueryResult* result = WorldDatabase.Query("SELECT id, MinPlayersPerTeam,MaxPlayersPerTeam,AllianceStartLoc,AllianceStartO,HordeStartLoc,HordeStartO,StartMaxDist FROM battleground_template");
if (!result)
{
BarGoLink bar(1);
bar.step();
sLog.outErrorDb(">> Loaded 0 battlegrounds. DB table `battleground_template` is empty.");
sLog.outString();
return;
}
BarGoLink bar(result->GetRowCount());
do
{
Field* fields = result->Fetch();
bar.step();
uint32 bgTypeID_ = fields[0].GetUInt32();
// can be overwrite by values from DB
BattlemasterListEntry const* bl = sBattlemasterListStore.LookupEntry(bgTypeID_);
if (!bl)
{
sLog.outError("Battleground ID %u not found in BattlemasterList.dbc. Battleground not created.", bgTypeID_);
continue;
}
BattleGroundTypeId bgTypeID = BattleGroundTypeId(bgTypeID_);
bool IsArena = (bl->type == TYPE_ARENA);
uint32 MinPlayersPerTeam = fields[1].GetUInt32();
uint32 MaxPlayersPerTeam = fields[2].GetUInt32();
// check values from DB
if (MaxPlayersPerTeam == 0)
{
sLog.outErrorDb("Table `battleground_template` for id %u doesn't allow any player per team settings. BG not created.", bgTypeID);
continue;
}
if (MinPlayersPerTeam > MaxPlayersPerTeam)
{
MinPlayersPerTeam = MaxPlayersPerTeam;
sLog.outErrorDb("Table `battleground_template` for id %u has min players > max players per team settings. Min players will use same value as max players.", bgTypeID);
}
float AStartLoc[4];
float HStartLoc[4];
uint32 start1 = fields[3].GetUInt32();
WorldSafeLocsEntry const* start = sWorldSafeLocsStore.LookupEntry(start1);
if (start)
{
AStartLoc[0] = start->x;
AStartLoc[1] = start->y;
AStartLoc[2] = start->z;
AStartLoc[3] = fields[4].GetFloat();
}
else if (bgTypeID == BATTLEGROUND_AA || bgTypeID == BATTLEGROUND_RB)
{
AStartLoc[0] = 0;
AStartLoc[1] = 0;
AStartLoc[2] = 0;
AStartLoc[3] = fields[4].GetFloat();
}
else
{
sLog.outErrorDb("Table `battleground_template` for id %u have nonexistent WorldSafeLocs.dbc id %u in field `AllianceStartLoc`. BG not created.", bgTypeID, start1);
continue;
}
uint32 start2 = fields[5].GetUInt32();
start = sWorldSafeLocsStore.LookupEntry(start2);
if (start)
{
HStartLoc[0] = start->x;
HStartLoc[1] = start->y;
HStartLoc[2] = start->z;
HStartLoc[3] = fields[6].GetFloat();
}
else if (bgTypeID == BATTLEGROUND_AA || bgTypeID == BATTLEGROUND_RB)
{
HStartLoc[0] = 0;
HStartLoc[1] = 0;
HStartLoc[2] = 0;
HStartLoc[3] = fields[6].GetFloat();
}
else
{
sLog.outErrorDb("Table `battleground_template` for id %u have nonexistent WorldSafeLocs.dbc id %u in field `HordeStartLoc`. BG not created.", bgTypeID, start2);
continue;
}
float startMaxDist = fields[7].GetFloat();
// sLog.outDetail("Creating battleground %s, %u-%u", bl->name[sWorld.GetDBClang()], MinLvl, MaxLvl);
if (!CreateBattleGround(bgTypeID, IsArena, MinPlayersPerTeam, MaxPlayersPerTeam, bl->minLevel, bl->maxLevel, bl->name[sWorld.GetDefaultDbcLocale()], bl->mapid[0], AStartLoc[0], AStartLoc[1], AStartLoc[2], AStartLoc[3], HStartLoc[0], HStartLoc[1], HStartLoc[2], HStartLoc[3], startMaxDist))
continue;
++count;
}
while (result->NextRow());
delete result;
sLog.outString(">> Loaded %u battlegrounds", count);
sLog.outString();
}
void BattleGroundMgr::InitAutomaticArenaPointDistribution()
{
if (sWorld.getConfig(CONFIG_BOOL_ARENA_AUTO_DISTRIBUTE_POINTS))
{
QueryResult* result = CharacterDatabase.Query("SELECT NextArenaPointDistributionTime FROM saved_variables");
if (!result) // if not set generate time for next wednesday
{
// generate time by config on first server launch
time_t curTime = time(nullptr);
tm localTm = *localtime(&curTime);
localTm.tm_hour = sWorld.getConfig(CONFIG_UINT32_QUEST_DAILY_RESET_HOUR);
localTm.tm_min = 0;
localTm.tm_sec = 0;
localTm.tm_mday += ((7 - localTm.tm_wday + sWorld.getConfig(CONFIG_UINT32_ARENA_FIRST_RESET_DAY)) % 7);
localTm.tm_isdst = -1;
m_NextAutoDistributionTime = mktime(&localTm);
CharacterDatabase.PExecute("INSERT INTO saved_variables (NextArenaPointDistributionTime) VALUES ('" UI64FMTD "')", uint64(m_NextAutoDistributionTime));
}
else
{
m_NextAutoDistributionTime = time_t((*result)[0].GetUInt64());
delete result;
}
//uint32 dayofweek = sWorld.getConfig(CONFIG_UINT32_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS);
}
}
void BattleGroundMgr::DistributeArenaPoints() const
{
// used to distribute arena points based on last week's stats
sWorld.SendWorldText(LANG_DIST_ARENA_POINTS_START);
sWorld.SendWorldText(LANG_DIST_ARENA_POINTS_ONLINE_START);
// temporary structure for storing maximum points to add values for all players
std::map<uint32, uint32> PlayerPoints;
// at first update all points for all team members
for (ObjectMgr::ArenaTeamMap::iterator team_itr = sObjectMgr.GetArenaTeamMapBegin(); team_itr != sObjectMgr.GetArenaTeamMapEnd(); ++team_itr)
{
if (ArenaTeam* at = team_itr->second)
{
at->UpdateArenaPointsHelper(PlayerPoints);
}
}
// cycle that gives points to all players
for (std::map<uint32, uint32>::iterator plr_itr = PlayerPoints.begin(); plr_itr != PlayerPoints.end(); ++plr_itr)
{
// update to database
CharacterDatabase.PExecute("UPDATE characters SET arenaPoints = arenaPoints + '%u' WHERE guid = '%u'", plr_itr->second, plr_itr->first);
// add points if player is online
if (Player* pl = sObjectMgr.GetPlayer(ObjectGuid(HIGHGUID_PLAYER, plr_itr->first)))
pl->ModifyArenaPoints(plr_itr->second);
}
PlayerPoints.clear();
sWorld.SendWorldText(LANG_DIST_ARENA_POINTS_ONLINE_END);
sWorld.SendWorldText(LANG_DIST_ARENA_POINTS_TEAM_START);
for (ObjectMgr::ArenaTeamMap::iterator titr = sObjectMgr.GetArenaTeamMapBegin(); titr != sObjectMgr.GetArenaTeamMapEnd(); ++titr)
{
if (ArenaTeam* at = titr->second)
{
at->FinishWeek(); // set played this week etc values to 0 in memory, too
at->SaveToDB(); // save changes
at->NotifyStatsChanged(); // notify the players of the changes
}
}
sWorld.SendWorldText(LANG_DIST_ARENA_POINTS_TEAM_END);
sWorld.SendWorldText(LANG_DIST_ARENA_POINTS_END);
}
void BattleGroundMgr::BuildBattleGroundListPacket(WorldPacket& data, ObjectGuid guid, Player* plr, BattleGroundTypeId bgTypeId, uint8 fromWhere) const
{
if (!plr)
return;
data.Initialize(SMSG_BATTLEFIELD_LIST);
data << guid; // battlemaster guid
data << uint8(fromWhere); // from where you joined
data << uint32(bgTypeId); // battleground id
data << uint8(0); // unk
data << uint8(0); // unk
// Rewards
data << uint8(0); // 3.3.3 hasWin
data << uint32(0); // 3.3.3 winHonor
data << uint32(0); // 3.3.3 winArena
data << uint32(0); // 3.3.3 lossHonor
uint8 isRandom = 0;
data << uint8(isRandom); // 3.3.3 isRandom
if (isRandom)
{
// Rewards (random)
data << uint8(0); // 3.3.3 hasWin_Random
data << uint32(0); // 3.3.3 winHonor_Random
data << uint32(0); // 3.3.3 winArena_Random
data << uint32(0); // 3.3.3 lossHonor_Random
}
if (bgTypeId == BATTLEGROUND_AA) // arena
{
data << uint32(0); // arena - no instances showed
}
else // battleground
{
size_t count_pos = data.wpos();
uint32 count = 0;
data << uint32(0); // number of bg instances
if (BattleGround* bgTemplate = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId))
{
// expected bracket entry
if (PvPDifficultyEntry const* bracketEntry = GetBattlegroundBracketByLevel(bgTemplate->GetMapId(), plr->getLevel()))
{
BattleGroundBracketId bracketId = bracketEntry->GetBracketId();
ClientBattleGroundIdSet const& ids = m_ClientBattleGroundIds[bgTypeId][bracketId];
for (ClientBattleGroundIdSet::const_iterator itr = ids.begin(); itr != ids.end(); ++itr)
{
data << uint32(*itr);
++count;
}
data.put<uint32>(count_pos, count);
}
}
}
}
void BattleGroundMgr::SendToBattleGround(Player* pl, uint32 instanceId, BattleGroundTypeId bgTypeId)
{
BattleGround* bg = GetBattleGround(instanceId, bgTypeId);
if (bg)
{
uint32 mapid = bg->GetMapId();
float x, y, z, O;
Team team = pl->GetBGTeam();
if (team == 0)
team = pl->GetTeam();
bg->GetTeamStartLoc(team, x, y, z, O);
DETAIL_LOG("BATTLEGROUND: Sending %s to map %u, X %f, Y %f, Z %f, O %f", pl->GetName(), mapid, x, y, z, O);
pl->TeleportTo(mapid, x, y, z, O);
}
else
{
sLog.outError("player %u trying to port to nonexistent bg instance %u", pl->GetGUIDLow(), instanceId);
}
}
bool BattleGroundMgr::IsArenaType(BattleGroundTypeId bgTypeId)
{
switch (bgTypeId)
{
case BATTLEGROUND_NA:
case BATTLEGROUND_BE:
case BATTLEGROUND_RL:
case BATTLEGROUND_DS:
case BATTLEGROUND_RV:
case BATTLEGROUND_AA:
return true;
default:
return false;
};
}
BattleGroundQueueTypeId BattleGroundMgr::BGQueueTypeId(BattleGroundTypeId bgTypeId, ArenaType arenaType)
{
switch (bgTypeId)
{
case BATTLEGROUND_WS:
return BATTLEGROUND_QUEUE_WS;
case BATTLEGROUND_AB:
return BATTLEGROUND_QUEUE_AB;
case BATTLEGROUND_AV:
return BATTLEGROUND_QUEUE_AV;
case BATTLEGROUND_EY:
return BATTLEGROUND_QUEUE_EY;
case BATTLEGROUND_SA:
return BATTLEGROUND_QUEUE_SA;
case BATTLEGROUND_IC:
return BATTLEGROUND_QUEUE_IC;
case BATTLEGROUND_RB:
return BATTLEGROUND_QUEUE_NONE;
case BATTLEGROUND_AA:
case BATTLEGROUND_NA:
case BATTLEGROUND_RL:
case BATTLEGROUND_BE:
case BATTLEGROUND_DS:
case BATTLEGROUND_RV:
switch (arenaType)
{
case ARENA_TYPE_2v2:
return BATTLEGROUND_QUEUE_2v2;
case ARENA_TYPE_3v3:
return BATTLEGROUND_QUEUE_3v3;
case ARENA_TYPE_5v5:
return BATTLEGROUND_QUEUE_5v5;
default:
return BATTLEGROUND_QUEUE_NONE;
}
default:
return BATTLEGROUND_QUEUE_NONE;
}
}
BattleGroundTypeId BattleGroundMgr::BGTemplateId(BattleGroundQueueTypeId bgQueueTypeId)
{
switch (bgQueueTypeId)
{
case BATTLEGROUND_QUEUE_WS:
return BATTLEGROUND_WS;
case BATTLEGROUND_QUEUE_AB:
return BATTLEGROUND_AB;
case BATTLEGROUND_QUEUE_AV:
return BATTLEGROUND_AV;
case BATTLEGROUND_QUEUE_EY:
return BATTLEGROUND_EY;
case BATTLEGROUND_QUEUE_SA:
return BATTLEGROUND_SA;
case BATTLEGROUND_QUEUE_IC:
return BATTLEGROUND_IC;
case BATTLEGROUND_QUEUE_2v2:
case BATTLEGROUND_QUEUE_3v3:
case BATTLEGROUND_QUEUE_5v5:
return BATTLEGROUND_AA;
default:
return BattleGroundTypeId(0); // used for unknown template (it exist and do nothing)
}
}
ArenaType BattleGroundMgr::BGArenaType(BattleGroundQueueTypeId bgQueueTypeId)
{
switch (bgQueueTypeId)
{
case BATTLEGROUND_QUEUE_2v2:
return ARENA_TYPE_2v2;
case BATTLEGROUND_QUEUE_3v3:
return ARENA_TYPE_3v3;
case BATTLEGROUND_QUEUE_5v5:
return ARENA_TYPE_5v5;
default:
return ARENA_TYPE_NONE;
}
}
void BattleGroundMgr::ToggleTesting()
{
m_Testing = !m_Testing;
if (m_Testing)
sWorld.SendWorldText(LANG_DEBUG_BG_ON);
else
sWorld.SendWorldText(LANG_DEBUG_BG_OFF);
}
void BattleGroundMgr::ToggleArenaTesting()
{
m_ArenaTesting = !m_ArenaTesting;
if (m_ArenaTesting)
sWorld.SendWorldText(LANG_DEBUG_ARENA_ON);
else
sWorld.SendWorldText(LANG_DEBUG_ARENA_OFF);
}
void BattleGroundMgr::ScheduleQueueUpdate(uint32 arenaRating, ArenaType arenaType, BattleGroundQueueTypeId bgQueueTypeId, BattleGroundTypeId bgTypeId, BattleGroundBracketId bracket_id)
{
// std::lock_guard<std::mutex> guard(SchedulerLock);
// we will use only 1 number created of bgTypeId and bracket_id
uint64 schedule_id = ((uint64)arenaRating << 32) | (arenaType << 24) | (bgQueueTypeId << 16) | (bgTypeId << 8) | bracket_id;
bool found = false;
for (uint8 i = 0; i < m_QueueUpdateScheduler.size(); ++i)
{
if (m_QueueUpdateScheduler[i] == schedule_id)
{
found = true;
break;
}
}
if (!found)
m_QueueUpdateScheduler.push_back(schedule_id);
}
uint32 BattleGroundMgr::GetMaxRatingDifference() const
{
// this is for stupid people who can't use brain and set max rating difference to 0
uint32 diff = sWorld.getConfig(CONFIG_UINT32_ARENA_MAX_RATING_DIFFERENCE);
if (diff == 0)
diff = 5000;
return diff;
}
uint32 BattleGroundMgr::GetRatingDiscardTimer() const
{
return sWorld.getConfig(CONFIG_UINT32_ARENA_RATING_DISCARD_TIMER);
}
uint32 BattleGroundMgr::GetPrematureFinishTime() const
{
return sWorld.getConfig(CONFIG_UINT32_BATTLEGROUND_PREMATURE_FINISH_TIMER);
}
void BattleGroundMgr::LoadBattleMastersEntry()
{
mBattleMastersMap.clear(); // need for reload case
QueryResult* result = WorldDatabase.Query("SELECT entry,bg_template FROM battlemaster_entry");
uint32 count = 0;
if (!result)
{
BarGoLink bar(1);
bar.step();
sLog.outString(">> Loaded 0 battlemaster entries - table is empty!");
sLog.outString();
return;
}
BarGoLink bar(result->GetRowCount());
do
{
++count;
bar.step();
Field* fields = result->Fetch();
uint32 entry = fields[0].GetUInt32();
uint32 bgTypeId = fields[1].GetUInt32();
if (!sBattlemasterListStore.LookupEntry(bgTypeId))
{
sLog.outErrorDb("Table `battlemaster_entry` contain entry %u for nonexistent battleground type %u, ignored.", entry, bgTypeId);
continue;
}
mBattleMastersMap[entry] = BattleGroundTypeId(bgTypeId);
}
while (result->NextRow());
delete result;
sLog.outString(">> Loaded %u battlemaster entries", count);
sLog.outString();
}
HolidayIds BattleGroundMgr::BGTypeToWeekendHolidayId(BattleGroundTypeId bgTypeId)
{
switch (bgTypeId)
{
case BATTLEGROUND_AV: return HOLIDAY_CALL_TO_ARMS_AV;
case BATTLEGROUND_EY: return HOLIDAY_CALL_TO_ARMS_EY;
case BATTLEGROUND_WS: return HOLIDAY_CALL_TO_ARMS_WS;
case BATTLEGROUND_SA: return HOLIDAY_CALL_TO_ARMS_SA;
case BATTLEGROUND_AB: return HOLIDAY_CALL_TO_ARMS_AB;
default: return HOLIDAY_NONE;
}
}
BattleGroundTypeId BattleGroundMgr::WeekendHolidayIdToBGType(HolidayIds holiday)
{
switch (holiday)
{
case HOLIDAY_CALL_TO_ARMS_AV: return BATTLEGROUND_AV;
case HOLIDAY_CALL_TO_ARMS_EY: return BATTLEGROUND_EY;
case HOLIDAY_CALL_TO_ARMS_WS: return BATTLEGROUND_WS;
case HOLIDAY_CALL_TO_ARMS_SA: return BATTLEGROUND_SA;
case HOLIDAY_CALL_TO_ARMS_AB: return BATTLEGROUND_AB;
default: return BATTLEGROUND_TYPE_NONE;
}
}
bool BattleGroundMgr::IsBGWeekend(BattleGroundTypeId bgTypeId)
{
return sGameEventMgr.IsActiveHoliday(BGTypeToWeekendHolidayId(bgTypeId));
}
void BattleGroundMgr::LoadBattleEventIndexes()
{
BattleGroundEventIdx events;
events.event1 = BG_EVENT_NONE;
events.event2 = BG_EVENT_NONE;
m_GameObjectBattleEventIndexMap.clear(); // need for reload case
m_GameObjectBattleEventIndexMap[-1] = events;
m_CreatureBattleEventIndexMap.clear(); // need for reload case
m_CreatureBattleEventIndexMap[-1] = events;
uint32 count = 0;
QueryResult* result =
// 0 1 2 3 4 5 6
WorldDatabase.Query("SELECT data.typ, data.guid1, data.ev1 AS ev1, data.ev2 AS ev2, data.map AS m, data.guid2, description.map, "
// 7 8 9
"description.event1, description.event2, description.description "
"FROM "
"(SELECT '1' AS typ, a.guid AS guid1, a.event1 AS ev1, a.event2 AS ev2, b.map AS map, b.guid AS guid2 "
"FROM gameobject_battleground AS a "
"LEFT OUTER JOIN gameobject AS b ON a.guid = b.guid "
"UNION "
"SELECT '2' AS typ, a.guid AS guid1, a.event1 AS ev1, a.event2 AS ev2, b.map AS map, b.guid AS guid2 "
"FROM creature_battleground AS a "
"LEFT OUTER JOIN creature AS b ON a.guid = b.guid "
") data "
"RIGHT OUTER JOIN battleground_events AS description ON data.map = description.map "
"AND data.ev1 = description.event1 AND data.ev2 = description.event2 "
// full outer join doesn't work in mysql :-/ so just UNION-select the same again and add a left outer join
"UNION "
"SELECT data.typ, data.guid1, data.ev1, data.ev2, data.map, data.guid2, description.map, "
"description.event1, description.event2, description.description "
"FROM "
"(SELECT '1' AS typ, a.guid AS guid1, a.event1 AS ev1, a.event2 AS ev2, b.map AS map, b.guid AS guid2 "
"FROM gameobject_battleground AS a "
"LEFT OUTER JOIN gameobject AS b ON a.guid = b.guid "
"UNION "
"SELECT '2' AS typ, a.guid AS guid1, a.event1 AS ev1, a.event2 AS ev2, b.map AS map, b.guid AS guid2 "
"FROM creature_battleground AS a "
"LEFT OUTER JOIN creature AS b ON a.guid = b.guid "
") data "
"LEFT OUTER JOIN battleground_events AS description ON data.map = description.map "
"AND data.ev1 = description.event1 AND data.ev2 = description.event2 "
"ORDER BY m, ev1, ev2");
if (!result)
{
BarGoLink bar(1);
bar.step();
sLog.outErrorDb(">> Loaded 0 battleground eventindexes.");
sLog.outString();
return;
}
BarGoLink bar(result->GetRowCount());
do
{
bar.step();
Field* fields = result->Fetch();
if (fields[2].GetUInt8() == BG_EVENT_NONE || fields[3].GetUInt8() == BG_EVENT_NONE)
continue; // we don't need to add those to the eventmap
bool gameobject = (fields[0].GetUInt8() == 1);
uint32 dbTableGuidLow = fields[1].GetUInt32();
events.event1 = fields[2].GetUInt8();
events.event2 = fields[3].GetUInt8();
uint32 map = fields[4].GetUInt32();
uint32 desc_map = fields[6].GetUInt32();
uint8 desc_event1 = fields[7].GetUInt8();
uint8 desc_event2 = fields[8].GetUInt8();
const char* description = fields[9].GetString();
// checking for nullptr - through right outer join this will mean following:
if (fields[5].GetUInt32() != dbTableGuidLow)
{
sLog.outErrorDb("BattleGroundEvent: %s with nonexistent guid %u for event: map:%u, event1:%u, event2:%u (\"%s\")",
(gameobject) ? "gameobject" : "creature", dbTableGuidLow, map, events.event1, events.event2, description);
continue;
}
// checking for nullptr - through full outer join this can mean 2 things:
if (desc_map != map)
{
// there is an event missing
if (dbTableGuidLow == 0)
{
sLog.outErrorDb("BattleGroundEvent: missing db-data for map:%u, event1:%u, event2:%u (\"%s\")", desc_map, desc_event1, desc_event2, description);
continue;
}
// we have an event which shouldn't exist
else
{
sLog.outErrorDb("BattleGroundEvent: %s with guid %u is registered, for a nonexistent event: map:%u, event1:%u, event2:%u",
(gameobject) ? "gameobject" : "creature", dbTableGuidLow, map, events.event1, events.event2);
continue;
}
}
if (gameobject)
m_GameObjectBattleEventIndexMap[dbTableGuidLow] = events;
else
m_CreatureBattleEventIndexMap[dbTableGuidLow] = events;
++count;
}
while (result->NextRow());
sLog.outString(">> Loaded %u battleground eventindexes", count);
sLog.outString();
delete result;
}
| gpl-2.0 |
blackducksoftware/appedit | src/test/java/com/blackducksoftware/tools/appedit/mocks/MockCodeCenterServerWrapper.java | 3904 | /**
* Application Details Edit Webapp
*
* Copyright (C) 2017 Black Duck Software, Inc.
* http://www.blackducksoftware.com/
*
* 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.
*/
package com.blackducksoftware.tools.appedit.mocks;
import java.util.List;
import com.blackducksoftware.tools.commonframework.core.config.ConfigurationManager;
import com.blackducksoftware.tools.commonframework.standard.common.ProjectPojo;
import com.blackducksoftware.tools.connector.codecenter.CodeCenterAPIWrapper;
import com.blackducksoftware.tools.connector.codecenter.ICodeCenterServerWrapper;
import com.blackducksoftware.tools.connector.codecenter.application.IApplicationManager;
import com.blackducksoftware.tools.connector.codecenter.attribute.IAttributeDefinitionManager;
import com.blackducksoftware.tools.connector.codecenter.component.ICodeCenterComponentManager;
import com.blackducksoftware.tools.connector.codecenter.externalId.IExternalIdManager;
import com.blackducksoftware.tools.connector.codecenter.protexservers.IProtexServerManager;
import com.blackducksoftware.tools.connector.codecenter.request.IRequestManager;
import com.blackducksoftware.tools.connector.codecenter.user.ICodeCenterUserManager;
import com.blackducksoftware.tools.connector.common.ILicenseManager;
import com.blackducksoftware.tools.connector.common.LicensePojo;
public class MockCodeCenterServerWrapper implements ICodeCenterServerWrapper {
@Override
public ProjectPojo getProjectByName(String projectName) throws Exception {
// TODO Auto-generated method stub
return null;
}
@Override
public ProjectPojo getProjectByID(String projectID) throws Exception {
// TODO Auto-generated method stub
return null;
}
@Override
public <T> List<T> getProjects(Class<T> classType) throws Exception {
// TODO Auto-generated method stub
return null;
}
@Override
public ConfigurationManager getConfigManager() {
// TODO Auto-generated method stub
return null;
}
@Override
public CodeCenterAPIWrapper getInternalApiWrapper() {
// TODO Auto-generated method stub
return null;
}
@Override
public IApplicationManager getApplicationManager() {
// TODO Auto-generated method stub
return null;
}
@Override
public IExternalIdManager getExternalIdManager() {
// TODO Auto-generated method stub
return null;
}
@Override
public IAttributeDefinitionManager getAttributeDefinitionManager() {
// TODO Auto-generated method stub
return null;
}
@Override
public ILicenseManager<LicensePojo> getLicenseManager() {
// TODO Auto-generated method stub
return null;
}
@Override
public IProtexServerManager getProtexServerManager() {
// TODO Auto-generated method stub
return null;
}
@Override
public ICodeCenterComponentManager getComponentManager() {
// TODO Auto-generated method stub
return null;
}
@Override
public ICodeCenterUserManager getUserManager() {
// TODO Auto-generated method stub
return null;
}
@Override
public IRequestManager getRequestManager() {
// TODO Auto-generated method stub
return null;
}
}
| gpl-2.0 |
stweil/TYPO3.CMS | typo3/sysext/fluid/Classes/ViewHelpers/Format/DateViewHelper.php | 5167 | <?php
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
namespace TYPO3\CMS\Fluid\ViewHelpers\Format;
use TYPO3\CMS\Core\Context\Context;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\MathUtility;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;
use TYPO3Fluid\Fluid\Core\ViewHelper\Exception;
use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithContentArgumentAndRenderStatic;
/**
* Formats an object implementing :php:`\DateTimeInterface`.
*
* Examples
* ========
*
* Defaults
* --------
*
* ::
*
* <f:format.date>{dateObject}</f:format.date>
*
* ``1980-12-13``
* Depending on the current date.
*
* Custom date format
* ------------------
*
* ::
*
* <f:format.date format="H:i">{dateObject}</f:format.date>
*
* ``01:23``
* Depending on the current time.
*
* Relative date with given time
* -----------------------------
*
* ::
*
* <f:format.date format="Y" base="{dateObject}">-1 year</f:format.date>
*
* ``2016``
* Assuming dateObject is in 2017.
*
* strtotime string
* ----------------
*
* ::
*
* <f:format.date format="d.m.Y - H:i:s">+1 week 2 days 4 hours 2 seconds</f:format.date>
*
* ``13.12.1980 - 21:03:42``
* Depending on the current time, see https://www.php.net/manual/function.strtotime.php.
*
* Localized dates using strftime date format
* ------------------------------------------
*
* ::
*
* <f:format.date format="%d. %B %Y">{dateObject}</f:format.date>
*
* ``13. Dezember 1980``
* Depending on the current date and defined locale. In the example you see the 1980-12-13 in a german locale.
*
* Inline notation
* ---------------
*
* ::
*
* {f:format.date(date: dateObject)}
*
* ``1980-12-13``
* Depending on the value of ``{dateObject}``.
*
* Inline notation (2nd variant)
* -----------------------------
*
* ::
*
* {dateObject -> f:format.date()}
*
* ``1980-12-13``
* Depending on the value of ``{dateObject}``.
*/
class DateViewHelper extends AbstractViewHelper
{
use CompileWithContentArgumentAndRenderStatic;
/**
* Needed as child node's output can return a DateTime object which can't be escaped
*
* @var bool
*/
protected $escapeChildren = false;
/**
* Initialize arguments
*/
public function initializeArguments()
{
$this->registerArgument('date', 'mixed', 'Either an object implementing DateTimeInterface or a string that is accepted by DateTime constructor');
$this->registerArgument('format', 'string', 'Format String which is taken to format the Date/Time', false, '');
$this->registerArgument('base', 'mixed', 'A base time (an object implementing DateTimeInterface or a string) used if $date is a relative date specification. Defaults to current time.');
}
/**
* @param array $arguments
* @param \Closure $renderChildrenClosure
* @param RenderingContextInterface $renderingContext
*
* @return string
* @throws Exception
*/
public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext)
{
$format = $arguments['format'];
$base = $arguments['base'] ?? GeneralUtility::makeInstance(Context::class)->getPropertyFromAspect('date', 'timestamp');
if (is_string($base)) {
$base = trim($base);
}
if ($format === '') {
$format = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] ?: 'Y-m-d';
}
$date = $renderChildrenClosure();
if ($date === null) {
return '';
}
if (is_string($date)) {
$date = trim($date);
}
if ($date === '') {
$date = 'now';
}
if (!$date instanceof \DateTimeInterface) {
try {
$base = $base instanceof \DateTimeInterface ? (int)$base->format('U') : (int)strtotime((MathUtility::canBeInterpretedAsInteger($base) ? '@' : '') . $base);
$dateTimestamp = strtotime((MathUtility::canBeInterpretedAsInteger($date) ? '@' : '') . $date, $base);
$date = new \DateTime('@' . $dateTimestamp);
$date->setTimezone(new \DateTimeZone(date_default_timezone_get()));
} catch (\Exception $exception) {
throw new Exception('"' . $date . '" could not be parsed by \DateTime constructor: ' . $exception->getMessage(), 1241722579);
}
}
if (str_contains($format, '%')) {
// @todo Replace deprecated strftime in php 8.1. Suppress warning in v11.
return @strftime($format, (int)$date->format('U'));
}
return $date->format($format);
}
}
| gpl-2.0 |
rlugojr/rekall | rekall-core/rekall/plugins/response/processes.py | 7465 | """Rekall plugins for displaying processes in live triaging."""
import psutil
from efilter.protocols import structured
from rekall import utils
from rekall.plugins import core
from rekall.plugins.response import common
from rekall.plugins.overlays import basic
from rekall.plugins import yarascanner
class _LiveProcess(utils.SlottedObject):
"""An object to represent a live process.
This is the live equivalent of _EPROCESS.
"""
__slots__ = ("_proc", "_obj_profile", "session",
"start_time", "pid")
def __init__(self, proc, session=None):
"""Construct a representation of the live process.
Args:
proc: The psutil.Process instance.
"""
# Hold on to the original psutil object.
self._proc = proc
self._obj_profile = None
self.session = session
super(_LiveProcess, self).__init__()
self.start_time = basic.UnixTimeStamp(
name="create_time", value=self.create_time, session=self.session)
@utils.safe_property
def obj_profile(self):
# Delay creation of the profile because it needs to look in the
# environment which is slow.
if self._obj_profile is None:
self._obj_profile = common.APIProfile(
session=self.session, proc=self)
return self._obj_profile
def __int__(self):
return self.pid
def _get_field(self, field_name):
try:
result = getattr(self._proc, field_name)
if callable(result):
result = result()
return result
except psutil.Error:
# Some processes do not have environ defined.
if field_name == "environ":
return {}
return None
except AttributeError:
return None
def __format__(self, formatspec):
"""Support the format() protocol."""
if not formatspec:
formatspec = "s"
if formatspec[-1] in "xdXD":
return format(int(self), formatspec)
return object.__format__(self, formatspec)
def __repr__(self):
return "<Live Process pid=%s>" % self.pid
def get_process_address_space(self):
return common.APIProcessAddressSpace(self.pid, session=self.session)
def as_dict(self):
try:
return self._proc.as_dict()
except Exception:
# This can happen if the process no longer exists.
return {}
# Automatically add accessors for psutil fields.
psutil_fields = ['cmdline', 'connections', 'cpu_affinity',
'cpu_percent', 'cpu_times', 'create_time',
'cwd', 'environ', 'exe', 'gids', 'io_counters',
'ionice', 'memory_full_info', 'memory_info',
'memory_info_ex', 'memory_maps', 'memory_percent',
'name', 'nice', 'num_ctx_switches', 'num_fds',
'num_threads', 'open_files', 'pid', 'ppid',
'status', 'terminal', 'threads', 'uids', 'username',
'num_handles']
# Generate accessors for psutil derived properties.
properties = dict(__slots__=())
for field in psutil_fields:
properties[field] = property(
lambda self, field=field: self._get_field(field))
LiveProcess = type("LiveProcess", (_LiveProcess, ), properties)
structured.IStructured.implement(
for_type=LiveProcess,
implementations={
structured.resolve: lambda d, m: getattr(d, m, None),
structured.getmembers_runtime: lambda d: psutil_fields + d.keys(),
}
)
class APIProcessFilter(common.AbstractAPICommandPlugin):
"""A live process filter using the system APIs."""
__abstract = True
__args = [
dict(name="pids", positional=True, type="ArrayIntParser", default=[],
help="One or more pids of processes to select."),
dict(name="proc_regex", default=None, type="RegEx",
help="A regex to select a process by name."),
]
@utils.safe_property
def filtering_requested(self):
return (self.plugin_args.pids or self.plugin_args.proc_regex)
def filter_processes(self):
"""Filters eprocess list using pids lists."""
for proc in self.list_process():
if not self.filtering_requested:
yield proc
else:
if int(proc.pid) in self.plugin_args.pids:
yield proc
elif (self.plugin_args.proc_regex and
self.plugin_args.proc_regex.match(
utils.SmartUnicode(proc.name))):
yield proc
def list_process(self):
result = [LiveProcess(x, session=self.session)
for x in psutil.process_iter()]
return result
class APIPslist(APIProcessFilter):
"""A live pslist plugin using the APIs."""
name = "pslist"
table_header = [
dict(name="proc", hidden=True),
dict(name="Name", width=30),
dict(name="pid", width=6, align="r"),
dict(name="ppid", width=6, align="r"),
dict(name="Thds", width=6, align="r"),
dict(name="Hnds", width=8, align="r"),
dict(name="wow64", width=6),
dict(name="start", width=24),
dict(name="binary"),
]
def column_types(self):
return self._row(LiveProcess(psutil.Process(), session=self.session))
def is_wow64(self, proc):
"""Determine if the proc is Wow64."""
# Not the most accurate method but very fast.
return (proc.environ.get("PROCESSOR_ARCHITECTURE") == 'x86' and
proc.environ.get("PROCESSOR_ARCHITEW6432") == 'AMD64')
def _row(self, proc):
return dict(proc=proc,
Name=proc.name,
pid=proc.pid,
ppid=proc.ppid,
Thds=proc.num_threads,
Hnds=proc.num_handles,
wow64=self.is_wow64(proc),
start=proc.start_time,
binary=proc.exe)
def collect(self):
for proc in self.filter_processes():
yield self._row(proc)
class APISetProcessContext(core.SetProcessContextMixin,
APIProcessFilter):
"""A cc plugin for setting process context to live mode."""
name = "cc"
class APIProcessScanner(APIProcessFilter):
"""Scanner for scanning processes using the ReadProcessMemory() API."""
__abstract = True
def generate_memory_ranges(self):
with self.session.plugins.cc() as cc:
for task in self.filter_processes():
comment = "%s (%s)" % (task.name, task.pid)
cc.SwitchProcessContext(task)
process_address_space = self.session.GetParameter(
"default_address_space")
for _, _, run in process_address_space.runs:
vad = run.data["vad"]
self.session.logging.info(
"Scanning %s (%s) in: %s [%#x-%#x]",
task.name, task.pid, vad.filename or "",
vad.start, vad.end)
run.data["comment"] = comment
run.data["task"] = task
yield run
class ProcessYaraScanner(yarascanner.YaraScanMixin, APIProcessScanner):
"""Yara scan process memory using the ReadProcessMemory() API."""
name = "yarascan"
| gpl-2.0 |
nathanscottdaniels/pnant | src/NAnt.Core/Tasks/ExternalProgramBase.cs | 27917 | // pNAnt - A parallel .NET build tool
// Copyright (C) 2016 Nathan Daniels
// Original NAnt Copyright (C) 2001-2003 Gerry Shaw
//
// 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
//
// Gerry Shaw (gerry_shaw@yahoo.com)
// Scott Hernandez (ScottHernandez@hotmail.com)
// Gert Driesen (drieseng@users.sourceforge.net)
using System;
using System.Configuration;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using NAnt.Core.Attributes;
using NAnt.Core.Configuration;
using NAnt.Core.Types;
using NAnt.Core.Util;
namespace NAnt.Core.Tasks {
/// <summary>
/// Provides the abstract base class for tasks that execute external applications.
/// </summary>
/// <remarks>
/// <para>
/// When a <see cref="ProgramLocationAttribute" /> is applied to the
/// deriving class and <see cref="ExeName" /> does not return an
/// absolute path, then the program to execute will first be searched for
/// in the location specified by <see cref="ProgramLocationAttribute.LocationType" />.
/// </para>
/// <para>
/// If the program does not exist in that location, then the list of tool
/// paths of the current target framework will be scanned in the order in
/// which they are defined in the NAnt configuration file.
/// </para>
/// </remarks>
[Serializable()]
public abstract class ExternalProgramBase : Task {
private StreamReader _stdError;
private StreamReader _stdOut;
private ArgumentCollection _arguments = new ArgumentCollection();
private ManagedExecution _managed = ManagedExecution.Default;
private string _exeName;
private int _timeout = Int32.MaxValue;
private TextWriter _outputWriter;
private TextWriter _errorWriter;
private int _exitCode = UnknownExitCode;
private bool _spawn;
private int _processId = 0;
private bool _useRuntimeEngine;
/// <summary>
/// Defines the exit code that will be returned by <see cref="ExitCode" />
/// if the process could not be started, or did not exit (in time).
/// </summary>
public const int UnknownExitCode = -1000;
private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Used to specify the time out value (in milliseconds) to use for the
/// executetask method output threads
/// </summary>
private static readonly int outputTimeout;
/// <summary>
/// The app.config app settings key to get the output timeout value from.
/// </summary>
private const string outputTimeoutKey = "nant.externalprogram.output.timeout";
/// <summary>
/// Will be used to ensure thread-safe operations.
/// </summary>
private static object _lockObject = new object();
/// <summary>
/// Static constructor that retrieves the specified timeout value for program
/// output.
/// </summary>
static ExternalProgramBase()
{
// Assigns the appropriate timeout value (in milliseconds) to use for
// the output threads.
const int defaultTimeout = 2000;
string appSettingStage =
ConfigurationManager.AppSettings.Get(outputTimeoutKey);
if (!String.IsNullOrEmpty(appSettingStage))
{
int stageTimeout;
if (Int32.TryParse(appSettingStage, out stageTimeout))
{
// Make sure that the stage Timeout value is valid
if (stageTimeout >= 0 || stageTimeout == Timeout.Infinite)
{
outputTimeout = stageTimeout;
return;
}
}
}
// If the default timeout isn't specified or valid, use the specified
// default value.
outputTimeout = defaultTimeout;
}
/// <summary>
/// The name of the executable that should be used to launch the
/// external program.
/// </summary>
/// <value>
/// The name of the executable that should be used to launch the external
/// program, or <see langword="null" /> if no name is specified.
/// </value>
/// <remarks>
/// If available, the configured value in the NAnt configuration
/// file will be used if no name is specified.
/// </remarks>
[FrameworkConfigurable("exename")]
public virtual string ExeName {
get { return (_exeName != null) ? _exeName : Name; }
set { _exeName = value; }
}
/// <summary>
/// Gets the filename of the external program to start.
/// </summary>
/// <value>
/// The filename of the external program.
/// </value>
/// <remarks>
/// Override in derived classes to explicitly set the location of the
/// external tool.
/// </remarks>
public virtual string ProgramFileName {
get { return DetermineFilePath(); }
}
/// <summary>
/// Gets the command-line arguments for the external program.
/// </summary>
/// <value>
/// The command-line arguments for the external program.
/// </value>
public abstract string ProgramArguments { get; }
/// <summary>
/// Gets the file to which the standard output should be redirected.
/// </summary>
/// <value>
/// The file to which the standard output should be redirected, or
/// <see langword="null" /> if the standard output should not be
/// redirected.
/// </value>
/// <remarks>
/// The default implementation will never allow the standard output
/// to be redirected to a file. Deriving classes should override this
/// property to change this behaviour.
/// </remarks>
public virtual FileInfo Output {
get { return null; }
set {} //so that it can be overriden.
}
/// <summary>
/// Gets a value indicating whether output will be appended to the
/// <see cref="Output" />.
/// </summary>
/// <value>
/// <see langword="true" /> if output should be appended to the <see cref="Output" />;
/// otherwise, <see langword="false" />.
/// </value>
public virtual bool OutputAppend {
get { return false; }
set {} //so that it can be overriden.
}
/// <summary>
/// Gets the working directory for the application.
/// </summary>
/// <value>
/// The working directory for the application.
/// </value>
public virtual DirectoryInfo BaseDirectory {
get { return new DirectoryInfo(Project.BaseDirectory); }
set {} // so that it can be overriden.
}
/// <summary>
/// The maximum amount of time the application is allowed to execute,
/// expressed in milliseconds. Defaults to no time-out.
/// </summary>
[TaskAttribute("timeout")]
[Int32Validator()]
public int TimeOut {
get { return _timeout; }
set { _timeout = value; }
}
/// <summary>
/// The command-line arguments for the external program.
/// </summary>
[BuildElementArray("arg")]
public virtual ArgumentCollection Arguments {
get { return _arguments; }
}
/// <summary>
/// Specifies whether the external program is a managed application
/// which should be executed using a runtime engine, if configured.
/// The default is <see langword="false" />.
/// </summary>
/// <value>
/// <see langword="true" /> if the external program should be executed
/// using a runtime engine; otherwise, <see langword="false" />.
/// </value>
/// <remarks>
/// <para>
/// The value of <see cref="UseRuntimeEngine" /> is only used from
/// <see cref="Managed" />, and then only if its value is set to
/// <see cref="ManagedExecution.Default" />. In which case
/// <see cref="Managed" /> returns <see cref="ManagedExecution.Auto" />
/// if <see cref="UseRuntimeEngine" /> is <see langword="true" />.
/// </para>
/// <para>
/// In all other cases, the value of <see cref="UseRuntimeEngine" />
/// is ignored.
/// </para>
/// </remarks>
[FrameworkConfigurable("useruntimeengine")]
[Obsolete("Use the managed attribute and Managed property instead.", false)]
public virtual bool UseRuntimeEngine {
get { return _useRuntimeEngine; }
set { _useRuntimeEngine = value; }
}
/// <summary>
/// Specifies whether the external program should be treated as a managed
/// application, possibly forcing it to be executed under the currently
/// targeted version of the CLR.
/// </summary>
/// <value>
/// A <see cref="ManagedExecution" /> indicating how the program should
/// be treated.
/// </value>
/// <remarks>
/// <para>
/// If <see cref="Managed" /> is set to <see cref="ManagedExecution.Default" />,
/// which is the default value, and <see cref="UseRuntimeEngine" /> is
/// <see langword="true" /> then <see cref="ManagedExecution.Auto" />
/// is returned.
/// </para>
/// <para>
/// When the changing <see cref="Managed" /> to <see cref="ManagedExecution.Default" />,
/// then <see cref="UseRuntimeEngine" /> is set to <see langword="false" />;
/// otherwise, it is changed to <see langword="true" />.
/// </para>
/// </remarks>
[FrameworkConfigurable("managed")]
public virtual ManagedExecution Managed {
get {
// deal with cases where UseRuntimeEngine is overridden to
// return true by default
if (UseRuntimeEngine && _managed == ManagedExecution.Default) {
return ManagedExecution.Auto;
}
return _managed;
}
set {
_managed = value;
UseRuntimeEngine = (value != ManagedExecution.Default);
}
}
/// <summary>
/// Gets or sets the <see cref="TextWriter" /> to which standard output
/// messages of the external program will be written.
/// </summary>
/// <value>
/// The <see cref="TextWriter" /> to which standard output messages of
/// the external program will be written.
/// </value>
/// <remarks>
/// By default, standard output messages wil be written to the build log
/// with level <see cref="Level.Info" />.
/// </remarks>
public virtual TextWriter OutputWriter {
get {
if (_outputWriter == null) {
_outputWriter = new LogWriter(this, Level.Info,
CultureInfo.InvariantCulture);
}
return _outputWriter;
}
set { _outputWriter = value; }
}
/// <summary>
/// Gets or sets the <see cref="TextWriter" /> to which error output
/// of the external program will be written.
/// </summary>
/// <value>
/// The <see cref="TextWriter" /> to which error output of the external
/// program will be written.
/// </value>
/// <remarks>
/// By default, error output wil be written to the build log with level
/// <see cref="Level.Warning" />.
/// </remarks>
public virtual TextWriter ErrorWriter {
get {
if (_errorWriter == null) {
_errorWriter = new LogWriter(this, Level.Warning,
CultureInfo.InvariantCulture);
}
return _errorWriter;
}
set { _errorWriter = value; }
}
/// <summary>
/// Gets the value that the process specified when it terminated.
/// </summary>
/// <value>
/// The code that the associated process specified when it terminated,
/// or <c>-1000</c> if the process could not be started or did not
/// exit (in time).
/// </value>
public int ExitCode {
get { return _exitCode; }
}
/// <summary>
/// Gets the unique identifier for the spawned application.
/// </summary>
protected int ProcessId {
get {
if (!Spawn) {
throw new InvalidOperationException ("The unique identifier" +
" only applies to spawned applications.");
}
if (_processId == 0) {
throw new InvalidOperationException ("The application was not started.");
}
return _processId;
}
}
/// <summary>
/// Gets or sets a value indicating whether the application should be
/// spawned. If you spawn an application, its output will not be logged
/// by NAnt. The default is <see langword="false" />.
/// </summary>
public virtual bool Spawn {
get { return _spawn; }
set { _spawn = value; }
}
/// <summary>
/// Starts the external process and captures its output.
/// </summary>
/// <exception cref="BuildException">
/// <para>The external process did not finish within the configured timeout.</para>
/// <para>-or-</para>
/// <para>The exit code of the external process indicates a failure.</para>
/// </exception>
protected override void ExecuteTask() {
Thread outputThread = null;
Thread errorThread = null;
try {
// Start the external process
Process process = StartProcess();
if (Spawn) {
_processId = process.Id;
return;
}
outputThread = new Thread(new ThreadStart(StreamReaderThread_Output));
errorThread = new Thread(new ThreadStart(StreamReaderThread_Error));
_stdOut = process.StandardOutput;
_stdError = process.StandardError;
outputThread.Start();
errorThread.Start();
// Wait for the process to terminate
process.WaitForExit(TimeOut);
// Wait for the threads to terminate
outputThread.Join(outputTimeout);
errorThread.Join(outputTimeout);
if (!process.HasExited) {
try {
process.Kill();
} catch {
// ignore possible exceptions that are thrown when the
// process is terminated
}
throw new BuildException(
String.Format(CultureInfo.InvariantCulture,
ResourceUtils.GetString("NA1118"),
ProgramFileName,
TimeOut),
Location);
}
_exitCode = process.ExitCode;
if (process.ExitCode != 0) {
throw new BuildException(
String.Format(CultureInfo.InvariantCulture,
ResourceUtils.GetString("NA1119"),
ProgramFileName,
process.ExitCode),
Location);
}
} catch (BuildException e) {
if (FailOnError) {
throw;
} else {
logger.Error("Execution Error", e);
Log(Level.Error, e.Message);
}
} catch (Exception e) {
logger.Error("Execution Error", e);
throw new BuildException(
string.Format(CultureInfo.InvariantCulture, "{0}: {1} had errors. Please see log4net log.", GetType().ToString(), ProgramFileName),
Location,
e);
} finally {
// ensure outputThread is always aborted
if (outputThread != null && outputThread.IsAlive) {
outputThread.Abort();
}
// ensure errorThread is always aborted
if (errorThread != null && errorThread.IsAlive) {
errorThread.Abort();
}
}
}
/// <summary>
/// Gets the command-line arguments, separated by spaces.
/// </summary>
public string CommandLine {
get {
// append any nested <arg> arguments to the command line
StringBuilder arguments = new StringBuilder(ProgramArguments);
Arguments.ToString(arguments);
return arguments.ToString();
}
}
/// <summary>
/// Updates the <see cref="ProcessStartInfo" /> of the specified
/// <see cref="Process"/>.
/// </summary>
/// <param name="process">The <see cref="Process" /> of which the <see cref="ProcessStartInfo" /> should be updated.</param>
protected virtual void PrepareProcess(Process process){
ManagedExecutionMode executionMode = ManagedExecutionMode;
// create process (redirect standard output to temp buffer)
if (executionMode != null && executionMode.Engine != null) {
process.StartInfo.FileName = executionMode.Engine.Program.FullName;
StringBuilder arguments = new StringBuilder();
executionMode.Engine.Arguments.ToString (arguments);
if (arguments.Length >= 0) {
arguments.Append (' ');
}
arguments.AppendFormat("\"{0}\" {1}", ProgramFileName, CommandLine);
process.StartInfo.Arguments = arguments.ToString();
} else {
process.StartInfo.FileName = ProgramFileName;
process.StartInfo.Arguments = CommandLine;
}
if (!Spawn) {
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
}
// required to allow redirects and allow environment variables to
// be set
process.StartInfo.UseShellExecute = false;
// do not start process in new window unless we're spawning (if not,
// the console output of spawned application is not displayed on MS)
process.StartInfo.CreateNoWindow = !Spawn;
process.StartInfo.WorkingDirectory = BaseDirectory.FullName;
// set framework-specific environment variables if executing the
// external process using the runtime engine of the currently
// active framework
if (executionMode != null) {
foreach (EnvironmentVariable environmentVariable in executionMode.Environment.EnvironmentVariables) {
if (environmentVariable.IfDefined && !environmentVariable.UnlessDefined) {
if (environmentVariable.Value == null) {
process.StartInfo.EnvironmentVariables[environmentVariable.VariableName] = "";
} else {
process.StartInfo.EnvironmentVariables[environmentVariable.VariableName] = environmentVariable.Value;
}
}
}
}
}
/// <summary>
/// Starts the process and handles errors.
/// </summary>
/// <returns>The <see cref="Process" /> that was started.</returns>
protected virtual Process StartProcess() {
Process p = new Process();
PrepareProcess(p);
try {
string msg = string.Format(
CultureInfo.InvariantCulture,
ResourceUtils.GetString("String_Starting_Program"),
p.StartInfo.WorkingDirectory,
p.StartInfo.FileName,
p.StartInfo.Arguments);
logger.Info(msg);
Log(Level.Verbose, msg);
p.Start();
return p;
} catch (Exception ex) {
throw new BuildException(string.Format(CultureInfo.InvariantCulture,
ResourceUtils.GetString("NA1121"), p.StartInfo.FileName), Location, ex);
}
}
/// <summary>
/// Reads from the stream until the external program is ended.
/// </summary>
private void StreamReaderThread_Output() {
StreamReader reader = _stdOut;
bool doAppend = OutputAppend;
while (true) {
string logContents = reader.ReadLine();
if (logContents == null) {
break;
}
// ensure only one thread writes to the log at any time
lock (_lockObject) {
if (Output != null) {
StreamWriter writer = new StreamWriter(Output.FullName, doAppend);
writer.WriteLine(logContents);
doAppend = true;
writer.Close();
} else {
OutputWriter.WriteLine(logContents);
}
}
}
lock (_lockObject) {
OutputWriter.Flush();
}
}
/// <summary>
/// Reads from the stream until the external program is ended.
/// </summary>
private void StreamReaderThread_Error() {
StreamReader reader = _stdError;
bool doAppend = OutputAppend;
while (true) {
string logContents = reader.ReadLine();
if (logContents == null) {
break;
}
// ensure only one thread writes to the log at any time
lock (_lockObject) {
ErrorWriter.WriteLine(logContents);
if (Output != null) {
StreamWriter writer = new StreamWriter(Output.FullName, doAppend);
writer.WriteLine(logContents);
doAppend = true;
writer.Close();
}
}
}
lock (_lockObject) {
ErrorWriter.Flush();
}
}
/// <summary>
/// Determines the path of the external program that should be executed.
/// </summary>
/// <returns>
/// A fully qualifies pathname including the program name.
/// </returns>
/// <exception cref="BuildException">The task is not available or not configured for the current framework.</exception>
private string DetermineFilePath() {
string fullPath = "";
// if the Exename is already specified as a full path then just use that.
if (ExeName != null && Path.IsPathRooted(ExeName)) {
return ExeName;
}
// get the ProgramLocation attribute
ProgramLocationAttribute programLocationAttribute = (ProgramLocationAttribute) Attribute.GetCustomAttribute(this.GetType(),
typeof(ProgramLocationAttribute));
if (programLocationAttribute != null) {
// ensure we have a valid framework set.
if ((programLocationAttribute.LocationType == LocationType.FrameworkDir ||
programLocationAttribute.LocationType == LocationType.FrameworkSdkDir) &&
(Project.TargetFramework == null)) {
throw new BuildException(string.Format(CultureInfo.InvariantCulture,
ResourceUtils.GetString("NA1120") + Environment.NewLine, Name));
}
switch (programLocationAttribute.LocationType) {
case LocationType.FrameworkDir:
if (Project.TargetFramework.FrameworkDirectory != null) {
string frameworkDir = Project.TargetFramework.FrameworkDirectory.FullName;
fullPath = Path.Combine(frameworkDir, ExeName + ".exe");
} else {
throw new BuildException(
string.Format(CultureInfo.InvariantCulture,
ResourceUtils.GetString("NA1124"),
Project.TargetFramework.Name));
}
break;
case LocationType.FrameworkSdkDir:
if (Project.TargetFramework.SdkDirectory != null) {
string sdkDirectory = Project.TargetFramework.SdkDirectory.FullName;
fullPath = Path.Combine(sdkDirectory, ExeName + ".exe");
} else {
throw new BuildException(
string.Format(CultureInfo.InvariantCulture,
ResourceUtils.GetString("NA1122"),
Project.TargetFramework.Name));
}
break;
}
if (!File.Exists (fullPath)) {
string toolPath = Project.TargetFramework.GetToolPath (
ExeName + ".exe");
if (toolPath != null) {
fullPath = toolPath;
}
}
} else {
// rely on it being on the path.
fullPath = ExeName;
}
return fullPath;
}
private ManagedExecutionMode ManagedExecutionMode {
get {
if (Project.TargetFramework == null || Managed == ManagedExecution.Default) {
return null;
}
Runtime runtime = Project.TargetFramework.Runtime;
if (runtime != null) {
return runtime.Modes.GetExecutionMode (Managed);
}
return null;
}
}
}
}
| gpl-2.0 |
lispwriter/sirem | wp-content/themes/dynamo/ocmx/widgets/category-wiget.php | 6163 | <?php
class obox_category_widget extends WP_Widget {
/** constructor */
function obox_category_widget() {
parent::WP_Widget(false, $name = "(Obox) Product Category Widget", array("description" => "Home Page Widget - This widget displays your Product categories in a 3 or 4 column layout"));
}
/** @see WP_Widget::widget */
function widget($args, $instance) {
// Turn $instance array into variables
$instance_defaults = array ( 'title' => 'Product Categories', 'columns' => 3);
$instance_args = wp_parse_args( $instance, $instance_defaults );
extract( $instance_args, EXTR_SKIP );
if($columns == 4) :
$class = 'four';
elseif($columns == 3) :
$class = 'three';
endif; ?>
<li class="content-widget post-content-widget widget clearfix">
<?php if(isset($title)) : ?>
<h3 class="widgettitle"><?php echo $title; ?></h3>
<?php endif; ?>
<ul class="<?php echo $class; ?>-column content-widget-item ">
<?php for ($i = 1; $i <= $columns; $i++) {
// Term ID
$term_id = $instance['cat' . $i];
// Setup variables for this column
if(isset($instance['post_category_'.$i]))
$post_category = esc_attr($instance['post_category_'.$i]);
$cat = get_term($term_id, 'product_cat');
if(!is_wp_error($cat)) :
if(function_exists('get_woocommerce_term_meta')) :
$thumbnail_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true );
$image = wp_get_attachment_image_src($thumbnail_id, '4-3-medium');
endif;
$link = get_term_link($cat); ?>
<li class="column">
<?php if(isset($show_images) && $show_images == 'on') : ?>
<?php if(isset($image) && $image != "") : ?>
<div class="post-image fitvid">
<a href="<?php echo $link; ?>" class="thumbnail" title="<?php echo $cat->name; ?>"><img src="<?php echo $image[0]; ?>" alt="<?php echo $cat->name; ?>" /></a>
</div>
<?php endif; ?>
<?php endif; ?>
<?php if(isset($cat_title) && $cat_title == 'on' || isset($show_excerpts) && $show_excerpts == 'on') : ?>
<div class="content">
<?php if(isset($cat_title) && $cat_title == 'on') : ?>
<h4 class="post-title"><a href="<?php echo $link; ?>"><?php echo $cat->name; ?></a></h4>
<?php endif; ?>
<?php if(isset($show_excerpts) && $show_excerpts == 'on') : ?>
<p><?php echo $cat->description; ?></p>
<?php endif; ?>
</div>
<?php endif; ?>
</li>
<?php endif;
}; ?>
</ul>
</li>
<?php
}
/** @see WP_Widget::update */
function update($new_instance, $old_instance) {
return $new_instance;
}
/** @see WP_Widget::form */
function form($instance) {
// Turn $instance array into variables
$instance_defaults = array ( 'title' => 'Product Categories', 'columns' => 3);
$instance_args = wp_parse_args( $instance, $instance_defaults );
extract( $instance_args, EXTR_SKIP ); ?>
<p><em>Click Save after selecting a Column Layout to load each columns options</em></p>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>">Title<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" /></label>
</p>
<p>
<label for="<?php echo $this->get_field_id('columns'); ?>">Column Layout</label>
<select size="1" class="widefat" id="<?php echo $this->get_field_id('columns'); ?>" name="<?php echo $this->get_field_name('columns'); ?>">
<option <?php if($columns == "3") : ?>selected="selected"<?php endif; ?> value="3">3</option>
<option <?php if($columns == "4") : ?>selected="selected"<?php endif; ?> value="4">4</option>
</select>
</p>
<?php
for ($i = 1; $i <= $columns; $i++) {
echo "<h4>" . _('Column '. $i ) . "</h4>"; ?>
<?php
$terms = get_terms('product_cat', "orderby=count&hide_empty=0"); ?>
<p><label for="<?php echo $this->get_field_id('cat' . $i); ?>"><?php echo isset($tax->labels->singular_name); ?></label>
<select size="1" class="widefat" id="<?php echo $this->get_field_id('cat' . $i); ?>" name="<?php echo $this->get_field_name('cat' . $i); ?>">
<?php foreach($terms as $term => $details) :?>
<option <?php if(isset($instance['cat' . $i]) && $instance['cat' . $i] == $details->term_id){echo "selected=\"selected\"";} ?> value="<?php echo $details->term_id; ?>"><?php echo $details->name; ?></option>
<?php endforeach;?>
</select>
</p>
<?php }; ?>
<p>
<label for="<?php echo $this->get_field_id('cat_title'); ?>">
<input type="checkbox" <?php if(isset($cat_title) && isset($cat_title) && $cat_title == 'on') : ?>checked="checked"<?php endif; ?> id="<?php echo $this->get_field_id('cat_title'); ?>" name="<?php echo $this->get_field_name('cat_title'); ?>">
Show Category Title
</label>
</p>
<p>
<label for="<?php echo $this->get_field_id('show_images'); ?>">
<input type="checkbox" <?php if(isset($show_images) && $show_images == "on") : ?>checked="checked"<?php endif; ?> id="<?php echo $this->get_field_id('show_images'); ?>" name="<?php echo $this->get_field_name('show_images'); ?>">
Show Images
</label>
</p>
<p>
<label for="<?php echo $this->get_field_id('show_excerpts'); ?>">
<input type="checkbox" <?php if(isset($show_excerpts) && $show_excerpts == "on") : ?>checked="checked"<?php endif; ?> id="<?php echo $this->get_field_id('show_excerpts'); ?>" name="<?php echo $this->get_field_name('show_excerpts'); ?>">
Show Description
</label>
</p>
<?php } // form
}// class
//This sample widget can then be registered in the widgets_init hook:
// register FooWidget widget
add_action('widgets_init', create_function('', 'return register_widget("obox_category_widget");'));
?> | gpl-2.0 |
andryw/quemMeRepresenta | preprocessamento-senado/print_date.py | 426 | #!/usr/bin/python
import time
from datetime import date, timedelta as td
print "hello, it me"
fileToWrite = open("dias.txt",'w')
#AAAA,MM,DD
d1 = date(2015, 6, 15)
d2 = date(int(time.strftime("%Y")), int(time.strftime("%m")), int(time.strftime("%d")))
delta = d2 - d1
for i in range(delta.days + 1):
dia = d1 + td(days=i)
fileToWrite.write(str(dia).replace("-", "") + "\n")
fileToWrite.close() | gpl-2.0 |
padmanabhan-developer/EstarProd | sites/default/files/php/twig/075870e6_feed-icon.html.twig_319d734a2973057fa5cba34c071e8b6c98b2160b81200b5fdb6739604f154385/ea7f44a8ae00ff8c84e45d706b7e0a111648f2f382d13d7c5fb059d243aaa84c.php | 3105 | <?php
/* core/themes/stable/templates/misc/feed-icon.html.twig */
class __TwigTemplate_03b6e2a5e6e57728a0bbeada527bdfad19ec0a5379760a0d6eb10f8ced0509e6 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
$tags = array();
$filters = array("t" => 14);
$functions = array();
try {
$this->env->getExtension('sandbox')->checkSecurity(
array(),
array('t'),
array()
);
} catch (Twig_Sandbox_SecurityError $e) {
$e->setTemplateFile($this->getTemplateName());
if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) {
$e->setTemplateLine($tags[$e->getTagName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) {
$e->setTemplateLine($filters[$e->getFilterName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) {
$e->setTemplateLine($functions[$e->getFunctionName()]);
}
throw $e;
}
// line 13
echo "<a href=\"";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["url"]) ? $context["url"] : null), "html", null, true));
echo "\"";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute((isset($context["attributes"]) ? $context["attributes"] : null), "addClass", array(0 => "feed-icon"), "method"), "html", null, true));
echo ">
";
// line 14
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->renderVar(t("Subscribe to @title", array("@title" => (isset($context["title"]) ? $context["title"] : null)))));
echo "
</a>
";
}
public function getTemplateName()
{
return "core/themes/stable/templates/misc/feed-icon.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 50 => 14, 43 => 13,);
}
}
/* {#*/
/* /***/
/* * @file*/
/* * Theme override for a feed icon.*/
/* **/
/* * Available variables:*/
/* * - url: An internal system path or a fully qualified external URL of the feed.*/
/* * - attributes: Remaining HTML attributes for the feed link.*/
/* * - title: A descriptive title of the feed link.*/
/* * - class: HTML classes to be applied to the feed link.*/
/* *//* */
/* #}*/
/* <a href="{{ url }}"{{ attributes.addClass('feed-icon') }}>*/
/* {{ 'Subscribe to @title'|t({'@title': title}) }}*/
/* </a>*/
/* */
| gpl-2.0 |
FRCTeam4069/RobotCode2014 | src/frc/team4069/thirdyear/subsystems/Pickup.java | 2645 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package frc.team4069.thirdyear.subsystems;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.DoubleSolenoid;
import edu.wpi.first.wpilibj.Talon;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.networktables.NetworkTable;
import edu.wpi.first.wpilibj.tables.ITable;
import frc.team4069.thirdyear.RobotMap;
/**
* Pickup system. Includes roller motor and arm solenoid. Batteries not
* included.
*
* @author Edmund
*/
public class Pickup extends Subsystem {
DoubleSolenoid pickupArm;
Talon pickupRoller;
DigitalInput reedSwitch;
public Pickup() {
pickupArm = new DoubleSolenoid(RobotMap.PICKUP_PISTON_1,
RobotMap.PICKUP_PISTON_2);
pickupRoller = new Talon(RobotMap.PICKUP_ROLLER);
reedSwitch = new DigitalInput(RobotMap.WINCH_REEDSWITCH);
}
/**
* Makes the pickup mechanism move.
*
* @param up The direction of movement. True for upward, false for downward.
*/
public void move(boolean up) {
pickupArm.set(up ? DoubleSolenoid.Value.kReverse
: DoubleSolenoid.Value.kForward);
}
public void toggle() {
pickupArm.set(
pickupArm.get() == DoubleSolenoid.Value.kForward ? DoubleSolenoid.Value.kReverse : DoubleSolenoid.Value.kForward);
}
/**
* Spins the pickup roller.
*
* @param speed The speed for spinning.
*/
public void spin(double speed) {
pickupRoller.set(speed);
}
/**
* Checks if the pickup arm is in the correct position for shooter usage.
*
* @return The value of the reed switch on the pickup arm.
*/
public boolean getReedSwitch() {
return reedSwitch.get();
}
/**
* There is <b>no</b> default command.
*/
public void initDefaultCommand() {
// Set the default command for a subsystem here.
//setDefaultCommand(new MySpecialCommand());
}
/**
* Adds motor and sensor data to the SmartDashboard.
*
* @return The NetworkTable instance containing the shooter data.
*/
public ITable getTable() {
NetworkTable shooterTable;
shooterTable = NetworkTable.getTable("Pickup");
shooterTable.putBoolean("Reed Switch", getReedSwitch());
shooterTable.putNumber("Roller Speed", pickupRoller.get());
return shooterTable;
}
/**
*
* @return The name of the NamedSendable.
*/
public String getName() {
return "Pickup";
}
}
| gpl-2.0 |
wangtaoenter/Books | Main/src/org/geometerplus/zlibrary/core/html/ZLHtmlProcessor.java | 1234 | /*
* Copyright (C) 2007-2014 Geometer Plus <contact@geometerplus.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.zlibrary.core.html;
import java.io.InputStream;
import java.io.IOException;
public abstract class ZLHtmlProcessor {
public static boolean read(ZLHtmlReader reader, InputStream stream) {
try {
ZLHtmlParser parser = new ZLHtmlParser(reader, stream);
reader.startDocumentHandler();
parser.doIt();
reader.endDocumentHandler();
} catch (IOException e) {
return false;
}
return true;
}
}
| gpl-2.0 |
ahmedmusawir/tripasia | page-templates/country-post-template.php | 2548 | <?php
/**
* Template Name: Country Post Template
*
*/
get_header(); ?>
<section id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<?php if ( have_posts() ) : ?>
<header class="page-header">
<h1 class="page-title pull-left">
<?php
if ( is_day() ) :
printf( __( 'Daily Archives: %s', 'twentyfourteen' ), get_the_date() );
elseif ( is_month() ) :
printf( __( 'Monthly Archives: %s', 'twentyfourteen' ), get_the_date( _x( 'F Y', 'monthly archives date format', 'twentyfourteen' ) ) );
elseif ( is_year() ) :
printf( __( 'Yearly Archives: %s', 'twentyfourteen' ), get_the_date( _x( 'Y', 'yearly archives date format', 'twentyfourteen' ) ) );
else :
_e( 'More Countries to visit ...', 'twentyfourteen' );
endif;
?>
</h1>
</header><!-- .page-header -->
<?php
/*========================================================
= This is my Shit from wp codex site =
==========================================================*/
$args = array(
'posts_per_page' => 15,
'offset' => 0,
'category' => '',
'category_name' => 'Featured Country',
'orderby' => 'post_date',
'order' => 'DESC',
'include' => '',
'exclude' => '',
'meta_key' => '',
'meta_value' => '',
'post_type' => 'country',
'post_mime_type' => '',
'post_parent' => '',
'post_status' => 'publish',
'suppress_filters' => true );
$countrys = new WP_Query( $args );
/*----- End of This is my Shit from wp codex site ------*/
// Start the Loop.
while ( $countrys->have_posts() ) : $countrys->the_post();
/*
* Include the post format-specific template for the content. If you want to
* use this in a child theme, then include a file called called content-___.php
* (where ___ is the post format) and that will be used instead.
*/
get_template_part( 'content', 'country' );
// get_template_part( 'content', get_post_format() );
endwhile;
wp_reset_postdata();
// Previous/next page navigation.
twentyfourteen_paging_nav();
else :
// If no content, include the "No posts found" template.
get_template_part( 'content', 'none' );
endif;
?>
</div><!-- #content -->
</section><!-- #primary -->
<?php
get_sidebar( 'content' );
get_sidebar();
get_footer();
| gpl-2.0 |
evanbuss/wordpress | wp-content/plugins/js_composer/include/classes/shortcodes/shortcodes.php | 37349 | <?php
/**
* WPBakery Visual Composer Shortcodes main
*
* @package WPBakeryVisualComposer
*
*/
/* abstract VisualComposer class to create structural object of any type */
if ( ! class_exists( 'WPBakeryVisualComposerAbstract' ) ) {
/**
* Class WPBakeryVisualComposerAbstract
*/
abstract class WPBakeryVisualComposerAbstract {
/**
* @var
*/
public static $config;
/**
* @var bool
*/
protected $is_plugin = true;
/**
* @var bool
*/
protected $is_theme = false;
/**
* @var bool
*/
protected $disable_updater = false;
/**
* @var bool
*/
protected $settings_as_theme = false;
/**
* @var bool
*/
protected $as_network_plugin = false;
/**
* @var bool
*/
protected $is_init = false;
/**
* @var string
*/
protected $controls_css_settings = 'cc';
/**
* @var array
*/
protected $controls_list = array( 'edit', 'clone', 'delete' );
/**
* @var string
*/
protected $shortcode_content = '';
/**
*
*/
public function __construct() {
}
/**
* @param $settings
*/
public function init( $settings ) {
self::$config = (array) $settings;
}
/**
* @param $action
* @param $method
* @param int $priority
*/
public function addAction( $action, $method, $priority = 10 ) {
add_action( $action, array( &$this, $method ), $priority );
}
/**
* @param $action
* @param $method
* @param int $priority
*
* @return bool
*/
public function removeAction( $action, $method, $priority = 10 ) {
return remove_action( $action, array( $this, $method ), $priority );
}
/**
* @param $filter
* @param $method
* @param int $priority
*
* @return bool|void
*/
public function addFilter( $filter, $method, $priority = 10 ) {
return add_filter( $filter, array( &$this, $method ), $priority );
}
/**
* @param $filter
* @param $method
* @param int $priority
*/
public function removeFilter( $filter, $method, $priority = 10 ) {
remove_filter( $filter, array( &$this, $method ), $priority );
}
/* Shortcode methods */
/**
* @param $tag
* @param $func
*/
public function addShortCode( $tag, $func ) {
add_shortcode( $tag, $func );
}
/**
* @param $content
*/
public function doShortCode( $content ) {
do_shortcode( $content );
}
/**
* @param $tag
*/
public function removeShortCode( $tag ) {
remove_shortcode( $tag );
}
/**
* @param $param
*
* @return null
*/
public function post( $param ) {
return isset( $_POST[ $param ] ) ? $_POST[ $param ] : null;
}
/**
* @param $param
*
* @return null
*/
public function get( $param ) {
return isset( $_GET[ $param ] ) ? $_GET[ $param ] : null;
}
/**
* @deprecated
*
* @param $asset
*
* @return string
*/
public function assetURL( $asset ) {
return vc_asset_url( $asset );
}
/**
* @param $asset
*
* @return string
*/
public function assetPath( $asset ) {
return self::$config['APP_ROOT'] . self::$config['ASSETS_DIR'] . $asset;
}
/**
* @param $name
*
* @return null
*/
public static function config( $name ) {
return isset( self::$config[ $name ] ) ? self::$config[ $name ] : null;
}
}
}
/**
*
*/
define( 'VC_SHORTCODE_CUSTOMIZE_PREFIX', 'vc_theme_' );
/**
*
*/
define( 'VC_SHORTCODE_BEFORE_CUSTOMIZE_PREFIX', 'vc_theme_before_' );
/**
*
*/
define( 'VC_SHORTCODE_AFTER_CUSTOMIZE_PREFIX', 'vc_theme_after_' );
/**
*
*/
define( 'VC_SHORTCODE_CUSTOM_CSS_FILTER_TAG', 'vc_shortcodes_css_class' );
if ( ! class_exists( 'WPBakeryShortCode' ) ) {
/**
* Class WPBakeryShortCode
*/
abstract class WPBakeryShortCode extends WPBakeryVisualComposerAbstract {
/**
* @var
*/
protected $shortcode;
/**
* @var
*/
protected $html_template;
/**
* @var
*/
/**
* @var
*/
protected $atts, $settings;
/**
* @var int
*/
protected static $enqueue_index = 0;
/**
* @var array
*/
protected static $js_scripts = array();
/**
* @var array
*/
protected static $css_scripts = array();
/**
* default scripts like scripts
* @var bool
* @since 4.4.3
*/
protected static $default_scripts_enqueued = false;
/**
* @var string
*/
protected $shortcode_string = '';
/**
* @var string
*/
protected $controls_template_file = 'editors/partials/backend_controls.tpl.php';
/**
* @param $settings
*/
public function __construct( $settings ) {
$this->settings = $settings;
$this->shortcode = $this->settings['base'];
$this->addAction( 'admin_init', 'enqueueAssets' );
$this->addAction( 'admin_head', 'printIconStyles' );
}
/**
* @param $content
*
* @return string
*/
public function addInlineAnchors( $content ) {
return ( $this->isInline() || $this->isEditor() && $this->settings( 'is_container' ) === true ? '<span class="vc_container-anchor"></span>' : '' ) . $content;
}
/**
*
*/
public function enqueueAssets() {
if ( ! empty( $this->settings['admin_enqueue_js'] ) ) {
$this->registerJs( $this->settings['admin_enqueue_js'] );
}
if ( ! empty( $this->settings['admin_enqueue_css'] ) ) {
$this->registerCss( $this->settings['admin_enqueue_css'] );
}
}
/**
* Prints out the styles needed to render the element icon for the back end interface.
* Only performed if the 'icon' setting is a valid URL.
*
* @return void
* @since 4.2
* @modified 4.4
* @author Benjamin Intal
*/
public function printIconStyles() {
if ( ! filter_var( $this->settings( 'icon' ), FILTER_VALIDATE_URL ) ) {
return;
}
echo "
<style>
.vc_el-container #" . esc_attr( $this->settings['base'] ) . " .vc_element-icon,
.wpb_" . esc_attr( $this->settings['base'] ) . " .wpb_element_title .vc_element-icon,
.vc_el-container > #" . esc_attr( $this->settings['base'] ) . " > .vc_element-icon,
.vc_el-container > #" . esc_attr( $this->settings['base'] ) . " > .vc_element-icon[data-is-container=\"true\"],
.compose_mode .vc_helper.vc_helper-" . esc_attr( $this->settings['base'] ) . " > .vc_element-icon,
.vc_helper.vc_helper-" . esc_attr( $this->settings['base'] ) . " > .vc_element-icon,
.compose_mode .vc_helper.vc_helper-" . esc_attr( $this->settings['base'] ) . " > .vc_element-icon[data-is-container=\"true\"],
.vc_helper.vc_helper-" . esc_attr( $this->settings['base'] ) . " > .vc_element-icon[data-is-container=\"true\"],
.wpb_" . esc_attr( $this->settings['base'] ) . " > .wpb_element_wrapper > .wpb_element_title > .vc_element-icon,
.wpb_" . esc_attr( $this->settings['base'] ) . " > .wpb_element_wrapper > .wpb_element_title > .vc_element-icon[data-is-container=\"true\"] {
background-position: 0 0;
background-image: url(" . esc_url( $this->settings['icon'] ) . ");
-webkit-background-size: contain;
-moz-background-size: contain;
-ms-background-size: contain;
-o-background-size: contain;
background-size: contain;
}
</style>";
}
/**
* @param $param
*/
protected function registerJs( $param ) {
if ( is_array( $param ) && ! empty( $param ) ) {
foreach ( $param as $value ) {
$this->registerJs( $value );
}
} elseif ( is_string( $param ) && ! empty( $param ) ) {
$name = 'admin_enqueue_js_' . md5( $param );
self::$js_scripts[] = $name;
wp_register_script( $name, $param, array( 'jquery' ), WPB_VC_VERSION, true );
}
}
/**
* @param $param
*/
protected function registerCss( $param ) {
if ( is_array( $param ) && ! empty( $param ) ) {
foreach ( $param as $value ) {
$this->registerCss( $value );
}
} elseif ( is_string( $param ) && ! empty( $param ) ) {
$name = 'admin_enqueue_css_' . md5( $param );
self::$css_scripts[] = $name;
wp_register_style( $name, $param, array( 'js_composer' ), WPB_VC_VERSION );
}
}
/**
*
*/
public static function enqueueCss() {
if ( ! empty( self::$css_scripts ) ) {
foreach ( self::$css_scripts as $stylesheet ) {
wp_enqueue_style( $stylesheet );
}
}
}
/**
*
*/
public static function enqueueJs() {
if ( ! empty( self::$js_scripts ) ) {
foreach ( self::$js_scripts as $script ) {
wp_enqueue_script( $script );
}
}
}
/**
* @param $shortcode
*/
public function shortcode( $shortcode ) {
}
/**
* @param $template
*
* @return string
*/
protected function setTemplate( $template ) {
return $this->html_template = apply_filters( 'vc_shortcode_set_template_' . $this->shortcode, $template );
}
/**
* @return bool
*/
protected function getTemplate() {
if ( isset( $this->html_template ) ) {
return $this->html_template;
}
return false;
}
/**
* @return mixed
*/
protected function getFileName() {
return $this->shortcode;
}
/**
* Find html template for shortcode output.
*/
protected function findShortcodeTemplate() {
// Check template path in shortcode's mapping settings
if ( ! empty( $this->settings['html_template'] ) && is_file( $this->settings( 'html_template' ) ) ) {
return $this->setTemplate( $this->settings['html_template'] );
}
// Check template in theme directory
$user_template = vc_shortcodes_theme_templates_dir( $this->getFilename() . '.php' );
if ( is_file( $user_template ) ) {
return $this->setTemplate( $user_template );
}
// Check default place
$default_dir = vc_manager()->getDefaultShortcodesTemplatesDir() . '/';
if ( is_file( $default_dir . $this->getFilename() . '.php' ) ) {
return $this->setTemplate( $default_dir . $this->getFilename() . '.php' );
}
return '';
}
/**
* @param $atts
* @param null $content
*
* @return mixed|void
*/
protected function content( $atts, $content = null ) {
return $this->loadTemplate( $atts, $content );
}
/**
* @param $atts
* @param null $content
*
* vc_filter: vc_shortcode_content_filter - hook to edit template content
* vc_filter: vc_shortcode_content_filter_after - hook after template is loaded to override output
*
* @return mixed|void
*/
protected function loadTemplate( $atts, $content = null ) {
$output = '';
if ( ! is_null( $content ) ) {
$content = apply_filters( 'vc_shortcode_content_filter', $content, $this->shortcode );
}
$this->findShortcodeTemplate();
if ( $this->html_template ) {
ob_start();
include( $this->html_template );
$output = ob_get_contents();
ob_end_clean();
} else {
trigger_error( sprintf( __( 'Template file is missing for `%s` shortcode. Make sure you have `%s` file in your theme folder.', 'js_composer' ), $this->shortcode, 'wp-content/themes/your_theme/vc_templates/' . $this->shortcode . '.php' ) );
}
return apply_filters( 'vc_shortcode_content_filter_after', $output, $this->shortcode );
}
/**
* @param $atts
* @param $content
*
* @return string
*/
public function contentAdmin( $atts, $content ) {
$output = $custom_markup = $width = $el_position = '';
if ( $content !== null ) {
$content = wpautop( stripslashes( $content ) );
}
$shortcode_attributes = array( 'width' => '1/1' );
if ( isset( $this->settings['params'] ) && is_array( $this->settings['params'] ) ) {
foreach ( $this->settings['params'] as $param ) {
if ( $param['param_name'] !== 'content' ) {
if ( isset( $param['value'] ) ) {
$value = $param['value'];
} else {
$value = '';
}
$shortcode_attributes[ $param['param_name'] ] = $value;
} else if ( $param['param_name'] === 'content' && $content === null ) {
$content = isset( $param['value'] ) ? $param['value'] : '';
}
}
}
$atts = shortcode_atts( $shortcode_attributes, $atts );
extract( $atts );
$this->atts = $atts;
$elem = $this->getElementHolder( $width );
if ( isset( $this->settings['custom_markup'] ) && $this->settings['custom_markup'] !== '' ) {
$markup = $this->settings['custom_markup'];
$elem = str_ireplace( '%wpb_element_content%', $this->customMarkup( $markup, $content ), $elem );
$output .= $elem;
} else {
$inner = $this->outputTitle( $this->settings['name'] );
$inner .= $this->paramsHtmlHolders( $atts );
$elem = str_ireplace( '%wpb_element_content%', $inner, $elem );
$output .= $elem;
}
return $output;
}
/**
* @return bool
*/
public function isAdmin() {
return apply_filters( 'vc_shortcodes_is_admin', is_admin() );
}
/**
* @return bool
*/
public function isInline() {
return vc_is_inline();
}
/**
* @return bool
*/
public function isEditor() {
return vc_is_editor();
}
/**
* @param $atts
* @param null $content
* @param string $base
*
* vc_filter: vc_shortcode_output - hook to override output of shortcode
*
* @return string
*/
public function output( $atts, $content = null, $base = '' ) {
$this->atts = $this->prepareAtts( $atts );
$this->shortcode_content = $content;
$output = '';
$content = empty( $content ) && ! empty( $atts['content'] ) ? $atts['content'] : $content;
if ( ( $this->isInline() || vc_is_page_editable() ) && method_exists( $this, 'contentInline' ) ) {
$output .= $this->contentInline( $this->atts, $content );
} else {
$this->enqueueDefaultScripts();
$custom_output = VC_SHORTCODE_CUSTOMIZE_PREFIX . $this->shortcode;
$custom_output_before = VC_SHORTCODE_BEFORE_CUSTOMIZE_PREFIX . $this->shortcode; // before shortcode function hook
$custom_output_after = VC_SHORTCODE_AFTER_CUSTOMIZE_PREFIX . $this->shortcode; // after shortcode function hook
// Before shortcode
if ( function_exists( $custom_output_before ) ) {
$output .= $custom_output_before( $this->atts, $content );
} else {
$output .= $this->beforeShortcode( $this->atts, $content );
}
// Shortcode content
if ( function_exists( $custom_output ) ) {
$output .= $custom_output( $this->atts, $content );
} else {
$output .= $this->content( $this->atts, $content );
}
// After shortcode
if ( function_exists( $custom_output_after ) ) {
$output .= $custom_output_after( $this->atts, $content );
} else {
$output .= $this->afterShortcode( $this->atts, $content );
}
}
// Filter for overriding outputs
$output = apply_filters( 'vc_shortcode_output', $output, $this, $this->atts );
return $output;
}
public function enqueueDefaultScripts() {
if ( false === self::$default_scripts_enqueued ) {
wp_enqueue_script( 'wpb_composer_front_js' );
wp_enqueue_style( 'js_composer_front' );
self::$default_scripts_enqueued = true;
}
}
/**
* Return shortcode attributes, see \WPBakeryShortCode::output
* @since 4.4
* @return array
*/
public function getAtts() {
return $this->atts;
}
/**
* Creates html before shortcode html.
*
* @param $atts - shortcode attributes list
* @param $content - shortcode content
*
* @return string - html which will be displayed before shortcode html.
*/
public function beforeShortcode( $atts, $content ) {
return '';
}
/**
* Creates html before shortcode html.
*
* @param $atts - shortcode attributes list
* @param $content - shortcode content
*
* @return string - html which will be displayed after shortcode html.
*/
public function afterShortcode( $atts, $content ) {
return '';
}
/**
* @param $el_class
*
* @return string
*/
public function getExtraClass( $el_class ) {
$output = '';
if ( $el_class !== '' ) {
$output = ' ' . str_replace( '.', '', $el_class );
}
return $output;
}
/**
* @param $css_animation
*
* @return string
*/
public function getCSSAnimation( $css_animation ) {
$output = '';
if ( $css_animation !== '' ) {
wp_enqueue_script( 'waypoints' );
$output = ' wpb_animate_when_almost_visible wpb_' . $css_animation;
}
return $output;
}
/**
* Create HTML comment for blocks only if wpb_debug=true
*
* @deprecated 4.7 For debug type html comments use more generic debugComment function.
*
* @param $string
*
* @return string
*/
public function endBlockComment( $string ) {
return wpb_debug() ? '<!-- END ' . $string . ' -->' : '';
}
/**
* if wpb_debug=true return HTML comment
*
* @since 4.7
*
* @param string $comment
*
* @return string
*/
public function debugComment( $comment ) {
return wpb_debug() ? '<!-- ' . $comment . ' -->' : '';
}
/**
* @param $name
*
* @return null
*/
public function settings( $name ) {
return isset( $this->settings[ $name ] ) ? $this->settings[ $name ] : null;
}
/**
* @param $name
* @param $value
*/
public function setSettings( $name, $value ) {
$this->settings[ $name ] = $value;
}
/**
* @param $width
*
* @return string
*/
public function getElementHolder( $width ) {
$output = '';
$column_controls = $this->getColumnControlsModular();
$css_class = 'wpb_' . $this->settings["base"] . ' wpb_content_element wpb_sortable' . ( ! empty( $this->settings["class"] ) ? ' ' . $this->settings["class"] : '' );
$output .= '<div data-element_type="' . $this->settings["base"] . '" class="' . $css_class . '">';
$output .= str_replace( "%column_size%", wpb_translateColumnWidthToFractional( $width ), $column_controls );
$output .= $this->getCallbacks( $this->shortcode );
$output .= '<div class="wpb_element_wrapper ' . $this->settings( "wrapper_class" ) . '">';
$output .= '%wpb_element_content%';
$output .= '</div>';
$output .= '</div>';
return $output;
}
// Return block controls
/**
* @param $controls
* @param string $extended_css
*
* @return string
*/
public function getColumnControls( $controls, $extended_css = '' ) {
$controls_start = '<div class="vc_controls controls controls_element' . ( ! empty( $extended_css ) ? " {$extended_css}" : '' ) . '">';
$controls_end = '</div>';
$controls_add = '';
$controls_edit = ' <a class="vc_control column_edit" href="#" title="' . sprintf( __( 'Edit %s', 'js_composer' ), strtolower( $this->settings( 'name' ) ) ) . '"><span class="vc_icon"></span></a>';
$controls_delete = ' <a class="vc_control column_clone" href="#" title="' . sprintf( __( 'Clone %s', 'js_composer' ), strtolower( $this->settings( 'name' ) ) ) . '"><span class="vc_icon"></span></a> <a class="column_delete" href="#" title="' . sprintf( __( 'Delete %s', 'js_composer' ), strtolower( $this->settings( 'name' ) ) ) . '"><span class="vc_icon"></span></a>';
$column_controls_full = $controls_start . $controls_add . $controls_edit . $controls_delete . $controls_end;
$column_controls_size_delete = $controls_start . $controls_delete . $controls_end;
$column_controls_popup_delete = $controls_start . $controls_delete . $controls_end;
$column_controls_edit_popup_delete = $controls_start . $controls_edit . $controls_delete . $controls_end;
if ( $controls === 'popup_delete' ) {
return $column_controls_popup_delete;
} else if ( $controls === 'edit_popup_delete' ) {
return $column_controls_edit_popup_delete;
} else if ( $controls === 'size_delete' ) {
return $column_controls_size_delete;
} else if ( $controls === 'add' ) {
return $controls_start . $controls_add . $controls_end;
} else {
return $column_controls_full;
}
}
/**
* Return list of controls
* @return array
*/
public function getControlsList() {
return apply_filters( 'vc_wpbakery_shortcode_get_controls_list', $this->controls_list, $this->shortcode );
}
/**
* Build new modern controls for shortcode.
*
* @param string $extended_css
*
* @return string
*/
public function getColumnControlsModular( $extended_css = '' ) {
ob_start();
vc_include_template( apply_filters( 'vc_wpbakery_shortcode_get_column_controls_modular_template',
$this->controls_template_file ), array(
'shortcode' => $this->shortcode,
'position' => $this->controls_css_settings,
'extended_css' => $extended_css,
'name' => $this->settings( 'name' ),
'controls' => $this->getControlsList(),
'name_css_class' => $this->getBackendEditorControlsElementCssClass()
) );
return ob_get_clean();
}
public function getBackendEditorControlsElementCssClass() {
return 'vc_control-btn vc_element-name vc_element-move';
}
/**
* This will fire callbacks if they are defined in map.php
*
* @param $id
*
* @return string
*/
public function getCallbacks( $id ) {
$output = '';
if ( isset( $this->settings['js_callback'] ) ) {
foreach ( $this->settings['js_callback'] as $text_val => $val ) {
// TODO: name explain
$output .= '<input type="hidden" class="wpb_vc_callback wpb_vc_' . $text_val . '_callback " name="' . $text_val . '" value="' . $val . '" />';
}
}
return $output;
}
/**
* @param $param
* @param $value
*
* vc_filter: vc_wpbakeryshortcode_single_param_html_holder_value - hook to override param value (param type and etc is available in args)
*
* @return string
*/
public function singleParamHtmlHolder( $param, $value ) {
$value = apply_filters( 'vc_wpbakeryshortcode_single_param_html_holder_value', $value, $param, $this->settings, $this->atts );
$output = '';
// Compatibility fixes
$old_names = array(
'yellow_message',
'blue_message',
'green_message',
'button_green',
'button_grey',
'button_yellow',
'button_blue',
'button_red',
'button_orange'
);
$new_names = array(
'alert-block',
'alert-info',
'alert-success',
'btn-success',
'btn',
'btn-info',
'btn-primary',
'btn-danger',
'btn-warning'
);
$value = str_ireplace( $old_names, $new_names, $value );
$param_name = isset( $param['param_name'] ) ? $param['param_name'] : '';
$type = isset( $param['type'] ) ? $param['type'] : '';
$class = isset( $param['class'] ) ? $param['class'] : '';
if ( ! empty( $param['holder'] ) ) {
if ( $param['holder'] === 'input' ) {
$output .= '<' . $param['holder'] . ' readonly="true" class="wpb_vc_param_value ' . $param_name . ' ' . $type . ' ' . $class . '" name="' . $param_name . '" value="' . $value . '">';
} elseif ( in_array( $param['holder'], array( 'img', 'iframe' ) ) ) {
$output .= '<' . $param['holder'] . ' class="wpb_vc_param_value ' . $param_name . ' ' . $type . ' ' . $class . '" name="' . $param_name . '" src="' . $value . '">';
} elseif ( $param['holder'] !== 'hidden' ) {
$output .= '<' . $param['holder'] . ' class="wpb_vc_param_value ' . $param_name . ' ' . $type . ' ' . $class . '" name="' . $param_name . '">' . $value . '</' . $param['holder'] . '>';
}
}
if ( ! empty( $param['admin_label'] ) && $param['admin_label'] === true ) {
$output .= '<span class="vc_admin_label admin_label_' . $param['param_name'] . ( empty( $value ) ? ' hidden-label' : '' ) . '"><label>' . $param['heading'] . '</label>: ' . $value . '</span>';
}
return $output;
}
/**
* @param $params
*
* @return string
*/
protected function getIcon( $params ) {
$data = '';
if ( isset( $params['is_container'] ) && $params['is_container'] === true ) {
$data = ' data-is-container="true"';
}
$title = '';
if ( isset( $params['title'] ) ) {
$title = 'title="' . $params['title'] . '" ';
}
return '<i ' . $title . 'class="vc_element-icon' . ( ! empty( $params['icon'] ) ? ' ' . sanitize_text_field( $params['icon'] ) : '' ) . '"' . $data . '></i> ';
}
/**
* @param $title
*
* @return string
*/
protected function outputTitle( $title ) {
$icon = $this->settings( 'icon' );
if ( filter_var( $icon, FILTER_VALIDATE_URL ) ) {
$icon = '';
}
$params = array(
'icon' => $icon,
'is_container' => $this->settings( 'is_container' ),
);
return '<h4 class="wpb_element_title"> ' . $this->getIcon( $params ) . esc_attr( $title ) . '</h4>';
}
/**
* @param string $content
*
* @return string
*/
public function template( $content = '' ) {
return $this->contentAdmin( $this->atts, $content );
}
/**
* @param $atts
*
* @return array
*/
protected function prepareAtts( $atts ) {
$return = array();
if ( is_array( $atts ) ) {
foreach ( $atts as $key => $val ) {
$return[ $key ] = str_replace( '``', '"', $val );
}
}
return $return;
}
/**
* @return mixed
*/
public function getShortcode() {
return $this->shortcode;
}
/**
* Since 4.5
* Possible placeholders:
* {{ content }}
* {{ title }}
* {{ container-class }}
* {{ params }}
*
* Possible keys:
* {{
* <%
* %
* @since 4.5
*
* @param $markup
* @param string $content
*
* @return string
*/
protected function customMarkup( $markup, $content = '' ) {
$pattern = '/\{\{([\s\S][^\n]+?)\}\}|<%([\s\S][^\n]+?)%>|%([\s\S][^\n]+?)%/';
preg_match_all( $pattern, $markup, $matches, PREG_SET_ORDER );
if ( is_array( $matches ) && ! empty( $matches ) ) {
foreach ( $matches as $match ) {
switch ( strtolower( trim( $match[1] ) ) ) {
// TODO: remove maybe create an wrappers as classes
case 'content': {
if ( $content !== '' ) {
$markup = str_replace( $match[0], $content, $markup );
} else if ( isset( $this->settings["default_content_in_template"] ) && $this->settings["default_content_in_template"] !== '' ) {
$markup = str_replace( $match[0], $this->settings["default_content_in_template"], $markup );
} else {
$markup = str_replace( $match[0], '', $markup );
}
break;
}
case 'title': {
$markup = str_replace( $match[0], $this->outputTitle( $this->settings['name'] ), $markup );
break;
}
case 'container-class': {
if ( method_exists( $this, 'containerContentClass' ) ) {
$markup = str_replace( $match[0], $this->containerContentClass(), $markup );
} else {
$markup = str_replace( $match[0], '', $markup );
}
break;
}
case 'params': {
$inner = '';
if ( isset( $this->settings['params'] ) && is_array( $this->settings['params'] ) ) {
foreach ( $this->settings['params'] as $param ) {
$param_value = isset( $$param['param_name'] ) ? $$param['param_name'] : '';
if ( is_array( $param_value ) ) {
// Get first element from the array
reset( $param_value );
$first_key = key( $param_value );
$param_value = is_null( $first_key ) ? '' : $param_value[ $first_key ];
}
$inner .= $this->singleParamHtmlHolder( $param, $param_value );
}
}
$markup = str_replace( $match[0], $inner, $markup );
break;
}
case 'editor_controls': {
$markup = str_replace( $match[0], $this->getColumnControls( $this->settings( 'controls' ) ), $markup );
break;
}
case 'editor_controls_bottom_add': {
$markup = str_replace( $match[0], $this->getColumnControls( 'add', 'bottom-controls' ), $markup );
break;
}
}
}
}
return do_shortcode( $markup );
}
/**
* @param $atts
*
* @return string
*/
protected function paramsHtmlHolders( $atts ) {
extract( $atts );
$inner = '';
if ( isset( $this->settings['params'] ) && is_array( $this->settings['params'] ) ) {
foreach ( $this->settings['params'] as $param ) {
$param_value = isset( $$param['param_name'] ) ? $$param['param_name'] : '';
if ( is_array( $param_value ) ) {
// Get first element from the array
reset( $param_value );
$first_key = key( $param_value );
$param_value = is_null( $first_key ) ? '' : $param_value[ $first_key ];
}
$inner .= $this->singleParamHtmlHolder( $param, $param_value );
}
}
return $inner;
}
}
}
if ( ! class_exists( 'WPBakeryShortCodesContainer' ) ) {
/**
* Class WPBakeryShortCodesContainer
*/
abstract class WPBakeryShortCodesContainer extends WPBakeryShortCode {
/**
* @var array
*/
protected $predefined_atts = array();
protected $backened_editor_prepend_controls = true;
/**
* @return string
*/
public function customAdminBlockParams() {
return '';
}
/**
* @param $width
* @param $i
*
* @return string
*/
public function mainHtmlBlockParams( $width, $i ) {
return 'data-element_type="' . $this->settings["base"] . '" class="wpb_' . $this->settings['base'] . ' wpb_sortable wpb_content_holder vc_shortcodes_container"' . $this->customAdminBlockParams();
}
/**
* @param $width
* @param $i
*
* @return string
*/
public function containerHtmlBlockParams( $width, $i ) {
return 'class="' . $this->containerContentClass() . '"';
}
/**
*
* @return string
*/
public function containerContentClass() {
return 'wpb_column_container vc_container_for_children vc_clearfix';
}
/**
* @param $controls
* @param string $extended_css
*
* @return string
*/
public function getColumnControls( $controls = 'full', $extended_css = '' ) {
$controls_start = '<div class="vc_controls vc_controls-visible controls controls_column' . ( ! empty( $extended_css ) ? " {$extended_css}" : '' ) . '">';
$controls_end = '</div>';
if ( $extended_css === 'bottom-controls' ) {
$control_title = sprintf( __( 'Append to this %s', 'js_composer' ), strtolower( $this->settings( 'name' ) ) );
} else {
$control_title = sprintf( __( 'Prepend to this %s', 'js_composer' ), strtolower( $this->settings( 'name' ) ) );
}
$controls_move = '<a class="vc_control column_move" data-vc-control="move" href="#" title="' . sprintf( __( 'Move this %s', 'js_composer' ), strtolower( $this->settings( 'name' ) ) ) . '"><span class="vc_icon"></span></a>';
$controls_add = '<a class="vc_control column_add" data-vc-control="add" href="#" title="' . $control_title . '"><span class="vc_icon"></span></a>';
$controls_edit = '<a class="vc_control column_edit" data-vc-control="edit" href="#" title="' . sprintf( __( 'Edit this %s', 'js_composer' ), strtolower( $this->settings( 'name' ) ) ) . '"><span class="vc_icon"></span></a>';
$controls_clone = '<a class="vc_control column_clone" data-vc-control="clone" href="#" title="' . sprintf( __( 'Clone this %s', 'js_composer' ), strtolower( $this->settings( 'name' ) ) ) . '"><span class="vc_icon"></span></a>';
$controls_delete = '<a class="vc_control column_delete" data-vc-control="delete" href="#" title="' . sprintf( __( 'Delete this %s', 'js_composer' ), strtolower( $this->settings( 'name' ) ) ) . '"><span class="vc_icon"></span></a>';
$controls_full = $controls_move . $controls_add . $controls_edit . $controls_clone . $controls_delete;
if ( ! empty( $controls ) ) {
if ( is_string( $controls ) ) {
$controls = array( $controls );
}
$controls_string = $controls_start;
foreach ( $controls as $control ) {
$control_var = 'controls_' . $control;
$controls_string .= $$control_var;
}
return $controls_string . $controls_end;
}
return $controls_start . $controls_full . $controls_end;
}
/**
* @param $atts
* @param null $content
*
* @return string
*/
public function contentAdmin( $atts, $content = null ) {
$width = $el_class = '';
$atts = shortcode_atts( $this->predefined_atts, $atts );
extract( $atts );
$this->atts = $atts;
$output = '';
for ( $i = 0; $i < count( $width ); $i ++ ) {
$output .= '<div ' . $this->mainHtmlBlockParams( $width, $i ) . '>';
if ( $this->backened_editor_prepend_controls ) {
$output .= $this->getColumnControls( $this->settings( 'controls' ) );
}
$output .= '<div class="wpb_element_wrapper">';
if ( isset( $this->settings["custom_markup"] ) && $this->settings["custom_markup"] !== '' ) {
$markup = $this->settings['custom_markup'];
$output .= $this->customMarkup( $markup );
} else {
$output .= $this->outputTitle( $this->settings['name'] );
$output .= '<div ' . $this->containerHtmlBlockParams( $width, $i ) . '>';
$output .= do_shortcode( shortcode_unautop( $content ) );
$output .= '</div>';
$output .= $this->paramsHtmlHolders( $atts );
}
$output .= '</div>';
if ( $this->backened_editor_prepend_controls ) {
$output .= $this->getColumnControls( 'add', 'bottom-controls' );
}
$output .= '</div>';
}
return $output;
}
/**
* @param $title
*
* @return string
*/
protected function outputTitle( $title ) {
$icon = $this->settings( 'icon' );
if ( filter_var( $icon, FILTER_VALIDATE_URL ) ) {
$icon = '';
}
$params = array(
'icon' => $icon,
'is_container' => $this->settings( 'is_container' ),
'title' => $title,
);
return '<h4 class="wpb_element_title"> ' . $this->getIcon( $params ) . '</h4>';
}
public function getBackendEditorChildControlsElementCssClass() {
return 'vc_element-name';
}
}
}
if ( ! class_exists( 'WPBakeryShortCodeFishBones' ) ) {
/**
* Class WPBakeryShortCodeFishBones
*/
class WPBakeryShortCodeFishBones extends WPBakeryShortCode {
/**
* @var bool
*/
protected $shortcode_class = false;
/**
* @param $settings
*/
public function __construct( $settings ) {
$this->settings = $settings;
$this->shortcode = $this->settings['base'];
$this->addAction( 'admin_init', 'enqueueAssets' );
if ( vc_is_page_editable() ) {
// fix for page editable
$this->addAction( 'wp_head', 'printIconStyles' );
}
$this->addAction( 'admin_head', 'printIconStyles' ); // fe+be
$this->addAction( 'admin_print_scripts-post.php', 'enqueueAssets' );
$this->addAction( 'admin_print_scripts-post-new.php', 'enqueueAssets' );
if ( ! shortcode_exists( $this->shortcode ) ) {
add_shortcode( $this->shortcode, Array( &$this, 'render' ) );
}
}
/**
* @return WPBakeryShortCodeFishBones
*/
public function shortcodeClass() {
if ( $this->shortcode_class !== false ) {
return $this->shortcode_class;
}
require_once vc_path_dir( 'SHORTCODES_DIR', 'wordpress-widgets.php' );
$class_name = $this->settings( 'php_class_name' ) ? $this->settings( 'php_class_name' ) : 'WPBakeryShortCode_' . $this->settings( 'base' );
$autoloaded_dependencies = VcShortcodeAutoloader::getInstance()->includeClass( $class_name );
if ( ! $autoloaded_dependencies ) {
$file = vc_path_dir( 'SHORTCODES_DIR', str_replace( '_', '-', $this->settings( 'base' ) ) . '.php' );
if ( is_file( $file ) ) {
require_once( $file );
}
}
if ( class_exists( $class_name ) && is_subclass_of( $class_name, 'WPBakeryShortCode' ) ) {
$this->shortcode_class = new $class_name( $this->settings );
} else {
$this->shortcode_class = $this;
}
return $this->shortcode_class;
}
/**
* @param $atts
* @param null $content
*
* @return string
*/
public function render( $atts, $content = null ) {
return $this->shortcodeClass()->output( $atts, $content );
}
/**
* This method is not used
*
* @param $atts
* @param null $content
*
* @return string
*/
protected function content( $atts, $content = null ) {
return '';
}
/**
* @param string $content
*
* @return string
*/
public function template( $content = '' ) {
return $this->shortcodeClass()->contentAdmin( $this->atts, $content );
}
}
} | gpl-2.0 |
yast/yast-configuration-management | src/lib/y2configuration_management/salt/form_element_locator.rb | 7241 | # encoding: utf-8
# Copyright (c) [2019] SUSE LLC
#
# All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of version 2 of the GNU General Public License as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, contact SUSE LLC.
#
# To contact SUSE LLC about this file by physical or electronic mail, you may
# find current contact information at www.suse.com.
require "forwardable"
module Y2ConfigurationManagement
module Salt
# Represent the locator to a form element
#
# The locator can be seen as a path to the form element. In a human readable form, the locator
# looks like: "root#person#computers[1]" or "root#hosts[router]".
#
# @example Building a locator from a string for an array based collection
# locator = FormElementLocator.from_string("root#person#computers[1]")
# locator.to_s #=> "root#person#computers[1]"
# locator.parts #=> [:root, :person, :computers, 1]
#
# @example Building a locator from a string for a hash based collection
# locator = FormElementLocator.from_string("root#hosts[router]")
# locator.to_s #=> "root#hosts[router]"
# locator.parts #=> [:root, :hosts, "router"]
#
# @example Building a locator from its parts
# locator = FormElementLocator.new(:root, :hosts, "router")
# locator.to_s #=> "root#hosts[router]"
#
# @example Extending a locator
# locator = FormElementLocator.new(:root, :hosts, "router")
# locator.join(:interfaces).to_s #=> "root#hosts[router]#interfaces"
#
# @example Joining relative locators
# relative = FormElementLocator.from_string(".subnets")
# locator = FormElementLocator.new(:root, :hosts)
# locator.join(relative).to_s #=> "root#subnets"
#
# @example Building a relative locator using the {.new} method
# relative = FormElementLocator.new([:hosts], upto: 2)
# relative.to_s #=> "..hosts"
class FormElementLocator
extend Forwardable
def_delegators :@parts, :first, :last
class << self
# Builds a locator from a string
#
# @todo Support specifying dots within hash keys (e.g. `.hosts[download.opensuse.org]`).
#
# @param string [String] String representing an element locator
# @return [FormElementLocator]
def from_string(string)
string.scan(TOKENS).reduce(neutral) do |locator, part|
locator.join(from_part(part))
end
end
# Returns a neutral locator
#
# Convenience method to return the neutral locator
#
# @return [FormElementLocator]
def neutral
new(nil)
end
# Returns the root locator
#
# Convenience method to return the root locator
#
# @return [FormElementLocator]
def root
new([:root])
end
private
# @return [String] Locator segments separator
SEPARATOR = "#".freeze
# @return [Regexp] Regular expresion to extract locator segments
TOKENS = /(?:\[.*?\]|[^#{SEPARATOR}\[])+/
# @return [Regexp] Regular expression representing a indexed locator segment
INDEXED_SEGMENT = /([^\[]+)(?:\[(.+)\])?/
# @return []
SEGMENT = /(\.*)#{INDEXED_SEGMENT}/
# Parses a locator part
#
# @param string [String]
# @return [Array<Integer,String,Symbol>] Locator subparts
def from_part(string)
match = SEGMENT.match(string)
return nil unless match
prefix, path, index = match[1..3]
ids = index.to_s.split("][").map do |id|
numeric_id?(id) ? id.to_i : id
end
parts = [path.to_sym] + ids
FormElementLocator.new(parts, upto: prefix.size)
end
# Determines whether the id is numeric or not
#
# @return [Boolean]
def numeric_id?(id)
id =~ /\A\d+\z/
end
end
# @return [Array<Integer,String,Symbol>] Locator parts
attr_reader :parts
# Zero for absolute locators, nonzero for relative ones
# @return [Integer] how many levels up do we go for a relative locator
attr_reader :upto
# Constructor
#
# @param parts [Array<Integer,String,Symbol>,nil] Locator parts; nil for the neutral element
def initialize(parts, upto: 0)
@parts = parts
@upto = upto
end
# Determines whether this is a neutral locator
#
# The neutral locator does not modify any other locator when joining.
#
# @return [Boolean]
def neutral?
@parts.nil?
end
# Locator of the parent element
#
# @return [Locator] Locator's parent
def parent
self.class.new(parts[0..-2])
end
# Removes the first part of the locator
#
# @return [Locator] Locator without the prefix
def rest
self.class.new(parts[1..-1])
end
# Returns the string representation
#
# @return [String] String representation
def to_s
as_string = parts.reduce("") do |memo, part|
part_as_string = part.is_a?(Symbol) ? "##{part}" : "[#{part}]"
memo << part_as_string
end
"." * upto + as_string[1..-1]
end
# Extends a locator
#
# @param locators_or_parts [FormElementLocator,Integer,String,Symbol] Parts or locators
# to join
# @return [Locator] Augmented locator
def join(*locators_or_parts)
locators_or_parts.reduce(self) do |locator, item|
other = item.is_a?(FormElementLocator) ? item : FormElementLocator.new([item])
locator.join_with_locator(other)
end
end
# Determines whether two locators are equivalent
#
# @param other [Locator] Locator to compare with
# @return [Boolean] true if both locators are equal; false otherwise
def ==(other)
upto == other.upto && parts == other.parts
end
# Removes references to specific collection elements
#
# @return [FormElementLocator]
def unbounded
self.class.new(parts.select { |i| i.is_a?(Symbol) })
end
# Determines whether a locator is relative or not
#
# @return [Boolean] true if its relative; false otherwise
def relative?
!upto.zero?
end
protected
# Extends a locator with another one
#
# @param other [FormElementLocator] Locator to join
# @return [Locator] Augmented locator
# @see join
def join_with_locator(other)
return self if other.neutral?
return other if neutral?
limit = -1 - other.upto
self.class.new(parts[0..limit] + other.parts, upto: upto)
end
end
end
end
| gpl-2.0 |
Jun-Yuan/percona-server | sql/sql_lex.cc | 116402 | /*
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/* A lexical scanner on a temporary buffer with a yacc interface */
#define MYSQL_LEX 1
#include "sql_priv.h"
#include "unireg.h" // REQUIRED: for other includes
#include "sql_class.h" // sql_lex.h: SQLCOM_END
#include "sql_lex.h"
#include "sql_parse.h" // add_to_list
#include "item_create.h"
#include <m_ctype.h>
#include <hash.h>
#include "sp.h"
#include "sp_head.h"
#include "sql_table.h" // primary_key_name
#include "sql_show.h" // append_identifier
#include "sql_select.h" // JOIN
#include "sql_optimizer.h" // JOIN
#include <mysql/psi/mysql_statement.h>
static int lex_one_token(YYSTYPE *yylval, THD *thd);
/*
We are using pointer to this variable for distinguishing between assignment
to NEW row field (when parsing trigger definition) and structured variable.
*/
sys_var *trg_new_row_fake_var= (sys_var*) 0x01;
/**
LEX_STRING constant for null-string to be used in parser and other places.
*/
const LEX_STRING null_lex_str= {NULL, 0};
const LEX_STRING empty_lex_str= {(char *) "", 0};
const LEX_CSTRING null_lex_cstr= {NULL, 0};
const LEX_CSTRING empty_lex_cstr= {"", 0};
/**
@note The order of the elements of this array must correspond to
the order of elements in enum_binlog_stmt_unsafe.
*/
const int
Query_tables_list::binlog_stmt_unsafe_errcode[BINLOG_STMT_UNSAFE_COUNT] =
{
ER_BINLOG_UNSAFE_LIMIT,
ER_BINLOG_UNSAFE_INSERT_DELAYED,
ER_BINLOG_UNSAFE_SYSTEM_TABLE,
ER_BINLOG_UNSAFE_AUTOINC_COLUMNS,
ER_BINLOG_UNSAFE_UDF,
ER_BINLOG_UNSAFE_SYSTEM_VARIABLE,
ER_BINLOG_UNSAFE_SYSTEM_FUNCTION,
ER_BINLOG_UNSAFE_NONTRANS_AFTER_TRANS,
ER_BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE,
ER_BINLOG_UNSAFE_MIXED_STATEMENT,
ER_BINLOG_UNSAFE_INSERT_IGNORE_SELECT,
ER_BINLOG_UNSAFE_INSERT_SELECT_UPDATE,
ER_BINLOG_UNSAFE_WRITE_AUTOINC_SELECT,
ER_BINLOG_UNSAFE_REPLACE_SELECT,
ER_BINLOG_UNSAFE_CREATE_IGNORE_SELECT,
ER_BINLOG_UNSAFE_CREATE_REPLACE_SELECT,
ER_BINLOG_UNSAFE_CREATE_SELECT_AUTOINC,
ER_BINLOG_UNSAFE_UPDATE_IGNORE,
ER_BINLOG_UNSAFE_INSERT_TWO_KEYS,
ER_BINLOG_UNSAFE_AUTOINC_NOT_FIRST
};
/* Longest standard keyword name */
#define TOCK_NAME_LENGTH 24
/*
The following data is based on the latin1 character set, and is only
used when comparing keywords
*/
static uchar to_upper_lex[]=
{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,123,124,125,126,127,
128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
208,209,210,211,212,213,214,247,216,217,218,219,220,221,222,255
};
/*
Names of the index hints (for error messages). Keep in sync with
index_hint_type
*/
const char * index_hint_type_name[] =
{
"IGNORE INDEX",
"USE INDEX",
"FORCE INDEX"
};
/**
@note The order of the elements of this array must correspond to
the order of elements in type_enum
*/
const char *st_select_lex::type_str[SLT_total]=
{ "NONE",
"PRIMARY",
"SIMPLE",
"DERIVED",
"SUBQUERY",
"UNION",
"UNION RESULT",
"MATERIALIZED"
};
inline int lex_casecmp(const char *s, const char *t, uint len)
{
while (len-- != 0 &&
to_upper_lex[(uchar) *s++] == to_upper_lex[(uchar) *t++]) ;
return (int) len+1;
}
#include <lex_hash.h>
void lex_init(void)
{
uint i;
DBUG_ENTER("lex_init");
for (i=0 ; i < array_elements(symbols) ; i++)
symbols[i].length=(uchar) strlen(symbols[i].name);
for (i=0 ; i < array_elements(sql_functions) ; i++)
sql_functions[i].length=(uchar) strlen(sql_functions[i].name);
DBUG_VOID_RETURN;
}
void lex_free(void)
{ // Call this when daemon ends
DBUG_ENTER("lex_free");
DBUG_VOID_RETURN;
}
void
st_parsing_options::reset()
{
allows_variable= TRUE;
allows_select_into= TRUE;
allows_select_procedure= TRUE;
allows_derived= TRUE;
}
/**
Cleans slave connection info.
*/
void struct_slave_connection::reset()
{
user= 0;
password= 0;
plugin_auth= 0;
plugin_dir= 0;
}
/**
Perform initialization of Lex_input_stream instance.
Basically, a buffer for pre-processed query. This buffer should be large
enough to keep multi-statement query. The allocation is done once in
Lex_input_stream::init() in order to prevent memory pollution when
the server is processing large multi-statement queries.
*/
bool Lex_input_stream::init(THD *thd,
char* buff,
unsigned int length)
{
DBUG_EXECUTE_IF("bug42064_simulate_oom",
DBUG_SET("+d,simulate_out_of_memory"););
m_cpp_buf= (char*) thd->alloc(length + 1);
DBUG_EXECUTE_IF("bug42064_simulate_oom",
DBUG_SET("-d,bug42064_simulate_oom"););
if (m_cpp_buf == NULL)
return TRUE;
m_thd= thd;
reset(buff, length);
return FALSE;
}
/**
Prepare Lex_input_stream instance state for use for handling next SQL statement.
It should be called between two statements in a multi-statement query.
The operation resets the input stream to the beginning-of-parse state,
but does not reallocate m_cpp_buf.
*/
void
Lex_input_stream::reset(char *buffer, unsigned int length)
{
yylineno= 1;
yytoklen= 0;
yylval= NULL;
lookahead_token= -1;
lookahead_yylval= NULL;
m_ptr= buffer;
m_tok_start= NULL;
m_tok_end= NULL;
m_end_of_query= buffer + length;
m_tok_start_prev= NULL;
m_buf= buffer;
m_buf_length= length;
m_echo= TRUE;
m_cpp_tok_start= NULL;
m_cpp_tok_start_prev= NULL;
m_cpp_tok_end= NULL;
m_body_utf8= NULL;
m_cpp_utf8_processed_ptr= NULL;
next_state= MY_LEX_START;
found_semicolon= NULL;
ignore_space= MY_TEST(m_thd->variables.sql_mode & MODE_IGNORE_SPACE);
stmt_prepare_mode= FALSE;
multi_statements= TRUE;
in_comment=NO_COMMENT;
m_underscore_cs= NULL;
m_cpp_ptr= m_cpp_buf;
}
/**
The operation is called from the parser in order to
1) designate the intention to have utf8 body;
1) Indicate to the lexer that we will need a utf8 representation of this
statement;
2) Determine the beginning of the body.
@param thd Thread context.
@param begin_ptr Pointer to the start of the body in the pre-processed
buffer.
*/
void Lex_input_stream::body_utf8_start(THD *thd, const char *begin_ptr)
{
DBUG_ASSERT(begin_ptr);
DBUG_ASSERT(m_cpp_buf <= begin_ptr && begin_ptr <= m_cpp_buf + m_buf_length);
uint body_utf8_length=
(m_buf_length / thd->variables.character_set_client->mbminlen) *
my_charset_utf8_bin.mbmaxlen;
m_body_utf8= (char *) thd->alloc(body_utf8_length + 1);
m_body_utf8_ptr= m_body_utf8;
*m_body_utf8_ptr= 0;
m_cpp_utf8_processed_ptr= begin_ptr;
}
/**
@brief The operation appends unprocessed part of pre-processed buffer till
the given pointer (ptr) and sets m_cpp_utf8_processed_ptr to end_ptr.
The idea is that some tokens in the pre-processed buffer (like character
set introducers) should be skipped.
Example:
CPP buffer: SELECT 'str1', _latin1 'str2';
m_cpp_utf8_processed_ptr -- points at the "SELECT ...";
In order to skip "_latin1", the following call should be made:
body_utf8_append(<pointer to "_latin1 ...">, <pointer to " 'str2'...">)
@param ptr Pointer in the pre-processed buffer, which specifies the
end of the chunk, which should be appended to the utf8
body.
@param end_ptr Pointer in the pre-processed buffer, to which
m_cpp_utf8_processed_ptr will be set in the end of the
operation.
*/
void Lex_input_stream::body_utf8_append(const char *ptr,
const char *end_ptr)
{
DBUG_ASSERT(m_cpp_buf <= ptr && ptr <= m_cpp_buf + m_buf_length);
DBUG_ASSERT(m_cpp_buf <= end_ptr && end_ptr <= m_cpp_buf + m_buf_length);
if (!m_body_utf8)
return;
if (m_cpp_utf8_processed_ptr >= ptr)
return;
int bytes_to_copy= ptr - m_cpp_utf8_processed_ptr;
memcpy(m_body_utf8_ptr, m_cpp_utf8_processed_ptr, bytes_to_copy);
m_body_utf8_ptr += bytes_to_copy;
*m_body_utf8_ptr= 0;
m_cpp_utf8_processed_ptr= end_ptr;
}
/**
The operation appends unprocessed part of the pre-processed buffer till
the given pointer (ptr) and sets m_cpp_utf8_processed_ptr to ptr.
@param ptr Pointer in the pre-processed buffer, which specifies the end
of the chunk, which should be appended to the utf8 body.
*/
void Lex_input_stream::body_utf8_append(const char *ptr)
{
body_utf8_append(ptr, ptr);
}
/**
The operation converts the specified text literal to the utf8 and appends
the result to the utf8-body.
@param thd Thread context.
@param txt Text literal.
@param txt_cs Character set of the text literal.
@param end_ptr Pointer in the pre-processed buffer, to which
m_cpp_utf8_processed_ptr will be set in the end of the
operation.
*/
void Lex_input_stream::body_utf8_append_literal(THD *thd,
const LEX_STRING *txt,
const CHARSET_INFO *txt_cs,
const char *end_ptr)
{
if (!m_cpp_utf8_processed_ptr)
return;
LEX_STRING utf_txt;
if (!my_charset_same(txt_cs, &my_charset_utf8_general_ci))
{
thd->convert_string(&utf_txt,
&my_charset_utf8_general_ci,
txt->str, (uint) txt->length,
txt_cs);
}
else
{
utf_txt.str= txt->str;
utf_txt.length= txt->length;
}
/* NOTE: utf_txt.length is in bytes, not in symbols. */
memcpy(m_body_utf8_ptr, utf_txt.str, utf_txt.length);
m_body_utf8_ptr += utf_txt.length;
*m_body_utf8_ptr= 0;
m_cpp_utf8_processed_ptr= end_ptr;
}
void Lex_input_stream::add_digest_token(uint token, LEX_YYSTYPE yylval)
{
if (m_digest != NULL)
{
m_digest= digest_add_token(m_digest, token, yylval);
}
}
void Lex_input_stream::reduce_digest_token(uint token_left, uint token_right)
{
if (m_digest != NULL)
{
m_digest= digest_reduce_token(m_digest, token_left, token_right);
}
}
/*
This is called before every query that is to be parsed.
Because of this, it's critical to not do too much things here.
(We already do too much here)
*/
void lex_start(THD *thd)
{
LEX *lex= thd->lex;
DBUG_ENTER("lex_start");
lex->thd= lex->unit.thd= thd;
lex->context_stack.empty();
lex->unit.init_query();
lex->unit.init_select();
/* 'parent_lex' is used in init_query() so it must be before it. */
lex->select_lex.parent_lex= lex;
lex->select_lex.init_query();
lex->load_set_str_list.empty();
lex->value_list.empty();
lex->update_list.empty();
lex->set_var_list.empty();
lex->param_list.empty();
lex->view_list.empty();
lex->prepared_stmt_params.empty();
lex->auxiliary_table_list.empty();
DBUG_ASSERT(!lex->unit.cleaned);
lex->unit.next= lex->unit.master= lex->unit.link_next= 0;
lex->unit.prev= lex->unit.link_prev= 0;
lex->unit.slave= lex->unit.global_parameters= lex->current_select=
lex->all_selects_list= &lex->select_lex;
lex->select_lex.master= &lex->unit;
lex->select_lex.prev= &lex->unit.slave;
lex->select_lex.link_next= lex->select_lex.slave= lex->select_lex.next= 0;
lex->select_lex.link_prev= (st_select_lex_node**)&(lex->all_selects_list);
lex->select_lex.options= 0;
lex->select_lex.sql_cache= SELECT_LEX::SQL_CACHE_UNSPECIFIED;
lex->select_lex.init_order();
lex->select_lex.group_list.empty();
if (lex->select_lex.group_list_ptrs)
lex->select_lex.group_list_ptrs->clear();
lex->describe= DESCRIBE_NONE;
lex->subqueries= FALSE;
lex->context_analysis_only= 0;
lex->derived_tables= 0;
lex->safe_to_cache_query= 1;
lex->leaf_tables_insert= 0;
lex->parsing_options.reset();
lex->empty_field_list_on_rset= 0;
lex->select_lex.select_number= 1;
lex->length=0;
lex->part_info= 0;
lex->select_lex.in_sum_expr=0;
lex->select_lex.ftfunc_list_alloc.empty();
lex->select_lex.ftfunc_list= &lex->select_lex.ftfunc_list_alloc;
lex->select_lex.group_list.empty();
lex->select_lex.order_list.empty();
if (lex->select_lex.order_list_ptrs)
lex->select_lex.order_list_ptrs->clear();
lex->select_lex.gorder_list.empty();
lex->duplicates= DUP_ERROR;
lex->ignore= 0;
lex->spname= NULL;
lex->sphead= NULL;
lex->set_sp_current_parsing_ctx(NULL);
lex->m_sql_cmd= NULL;
lex->proc_analyse= NULL;
lex->escape_used= FALSE;
lex->query_tables= 0;
lex->reset_query_tables_list(FALSE);
lex->expr_allows_subselect= TRUE;
lex->use_only_table_context= FALSE;
lex->contains_plaintext_password= false;
lex->name.str= 0;
lex->name.length= 0;
lex->event_parse_data= NULL;
lex->profile_options= PROFILE_NONE;
lex->nest_level=0 ;
lex->allow_sum_func= 0;
lex->in_sum_func= NULL;
/*
ok, there must be a better solution for this, long-term
I tried "bzero" in the sql_yacc.yy code, but that for
some reason made the values zero, even if they were set
*/
lex->server_options.server_name= 0;
lex->server_options.server_name_length= 0;
lex->server_options.host= 0;
lex->server_options.db= 0;
lex->server_options.username= 0;
lex->server_options.password= 0;
lex->server_options.scheme= 0;
lex->server_options.socket= 0;
lex->server_options.owner= 0;
lex->server_options.port= -1;
lex->explain_format= NULL;
lex->is_lex_started= TRUE;
lex->used_tables= 0;
lex->reset_slave_info.all= false;
lex->is_change_password= false;
lex->is_set_password_sql= false;
lex->mark_broken(false);
lex->set_statement= false;
lex->zip_dict_name.str= 0;
lex->zip_dict_name.length= 0;
DBUG_VOID_RETURN;
}
void lex_end(LEX *lex)
{
DBUG_ENTER("lex_end");
DBUG_PRINT("enter", ("lex: 0x%lx", (long) lex));
/* release used plugins */
if (lex->plugins.elements) /* No function call and no mutex if no plugins. */
{
plugin_unlock_list(0, (plugin_ref*)lex->plugins.buffer,
lex->plugins.elements);
}
reset_dynamic(&lex->plugins);
delete lex->sphead;
lex->sphead= NULL;
DBUG_VOID_RETURN;
}
Yacc_state::~Yacc_state()
{
if (yacc_yyss)
{
my_free(yacc_yyss);
my_free(yacc_yyvs);
}
}
static int find_keyword(Lex_input_stream *lip, uint len, bool function)
{
const char *tok= lip->get_tok_start();
SYMBOL *symbol= get_hash_symbol(tok, len, function);
if (symbol)
{
lip->yylval->symbol.symbol=symbol;
lip->yylval->symbol.str= (char*) tok;
lip->yylval->symbol.length=len;
if ((symbol->tok == NOT_SYM) &&
(lip->m_thd->variables.sql_mode & MODE_HIGH_NOT_PRECEDENCE))
return NOT2_SYM;
if ((symbol->tok == OR_OR_SYM) &&
!(lip->m_thd->variables.sql_mode & MODE_PIPES_AS_CONCAT))
return OR2_SYM;
return symbol->tok;
}
return 0;
}
/*
Check if name is a keyword
SYNOPSIS
is_keyword()
name checked name (must not be empty)
len length of checked name
RETURN VALUES
0 name is a keyword
1 name isn't a keyword
*/
bool is_keyword(const char *name, uint len)
{
DBUG_ASSERT(len != 0);
return get_hash_symbol(name,len,0)!=0;
}
/**
Check if name is a sql function
@param name checked name
@return is this a native function or not
@retval 0 name is a function
@retval 1 name isn't a function
*/
bool is_lex_native_function(const LEX_STRING *name)
{
DBUG_ASSERT(name != NULL);
return (get_hash_symbol(name->str, (uint) name->length, 1) != 0);
}
/* make a copy of token before ptr and set yytoklen */
static LEX_STRING get_token(Lex_input_stream *lip, uint skip, uint length)
{
LEX_STRING tmp;
lip->yyUnget(); // ptr points now after last token char
tmp.length=lip->yytoklen=length;
tmp.str= lip->m_thd->strmake(lip->get_tok_start() + skip, tmp.length);
lip->m_cpp_text_start= lip->get_cpp_tok_start() + skip;
lip->m_cpp_text_end= lip->m_cpp_text_start + tmp.length;
return tmp;
}
/*
todo:
There are no dangerous charsets in mysql for function
get_quoted_token yet. But it should be fixed in the
future to operate multichar strings (like ucs2)
*/
static LEX_STRING get_quoted_token(Lex_input_stream *lip,
uint skip,
uint length, char quote)
{
LEX_STRING tmp;
const char *from, *end;
char *to;
lip->yyUnget(); // ptr points now after last token char
tmp.length= lip->yytoklen=length;
tmp.str=(char*) lip->m_thd->alloc(tmp.length+1);
from= lip->get_tok_start() + skip;
to= tmp.str;
end= to+length;
lip->m_cpp_text_start= lip->get_cpp_tok_start() + skip;
lip->m_cpp_text_end= lip->m_cpp_text_start + length;
for ( ; to != end; )
{
if ((*to++= *from++) == quote)
{
from++; // Skip double quotes
lip->m_cpp_text_start++;
}
}
*to= 0; // End null for safety
return tmp;
}
/*
Return an unescaped text literal without quotes
Fix sometimes to do only one scan of the string
*/
static char *get_text(Lex_input_stream *lip, int pre_skip, int post_skip)
{
reg1 uchar c,sep;
uint found_escape=0;
const CHARSET_INFO *cs= lip->m_thd->charset();
lip->tok_bitmap= 0;
sep= lip->yyGetLast(); // String should end with this
while (! lip->eof())
{
c= lip->yyGet();
lip->tok_bitmap|= c;
#ifdef USE_MB
{
int l;
if (use_mb(cs) &&
(l = my_ismbchar(cs,
lip->get_ptr() -1,
lip->get_end_of_query()))) {
lip->skip_binary(l-1);
continue;
}
}
#endif
if (c == '\\' &&
!(lip->m_thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES))
{ // Escaped character
found_escape=1;
if (lip->eof())
return 0;
lip->yySkip();
}
else if (c == sep)
{
if (c == lip->yyGet()) // Check if two separators in a row
{
found_escape=1; // duplicate. Remember for delete
continue;
}
else
lip->yyUnget();
/* Found end. Unescape and return string */
const char *str, *end;
char *start;
str= lip->get_tok_start();
end= lip->get_ptr();
/* Extract the text from the token */
str += pre_skip;
end -= post_skip;
DBUG_ASSERT(end >= str);
if (!(start= (char*) lip->m_thd->alloc((uint) (end-str)+1)))
return (char*) ""; // Sql_alloc has set error flag
lip->m_cpp_text_start= lip->get_cpp_tok_start() + pre_skip;
lip->m_cpp_text_end= lip->get_cpp_ptr() - post_skip;
if (!found_escape)
{
lip->yytoklen=(uint) (end-str);
memcpy(start,str,lip->yytoklen);
start[lip->yytoklen]=0;
}
else
{
char *to;
for (to=start ; str != end ; str++)
{
#ifdef USE_MB
int l;
if (use_mb(cs) &&
(l = my_ismbchar(cs, str, end))) {
while (l--)
*to++ = *str++;
str--;
continue;
}
#endif
if (!(lip->m_thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES) &&
*str == '\\' && str+1 != end)
{
switch(*++str) {
case 'n':
*to++='\n';
break;
case 't':
*to++= '\t';
break;
case 'r':
*to++ = '\r';
break;
case 'b':
*to++ = '\b';
break;
case '0':
*to++= 0; // Ascii null
break;
case 'Z': // ^Z must be escaped on Win32
*to++='\032';
break;
case '_':
case '%':
*to++= '\\'; // remember prefix for wildcard
/* Fall through */
default:
*to++= *str;
break;
}
}
else if (*str == sep)
*to++= *str++; // Two ' or "
else
*to++ = *str;
}
*to=0;
lip->yytoklen=(uint) (to-start);
}
return start;
}
}
return 0; // unexpected end of query
}
/*
** Calc type of integer; long integer, longlong integer or real.
** Returns smallest type that match the string.
** When using unsigned long long values the result is converted to a real
** because else they will be unexpected sign changes because all calculation
** is done with longlong or double.
*/
static const char *long_str="2147483647";
static const uint long_len=10;
static const char *signed_long_str="-2147483648";
static const char *longlong_str="9223372036854775807";
static const uint longlong_len=19;
static const char *signed_longlong_str="-9223372036854775808";
static const uint signed_longlong_len=19;
static const char *unsigned_longlong_str="18446744073709551615";
static const uint unsigned_longlong_len=20;
static inline uint int_token(const char *str,uint length)
{
if (length < long_len) // quick normal case
return NUM;
bool neg=0;
if (*str == '+') // Remove sign and pre-zeros
{
str++; length--;
}
else if (*str == '-')
{
str++; length--;
neg=1;
}
while (*str == '0' && length)
{
str++; length --;
}
if (length < long_len)
return NUM;
uint smaller,bigger;
const char *cmp;
if (neg)
{
if (length == long_len)
{
cmp= signed_long_str+1;
smaller=NUM; // If <= signed_long_str
bigger=LONG_NUM; // If >= signed_long_str
}
else if (length < signed_longlong_len)
return LONG_NUM;
else if (length > signed_longlong_len)
return DECIMAL_NUM;
else
{
cmp=signed_longlong_str+1;
smaller=LONG_NUM; // If <= signed_longlong_str
bigger=DECIMAL_NUM;
}
}
else
{
if (length == long_len)
{
cmp= long_str;
smaller=NUM;
bigger=LONG_NUM;
}
else if (length < longlong_len)
return LONG_NUM;
else if (length > longlong_len)
{
if (length > unsigned_longlong_len)
return DECIMAL_NUM;
cmp=unsigned_longlong_str;
smaller=ULONGLONG_NUM;
bigger=DECIMAL_NUM;
}
else
{
cmp=longlong_str;
smaller=LONG_NUM;
bigger= ULONGLONG_NUM;
}
}
while (*cmp && *cmp++ == *str++) ;
return ((uchar) str[-1] <= (uchar) cmp[-1]) ? smaller : bigger;
}
/**
Given a stream that is advanced to the first contained character in
an open comment, consume the comment. Optionally, if we are allowed,
recurse so that we understand comments within this current comment.
At this level, we do not support version-condition comments. We might
have been called with having just passed one in the stream, though. In
that case, we probably want to tolerate mundane comments inside. Thus,
the case for recursion.
@retval Whether EOF reached before comment is closed.
*/
bool consume_comment(Lex_input_stream *lip, int remaining_recursions_permitted)
{
reg1 uchar c;
while (! lip->eof())
{
c= lip->yyGet();
if (remaining_recursions_permitted > 0)
{
if ((c == '/') && (lip->yyPeek() == '*'))
{
lip->yySkip(); /* Eat asterisk */
consume_comment(lip, remaining_recursions_permitted-1);
continue;
}
}
if (c == '*')
{
if (lip->yyPeek() == '/')
{
lip->yySkip(); /* Eat slash */
return FALSE;
}
}
if (c == '\n')
lip->yylineno++;
}
return TRUE;
}
/*
MYSQLlex remember the following states from the following MYSQLlex()
@param yylval [out] semantic value of the token being parsed (yylval)
@param thd THD
- MY_LEX_EOQ Found end of query
- MY_LEX_OPERATOR_OR_IDENT Last state was an ident, text or number
(which can't be followed by a signed number)
*/
int MYSQLlex(YYSTYPE *yylval, THD *thd)
{
Lex_input_stream *lip= & thd->m_parser_state->m_lip;
int token;
if (lip->lookahead_token >= 0)
{
/*
The next token was already parsed in advance,
return it.
*/
token= lip->lookahead_token;
lip->lookahead_token= -1;
*yylval= *(lip->lookahead_yylval);
lip->lookahead_yylval= NULL;
lip->add_digest_token(token, yylval);
return token;
}
token= lex_one_token(yylval, thd);
switch(token) {
case WITH:
/*
Parsing 'WITH' 'ROLLUP' or 'WITH' 'CUBE' requires 2 look ups,
which makes the grammar LALR(2).
Replace by a single 'WITH_ROLLUP' or 'WITH_CUBE' token,
to transform the grammar into a LALR(1) grammar,
which sql_yacc.yy can process.
*/
token= lex_one_token(yylval, thd);
switch(token) {
case CUBE_SYM:
lip->add_digest_token(WITH_CUBE_SYM, yylval);
return WITH_CUBE_SYM;
case ROLLUP_SYM:
lip->add_digest_token(WITH_ROLLUP_SYM, yylval);
return WITH_ROLLUP_SYM;
default:
/*
Save the token following 'WITH'
*/
lip->lookahead_yylval= lip->yylval;
lip->yylval= NULL;
lip->lookahead_token= token;
lip->add_digest_token(WITH, yylval);
return WITH;
}
break;
default:
break;
}
lip->add_digest_token(token, yylval);
return token;
}
static int lex_one_token(YYSTYPE *yylval, THD *thd)
{
reg1 uchar c= 0;
bool comment_closed;
int tokval, result_state;
uint length;
enum my_lex_states state;
Lex_input_stream *lip= & thd->m_parser_state->m_lip;
LEX *lex= thd->lex;
const CHARSET_INFO *cs= thd->charset();
uchar *state_map= cs->state_map;
uchar *ident_map= cs->ident_map;
lip->yylval=yylval; // The global state
lip->start_token();
state=lip->next_state;
lip->next_state=MY_LEX_OPERATOR_OR_IDENT;
for (;;)
{
switch (state) {
case MY_LEX_OPERATOR_OR_IDENT: // Next is operator or keyword
case MY_LEX_START: // Start of token
// Skip starting whitespace
while(state_map[c= lip->yyPeek()] == MY_LEX_SKIP)
{
if (c == '\n')
lip->yylineno++;
lip->yySkip();
}
/* Start of real token */
lip->restart_token();
c= lip->yyGet();
state= (enum my_lex_states) state_map[c];
break;
case MY_LEX_ESCAPE:
if (lip->yyGet() == 'N')
{ // Allow \N as shortcut for NULL
yylval->lex_str.str=(char*) "\\N";
yylval->lex_str.length=2;
return NULL_SYM;
}
case MY_LEX_CHAR: // Unknown or single char token
case MY_LEX_SKIP: // This should not happen
if (c == '-' && lip->yyPeek() == '-' &&
(my_isspace(cs,lip->yyPeekn(1)) ||
my_iscntrl(cs,lip->yyPeekn(1))))
{
state=MY_LEX_COMMENT;
break;
}
if (c != ')')
lip->next_state= MY_LEX_START; // Allow signed numbers
if (c == ',')
{
/*
Warning:
This is a work around, to make the "remember_name" rule in
sql/sql_yacc.yy work properly.
The problem is that, when parsing "select expr1, expr2",
the code generated by bison executes the *pre* action
remember_name (see select_item) *before* actually parsing the
first token of expr2.
*/
lip->restart_token();
}
else
{
/*
Check for a placeholder: it should not precede a possible identifier
because of binlogging: when a placeholder is replaced with
its value in a query for the binlog, the query must stay
grammatically correct.
*/
if (c == '?' && lip->stmt_prepare_mode && !ident_map[lip->yyPeek()])
return(PARAM_MARKER);
}
return((int) c);
case MY_LEX_IDENT_OR_NCHAR:
if (lip->yyPeek() != '\'')
{
state= MY_LEX_IDENT;
break;
}
/* Found N'string' */
lip->yySkip(); // Skip '
if (!(yylval->lex_str.str = get_text(lip, 2, 1)))
{
state= MY_LEX_CHAR; // Read char by char
break;
}
yylval->lex_str.length= lip->yytoklen;
lex->text_string_is_7bit= (lip->tok_bitmap & 0x80) ? 0 : 1;
return(NCHAR_STRING);
case MY_LEX_IDENT_OR_HEX:
if (lip->yyPeek() == '\'')
{ // Found x'hex-number'
state= MY_LEX_HEX_NUMBER;
break;
}
case MY_LEX_IDENT_OR_BIN:
if (lip->yyPeek() == '\'')
{ // Found b'bin-number'
state= MY_LEX_BIN_NUMBER;
break;
}
case MY_LEX_IDENT:
const char *start;
#if defined(USE_MB) && defined(USE_MB_IDENT)
if (use_mb(cs))
{
result_state= IDENT_QUOTED;
if (my_mbcharlen(cs, lip->yyGetLast()) > 1)
{
int l = my_ismbchar(cs,
lip->get_ptr() -1,
lip->get_end_of_query());
if (l == 0) {
state = MY_LEX_CHAR;
continue;
}
lip->skip_binary(l - 1);
}
while (ident_map[c=lip->yyGet()])
{
if (my_mbcharlen(cs, c) > 1)
{
int l;
if ((l = my_ismbchar(cs,
lip->get_ptr() -1,
lip->get_end_of_query())) == 0)
break;
lip->skip_binary(l-1);
}
}
}
else
#endif
{
for (result_state= c; ident_map[c= lip->yyGet()]; result_state|= c) ;
/* If there were non-ASCII characters, mark that we must convert */
result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
}
length= lip->yyLength();
start= lip->get_ptr();
if (lip->ignore_space)
{
/*
If we find a space then this can't be an identifier. We notice this
below by checking start != lex->ptr.
*/
for (; state_map[c] == MY_LEX_SKIP ; c= lip->yyGet()) ;
}
if (start == lip->get_ptr() && c == '.' && ident_map[lip->yyPeek()])
lip->next_state=MY_LEX_IDENT_SEP;
else
{ // '(' must follow directly if function
lip->yyUnget();
if ((tokval = find_keyword(lip, length, c == '(')))
{
lip->next_state= MY_LEX_START; // Allow signed numbers
return(tokval); // Was keyword
}
lip->yySkip(); // next state does a unget
}
yylval->lex_str=get_token(lip, 0, length);
/*
Note: "SELECT _bla AS 'alias'"
_bla should be considered as a IDENT if charset haven't been found.
So we don't use MYF(MY_WME) with get_charset_by_csname to avoid
producing an error.
*/
if (yylval->lex_str.str[0] == '_')
{
CHARSET_INFO *cs= get_charset_by_csname(yylval->lex_str.str + 1,
MY_CS_PRIMARY, MYF(0));
if (cs)
{
yylval->charset= cs;
lip->m_underscore_cs= cs;
lip->body_utf8_append(lip->m_cpp_text_start,
lip->get_cpp_tok_start() + length);
return(UNDERSCORE_CHARSET);
}
}
lip->body_utf8_append(lip->m_cpp_text_start);
lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
lip->m_cpp_text_end);
return(result_state); // IDENT or IDENT_QUOTED
case MY_LEX_IDENT_SEP: // Found ident and now '.'
yylval->lex_str.str= (char*) lip->get_ptr();
yylval->lex_str.length= 1;
c= lip->yyGet(); // should be '.'
lip->next_state= MY_LEX_IDENT_START;// Next is an ident (not a keyword)
if (!ident_map[lip->yyPeek()]) // Probably ` or "
lip->next_state= MY_LEX_START;
return((int) c);
case MY_LEX_NUMBER_IDENT: // number or ident which num-start
if (lip->yyGetLast() == '0')
{
c= lip->yyGet();
if (c == 'x')
{
while (my_isxdigit(cs,(c = lip->yyGet()))) ;
if ((lip->yyLength() >= 3) && !ident_map[c])
{
/* skip '0x' */
yylval->lex_str=get_token(lip, 2, lip->yyLength()-2);
return (HEX_NUM);
}
lip->yyUnget();
state= MY_LEX_IDENT_START;
break;
}
else if (c == 'b')
{
while ((c= lip->yyGet()) == '0' || c == '1') ;
if ((lip->yyLength() >= 3) && !ident_map[c])
{
/* Skip '0b' */
yylval->lex_str= get_token(lip, 2, lip->yyLength()-2);
return (BIN_NUM);
}
lip->yyUnget();
state= MY_LEX_IDENT_START;
break;
}
lip->yyUnget();
}
while (my_isdigit(cs, (c = lip->yyGet()))) ;
if (!ident_map[c])
{ // Can't be identifier
state=MY_LEX_INT_OR_REAL;
break;
}
if (c == 'e' || c == 'E')
{
// The following test is written this way to allow numbers of type 1e1
if (my_isdigit(cs,lip->yyPeek()) ||
(c=(lip->yyGet())) == '+' || c == '-')
{ // Allow 1E+10
if (my_isdigit(cs,lip->yyPeek())) // Number must have digit after sign
{
lip->yySkip();
while (my_isdigit(cs,lip->yyGet())) ;
yylval->lex_str=get_token(lip, 0, lip->yyLength());
return(FLOAT_NUM);
}
}
lip->yyUnget();
}
// fall through
case MY_LEX_IDENT_START: // We come here after '.'
result_state= IDENT;
#if defined(USE_MB) && defined(USE_MB_IDENT)
if (use_mb(cs))
{
result_state= IDENT_QUOTED;
while (ident_map[c=lip->yyGet()])
{
if (my_mbcharlen(cs, c) > 1)
{
int l;
if ((l = my_ismbchar(cs,
lip->get_ptr() -1,
lip->get_end_of_query())) == 0)
break;
lip->skip_binary(l-1);
}
}
}
else
#endif
{
for (result_state=0; ident_map[c= lip->yyGet()]; result_state|= c) ;
/* If there were non-ASCII characters, mark that we must convert */
result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
}
if (c == '.' && ident_map[lip->yyPeek()])
lip->next_state=MY_LEX_IDENT_SEP;// Next is '.'
yylval->lex_str= get_token(lip, 0, lip->yyLength());
lip->body_utf8_append(lip->m_cpp_text_start);
lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
lip->m_cpp_text_end);
return(result_state);
case MY_LEX_USER_VARIABLE_DELIMITER: // Found quote char
{
uint double_quotes= 0;
char quote_char= c; // Used char
for(;;)
{
c= lip->yyGet();
if (c == 0)
{
lip->yyUnget();
return ABORT_SYM; // Unmatched quotes
}
int var_length;
if ((var_length= my_mbcharlen(cs, c)) == 1)
{
if (c == quote_char)
{
if (lip->yyPeek() != quote_char)
break;
c=lip->yyGet();
double_quotes++;
continue;
}
}
#ifdef USE_MB
else if (use_mb(cs))
{
if ((var_length= my_ismbchar(cs, lip->get_ptr() - 1,
lip->get_end_of_query())))
lip->skip_binary(var_length-1);
}
#endif
}
if (double_quotes)
yylval->lex_str=get_quoted_token(lip, 1,
lip->yyLength() - double_quotes -1,
quote_char);
else
yylval->lex_str=get_token(lip, 1, lip->yyLength() -1);
if (c == quote_char)
lip->yySkip(); // Skip end `
lip->next_state= MY_LEX_START;
lip->body_utf8_append(lip->m_cpp_text_start);
lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
lip->m_cpp_text_end);
return(IDENT_QUOTED);
}
case MY_LEX_INT_OR_REAL: // Complete int or incomplete real
if (c != '.')
{ // Found complete integer number.
yylval->lex_str=get_token(lip, 0, lip->yyLength());
return int_token(yylval->lex_str.str, (uint) yylval->lex_str.length);
}
// fall through
case MY_LEX_REAL: // Incomplete real number
while (my_isdigit(cs,c = lip->yyGet())) ;
if (c == 'e' || c == 'E')
{
c = lip->yyGet();
if (c == '-' || c == '+')
c = lip->yyGet(); // Skip sign
if (!my_isdigit(cs,c))
{ // No digit after sign
state= MY_LEX_CHAR;
break;
}
while (my_isdigit(cs,lip->yyGet())) ;
yylval->lex_str=get_token(lip, 0, lip->yyLength());
return(FLOAT_NUM);
}
yylval->lex_str=get_token(lip, 0, lip->yyLength());
return(DECIMAL_NUM);
case MY_LEX_HEX_NUMBER: // Found x'hexstring'
lip->yySkip(); // Accept opening '
while (my_isxdigit(cs, (c= lip->yyGet()))) ;
if (c != '\'')
return(ABORT_SYM); // Illegal hex constant
lip->yySkip(); // Accept closing '
length= lip->yyLength(); // Length of hexnum+3
if ((length % 2) == 0)
return(ABORT_SYM); // odd number of hex digits
yylval->lex_str=get_token(lip,
2, // skip x'
length-3); // don't count x' and last '
return (HEX_NUM);
case MY_LEX_BIN_NUMBER: // Found b'bin-string'
lip->yySkip(); // Accept opening '
while ((c= lip->yyGet()) == '0' || c == '1') ;
if (c != '\'')
return(ABORT_SYM); // Illegal hex constant
lip->yySkip(); // Accept closing '
length= lip->yyLength(); // Length of bin-num + 3
yylval->lex_str= get_token(lip,
2, // skip b'
length-3); // don't count b' and last '
return (BIN_NUM);
case MY_LEX_CMP_OP: // Incomplete comparison operator
if (state_map[lip->yyPeek()] == MY_LEX_CMP_OP ||
state_map[lip->yyPeek()] == MY_LEX_LONG_CMP_OP)
lip->yySkip();
if ((tokval = find_keyword(lip, lip->yyLength() + 1, 0)))
{
lip->next_state= MY_LEX_START; // Allow signed numbers
return(tokval);
}
state = MY_LEX_CHAR; // Something fishy found
break;
case MY_LEX_LONG_CMP_OP: // Incomplete comparison operator
if (state_map[lip->yyPeek()] == MY_LEX_CMP_OP ||
state_map[lip->yyPeek()] == MY_LEX_LONG_CMP_OP)
{
lip->yySkip();
if (state_map[lip->yyPeek()] == MY_LEX_CMP_OP)
lip->yySkip();
}
if ((tokval = find_keyword(lip, lip->yyLength() + 1, 0)))
{
lip->next_state= MY_LEX_START; // Found long op
return(tokval);
}
state = MY_LEX_CHAR; // Something fishy found
break;
case MY_LEX_BOOL:
if (c != lip->yyPeek())
{
state=MY_LEX_CHAR;
break;
}
lip->yySkip();
tokval = find_keyword(lip,2,0); // Is a bool operator
lip->next_state= MY_LEX_START; // Allow signed numbers
return(tokval);
case MY_LEX_STRING_OR_DELIMITER:
if (thd->variables.sql_mode & MODE_ANSI_QUOTES)
{
state= MY_LEX_USER_VARIABLE_DELIMITER;
break;
}
/* " used for strings */
case MY_LEX_STRING: // Incomplete text string
if (!(yylval->lex_str.str = get_text(lip, 1, 1)))
{
state= MY_LEX_CHAR; // Read char by char
break;
}
yylval->lex_str.length=lip->yytoklen;
lip->body_utf8_append(lip->m_cpp_text_start);
lip->body_utf8_append_literal(thd, &yylval->lex_str,
lip->m_underscore_cs ? lip->m_underscore_cs : cs,
lip->m_cpp_text_end);
lip->m_underscore_cs= NULL;
lex->text_string_is_7bit= (lip->tok_bitmap & 0x80) ? 0 : 1;
return(TEXT_STRING);
case MY_LEX_COMMENT: // Comment
lex->select_lex.options|= OPTION_FOUND_COMMENT;
while ((c = lip->yyGet()) != '\n' && c) ;
lip->yyUnget(); // Safety against eof
state = MY_LEX_START; // Try again
break;
case MY_LEX_LONG_COMMENT: /* Long C comment? */
if (lip->yyPeek() != '*')
{
state=MY_LEX_CHAR; // Probable division
break;
}
lex->select_lex.options|= OPTION_FOUND_COMMENT;
/* Reject '/' '*', since we might need to turn off the echo */
lip->yyUnget();
lip->save_in_comment_state();
if (lip->yyPeekn(2) == '!')
{
lip->in_comment= DISCARD_COMMENT;
/* Accept '/' '*' '!', but do not keep this marker. */
lip->set_echo(FALSE);
lip->yySkip();
lip->yySkip();
lip->yySkip();
/*
The special comment format is very strict:
'/' '*' '!', followed by exactly
1 digit (major), 2 digits (minor), then 2 digits (dot).
32302 -> 3.23.02
50032 -> 5.0.32
50114 -> 5.1.14
*/
char version_str[6];
version_str[0]= lip->yyPeekn(0);
version_str[1]= lip->yyPeekn(1);
version_str[2]= lip->yyPeekn(2);
version_str[3]= lip->yyPeekn(3);
version_str[4]= lip->yyPeekn(4);
version_str[5]= 0;
if ( my_isdigit(cs, version_str[0])
&& my_isdigit(cs, version_str[1])
&& my_isdigit(cs, version_str[2])
&& my_isdigit(cs, version_str[3])
&& my_isdigit(cs, version_str[4])
)
{
ulong version;
version=strtol(version_str, NULL, 10);
if (version <= MYSQL_VERSION_ID)
{
/* Accept 'M' 'm' 'm' 'd' 'd' */
lip->yySkipn(5);
/* Expand the content of the special comment as real code */
lip->set_echo(TRUE);
state=MY_LEX_START;
break; /* Do not treat contents as a comment. */
}
else
{
/*
Patch and skip the conditional comment to avoid it
being propagated infinitely (eg. to a slave).
*/
char *pcom= lip->yyUnput(' ');
comment_closed= ! consume_comment(lip, 1);
if (! comment_closed)
{
*pcom= '!';
}
/* version allowed to have one level of comment inside. */
}
}
else
{
/* Not a version comment. */
state=MY_LEX_START;
lip->set_echo(TRUE);
break;
}
}
else
{
lip->in_comment= PRESERVE_COMMENT;
lip->yySkip(); // Accept /
lip->yySkip(); // Accept *
comment_closed= ! consume_comment(lip, 0);
/* regular comments can have zero comments inside. */
}
/*
Discard:
- regular '/' '*' comments,
- special comments '/' '*' '!' for a future version,
by scanning until we find a closing '*' '/' marker.
Nesting regular comments isn't allowed. The first
'*' '/' returns the parser to the previous state.
/#!VERSI oned containing /# regular #/ is allowed #/
Inside one versioned comment, another versioned comment
is treated as a regular discardable comment. It gets
no special parsing.
*/
/* Unbalanced comments with a missing '*' '/' are a syntax error */
if (! comment_closed)
return (ABORT_SYM);
state = MY_LEX_START; // Try again
lip->restore_in_comment_state();
break;
case MY_LEX_END_LONG_COMMENT:
if ((lip->in_comment != NO_COMMENT) && lip->yyPeek() == '/')
{
/* Reject '*' '/' */
lip->yyUnget();
/* Accept '*' '/', with the proper echo */
lip->set_echo(lip->in_comment == PRESERVE_COMMENT);
lip->yySkipn(2);
/* And start recording the tokens again */
lip->set_echo(TRUE);
/*
C-style comments are replaced with a single space (as it
is in C and C++). If there is already a whitespace
character at this point in the stream, the space is
not inserted.
See also ISO/IEC 9899:1999 §5.1.1.2
("Programming languages — C")
*/
if (!my_isspace(cs, lip->yyPeek()) &&
lip->get_cpp_ptr() != lip->get_cpp_buf() &&
!my_isspace(cs, *(lip->get_cpp_ptr() - 1)))
lip->cpp_inject(' ');
lip->in_comment=NO_COMMENT;
state=MY_LEX_START;
}
else
state=MY_LEX_CHAR; // Return '*'
break;
case MY_LEX_SET_VAR: // Check if ':='
if (lip->yyPeek() != '=')
{
state=MY_LEX_CHAR; // Return ':'
break;
}
lip->yySkip();
return (SET_VAR);
case MY_LEX_SEMICOLON: // optional line terminator
state= MY_LEX_CHAR; // Return ';'
break;
case MY_LEX_EOL:
if (lip->eof())
{
lip->yyUnget(); // Reject the last '\0'
lip->set_echo(FALSE);
lip->yySkip();
lip->set_echo(TRUE);
/* Unbalanced comments with a missing '*' '/' are a syntax error */
if (lip->in_comment != NO_COMMENT)
return (ABORT_SYM);
lip->next_state=MY_LEX_END; // Mark for next loop
return(END_OF_INPUT);
}
state=MY_LEX_CHAR;
break;
case MY_LEX_END:
lip->next_state=MY_LEX_END;
return(0); // We found end of input last time
/* Actually real shouldn't start with . but allow them anyhow */
case MY_LEX_REAL_OR_POINT:
if (my_isdigit(cs,lip->yyPeek()))
state = MY_LEX_REAL; // Real
else
{
state= MY_LEX_IDENT_SEP; // return '.'
lip->yyUnget(); // Put back '.'
}
break;
case MY_LEX_USER_END: // end '@' of user@hostname
switch (state_map[lip->yyPeek()]) {
case MY_LEX_STRING:
case MY_LEX_USER_VARIABLE_DELIMITER:
case MY_LEX_STRING_OR_DELIMITER:
break;
case MY_LEX_USER_END:
lip->next_state=MY_LEX_SYSTEM_VAR;
break;
default:
lip->next_state=MY_LEX_HOSTNAME;
break;
}
yylval->lex_str.str=(char*) lip->get_ptr();
yylval->lex_str.length=1;
return((int) '@');
case MY_LEX_HOSTNAME: // end '@' of user@hostname
for (c=lip->yyGet() ;
my_isalnum(cs,c) || c == '.' || c == '_' || c == '$';
c= lip->yyGet()) ;
yylval->lex_str=get_token(lip, 0, lip->yyLength());
return(LEX_HOSTNAME);
case MY_LEX_SYSTEM_VAR:
yylval->lex_str.str=(char*) lip->get_ptr();
yylval->lex_str.length=1;
lip->yySkip(); // Skip '@'
lip->next_state= (state_map[lip->yyPeek()] ==
MY_LEX_USER_VARIABLE_DELIMITER ?
MY_LEX_OPERATOR_OR_IDENT :
MY_LEX_IDENT_OR_KEYWORD);
return((int) '@');
case MY_LEX_IDENT_OR_KEYWORD:
/*
We come here when we have found two '@' in a row.
We should now be able to handle:
[(global | local | session) .]variable_name
*/
for (result_state= 0; ident_map[c= lip->yyGet()]; result_state|= c) ;
/* If there were non-ASCII characters, mark that we must convert */
result_state= result_state & 0x80 ? IDENT_QUOTED : IDENT;
if (c == '.')
lip->next_state=MY_LEX_IDENT_SEP;
length= lip->yyLength();
if (length == 0)
return(ABORT_SYM); // Names must be nonempty.
if ((tokval= find_keyword(lip, length,0)))
{
lip->yyUnget(); // Put back 'c'
return(tokval); // Was keyword
}
yylval->lex_str=get_token(lip, 0, length);
lip->body_utf8_append(lip->m_cpp_text_start);
lip->body_utf8_append_literal(thd, &yylval->lex_str, cs,
lip->m_cpp_text_end);
return(result_state);
}
}
}
void trim_whitespace(const CHARSET_INFO *cs, LEX_STRING *str)
{
/*
TODO:
This code assumes that there are no multi-bytes characters
that can be considered white-space.
*/
while ((str->length > 0) && (my_isspace(cs, str->str[0])))
{
str->length --;
str->str ++;
}
/*
FIXME:
Also, parsing backward is not safe with multi bytes characters
*/
while ((str->length > 0) && (my_isspace(cs, str->str[str->length-1])))
{
str->length --;
/* set trailing spaces to 0 as there're places that don't respect length */
str->str[str->length]= 0;
}
}
/*
st_select_lex structures initialisations
*/
void st_select_lex_node::init_query()
{
options= 0;
sql_cache= SQL_CACHE_UNSPECIFIED;
linkage= UNSPECIFIED_TYPE;
no_error= no_table_names_allowed= 0;
uncacheable= 0;
}
void st_select_lex_node::init_select()
{
}
void st_select_lex_unit::init_query()
{
st_select_lex_node::init_query();
linkage= GLOBAL_OPTIONS_TYPE;
global_parameters= first_select();
select_limit_cnt= HA_POS_ERROR;
offset_limit_cnt= 0;
union_distinct= 0;
prepared= optimized= executed= 0;
item= 0;
union_result= 0;
table= 0;
fake_select_lex= 0;
cleaned= 0;
item_list.empty();
describe= 0;
found_rows_for_union= 0;
result= NULL;
}
void st_select_lex::init_query()
{
st_select_lex_node::init_query();
resolve_place= RESOLVE_NONE;
resolve_nest= NULL;
table_list.empty();
top_join_list.empty();
join_list= &top_join_list;
embedding= leaf_tables= 0;
item_list.empty();
join= 0;
having= prep_having= where= prep_where= 0;
olap= UNSPECIFIED_OLAP_TYPE;
having_fix_field= 0;
group_fix_field= 0;
context.select_lex= this;
context.init();
/*
Add the name resolution context of the current (sub)query to the
stack of contexts for the whole query.
TODO:
push_context may return an error if there is no memory for a new
element in the stack, however this method has no return value,
thus push_context should be moved to a place where query
initialization is checked for failure.
*/
parent_lex->push_context(&context);
cond_count= between_count= with_wild= 0;
max_equal_elems= 0;
ref_pointer_array.reset();
select_n_where_fields= 0;
select_n_having_items= 0;
n_sum_items= 0;
n_child_sum_items= 0;
subquery_in_having= explicit_limit= 0;
is_item_list_lookup= 0;
first_execution= 1;
first_natural_join_processing= 1;
first_cond_optimization= 1;
parsing_place= NO_MATTER;
exclude_from_table_unique_test= no_wrap_view_item= FALSE;
nest_level= 0;
link_next= 0;
select_list_tables= 0;
m_non_agg_field_used= false;
m_agg_func_used= false;
with_sum_func= false;
removed_select= NULL;
}
void st_select_lex::init_select()
{
st_select_lex_node::init_select();
sj_nests.empty();
group_list.empty();
if (group_list_ptrs)
group_list_ptrs->clear();
db= 0;
having= 0;
table_join_options= 0;
in_sum_expr= with_wild= 0;
options= 0;
sql_cache= SQL_CACHE_UNSPECIFIED;
braces= 0;
interval_list.empty();
ftfunc_list_alloc.empty();
inner_sum_func_list= 0;
ftfunc_list= &ftfunc_list_alloc;
linkage= UNSPECIFIED_TYPE;
order_list.elements= 0;
order_list.first= 0;
order_list.next= &order_list.first;
if (order_list_ptrs)
order_list_ptrs->clear();
/* Set limit and offset to default values */
select_limit= 0; /* denotes the default limit = HA_POS_ERROR */
offset_limit= 0; /* denotes the default offset = 0 */
with_sum_func= 0;
cur_pos_in_all_fields= ALL_FIELDS_UNDEF_POS;
non_agg_fields.empty();
cond_value= having_value= Item::COND_UNDEF;
inner_refs_list.empty();
m_non_agg_field_used= false;
m_agg_func_used= false;
}
/*
st_select_lex structures linking
*/
/* include on level down */
void st_select_lex_node::include_down(st_select_lex_node *upper)
{
if ((next= upper->slave))
next->prev= &next;
prev= &upper->slave;
upper->slave= this;
master= upper;
slave= 0;
}
/*
include on level down (but do not link)
SYNOPSYS
st_select_lex_node::include_standalone()
upper - reference on node underr which this node should be included
ref - references on reference on this node
*/
void st_select_lex_node::include_standalone(st_select_lex_node *upper,
st_select_lex_node **ref)
{
next= 0;
prev= ref;
master= upper;
slave= 0;
}
/* include neighbour (on same level) */
void st_select_lex_node::include_neighbour(st_select_lex_node *before)
{
if ((next= before->next))
next->prev= &next;
prev= &before->next;
before->next= this;
master= before->master;
slave= 0;
}
/* including in global SELECT_LEX list */
void st_select_lex_node::include_global(st_select_lex_node **plink)
{
if ((link_next= *plink))
link_next->link_prev= &link_next;
link_prev= plink;
*plink= this;
}
//excluding from global list (internal function)
void st_select_lex_node::fast_exclude()
{
if (link_prev)
{
if ((*link_prev= link_next))
link_next->link_prev= link_prev;
}
// Remove slave structure
for (; slave; slave= slave->next)
slave->fast_exclude();
}
/*
excluding select_lex structure (except first (first select can't be
deleted, because it is most upper select))
*/
void st_select_lex_node::exclude()
{
//exclude from global list
fast_exclude();
//exclude from other structures
if ((*prev= next))
next->prev= prev;
/*
We do not need following statements, because prev pointer of first
list element point to master->slave
if (master->slave == this)
master->slave= next;
*/
}
/*
Exclude level of current unit from tree of SELECTs
SYNOPSYS
st_select_lex_unit::exclude_level()
NOTE: units which belong to current will be brought up on level of
currernt unit
*/
void st_select_lex_unit::exclude_level()
{
SELECT_LEX_UNIT *units= NULL;
SELECT_LEX_UNIT **units_last= &units;
SELECT_LEX *sl= first_select();
while (sl)
{
SELECT_LEX *next_select= sl->next_select();
// unlink current level from global SELECTs list
if (sl->link_prev && (*sl->link_prev= sl->link_next))
sl->link_next->link_prev= sl->link_prev;
// bring up underlay levels
SELECT_LEX_UNIT **last= NULL;
for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
{
/*
We are excluding a SELECT_LEX from the hierarchy of
SELECT_LEX_UNITs and SELECT_LEXes. Since this level is
removed, we must also exclude the Name_resolution_context
belonging to this level. Do this by looping through inner
subqueries and changing their contexts' outer context pointers
to point to the outer context of the removed SELECT_LEX.
*/
for (SELECT_LEX *s= u->first_select(); s; s= s->next_select())
{
if (s->context.outer_context == &sl->context)
s->context.outer_context= sl->context.outer_context;
}
u->master= master;
last= (SELECT_LEX_UNIT**)&(u->next);
}
if (last)
{
(*units_last)= sl->first_inner_unit();
units_last= last;
}
// clean up and destroy join
sl->cleanup_level();
sl->invalidate();
sl= next_select;
}
if (units)
{
// include brought up levels in place of current
(*prev)= units;
(*units_last)= (SELECT_LEX_UNIT*)next;
if (next)
next->prev= (SELECT_LEX_NODE**)units_last;
units->prev= prev;
}
else
{
// exclude currect unit from list of nodes
if (prev)
(*prev)= next;
if (next)
next->prev= prev;
}
// clean up fake_select_lex and global_parameters
cleanup_level();
invalidate();
}
/*
Exclude subtree of current unit from tree of SELECTs
SYNOPSYS
st_select_lex_unit::exclude_tree()
*/
void st_select_lex_unit::exclude_tree()
{
SELECT_LEX *sl= first_select();
while (sl)
{
SELECT_LEX *next_select= sl->next_select();
// unlink current level from global SELECTs list
if (sl->link_prev && (*sl->link_prev= sl->link_next))
sl->link_next->link_prev= sl->link_prev;
// unlink underlay levels
for (SELECT_LEX_UNIT *u= sl->first_inner_unit(); u; u= u->next_unit())
{
u->exclude_level();
}
// clean up and destroy join
sl->cleanup();
sl->invalidate();
sl= next_select;
}
// exclude currect unit from list of nodes
if (prev)
(*prev)= next;
if (next)
next->prev= prev;
// clean up fake_select_lex and global_parameters
cleanup();
invalidate();
}
/**
Invalidate by nulling out pointers to other st_select_lex_units and
st_select_lexes.
*/
void st_select_lex_unit::invalidate()
{
next= NULL;
prev= NULL;
master= NULL;
slave= NULL;
link_next= NULL;
link_prev= NULL;
}
/*
st_select_lex_node::mark_as_dependent mark all st_select_lex struct from
this to 'last' as dependent
SYNOPSIS
last - pointer to last st_select_lex struct, before wich all
st_select_lex have to be marked as dependent
NOTE
'last' should be reachable from this st_select_lex_node
*/
void st_select_lex::mark_as_dependent(st_select_lex *last)
{
/*
Mark all selects from resolved to 1 before select where was
found table as depended (of select where was found table)
*/
for (SELECT_LEX *s= this;
s && s != last;
s= s->outer_select())
{
if (!(s->uncacheable & UNCACHEABLE_DEPENDENT))
{
// Select is dependent of outer select
s->uncacheable= (s->uncacheable & ~UNCACHEABLE_UNITED) |
UNCACHEABLE_DEPENDENT;
SELECT_LEX_UNIT *munit= s->master_unit();
munit->uncacheable= (munit->uncacheable & ~UNCACHEABLE_UNITED) |
UNCACHEABLE_DEPENDENT;
for (SELECT_LEX *sl= munit->first_select(); sl ; sl= sl->next_select())
{
if (sl != s &&
!(sl->uncacheable & (UNCACHEABLE_DEPENDENT | UNCACHEABLE_UNITED)))
sl->uncacheable|= UNCACHEABLE_UNITED;
}
}
}
}
bool st_select_lex_node::set_braces(bool value) { return 1; }
bool st_select_lex_node::inc_in_sum_expr() { return 1; }
uint st_select_lex_node::get_in_sum_expr() { return 0; }
TABLE_LIST* st_select_lex_node::get_table_list() { return 0; }
List<Item>* st_select_lex_node::get_item_list() { return 0; }
TABLE_LIST *st_select_lex_node::add_table_to_list(THD *thd, Table_ident *table,
LEX_STRING *alias,
ulong table_join_options,
thr_lock_type flags,
enum_mdl_type mdl_type,
List<Index_hint> *hints,
List<String> *partition_names,
LEX_STRING *option)
{
return 0;
}
ulong st_select_lex_node::get_table_join_options()
{
return 0;
}
/*
prohibit using LIMIT clause
*/
bool st_select_lex::test_limit()
{
if (select_limit != 0)
{
my_error(ER_NOT_SUPPORTED_YET, MYF(0),
"LIMIT & IN/ALL/ANY/SOME subquery");
return(1);
}
return(0);
}
st_select_lex_unit* st_select_lex_unit::master_unit()
{
return this;
}
st_select_lex* st_select_lex_unit::outer_select()
{
return (st_select_lex*) master;
}
bool st_select_lex::add_order_to_list(THD *thd, Item *item, bool asc)
{
return add_to_list(thd, order_list, item, asc);
}
bool st_select_lex::add_gorder_to_list(THD *thd, Item *item, bool asc)
{
return add_to_list(thd, gorder_list, item, asc);
}
bool st_select_lex::add_item_to_list(THD *thd, Item *item)
{
DBUG_ENTER("st_select_lex::add_item_to_list");
DBUG_PRINT("info", ("Item: 0x%lx", (long) item));
DBUG_RETURN(item_list.push_back(item));
}
bool st_select_lex::add_group_to_list(THD *thd, Item *item, bool asc)
{
return add_to_list(thd, group_list, item, asc);
}
bool st_select_lex::add_ftfunc_to_list(Item_func_match *func)
{
return !func || ftfunc_list->push_back(func); // end of memory?
}
st_select_lex_unit* st_select_lex::master_unit()
{
return (st_select_lex_unit*) master;
}
st_select_lex* st_select_lex::outer_select()
{
return (st_select_lex*) master->get_master();
}
/**
Invalidate by nulling out pointers to other st_select_lex_units and
st_select_lexes.
*/
void st_select_lex::invalidate()
{
next= NULL;
prev= NULL;
master= NULL;
slave= NULL;
link_next= NULL;
link_prev= NULL;
}
bool st_select_lex::set_braces(bool value)
{
braces= value;
return 0;
}
bool st_select_lex::inc_in_sum_expr()
{
in_sum_expr++;
return 0;
}
uint st_select_lex::get_in_sum_expr()
{
return in_sum_expr;
}
TABLE_LIST* st_select_lex::get_table_list()
{
return table_list.first;
}
List<Item>* st_select_lex::get_item_list()
{
return &item_list;
}
ulong st_select_lex::get_table_join_options()
{
return table_join_options;
}
bool st_select_lex::setup_ref_array(THD *thd, uint order_group_num)
{
// find_order_in_list() may need some extra space, so multiply by two.
order_group_num*= 2;
// create_distinct_group() may need some extra space
const bool select_distinct= MY_TEST(options & SELECT_DISTINCT);
if (select_distinct)
{
uint bitcount= 0;
Item *item;
List_iterator<Item> li(item_list);
while ((item= li++))
{
/*
Same test as in create_distinct_group, when it pushes new items to the
end of ref_pointer_array. An extra test for 'fixed' which, at this
stage, will be true only for columns inserted for a '*' wildcard.
*/
if (item->fixed &&
item->type() == Item::FIELD_ITEM &&
item->field_type() == MYSQL_TYPE_BIT)
++bitcount;
}
order_group_num+= bitcount;
}
/*
We have to create array in prepared statement memory if it is
prepared statement
*/
Query_arena *arena= thd->stmt_arena;
const uint n_elems= (n_sum_items +
n_child_sum_items +
item_list.elements +
select_n_having_items +
select_n_where_fields +
order_group_num) * 5;
DBUG_PRINT("info", ("setup_ref_array this %p %4u : %4u %4u %4u %4u %4u %4u",
this,
n_elems, // :
n_sum_items,
n_child_sum_items,
item_list.elements,
select_n_having_items,
select_n_where_fields,
order_group_num));
if (!ref_pointer_array.is_null())
{
/*
We need to take 'n_sum_items' into account when allocating the array,
and this may actually increase during the optimization phase due to
MIN/MAX rewrite in Item_in_subselect::single_value_transformer.
In the usual case we can reuse the array from the prepare phase.
If we need a bigger array, we must allocate a new one.
*/
if (ref_pointer_array.size() >= n_elems)
return false;
}
Item **array= static_cast<Item**>(arena->alloc(sizeof(Item*) * n_elems));
if (array != NULL)
ref_pointer_array= Ref_ptr_array(array, n_elems);
return array == NULL;
}
void st_select_lex_unit::print(String *str, enum_query_type query_type)
{
bool union_all= !union_distinct;
for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
{
if (sl != first_select())
{
str->append(STRING_WITH_LEN(" union "));
if (union_all)
str->append(STRING_WITH_LEN("all "));
else if (union_distinct == sl)
union_all= TRUE;
}
if (sl->braces)
str->append('(');
sl->print(thd, str, query_type);
if (sl->braces)
str->append(')');
}
if (fake_select_lex == global_parameters)
{
if (fake_select_lex->order_list.elements)
{
str->append(STRING_WITH_LEN(" order by "));
fake_select_lex->print_order(str,
fake_select_lex->order_list.first,
query_type);
}
fake_select_lex->print_limit(thd, str, query_type);
}
}
void st_select_lex::print_order(String *str,
ORDER *order,
enum_query_type query_type)
{
for (; order; order= order->next)
{
if (order->counter_used)
{
char buffer[20];
size_t length= my_snprintf(buffer, 20, "%d", order->counter);
str->append(buffer, (uint) length);
}
else
(*order->item)->print_for_order(str, query_type, order->used_alias);
if (order->direction == ORDER::ORDER_DESC)
str->append(STRING_WITH_LEN(" desc"));
if (order->next)
str->append(',');
}
}
void st_select_lex::print_limit(THD *thd,
String *str,
enum_query_type query_type)
{
SELECT_LEX_UNIT *unit= master_unit();
Item_subselect *item= unit->item;
if (item && unit->global_parameters == this)
{
Item_subselect::subs_type subs_type= item->substype();
if (subs_type == Item_subselect::EXISTS_SUBS ||
subs_type == Item_subselect::IN_SUBS ||
subs_type == Item_subselect::ALL_SUBS)
return;
}
if (explicit_limit)
{
str->append(STRING_WITH_LEN(" limit "));
if (offset_limit)
{
offset_limit->print(str, query_type);
str->append(',');
}
select_limit->print(str, query_type);
}
}
/**
@brief Print an index hint
@details Prints out the USE|FORCE|IGNORE index hint.
@param thd the current thread
@param[out] str appends the index hint here
@param hint what the hint is (as string : "USE INDEX"|
"FORCE INDEX"|"IGNORE INDEX")
@param hint_length the length of the string in 'hint'
@param indexes a list of index names for the hint
*/
void
Index_hint::print(THD *thd, String *str)
{
switch (type)
{
case INDEX_HINT_IGNORE: str->append(STRING_WITH_LEN("IGNORE INDEX")); break;
case INDEX_HINT_USE: str->append(STRING_WITH_LEN("USE INDEX")); break;
case INDEX_HINT_FORCE: str->append(STRING_WITH_LEN("FORCE INDEX")); break;
}
switch (clause)
{
case INDEX_HINT_MASK_ALL:
break;
case INDEX_HINT_MASK_JOIN:
str->append(STRING_WITH_LEN(" FOR JOIN"));
break;
case INDEX_HINT_MASK_ORDER:
str->append(STRING_WITH_LEN(" FOR ORDER BY"));
break;
case INDEX_HINT_MASK_GROUP:
str->append(STRING_WITH_LEN(" FOR GROUP BY"));
break;
}
str->append (STRING_WITH_LEN(" ("));
if (key_name.length)
{
if (thd && !my_strnncoll(system_charset_info,
(const uchar *)key_name.str, key_name.length,
(const uchar *)primary_key_name,
strlen(primary_key_name)))
str->append(primary_key_name);
else
append_identifier(thd, str, key_name.str, key_name.length);
}
str->append(')');
}
static void print_table_array(THD *thd, String *str, TABLE_LIST **table,
TABLE_LIST **end, enum_query_type query_type)
{
(*table)->print(thd, str, query_type);
for (TABLE_LIST **tbl= table + 1; tbl < end; tbl++)
{
TABLE_LIST *curr= *tbl;
// Print the join operator which relates this table to the previous one
if (curr->outer_join)
{
/* MySQL converts right to left joins */
str->append(STRING_WITH_LEN(" left join "));
}
else if (curr->straight)
str->append(STRING_WITH_LEN(" straight_join "));
else if (curr->sj_on_expr)
str->append(STRING_WITH_LEN(" semi join "));
else
str->append(STRING_WITH_LEN(" join "));
curr->print(thd, str, query_type); // Print table
if (curr->join_cond()) // Print join condition
{
str->append(STRING_WITH_LEN(" on("));
curr->join_cond()->print(str, query_type);
str->append(')');
}
}
}
/**
Print joins from the FROM clause.
@param thd thread handler
@param str string where table should be printed
@param tables list of tables in join
@query_type type of the query is being generated
*/
static void print_join(THD *thd,
String *str,
List<TABLE_LIST> *tables,
enum_query_type query_type)
{
/* List is reversed => we should reverse it before using */
List_iterator_fast<TABLE_LIST> ti(*tables);
TABLE_LIST **table;
/*
If the QT_NO_DATA_EXPANSION flag is specified, we print the
original table list, including constant tables that have been
optimized away, as the constant tables may be referenced in the
expression printed by Item_field::print() when this flag is given.
Otherwise, only non-const tables are printed.
Example:
Original SQL:
select * from (select 1) t
Printed without QT_NO_DATA_EXPANSION:
select '1' AS `1` from dual
Printed with QT_NO_DATA_EXPANSION:
select `t`.`1` from (select 1 AS `1`) `t`
*/
const bool print_const_tables= (query_type & QT_NO_DATA_EXPANSION);
size_t tables_to_print= 0;
for (TABLE_LIST *t= ti++; t ; t= ti++)
if (print_const_tables || !t->optimized_away)
tables_to_print++;
if (tables_to_print == 0)
{
str->append(STRING_WITH_LEN("dual"));
return; // all tables were optimized away
}
ti.rewind();
if (!(table= static_cast<TABLE_LIST **>(thd->alloc(sizeof(TABLE_LIST*) *
tables_to_print))))
return; // out of memory
TABLE_LIST *tmp, **t= table + (tables_to_print - 1);
while ((tmp= ti++))
{
if (tmp->optimized_away && !print_const_tables)
continue;
*t--= tmp;
}
/*
If the first table is a semi-join nest, swap it with something that is
not a semi-join nest. This is necessary because "A SEMIJOIN B" is not the
same as "B SEMIJOIN A".
*/
if ((*table)->sj_on_expr)
{
TABLE_LIST **end= table + tables_to_print;
for (TABLE_LIST **t2= table; t2!=end; t2++)
{
if (!(*t2)->sj_on_expr)
{
TABLE_LIST *tmp= *t2;
*t2= *table;
*table= tmp;
break;
}
}
}
DBUG_ASSERT(tables_to_print >= 1);
print_table_array(thd, str, table, table + tables_to_print, query_type);
}
/**
@returns whether a database is equal to the connection's default database
*/
bool db_is_default_db(const char *db, size_t db_len, const THD *thd)
{
return thd != NULL && thd->db != NULL &&
thd->db_length == db_len && !memcmp(db, thd->db, db_len);
}
/**
Print table as it should be in join list.
@param str string where table should be printed
*/
void TABLE_LIST::print(THD *thd, String *str, enum_query_type query_type)
{
if (nested_join)
{
str->append('(');
print_join(thd, str, &nested_join->join_list, query_type);
str->append(')');
}
else
{
const char *cmp_name; // Name to compare with alias
if (view_name.str)
{
// A view
if (!(belong_to_view &&
belong_to_view->compact_view_format) &&
!((query_type & QT_NO_DEFAULT_DB) &&
db_is_default_db(view_db.str, view_db.length, thd)))
{
append_identifier(thd, str, view_db.str, view_db.length);
str->append('.');
}
append_identifier(thd, str, view_name.str, view_name.length);
cmp_name= view_name.str;
}
else if (derived)
{
// A derived table
if (!(query_type & QT_DERIVED_TABLE_ONLY_ALIAS))
{
str->append('(');
derived->print(str, query_type);
str->append(')');
}
cmp_name= ""; // Force printing of alias
}
else
{
// A normal table
if (!(belong_to_view &&
belong_to_view->compact_view_format) &&
!((query_type & QT_NO_DEFAULT_DB) &&
db_is_default_db(db, db_length, thd)))
{
append_identifier(thd, str, db, db_length);
str->append('.');
}
if (schema_table)
{
append_identifier(thd, str, schema_table_name,
strlen(schema_table_name));
cmp_name= schema_table_name;
}
else
{
append_identifier(thd, str, table_name, table_name_length);
cmp_name= table_name;
}
#ifdef WITH_PARTITION_STORAGE_ENGINE
if (partition_names && partition_names->elements)
{
int i, num_parts= partition_names->elements;
List_iterator<String> name_it(*(partition_names));
str->append(STRING_WITH_LEN(" PARTITION ("));
for (i= 1; i <= num_parts; i++)
{
String *name= name_it++;
append_identifier(thd, str, name->c_ptr(), name->length());
if (i != num_parts)
str->append(',');
}
str->append(')');
}
#endif /* WITH_PARTITION_STORAGE_ENGINE */
}
if (my_strcasecmp(table_alias_charset, cmp_name, alias))
{
char t_alias_buff[MAX_ALIAS_NAME];
const char *t_alias= alias;
str->append(' ');
if (lower_case_table_names== 1)
{
if (alias && alias[0])
{
strmov(t_alias_buff, alias);
my_casedn_str(files_charset_info, t_alias_buff);
t_alias= t_alias_buff;
}
}
append_identifier(thd, str, t_alias, strlen(t_alias));
}
if (index_hints)
{
List_iterator<Index_hint> it(*index_hints);
Index_hint *hint;
while ((hint= it++))
{
str->append (STRING_WITH_LEN(" "));
hint->print (thd, str);
}
}
}
}
void st_select_lex::print(THD *thd, String *str, enum_query_type query_type)
{
/* QQ: thd may not be set for sub queries, but this should be fixed */
if (!thd)
thd= current_thd;
if (query_type & QT_SHOW_SELECT_NUMBER)
{
/* it makes EXPLAIN's "id" column understandable */
str->append("/* select#");
if (unlikely(select_number >= INT_MAX))
str->append("fake");
else
str->append_ulonglong(select_number);
str->append(" */ select ");
}
else
str->append(STRING_WITH_LEN("select "));
if (thd->is_error())
{
/*
It is possible that this query block had an optimization error, but the
caller didn't notice (caller evaluted this as a subquery and
Item::val*() don't have an error status). In this case the query block
may be broken and printing it may crash.
*/
str->append(STRING_WITH_LEN("had some error"));
return;
}
if (!thd->lex->describe && join && join->need_tmp)
{
/*
Items have been repointed to columns of an internal temporary table, it
is possible that the JOIN has gone through exec() and join_free(),
so items may have been freed by [tmp_JOIN_TAB]::cleanup(full=true),
and thus may not be printable. Unless this is EXPLAIN, in which case the
freeing is delayed by JOIN::join_free().
*/
str->append(STRING_WITH_LEN("<already_cleaned_up>"));
return;
}
/* First add options */
if (options & SELECT_STRAIGHT_JOIN)
str->append(STRING_WITH_LEN("straight_join "));
if (options & SELECT_HIGH_PRIORITY)
str->append(STRING_WITH_LEN("high_priority "));
if (options & SELECT_DISTINCT)
str->append(STRING_WITH_LEN("distinct "));
if (options & SELECT_SMALL_RESULT)
str->append(STRING_WITH_LEN("sql_small_result "));
if (options & SELECT_BIG_RESULT)
str->append(STRING_WITH_LEN("sql_big_result "));
if (options & OPTION_BUFFER_RESULT)
str->append(STRING_WITH_LEN("sql_buffer_result "));
if (options & OPTION_FOUND_ROWS)
str->append(STRING_WITH_LEN("sql_calc_found_rows "));
switch (sql_cache)
{
case SQL_NO_CACHE:
str->append(STRING_WITH_LEN("sql_no_cache "));
break;
case SQL_CACHE:
str->append(STRING_WITH_LEN("sql_cache "));
break;
case SQL_CACHE_UNSPECIFIED:
break;
default:
DBUG_ASSERT(0);
}
//Item List
bool first= 1;
List_iterator_fast<Item> it(item_list);
Item *item;
while ((item= it++))
{
if (first)
first= 0;
else
str->append(',');
if (master_unit()->item && item->item_name.is_autogenerated())
{
/*
Do not print auto-generated aliases in subqueries. It has no purpose
in a view definition or other contexts where the query is printed.
*/
item->print(str, query_type);
}
else
item->print_item_w_name(str, query_type);
/** @note that 'INTO variable' clauses are not printed */
}
/*
from clause
TODO: support USING/FORCE/IGNORE index
*/
if (table_list.elements)
{
str->append(STRING_WITH_LEN(" from "));
/* go through join tree */
print_join(thd, str, &top_join_list, query_type);
}
else if (where)
{
/*
"SELECT 1 FROM DUAL WHERE 2" should not be printed as
"SELECT 1 WHERE 2": the 1st syntax is valid, but the 2nd is not.
*/
str->append(STRING_WITH_LEN(" from DUAL "));
}
// Where
Item *cur_where= where;
if (join)
cur_where= join->conds;
if (cur_where || cond_value != Item::COND_UNDEF)
{
str->append(STRING_WITH_LEN(" where "));
if (cur_where)
cur_where->print(str, query_type);
else
str->append(cond_value != Item::COND_FALSE ? "1" : "0");
}
// group by & olap
if (group_list.elements)
{
str->append(STRING_WITH_LEN(" group by "));
print_order(str, group_list.first, query_type);
switch (olap)
{
case CUBE_TYPE:
str->append(STRING_WITH_LEN(" with cube"));
break;
case ROLLUP_TYPE:
str->append(STRING_WITH_LEN(" with rollup"));
break;
default:
; //satisfy compiler
}
}
// having
Item *cur_having= (join && join->optimized) ?
join->having_for_explain : having;
if (cur_having || having_value != Item::COND_UNDEF)
{
str->append(STRING_WITH_LEN(" having "));
if (cur_having)
cur_having->print(str, query_type);
else
str->append(having_value != Item::COND_FALSE ? "1" : "0");
}
if (order_list.elements)
{
str->append(STRING_WITH_LEN(" order by "));
print_order(str, order_list.first, query_type);
}
// limit
print_limit(thd, str, query_type);
// PROCEDURE unsupported here
}
/**
@brief Restore the LEX and THD in case of a parse error.
This is a clean up call that is invoked by the Bison generated
parser before returning an error from MYSQLparse. If your
semantic actions manipulate with the global thread state (which
is a very bad practice and should not normally be employed) and
need a clean-up in case of error, and you can not use %destructor
rule in the grammar file itself, this function should be used
to implement the clean up.
*/
void LEX::cleanup_lex_after_parse_error(THD *thd)
{
/*
Delete sphead for the side effect of restoring of the original
LEX state, thd->lex, thd->mem_root and thd->free_list if they
were replaced when parsing stored procedure statements. We
will never use sphead object after a parse error, so it's okay
to delete it only for the sake of the side effect.
TODO: make this functionality explicit in sp_head class.
Sic: we must nullify the member of the main lex, not the
current one that will be thrown away
*/
sp_head *sp= thd->lex->sphead;
if (sp)
{
sp->m_parser_data.finish_parsing_sp_body(thd);
delete sp;
thd->lex->sphead= NULL;
}
}
/*
Initialize (or reset) Query_tables_list object.
SYNOPSIS
reset_query_tables_list()
init TRUE - we should perform full initialization of object with
allocating needed memory
FALSE - object is already initialized so we should only reset
its state so it can be used for parsing/processing
of new statement
DESCRIPTION
This method initializes Query_tables_list so it can be used as part
of LEX object for parsing/processing of statement. One can also use
this method to reset state of already initialized Query_tables_list
so it can be used for processing of new statement.
*/
void Query_tables_list::reset_query_tables_list(bool init)
{
sql_command= SQLCOM_END;
if (!init && query_tables)
{
TABLE_LIST *table= query_tables;
for (;;)
{
delete table->view;
if (query_tables_last == &table->next_global ||
!(table= table->next_global))
break;
}
}
query_tables= 0;
query_tables_last= &query_tables;
query_tables_own_last= 0;
if (init)
{
/*
We delay real initialization of hash (and therefore related
memory allocation) until first insertion into this hash.
*/
my_hash_clear(&sroutines);
}
else if (sroutines.records)
{
/* Non-zero sroutines.records means that hash was initialized. */
my_hash_reset(&sroutines);
}
sroutines_list.empty();
sroutines_list_own_last= sroutines_list.next;
sroutines_list_own_elements= 0;
binlog_stmt_flags= 0;
stmt_accessed_table_flag= 0;
lock_tables_state= LTS_NOT_LOCKED;
table_count= 0;
}
/*
Destroy Query_tables_list object with freeing all resources used by it.
SYNOPSIS
destroy_query_tables_list()
*/
void Query_tables_list::destroy_query_tables_list()
{
my_hash_free(&sroutines);
}
/*
Initialize LEX object.
SYNOPSIS
LEX::LEX()
NOTE
LEX object initialized with this constructor can be used as part of
THD object for which one can safely call open_tables(), lock_tables()
and close_thread_tables() functions. But it is not yet ready for
statement parsing. On should use lex_start() function to prepare LEX
for this.
*/
LEX::LEX()
:result(0), option_type(OPT_DEFAULT), is_change_password(false),
is_set_password_sql(false), is_lex_started(0)
{
my_init_dynamic_array2(&plugins, sizeof(plugin_ref),
plugins_static_buffer,
INITIAL_LEX_PLUGIN_LIST_SIZE,
INITIAL_LEX_PLUGIN_LIST_SIZE);
memset(&mi, 0, sizeof(LEX_MASTER_INFO));
reset_query_tables_list(TRUE);
}
/*
Check whether the merging algorithm can be used on this VIEW
SYNOPSIS
LEX::can_be_merged()
DESCRIPTION
We can apply merge algorithm if it is single SELECT view with
subqueries only in WHERE clause (we do not count SELECTs of underlying
views, and second level subqueries) and we have not grpouping, ordering,
HAVING clause, aggregate functions, DISTINCT clause, LIMIT clause and
several underlying tables.
RETURN
FALSE - only temporary table algorithm can be used
TRUE - merge algorithm can be used
*/
bool LEX::can_be_merged()
{
// TODO: do not forget implement case when select_lex.table_list.elements==0
/* find non VIEW subqueries/unions */
bool selects_allow_merge= select_lex.next_select() == 0;
if (selects_allow_merge)
{
for (SELECT_LEX_UNIT *tmp_unit= select_lex.first_inner_unit();
tmp_unit;
tmp_unit= tmp_unit->next_unit())
{
if (tmp_unit->first_select()->parent_lex == this &&
(tmp_unit->item == 0 ||
(tmp_unit->item->place() != IN_WHERE &&
tmp_unit->item->place() != IN_ON)))
{
selects_allow_merge= 0;
break;
}
}
}
return (selects_allow_merge &&
select_lex.group_list.elements == 0 &&
select_lex.having == 0 &&
select_lex.with_sum_func == 0 &&
select_lex.table_list.elements >= 1 &&
!(select_lex.options & SELECT_DISTINCT) &&
select_lex.select_limit == 0);
}
/*
check if command can use VIEW with MERGE algorithm (for top VIEWs)
SYNOPSIS
LEX::can_use_merged()
DESCRIPTION
Only listed here commands can use merge algorithm in top level
SELECT_LEX (for subqueries will be used merge algorithm if
LEX::can_not_use_merged() is not TRUE).
RETURN
FALSE - command can't use merged VIEWs
TRUE - VIEWs with MERGE algorithms can be used
*/
bool LEX::can_use_merged()
{
switch (sql_command)
{
case SQLCOM_SELECT:
case SQLCOM_CREATE_TABLE:
case SQLCOM_UPDATE:
case SQLCOM_UPDATE_MULTI:
case SQLCOM_DELETE:
case SQLCOM_DELETE_MULTI:
case SQLCOM_INSERT:
case SQLCOM_INSERT_SELECT:
case SQLCOM_REPLACE:
case SQLCOM_REPLACE_SELECT:
case SQLCOM_LOAD:
return TRUE;
default:
return FALSE;
}
}
/*
Check if command can't use merged views in any part of command
SYNOPSIS
LEX::can_not_use_merged()
DESCRIPTION
Temporary table algorithm will be used on all SELECT levels for queries
listed here (see also LEX::can_use_merged()).
RETURN
FALSE - command can't use merged VIEWs
TRUE - VIEWs with MERGE algorithms can be used
*/
bool LEX::can_not_use_merged()
{
switch (sql_command)
{
case SQLCOM_CREATE_VIEW:
case SQLCOM_SHOW_CREATE:
/*
SQLCOM_SHOW_FIELDS is necessary to make
information schema tables working correctly with views.
see get_schema_tables_result function
*/
case SQLCOM_SHOW_FIELDS:
return TRUE;
default:
return FALSE;
}
}
/*
Detect that we need only table structure of derived table/view
SYNOPSIS
only_view_structure()
RETURN
TRUE yes, we need only structure
FALSE no, we need data
*/
bool LEX::only_view_structure()
{
switch (sql_command) {
case SQLCOM_SHOW_CREATE:
case SQLCOM_SHOW_TABLES:
case SQLCOM_SHOW_FIELDS:
case SQLCOM_REVOKE_ALL:
case SQLCOM_REVOKE:
case SQLCOM_GRANT:
case SQLCOM_CREATE_VIEW:
return TRUE;
default:
return FALSE;
}
}
/*
Should Items_ident be printed correctly
SYNOPSIS
need_correct_ident()
RETURN
TRUE yes, we need only structure
FALSE no, we need data
*/
bool LEX::need_correct_ident()
{
switch(sql_command)
{
case SQLCOM_SHOW_CREATE:
case SQLCOM_SHOW_TABLES:
case SQLCOM_CREATE_VIEW:
return TRUE;
default:
return FALSE;
}
}
/*
Get effective type of CHECK OPTION for given view
SYNOPSIS
get_effective_with_check()
view given view
NOTE
It have not sense to set CHECK OPTION for SELECT satement or subqueries,
so we do not.
RETURN
VIEW_CHECK_NONE no need CHECK OPTION
VIEW_CHECK_LOCAL CHECK OPTION LOCAL
VIEW_CHECK_CASCADED CHECK OPTION CASCADED
*/
uint8 LEX::get_effective_with_check(TABLE_LIST *view)
{
if (view->select_lex->master_unit() == &unit &&
which_check_option_applicable())
return (uint8)view->with_check;
return VIEW_CHECK_NONE;
}
/**
This method should be called only during parsing.
It is aware of compound statements (stored routine bodies)
and will initialize the destination with the default
database of the stored routine, rather than the default
database of the connection it is parsed in.
E.g. if one has no current database selected, or current database
set to 'bar' and then issues:
CREATE PROCEDURE foo.p1() BEGIN SELECT * FROM t1 END//
t1 is meant to refer to foo.t1, not to bar.t1.
This method is needed to support this rule.
@return TRUE in case of error (parsing should be aborted, FALSE in
case of success
*/
bool
LEX::copy_db_to(char **p_db, size_t *p_db_length) const
{
if (sphead)
{
DBUG_ASSERT(sphead->m_db.str && sphead->m_db.length);
/*
It is safe to assign the string by-pointer, both sphead and
its statements reside in the same memory root.
*/
*p_db= sphead->m_db.str;
if (p_db_length)
*p_db_length= sphead->m_db.length;
return FALSE;
}
return thd->copy_db_to(p_db, p_db_length);
}
/*
initialize limit counters
SYNOPSIS
st_select_lex_unit::set_limit()
values - SELECT_LEX with initial values for counters
*/
void st_select_lex_unit::set_limit(st_select_lex *sl)
{
ha_rows select_limit_val;
ulonglong val;
DBUG_ASSERT(! thd->stmt_arena->is_stmt_prepare());
if (sl->select_limit)
{
Item *item = sl->select_limit;
/*
fix_fields() has not been called for sl->select_limit. That's due to the
historical reasons -- this item could be only of type Item_int, and
Item_int does not require fix_fields(). Thus, fix_fields() was never
called for sl->select_limit.
Some time ago, Item_splocal was also allowed for LIMIT / OFFSET clauses.
However, the fix_fields() behavior was not updated, which led to a crash
in some cases.
There is no single place where to call fix_fields() for LIMIT / OFFSET
items during the fix-fields-phase. Thus, for the sake of readability,
it was decided to do it here, on the evaluation phase (which is a
violation of design, but we chose the lesser of two evils).
We can call fix_fields() here, because sl->select_limit can be of two
types only: Item_int and Item_splocal. Item_int::fix_fields() is trivial,
and Item_splocal::fix_fields() (or rather Item_sp_variable::fix_fields())
has the following specific:
1) it does not affect other items;
2) it does not fail.
Nevertheless DBUG_ASSERT was added to catch future changes in
fix_fields() implementation. Also added runtime check against a result
of fix_fields() in order to handle error condition in non-debug build.
*/
bool fix_fields_successful= true;
if (!item->fixed)
{
fix_fields_successful= !item->fix_fields(thd, NULL);
DBUG_ASSERT(fix_fields_successful);
}
val= fix_fields_successful ? item->val_uint() : HA_POS_ERROR;
}
else
val= HA_POS_ERROR;
select_limit_val= (ha_rows)val;
#ifndef BIG_TABLES
/*
Check for overflow : ha_rows can be smaller then ulonglong if
BIG_TABLES is off.
*/
if (val != (ulonglong)select_limit_val)
select_limit_val= HA_POS_ERROR;
#endif
if (sl->offset_limit)
{
Item *item = sl->offset_limit;
// see comment for sl->select_limit branch.
bool fix_fields_successful= true;
if (!item->fixed)
{
fix_fields_successful= !item->fix_fields(thd, NULL);
DBUG_ASSERT(fix_fields_successful);
}
val= fix_fields_successful ? item->val_uint() : HA_POS_ERROR;
}
else
val= ULL(0);
offset_limit_cnt= (ha_rows)val;
#ifndef BIG_TABLES
/* Check for truncation. */
if (val != (ulonglong)offset_limit_cnt)
offset_limit_cnt= HA_POS_ERROR;
#endif
select_limit_cnt= select_limit_val + offset_limit_cnt;
if (select_limit_cnt < select_limit_val)
select_limit_cnt= HA_POS_ERROR; // no limit
}
/**
@brief Set the initial purpose of this TABLE_LIST object in the list of used
tables.
We need to track this information on table-by-table basis, since when this
table becomes an element of the pre-locked list, it's impossible to identify
which SQL sub-statement it has been originally used in.
E.g.:
User request: SELECT * FROM t1 WHERE f1();
FUNCTION f1(): DELETE FROM t2; RETURN 1;
BEFORE DELETE trigger on t2: INSERT INTO t3 VALUES (old.a);
For this user request, the pre-locked list will contain t1, t2, t3
table elements, each needed for different DML.
The trigger event map is updated to reflect INSERT, UPDATE, DELETE,
REPLACE, LOAD DATA, CREATE TABLE .. SELECT, CREATE TABLE ..
REPLACE SELECT statements, and additionally ON DUPLICATE KEY UPDATE
clause.
*/
void LEX::set_trg_event_type_for_tables()
{
uint8 new_trg_event_map= 0;
/*
Some auxiliary operations
(e.g. GRANT processing) create TABLE_LIST instances outside
the parser. Additionally, some commands (e.g. OPTIMIZE) change
the lock type for a table only after parsing is done. Luckily,
these do not fire triggers and do not need to pre-load them.
For these TABLE_LISTs set_trg_event_type is never called, and
trg_event_map is always empty. That means that the pre-locking
algorithm will ignore triggers defined on these tables, if
any, and the execution will either fail with an assert in
sql_trigger.cc or with an error that a used table was not
pre-locked, in case of a production build.
TODO: this usage pattern creates unnecessary module dependencies
and should be rewritten to go through the parser.
Table list instances created outside the parser in most cases
refer to mysql.* system tables. It is not allowed to have
a trigger on a system table, but keeping track of
initialization provides extra safety in case this limitation
is circumvented.
*/
switch (sql_command) {
case SQLCOM_LOCK_TABLES:
/*
On a LOCK TABLE, all triggers must be pre-loaded for this TABLE_LIST
when opening an associated TABLE.
*/
new_trg_event_map= static_cast<uint8>
(1 << static_cast<int>(TRG_EVENT_INSERT)) |
static_cast<uint8>
(1 << static_cast<int>(TRG_EVENT_UPDATE)) |
static_cast<uint8>
(1 << static_cast<int>(TRG_EVENT_DELETE));
break;
/*
Basic INSERT. If there is an additional ON DUPLIATE KEY UPDATE
clause, it will be handled later in this method.
*/
case SQLCOM_INSERT: /* fall through */
case SQLCOM_INSERT_SELECT:
/*
LOAD DATA ... INFILE is expected to fire BEFORE/AFTER INSERT
triggers.
If the statement also has REPLACE clause, it will be
handled later in this method.
*/
case SQLCOM_LOAD: /* fall through */
/*
REPLACE is semantically equivalent to INSERT. In case
of a primary or unique key conflict, it deletes the old
record and inserts a new one. So we also may need to
fire ON DELETE triggers. This functionality is handled
later in this method.
*/
case SQLCOM_REPLACE: /* fall through */
case SQLCOM_REPLACE_SELECT:
/*
CREATE TABLE ... SELECT defaults to INSERT if the table or
view already exists. REPLACE option of CREATE TABLE ...
REPLACE SELECT is handled later in this method.
*/
case SQLCOM_CREATE_TABLE:
new_trg_event_map|= static_cast<uint8>
(1 << static_cast<int>(TRG_EVENT_INSERT));
break;
/* Basic update and multi-update */
case SQLCOM_UPDATE: /* fall through */
case SQLCOM_UPDATE_MULTI:
new_trg_event_map|= static_cast<uint8>
(1 << static_cast<int>(TRG_EVENT_UPDATE));
break;
/* Basic delete and multi-delete */
case SQLCOM_DELETE: /* fall through */
case SQLCOM_DELETE_MULTI:
new_trg_event_map|= static_cast<uint8>
(1 << static_cast<int>(TRG_EVENT_DELETE));
break;
default:
break;
}
switch (duplicates) {
case DUP_UPDATE:
new_trg_event_map|= static_cast<uint8>
(1 << static_cast<int>(TRG_EVENT_UPDATE));
break;
case DUP_REPLACE:
new_trg_event_map|= static_cast<uint8>
(1 << static_cast<int>(TRG_EVENT_DELETE));
break;
case DUP_ERROR:
default:
break;
}
/*
Do not iterate over sub-selects, only the tables in the outermost
SELECT_LEX can be modified, if any.
*/
TABLE_LIST *tables= select_lex.get_table_list();
while (tables)
{
/*
This is a fast check to filter out statements that do
not change data, or tables on the right side, in case of
INSERT .. SELECT, CREATE TABLE .. SELECT and so on.
Here we also filter out OPTIMIZE statement and non-updateable
views, for which lock_type is TL_UNLOCK or TL_READ after
parsing.
*/
if (static_cast<int>(tables->lock_type) >=
static_cast<int>(TL_WRITE_ALLOW_WRITE))
tables->trg_event_map= new_trg_event_map;
tables= tables->next_local;
}
}
/*
Unlink the first table from the global table list and the first table from
outer select (lex->select_lex) local list
SYNOPSIS
unlink_first_table()
link_to_local Set to 1 if caller should link this table to local list
NOTES
We assume that first tables in both lists is the same table or the local
list is empty.
RETURN
0 If 'query_tables' == 0
unlinked table
In this case link_to_local is set.
*/
TABLE_LIST *LEX::unlink_first_table(bool *link_to_local)
{
TABLE_LIST *first;
if ((first= query_tables))
{
/*
Exclude from global table list
*/
if ((query_tables= query_tables->next_global))
query_tables->prev_global= &query_tables;
else
query_tables_last= &query_tables;
first->next_global= 0;
if (query_tables_own_last == &first->next_global)
query_tables_own_last= &query_tables;
/*
and from local list if it is not empty
*/
if ((*link_to_local= MY_TEST(select_lex.table_list.first)))
{
select_lex.context.table_list=
select_lex.context.first_name_resolution_table= first->next_local;
select_lex.table_list.first= first->next_local;
select_lex.table_list.elements--; //safety
first->next_local= 0;
/*
Ensure that the global list has the same first table as the local
list.
*/
first_lists_tables_same();
}
}
return first;
}
/*
Bring first local table of first most outer select to first place in global
table list
SYNOPSYS
LEX::first_lists_tables_same()
NOTES
In many cases (for example, usual INSERT/DELETE/...) the first table of
main SELECT_LEX have special meaning => check that it is the first table
in global list and re-link to be first in the global list if it is
necessary. We need such re-linking only for queries with sub-queries in
the select list, as only in this case tables of sub-queries will go to
the global list first.
*/
void LEX::first_lists_tables_same()
{
TABLE_LIST *first_table= select_lex.table_list.first;
if (query_tables != first_table && first_table != 0)
{
TABLE_LIST *next;
if (query_tables_last == &first_table->next_global)
query_tables_last= first_table->prev_global;
if (query_tables_own_last == &first_table->next_global)
query_tables_own_last= first_table->prev_global;
if ((next= *first_table->prev_global= first_table->next_global))
next->prev_global= first_table->prev_global;
/* include in new place */
first_table->next_global= query_tables;
/*
We are sure that query_tables is not 0, because first_table was not
first table in the global list => we can use
query_tables->prev_global without check of query_tables
*/
query_tables->prev_global= &first_table->next_global;
first_table->prev_global= &query_tables;
query_tables= first_table;
}
}
/*
Link table back that was unlinked with unlink_first_table()
SYNOPSIS
link_first_table_back()
link_to_local do we need link this table to local
RETURN
global list
*/
void LEX::link_first_table_back(TABLE_LIST *first,
bool link_to_local)
{
if (first)
{
if ((first->next_global= query_tables))
query_tables->prev_global= &first->next_global;
else
query_tables_last= &first->next_global;
if (query_tables_own_last == &query_tables)
query_tables_own_last= &first->next_global;
query_tables= first;
if (link_to_local)
{
first->next_local= select_lex.table_list.first;
select_lex.context.table_list= first;
select_lex.table_list.first= first;
select_lex.table_list.elements++; //safety
}
}
}
/*
cleanup lex for case when we open table by table for processing
SYNOPSIS
LEX::cleanup_after_one_table_open()
NOTE
This method is mostly responsible for cleaning up of selects lists and
derived tables state. To rollback changes in Query_tables_list one has
to call Query_tables_list::reset_query_tables_list(FALSE).
*/
void LEX::cleanup_after_one_table_open()
{
/*
thd->lex->derived_tables & additional units may be set if we open
a view. It is necessary to clear thd->lex->derived_tables flag
to prevent processing of derived tables during next open_and_lock_tables
if next table is a real table and cleanup & remove underlying units
NOTE: all units will be connected to thd->lex->select_lex, because we
have not UNION on most upper level.
*/
if (all_selects_list != &select_lex)
{
derived_tables= 0;
/* cleunup underlying units (units of VIEW) */
for (SELECT_LEX_UNIT *un= select_lex.first_inner_unit();
un;
un= un->next_unit())
un->cleanup();
/* reduce all selects list to default state */
all_selects_list= &select_lex;
/* remove underlying units (units of VIEW) subtree */
select_lex.cut_subtree();
}
}
/*
Save current state of Query_tables_list for this LEX, and prepare it
for processing of new statemnt.
SYNOPSIS
reset_n_backup_query_tables_list()
backup Pointer to Query_tables_list instance to be used for backup
*/
void LEX::reset_n_backup_query_tables_list(Query_tables_list *backup)
{
backup->set_query_tables_list(this);
/*
We have to perform full initialization here since otherwise we
will damage backed up state.
*/
this->reset_query_tables_list(TRUE);
}
/*
Restore state of Query_tables_list for this LEX from backup.
SYNOPSIS
restore_backup_query_tables_list()
backup Pointer to Query_tables_list instance used for backup
*/
void LEX::restore_backup_query_tables_list(Query_tables_list *backup)
{
this->destroy_query_tables_list();
this->set_query_tables_list(backup);
}
/*
Checks for usage of routines and/or tables in a parsed statement
SYNOPSIS
LEX:table_or_sp_used()
RETURN
FALSE No routines and tables used
TRUE Either or both routines and tables are used.
*/
bool LEX::table_or_sp_used()
{
DBUG_ENTER("table_or_sp_used");
if (sroutines.records || query_tables)
DBUG_RETURN(TRUE);
DBUG_RETURN(FALSE);
}
/*
Do end-of-prepare fixup for list of tables and their merge-VIEWed tables
SYNOPSIS
fix_prepare_info_in_table_list()
thd Thread handle
tbl List of tables to process
DESCRIPTION
Perform end-end-of prepare fixup for list of tables, if any of the tables
is a merge-algorithm VIEW, recursively fix up its underlying tables as
well.
*/
static void fix_prepare_info_in_table_list(THD *thd, TABLE_LIST *tbl)
{
for (; tbl; tbl= tbl->next_local)
{
if (tbl->join_cond())
{
tbl->prep_join_cond= tbl->join_cond();
tbl->set_join_cond(tbl->join_cond()->copy_andor_structure(thd));
}
fix_prepare_info_in_table_list(thd, tbl->merge_underlying_list);
}
}
/*
Save WHERE/HAVING/ON clauses and replace them with disposable copies
SYNOPSIS
st_select_lex::fix_prepare_information
thd thread handler
conds in/out pointer to WHERE condition to be met at execution
having_conds in/out pointer to HAVING condition to be met at execution
DESCRIPTION
The passed WHERE and HAVING are to be saved for the future executions.
This function saves it, and returns a copy which can be thrashed during
this execution of the statement. By saving/thrashing here we mean only
We also save the chain of ORDER::next in group_list, in case
the list is modified by remove_const().
AND/OR trees.
We also save the chain of ORDER::next in group_list and order_list, in
case the list is modified by remove_const().
The function also calls fix_prepare_info_in_table_list that saves all
ON expressions.
*/
void st_select_lex::fix_prepare_information(THD *thd, Item **conds,
Item **having_conds)
{
if (!thd->stmt_arena->is_conventional() && first_execution)
{
first_execution= 0;
if (group_list.first)
{
if (!group_list_ptrs)
{
void *mem= thd->stmt_arena->alloc(sizeof(Group_list_ptrs));
group_list_ptrs= new (mem) Group_list_ptrs(thd->stmt_arena->mem_root);
}
group_list_ptrs->reserve(group_list.elements);
for (ORDER *order= group_list.first; order; order= order->next)
{
group_list_ptrs->push_back(order);
}
}
if (order_list.first)
{
if (!order_list_ptrs)
{
void *mem= thd->stmt_arena->alloc(sizeof(Group_list_ptrs));
order_list_ptrs= new (mem) Group_list_ptrs(thd->stmt_arena->mem_root);
}
order_list_ptrs->reserve(order_list.elements);
for (ORDER *order= order_list.first; order; order= order->next)
{
order_list_ptrs->push_back(order);
}
}
if (*conds)
{
/*
In "WHERE outer_field", *conds may be an Item_outer_ref allocated in
the execution memroot.
@todo change this line in WL#7082. Currently, when we execute a SP,
containing "SELECT (SELECT ... WHERE t1.col) FROM t1",
resolution may make *conds equal to an Item_outer_ref, then below
*conds becomes Item_field, which then goes straight on to execution,
undoing the effects of putting Item_outer_ref in the first place...
With a PS the problem is not as severe, as after the code below we
don't go to execution: a next execution will do a new name resolution
which will create Item_outer_ref again.
*/
prep_where= (*conds)->real_item();
*conds= where= prep_where->copy_andor_structure(thd);
}
if (*having_conds)
{
prep_having= *having_conds;
*having_conds= having= prep_having->copy_andor_structure(thd);
}
fix_prepare_info_in_table_list(thd, table_list.first);
}
}
/*
There are st_select_lex::add_table_to_list &
st_select_lex::set_lock_for_tables are in sql_parse.cc
st_select_lex::print is in sql_select.cc
st_select_lex_unit::prepare, st_select_lex_unit::exec,
st_select_lex_unit::cleanup, st_select_lex_unit::reinit_exec_mechanism,
st_select_lex_unit::change_result
are in sql_union.cc
*/
/*
Sets the kind of hints to be added by the calls to add_index_hint().
SYNOPSIS
set_index_hint_type()
type_arg The kind of hints to be added from now on.
clause The clause to use for hints to be added from now on.
DESCRIPTION
Used in filling up the tagged hints list.
This list is filled by first setting the kind of the hint as a
context variable and then adding hints of the current kind.
Then the context variable index_hint_type can be reset to the
next hint type.
*/
void st_select_lex::set_index_hint_type(enum index_hint_type type_arg,
index_clause_map clause)
{
current_index_hint_type= type_arg;
current_index_hint_clause= clause;
}
/*
Makes an array to store index usage hints (ADD/FORCE/IGNORE INDEX).
SYNOPSIS
alloc_index_hints()
thd current thread.
*/
void st_select_lex::alloc_index_hints (THD *thd)
{
index_hints= new (thd->mem_root) List<Index_hint>();
}
/*
adds an element to the array storing index usage hints
(ADD/FORCE/IGNORE INDEX).
SYNOPSIS
add_index_hint()
thd current thread.
str name of the index.
length number of characters in str.
RETURN VALUE
0 on success, non-zero otherwise
*/
bool st_select_lex::add_index_hint (THD *thd, char *str, uint length)
{
return index_hints->push_front (new (thd->mem_root)
Index_hint(current_index_hint_type,
current_index_hint_clause,
str, length));
}
/**
@brief Process all derived tables/views of the SELECT.
@param lex LEX of this thread
@details
This function runs given processor on all derived tables from the
table_list of this select.
The SELECT_LEX::leaf_tables/TABLE_LIST::next_leaf chain is used as the tables
list for current select. This chain is built by make_leaves_list and thus
this function can't be used prior to setup_tables. As the chain includes all
tables from merged views there is no need in diving into views.
@see mysql_handle_derived.
@return FALSE ok.
@return TRUE an error occur.
*/
bool st_select_lex::handle_derived(LEX *lex,
bool (*processor)(THD*, LEX*, TABLE_LIST*))
{
for (TABLE_LIST *table_ref= leaf_tables;
table_ref;
table_ref= table_ref->next_leaf)
{
if (table_ref->is_view_or_derived() &&
table_ref->handle_derived(lex, processor))
return TRUE;
}
return FALSE;
}
st_select_lex::type_enum st_select_lex::type(const THD *thd)
{
if (master_unit()->fake_select_lex == this)
return SLT_UNION_RESULT;
else if (&thd->lex->select_lex == this)
{
if (first_inner_unit() || next_select())
return SLT_PRIMARY;
else
return SLT_SIMPLE;
}
else if (this == master_unit()->first_select())
{
if (linkage == DERIVED_TABLE_TYPE)
return SLT_DERIVED;
else
return SLT_SUBQUERY;
}
else
return SLT_UNION;
}
/**
A routine used by the parser to decide whether we are specifying a full
partitioning or if only partitions to add or to split.
@note This needs to be outside of WITH_PARTITION_STORAGE_ENGINE since it
is used from the sql parser that doesn't have any ifdef's
@retval TRUE Yes, it is part of a management partition command
@retval FALSE No, not a management partition command
*/
bool LEX::is_partition_management() const
{
return (sql_command == SQLCOM_ALTER_TABLE &&
(alter_info.flags == Alter_info::ALTER_ADD_PARTITION ||
alter_info.flags == Alter_info::ALTER_REORGANIZE_PARTITION));
}
/**
Set all fields to their "unspecified" value.
*/
void st_lex_master_info::set_unspecified()
{
memset(this, 0, sizeof(*this));
sql_delay= -1;
}
#ifdef MYSQL_SERVER
uint binlog_unsafe_map[256];
#define UNSAFE(a, b, c) \
{ \
DBUG_PRINT("unsafe_mixed_statement", ("SETTING BASE VALUES: %s, %s, %02X\n", \
LEX::stmt_accessed_table_string(a), \
LEX::stmt_accessed_table_string(b), \
c)); \
unsafe_mixed_statement(a, b, c); \
}
/*
Sets the combination given by "a" and "b" and automatically combinations
given by other types of access, i.e. 2^(8 - 2), as unsafe.
It may happen a colision when automatically defining a combination as unsafe.
For that reason, a combination has its unsafe condition redefined only when
the new_condition is greater then the old. For instance,
. (BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY) is never overwritten by
. (BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF).
*/
void unsafe_mixed_statement(LEX::enum_stmt_accessed_table a,
LEX::enum_stmt_accessed_table b, uint condition)
{
int type= 0;
int index= (1U << a) | (1U << b);
for (type= 0; type < 256; type++)
{
if ((type & index) == index)
{
binlog_unsafe_map[type] |= condition;
}
}
}
/*
The BINLOG_* AND TRX_CACHE_* values can be combined by using '&' or '|',
which means that both conditions need to be satisfied or any of them is
enough. For example,
. BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY means that the statment is
unsafe when the option is on and trx-cache is not empty;
. BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF means the statement is unsafe
in all cases.
. TRX_CACHE_EMPTY | TRX_CACHE_NOT_EMPTY means the statement is unsafe
in all cases. Similar as above.
*/
void binlog_unsafe_map_init()
{
memset((void*) binlog_unsafe_map, 0, sizeof(uint) * 256);
/*
Classify a statement as unsafe when there is a mixed statement and an
on-going transaction at any point of the execution if:
1. The mixed statement is about to update a transactional table and
a non-transactional table.
2. The mixed statement is about to update a transactional table and
read from a non-transactional table.
3. The mixed statement is about to update a non-transactional table
and temporary transactional table.
4. The mixed statement is about to update a temporary transactional
table and read from a non-transactional table.
5. The mixed statement is about to update a transactional table and
a temporary non-transactional table.
6. The mixed statement is about to update a transactional table and
read from a temporary non-transactional table.
7. The mixed statement is about to update a temporary transactional
table and temporary non-transactional table.
8. The mixed statement is about to update a temporary transactional
table and read from a temporary non-transactional table.
After updating a transactional table if:
9. The mixed statement is about to update a non-transactional table
and read from a transactional table.
10. The mixed statement is about to update a non-transactional table
and read from a temporary transactional table.
11. The mixed statement is about to update a temporary non-transactional
table and read from a transactional table.
12. The mixed statement is about to update a temporary non-transactional
table and read from a temporary transactional table.
13. The mixed statement is about to update a temporary non-transactional
table and read from a non-transactional table.
The reason for this is that locks acquired may not protected a concurrent
transaction of interfering in the current execution and by consequence in
the result.
*/
/* Case 1. */
UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_WRITES_NON_TRANS_TABLE,
BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
/* Case 2. */
UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
/* Case 3. */
UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_WRITES_TEMP_TRANS_TABLE,
BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
/* Case 4. */
UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF);
/* Case 5. */
UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE,
BINLOG_DIRECT_ON);
/* Case 6. */
UNSAFE(LEX::STMT_WRITES_TRANS_TABLE, LEX::STMT_READS_TEMP_NON_TRANS_TABLE,
BINLOG_DIRECT_ON);
/* Case 7. */
UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE,
BINLOG_DIRECT_ON);
/* Case 8. */
UNSAFE(LEX::STMT_WRITES_TEMP_TRANS_TABLE, LEX::STMT_READS_TEMP_NON_TRANS_TABLE,
BINLOG_DIRECT_ON);
/* Case 9. */
UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_READS_TRANS_TABLE,
(BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF) & TRX_CACHE_NOT_EMPTY);
/* Case 10 */
UNSAFE(LEX::STMT_WRITES_NON_TRANS_TABLE, LEX::STMT_READS_TEMP_TRANS_TABLE,
(BINLOG_DIRECT_ON | BINLOG_DIRECT_OFF) & TRX_CACHE_NOT_EMPTY);
/* Case 11. */
UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_TRANS_TABLE,
BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY);
/* Case 12. */
UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_TEMP_TRANS_TABLE,
BINLOG_DIRECT_ON & TRX_CACHE_NOT_EMPTY);
/* Case 13. */
UNSAFE(LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE, LEX::STMT_READS_NON_TRANS_TABLE,
BINLOG_DIRECT_OFF & TRX_CACHE_NOT_EMPTY);
}
#endif
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
template class Mem_root_array<ORDER*, true>;
#endif
| gpl-2.0 |
geckoblu/kang | kang/modules/exceptionHandler.py | 2411 | # pylint: disable=global-statement
from PyQt4.QtCore import QT_VERSION_STR
import string
import sys
import traceback
from kang import VERSION
__mainWindow = None
__showedexmess = set()
__debug = False
def init(mainWindow, debug=False):
"""
Initialize the module
"""
global __mainWindow
global __debug
__mainWindow = mainWindow
__debug = debug
sys.excepthook = _excepthook
def _excepthook(excType, excValue, tracebackobj):
"""
Global function to catch unhandled exceptions.
@param excType exception type
@param excValue exception value
@param tracebackobj traceback object
"""
try:
tb = traceback.format_exception(excType, excValue, tracebackobj)
exmess = ''.join(tb)
sys.stderr.write(exmess)
if __mainWindow and not (exmess in __showedexmess):
__showedexmess.add(exmess)
msg = _formatMessage(exmess)
__mainWindow.signalException(msg)
except:
if __debug:
raise
def _formatMessage(exmess):
"""
Format the exception message
"""
msg = '==========================================================================\n'
msg += 'Kang Version:\t %s\n' % VERSION
msg += 'Python Version:\t %s\n' % unicode(string.replace(sys.version, '\n', ' - '))
msg += 'PyQt Version:\t %s\n' % unicode(QT_VERSION_STR)
msg += 'Operating System: %s\n' % unicode(sys.platform)
regex = __mainWindow.regexMultiLineEdit.toPlainText()
if regex:
msg += '=== REGEX ============================================================\n'
msg += unicode(regex)
if not msg.endswith('\n'):
msg += '\n'
rstr = __mainWindow.stringMultiLineEdit.toPlainText()
if rstr:
msg += '=== STRING ===========================================================\n'
msg += unicode(rstr)
if not msg.endswith('\n'):
msg += '\n'
replace = __mainWindow.replaceTextEdit.toPlainText()
if replace:
msg += '=== REPLACE ==========================================================\n'
msg += unicode(replace)
if not msg.endswith('\n'):
msg += '\n'
if exmess:
msg += '=== EXCEPTION ========================================================\n'
msg += unicode(exmess)
if not msg.endswith('\n'):
msg += '\n'
return msg
| gpl-2.0 |
kunj1988/Magento2 | app/code/Magento/Sales/Model/Order/Invoice/Item.php | 18364 | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Model\Order\Invoice;
use Magento\Framework\Api\AttributeValueFactory;
use Magento\Sales\Api\Data\InvoiceItemInterface;
use Magento\Sales\Model\AbstractModel;
/**
* @api
* @method float getBaseWeeeTaxRowDisposition()
* @method \Magento\Sales\Model\Order\Invoice\Item setBaseWeeeTaxRowDisposition(float $value)
* @method float getWeeeTaxAppliedRowAmount()
* @method \Magento\Sales\Model\Order\Invoice\Item setWeeeTaxAppliedRowAmount(float $value)
* @method float getBaseWeeeTaxAppliedAmount()
* @method \Magento\Sales\Model\Order\Invoice\Item setBaseWeeeTaxAppliedAmount(float $value)
* @method float getWeeeTaxRowDisposition()
* @method \Magento\Sales\Model\Order\Invoice\Item setWeeeTaxRowDisposition(float $value)
* @method float getBaseWeeeTaxDisposition()
* @method \Magento\Sales\Model\Order\Invoice\Item setBaseWeeeTaxDisposition(float $value)
* @method float getWeeeTaxAppliedAmount()
* @method \Magento\Sales\Model\Order\Invoice\Item setWeeeTaxAppliedAmount(float $value)
* @method float getWeeeTaxDisposition()
* @method \Magento\Sales\Model\Order\Invoice\Item setWeeeTaxDisposition(float $value)
* @method float getBaseWeeeTaxAppliedRowAmnt()
* @method \Magento\Sales\Model\Order\Invoice\Item setBaseWeeeTaxAppliedRowAmnt(float $value)
* @method string getWeeeTaxApplied()
* @method \Magento\Sales\Model\Order\Invoice\Item setWeeeTaxApplied(string $value)
* @SuppressWarnings(PHPMD.ExcessivePublicCount)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @since 100.0.2
*/
class Item extends AbstractModel implements InvoiceItemInterface
{
/**
* @var string
*/
protected $_eventPrefix = 'sales_invoice_item';
/**
* @var string
*/
protected $_eventObject = 'invoice_item';
/**
* @var \Magento\Sales\Model\Order\Item|null
*/
protected $_orderItem = null;
/**
* @var \Magento\Sales\Model\Order\ItemFactory
*/
protected $_orderItemFactory;
/**
* @param \Magento\Framework\Model\Context $context
* @param \Magento\Framework\Registry $registry
* @param \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory
* @param AttributeValueFactory $customAttributeFactory
* @param \Magento\Sales\Model\Order\ItemFactory $orderItemFactory
* @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource
* @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection
* @param array $data
*/
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory,
AttributeValueFactory $customAttributeFactory,
\Magento\Sales\Model\Order\ItemFactory $orderItemFactory,
\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
array $data = []
) {
parent::__construct(
$context,
$registry,
$extensionFactory,
$customAttributeFactory,
$resource,
$resourceCollection,
$data
);
$this->_orderItemFactory = $orderItemFactory;
}
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
$this->_init(\Magento\Sales\Model\ResourceModel\Order\Invoice\Item::class);
}
/**
* Declare invoice instance
*
* @param \Magento\Sales\Api\Data\InvoiceInterface $invoice
* @return $this
*/
public function setInvoice(\Magento\Sales\Api\Data\InvoiceInterface $invoice)
{
return $this->setData(self::INVOICE, $invoice);
}
/**
* Retrieve invoice instance
*
* @codeCoverageIgnore
*
* @return \Magento\Sales\Model\Order\Invoice
*/
public function getInvoice()
{
return $this->getData(self::INVOICE);
}
/**
* Declare order item instance
*
* @param \Magento\Sales\Model\Order\Item $item
* @return $this
*/
public function setOrderItem(\Magento\Sales\Model\Order\Item $item)
{
$this->_orderItem = $item;
$this->setOrderItemId($item->getId());
return $this;
}
/**
* Retrieve order item instance
*
* @return \Magento\Sales\Model\Order\Item
*/
public function getOrderItem()
{
if ($this->_orderItem === null) {
if ($this->getInvoice()) {
$this->_orderItem = $this->getInvoice()->getOrder()->getItemById($this->getOrderItemId());
} else {
$this->_orderItem = $this->_orderItemFactory->create()->load($this->getOrderItemId());
}
}
return $this->_orderItem;
}
/**
* Declare qty
*
* @codeCoverageIgnore
*
* @param float $qty
* @return $this
*/
public function setQty($qty)
{
return $this->setData(self::QTY, $qty);
}
/**
* Applying qty to order item
*
* @return $this
*/
public function register()
{
$orderItem = $this->getOrderItem();
$orderItem->setQtyInvoiced($orderItem->getQtyInvoiced() + $this->getQty());
$orderItem->setTaxInvoiced($orderItem->getTaxInvoiced() + $this->getTaxAmount());
$orderItem->setBaseTaxInvoiced($orderItem->getBaseTaxInvoiced() + $this->getBaseTaxAmount());
$orderItem->setDiscountTaxCompensationInvoiced(
$orderItem->getDiscountTaxCompensationInvoiced() + $this->getDiscountTaxCompensationAmount()
);
$orderItem->setBaseDiscountTaxCompensationInvoiced(
$orderItem->getBaseDiscountTaxCompensationInvoiced() + $this->getBaseDiscountTaxCompensationAmount()
);
$orderItem->setDiscountInvoiced($orderItem->getDiscountInvoiced() + $this->getDiscountAmount());
$orderItem->setBaseDiscountInvoiced($orderItem->getBaseDiscountInvoiced() + $this->getBaseDiscountAmount());
$orderItem->setRowInvoiced($orderItem->getRowInvoiced() + $this->getRowTotal());
$orderItem->setBaseRowInvoiced($orderItem->getBaseRowInvoiced() + $this->getBaseRowTotal());
return $this;
}
/**
* Cancelling invoice item
*
* @return $this
*/
public function cancel()
{
$orderItem = $this->getOrderItem();
$orderItem->setQtyInvoiced($orderItem->getQtyInvoiced() - $this->getQty());
$orderItem->setTaxInvoiced($orderItem->getTaxInvoiced() - $this->getTaxAmount());
$orderItem->setBaseTaxInvoiced($orderItem->getBaseTaxInvoiced() - $this->getBaseTaxAmount());
$orderItem->setDiscountTaxCompensationInvoiced(
$orderItem->getDiscountTaxCompensationInvoiced() - $this->getDiscountTaxCompensationAmount()
);
$orderItem->setBaseDiscountTaxCompensationInvoiced(
$orderItem->getBaseDiscountTaxCompensationInvoiced() - $this->getBaseDiscountTaxCompensationAmount()
);
$orderItem->setDiscountInvoiced($orderItem->getDiscountInvoiced() - $this->getDiscountAmount());
$orderItem->setBaseDiscountInvoiced($orderItem->getBaseDiscountInvoiced() - $this->getBaseDiscountAmount());
$orderItem->setRowInvoiced($orderItem->getRowInvoiced() - $this->getRowTotal());
$orderItem->setBaseRowInvoiced($orderItem->getBaseRowInvoiced() - $this->getBaseRowTotal());
return $this;
}
/**
* Invoice item row total calculation
*
* @return $this
*/
public function calcRowTotal()
{
$invoice = $this->getInvoice();
$orderItem = $this->getOrderItem();
$orderItemQty = $orderItem->getQtyOrdered();
$rowTotal = $orderItem->getRowTotal() - $orderItem->getRowInvoiced();
$baseRowTotal = $orderItem->getBaseRowTotal() - $orderItem->getBaseRowInvoiced();
$rowTotalInclTax = $orderItem->getRowTotalInclTax();
$baseRowTotalInclTax = $orderItem->getBaseRowTotalInclTax();
if (!$this->isLast()) {
$availableQty = $orderItemQty - $orderItem->getQtyInvoiced();
$rowTotal = $invoice->roundPrice($rowTotal / $availableQty * $this->getQty());
$baseRowTotal = $invoice->roundPrice($baseRowTotal / $availableQty * $this->getQty(), 'base');
}
$this->setRowTotal($rowTotal);
$this->setBaseRowTotal($baseRowTotal);
if ($rowTotalInclTax && $baseRowTotalInclTax) {
$this->setRowTotalInclTax(
$invoice->roundPrice($rowTotalInclTax / $orderItemQty * $this->getQty(), 'including')
);
$this->setBaseRowTotalInclTax(
$invoice->roundPrice($baseRowTotalInclTax / $orderItemQty * $this->getQty(), 'including_base')
);
}
return $this;
}
/**
* Checking if the item is last
*
* @return bool
*/
public function isLast()
{
if ((string)(double)$this->getQty() == (string)(double)$this->getOrderItem()->getQtyToInvoice()) {
return true;
}
return false;
}
//@codeCoverageIgnoreStart
/**
* Returns additional_data
*
* @return string|null
*/
public function getAdditionalData()
{
return $this->getData(InvoiceItemInterface::ADDITIONAL_DATA);
}
/**
* Returns base_cost
*
* @return float|null
*/
public function getBaseCost()
{
return $this->getData(InvoiceItemInterface::BASE_COST);
}
/**
* Returns base_discount_amount
*
* @return float|null
*/
public function getBaseDiscountAmount()
{
return $this->getData(InvoiceItemInterface::BASE_DISCOUNT_AMOUNT);
}
/**
* Returns base_discount_tax_compensation_amount
*
* @return float|null
*/
public function getBaseDiscountTaxCompensationAmount()
{
return $this->getData(InvoiceItemInterface::BASE_DISCOUNT_TAX_COMPENSATION_AMOUNT);
}
/**
* Returns base_price
*
* @return float|null
*/
public function getBasePrice()
{
return $this->getData(InvoiceItemInterface::BASE_PRICE);
}
/**
* Returns base_price_incl_tax
*
* @return float|null
*/
public function getBasePriceInclTax()
{
return $this->getData(InvoiceItemInterface::BASE_PRICE_INCL_TAX);
}
/**
* Returns base_row_total
*
* @return float|null
*/
public function getBaseRowTotal()
{
return $this->getData(InvoiceItemInterface::BASE_ROW_TOTAL);
}
/**
* Returns base_row_total_incl_tax
*
* @return float|null
*/
public function getBaseRowTotalInclTax()
{
return $this->getData(InvoiceItemInterface::BASE_ROW_TOTAL_INCL_TAX);
}
/**
* Returns base_tax_amount
*
* @return float|null
*/
public function getBaseTaxAmount()
{
return $this->getData(InvoiceItemInterface::BASE_TAX_AMOUNT);
}
/**
* Returns description
*
* @return string|null
*/
public function getDescription()
{
return $this->getData(InvoiceItemInterface::DESCRIPTION);
}
/**
* Returns discount_amount
*
* @return float|null
*/
public function getDiscountAmount()
{
return $this->getData(InvoiceItemInterface::DISCOUNT_AMOUNT);
}
/**
* Returns discount_tax_compensation_amount
*
* @return float|null
*/
public function getDiscountTaxCompensationAmount()
{
return $this->getData(InvoiceItemInterface::DISCOUNT_TAX_COMPENSATION_AMOUNT);
}
/**
* Returns name
*
* @return string|null
*/
public function getName()
{
return $this->getData(InvoiceItemInterface::NAME);
}
/**
* Returns order_item_id
*
* @return int
*/
public function getOrderItemId()
{
return $this->getData(InvoiceItemInterface::ORDER_ITEM_ID);
}
/**
* Returns parent_id
*
* @return int|null
*/
public function getParentId()
{
return $this->getData(InvoiceItemInterface::PARENT_ID);
}
/**
* Returns price
*
* @return float|null
*/
public function getPrice()
{
return $this->getData(InvoiceItemInterface::PRICE);
}
/**
* Returns price_incl_tax
*
* @return float|null
*/
public function getPriceInclTax()
{
return $this->getData(InvoiceItemInterface::PRICE_INCL_TAX);
}
/**
* Returns product_id
*
* @return int|null
*/
public function getProductId()
{
return $this->getData(InvoiceItemInterface::PRODUCT_ID);
}
/**
* Returns qty
*
* @return float
*/
public function getQty()
{
return $this->getData(InvoiceItemInterface::QTY);
}
/**
* Returns row_total
*
* @return float|null
*/
public function getRowTotal()
{
return $this->getData(InvoiceItemInterface::ROW_TOTAL);
}
/**
* Returns row_total_incl_tax
*
* @return float|null
*/
public function getRowTotalInclTax()
{
return $this->getData(InvoiceItemInterface::ROW_TOTAL_INCL_TAX);
}
/**
* Returns sku
*
* @return string
*/
public function getSku()
{
return $this->getData(InvoiceItemInterface::SKU);
}
/**
* Returns tax_amount
*
* @return float|null
*/
public function getTaxAmount()
{
return $this->getData(InvoiceItemInterface::TAX_AMOUNT);
}
/**
* {@inheritdoc}
*/
public function setParentId($id)
{
return $this->setData(InvoiceItemInterface::PARENT_ID, $id);
}
/**
* {@inheritdoc}
*/
public function setBasePrice($price)
{
return $this->setData(InvoiceItemInterface::BASE_PRICE, $price);
}
/**
* {@inheritdoc}
*/
public function setTaxAmount($amount)
{
return $this->setData(InvoiceItemInterface::TAX_AMOUNT, $amount);
}
/**
* {@inheritdoc}
*/
public function setBaseRowTotal($amount)
{
return $this->setData(InvoiceItemInterface::BASE_ROW_TOTAL, $amount);
}
/**
* {@inheritdoc}
*/
public function setDiscountAmount($amount)
{
return $this->setData(InvoiceItemInterface::DISCOUNT_AMOUNT, $amount);
}
/**
* {@inheritdoc}
*/
public function setRowTotal($amount)
{
return $this->setData(InvoiceItemInterface::ROW_TOTAL, $amount);
}
/**
* {@inheritdoc}
*/
public function setBaseDiscountAmount($amount)
{
return $this->setData(InvoiceItemInterface::BASE_DISCOUNT_AMOUNT, $amount);
}
/**
* {@inheritdoc}
*/
public function setPriceInclTax($amount)
{
return $this->setData(InvoiceItemInterface::PRICE_INCL_TAX, $amount);
}
/**
* {@inheritdoc}
*/
public function setBaseTaxAmount($amount)
{
return $this->setData(InvoiceItemInterface::BASE_TAX_AMOUNT, $amount);
}
/**
* {@inheritdoc}
*/
public function setBasePriceInclTax($amount)
{
return $this->setData(InvoiceItemInterface::BASE_PRICE_INCL_TAX, $amount);
}
/**
* {@inheritdoc}
*/
public function setBaseCost($baseCost)
{
return $this->setData(InvoiceItemInterface::BASE_COST, $baseCost);
}
/**
* {@inheritdoc}
*/
public function setPrice($price)
{
return $this->setData(InvoiceItemInterface::PRICE, $price);
}
/**
* {@inheritdoc}
*/
public function setBaseRowTotalInclTax($amount)
{
return $this->setData(InvoiceItemInterface::BASE_ROW_TOTAL_INCL_TAX, $amount);
}
/**
* {@inheritdoc}
*/
public function setRowTotalInclTax($amount)
{
return $this->setData(InvoiceItemInterface::ROW_TOTAL_INCL_TAX, $amount);
}
/**
* {@inheritdoc}
*/
public function setProductId($id)
{
return $this->setData(InvoiceItemInterface::PRODUCT_ID, $id);
}
/**
* {@inheritdoc}
*/
public function setOrderItemId($id)
{
return $this->setData(InvoiceItemInterface::ORDER_ITEM_ID, $id);
}
/**
* {@inheritdoc}
*/
public function setAdditionalData($additionalData)
{
return $this->setData(InvoiceItemInterface::ADDITIONAL_DATA, $additionalData);
}
/**
* {@inheritdoc}
*/
public function setDescription($description)
{
return $this->setData(InvoiceItemInterface::DESCRIPTION, $description);
}
/**
* {@inheritdoc}
*/
public function setSku($sku)
{
return $this->setData(InvoiceItemInterface::SKU, $sku);
}
/**
* {@inheritdoc}
*/
public function setName($name)
{
return $this->setData(InvoiceItemInterface::NAME, $name);
}
/**
* {@inheritdoc}
*/
public function setDiscountTaxCompensationAmount($amount)
{
return $this->setData(InvoiceItemInterface::DISCOUNT_TAX_COMPENSATION_AMOUNT, $amount);
}
/**
* {@inheritdoc}
*/
public function setBaseDiscountTaxCompensationAmount($amount)
{
return $this->setData(InvoiceItemInterface::BASE_DISCOUNT_TAX_COMPENSATION_AMOUNT, $amount);
}
/**
* {@inheritdoc}
*
* @return \Magento\Sales\Api\Data\InvoiceItemExtensionInterface|null
*/
public function getExtensionAttributes()
{
return $this->_getExtensionAttributes();
}
/**
* {@inheritdoc}
*
* @param \Magento\Sales\Api\Data\InvoiceItemExtensionInterface $extensionAttributes
* @return $this
*/
public function setExtensionAttributes(\Magento\Sales\Api\Data\InvoiceItemExtensionInterface $extensionAttributes)
{
return $this->_setExtensionAttributes($extensionAttributes);
}
//@codeCoverageIgnoreEnd
}
| gpl-2.0 |
chrizel/bt | src/alloc.cc | 1154 | /* Bermuda Triangle - action adventure game
Copyright (C) 2004 Christian Zeller <chrizel@gmx.net>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include <stdlib.h>
#include <stdio.h>
#include "alloc.h"
#include "error.h"
void *bt_malloc(size_t size)
{
void *ptr;
ptr = malloc(size);
if (!ptr)
error("Out of memory!\n");
return ptr;
}
void *bt_realloc(void *ptr, size_t size)
{
return realloc(ptr, size);
}
void bt_free(void *ptr)
{
free(ptr);
}
| gpl-2.0 |
Fluorohydride/ygopro-scripts | c58807980.lua | 2299 | --モノケロース
function c58807980.initial_effect(c)
c:EnableReviveLimit()
--special summon
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SPSUMMON_PROC)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetRange(LOCATION_HAND)
e1:SetCondition(c58807980.hspcon)
e1:SetOperation(c58807980.hspop)
c:RegisterEffect(e1)
--spsummon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(58807980,0))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_BE_MATERIAL)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCondition(c58807980.spcon)
e2:SetTarget(c58807980.sptg)
e2:SetOperation(c58807980.spop)
c:RegisterEffect(e2)
end
function c58807980.cfilter(c)
return c:IsType(TYPE_SPELL) and c:IsAbleToRemoveAsCost()
end
function c58807980.hspcon(e,c)
if c==nil then return true end
local tp=c:GetControler()
return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c58807980.cfilter,tp,LOCATION_HAND,0,1,nil)
end
function c58807980.hspop(e,tp,eg,ep,ev,re,r,rp,c)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,c58807980.cfilter,tp,LOCATION_HAND,0,1,1,nil)
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function c58807980.spcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsLocation(LOCATION_GRAVE) and r==REASON_SYNCHRO
end
function c58807980.filter(c,e,tp)
return c:IsLocation(LOCATION_GRAVE) and c:IsType(TYPE_TUNER) and c:IsRace(RACE_BEAST)
and c:IsCanBeEffectTarget(e) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c58807980.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
local mg=e:GetHandler():GetReasonCard():GetMaterial()
if chkc then return mg:IsContains(chkc) and c58807980.filter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and mg:IsExists(c58807980.filter,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=mg:FilterSelect(tp,c58807980.filter,1,1,nil,e,tp)
Duel.SetTargetCard(g)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c58807980.spop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
m-maste/Swordpaw | wp-content/themes/swordpaw/index.php | 1253 | <?php
/**
* The main template file.
*
* This is the most generic template file in a WordPress theme
* and one of the two required files for a theme (the other being style.css).
* It is used to display a page when nothing more specific matches a query.
* E.g., it puts together the home page when no home.php file exists.
* Learn more: http://codex.wordpress.org/Template_Hierarchy
*
* @package Swordpaw
*/
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php if ( have_posts() ) : ?>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
/*
* Include the Post-Format-specific template for the content.
* If you want to override this in a child theme, then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
get_template_part( 'template-parts/content', get_post_format() );
?>
<?php endwhile; ?>
<?php the_posts_navigation(); ?>
<?php else : ?>
<?php get_template_part( 'template-parts/content', 'none' ); ?>
<?php endif; ?>
</main><!-- #main -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
| gpl-2.0 |
Blaez/ZiosGram | TMessagesProj/src/main/java/org/telegram/messenger/exoplayer2/extractor/ts/Id3Reader.java | 3839 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.blaez.ziosgram.exoplayer2.extractor.ts;
import android.util.Log;
import org.blaez.ziosgram.exoplayer2.C;
import org.blaez.ziosgram.exoplayer2.Format;
import org.blaez.ziosgram.exoplayer2.extractor.ExtractorOutput;
import org.blaez.ziosgram.exoplayer2.extractor.TrackOutput;
import org.blaez.ziosgram.exoplayer2.extractor.ts.TsPayloadReader.TrackIdGenerator;
import org.blaez.ziosgram.exoplayer2.util.MimeTypes;
import org.blaez.ziosgram.exoplayer2.util.ParsableByteArray;
/**
* Parses ID3 data and extracts individual text information frames.
*/
/* package */ final class Id3Reader implements ElementaryStreamReader {
private static final String TAG = "Id3Reader";
private static final int ID3_HEADER_SIZE = 10;
private final ParsableByteArray id3Header;
private TrackOutput output;
// State that should be reset on seek.
private boolean writingSample;
// Per sample state that gets reset at the start of each sample.
private long sampleTimeUs;
private int sampleSize;
private int sampleBytesRead;
public Id3Reader() {
id3Header = new ParsableByteArray(ID3_HEADER_SIZE);
}
@Override
public void seek() {
writingSample = false;
}
@Override
public void createTracks(ExtractorOutput extractorOutput, TrackIdGenerator idGenerator) {
output = extractorOutput.track(idGenerator.getNextId());
output.format(Format.createSampleFormat(null, MimeTypes.APPLICATION_ID3, null, Format.NO_VALUE,
null));
}
@Override
public void packetStarted(long pesTimeUs, boolean dataAlignmentIndicator) {
if (!dataAlignmentIndicator) {
return;
}
writingSample = true;
sampleTimeUs = pesTimeUs;
sampleSize = 0;
sampleBytesRead = 0;
}
@Override
public void consume(ParsableByteArray data) {
if (!writingSample) {
return;
}
int bytesAvailable = data.bytesLeft();
if (sampleBytesRead < ID3_HEADER_SIZE) {
// We're still reading the ID3 header.
int headerBytesAvailable = Math.min(bytesAvailable, ID3_HEADER_SIZE - sampleBytesRead);
System.arraycopy(data.data, data.getPosition(), id3Header.data, sampleBytesRead,
headerBytesAvailable);
if (sampleBytesRead + headerBytesAvailable == ID3_HEADER_SIZE) {
// We've finished reading the ID3 header. Extract the sample size.
id3Header.setPosition(0);
if ('I' != id3Header.readUnsignedByte() || 'D' != id3Header.readUnsignedByte()
|| '3' != id3Header.readUnsignedByte()) {
Log.w(TAG, "Discarding invalid ID3 tag");
writingSample = false;
return;
}
id3Header.skipBytes(3); // version (2) + flags (1)
sampleSize = ID3_HEADER_SIZE + id3Header.readSynchSafeInt();
}
}
// Write data to the output.
int bytesToWrite = Math.min(bytesAvailable, sampleSize - sampleBytesRead);
output.sampleData(data, bytesToWrite);
sampleBytesRead += bytesToWrite;
}
@Override
public void packetFinished() {
if (!writingSample || sampleSize == 0 || sampleBytesRead != sampleSize) {
return;
}
output.sampleMetadata(sampleTimeUs, C.BUFFER_FLAG_KEY_FRAME, sampleSize, 0, null);
writingSample = false;
}
}
| gpl-2.0 |
dagochen/mangos-classic | src/scriptdev2/scripts/eastern_kingdoms/molten_core/boss_majordomo_executus.cpp | 18145 | /* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information
* 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
*/
/* ScriptData
SDName: Boss_Majordomo_Executus
SD%Complete: 95
SDComment: Minor weaknesses
SDCategory: Molten Core
EndScriptData */
#include "precompiled.h"
#include "molten_core.h"
#include "TemporarySummon.h"
enum
{
SAY_AGGRO = -1409003,
SAY_SLAY = -1409005,
SAY_SPECIAL = -1409006, // Use unknown
SAY_LAST_ADD = -1409019, // When only one add remaining
SAY_DEFEAT_1 = -1409007,
SAY_DEFEAT_2 = -1409020,
SAY_DEFEAT_3 = -1409021,
SAY_SUMMON_0 = -1409023,
SAY_SUMMON_1 = -1409024,
SAY_SUMMON_MAJ = -1409008,
SAY_ARRIVAL1_RAG = -1409009,
SAY_ARRIVAL2_MAJ = -1409010,
SAY_ARRIVAL3_RAG = -1409011,
SAY_ARRIVAL4_MAJ = -1409022,
GOSSIP_ITEM_SUMMON_1 = -3409000,
GOSSIP_ITEM_SUMMON_2 = -3409001,
GOSSIP_ITEM_SUMMON_3 = -3409002,
TEXT_ID_SUMMON_1 = 4995,
TEXT_ID_SUMMON_2 = 5011,
TEXT_ID_SUMMON_3 = 5012,
SPELL_MAGIC_REFLECTION = 20619,
SPELL_DAMAGE_REFLECTION = 21075,
SPELL_BLASTWAVE = 20229,
SPELL_AEGIS = 20620,
SPELL_TELEPORT = 20618,
SPELL_POLYMORPH_IMMUNE = 29183,
SPELL_TELEPORT_SELF = 19484,
SPELL_SUMMON_RAGNAROS = 19774,
SPELL_ELEMENTAL_FIRE = 19773,
SPELL_RAGNA_EMERGE = 20568,
};
struct boss_majordomoAI : public ScriptedAI
{
boss_majordomoAI(Creature* pCreature) : ScriptedAI(pCreature)
{
m_pInstance = (instance_molten_core*)pCreature->GetInstanceData();
m_bHasEncounterFinished = false;
Reset();
}
instance_molten_core* m_pInstance;
uint32 m_uiMagicReflectionTimer;
uint32 m_uiDamageReflectionTimer;
uint32 m_uiBlastwaveTimer;
uint32 m_uiTeleportTimer;
uint32 m_uiAegisTimer;
uint32 m_uiSpeechTimer;
ObjectGuid m_ragnarosGuid;
bool m_bHasEncounterFinished;
uint8 m_uiAddsKilled;
uint8 m_uiSpeech;
GuidList m_luiMajordomoAddsGUIDs;
void Reset() override
{
m_uiMagicReflectionTimer = 30000; // Damage reflection first so we alternate
m_uiDamageReflectionTimer = 15000;
m_uiBlastwaveTimer = 10000;
m_uiTeleportTimer = 20000;
m_uiAegisTimer = 5000;
m_uiSpeechTimer = 1000;
m_uiAddsKilled = 0;
m_uiSpeech = 0;
}
void KilledUnit(Unit* /*pVictim*/) override
{
if (urand(0, 4))
return;
DoScriptText(SAY_SLAY, m_creature);
}
void Aggro(Unit* pWho) override
{
if (pWho->GetTypeId() == TYPEID_UNIT && pWho->GetEntry() == NPC_RAGNAROS)
return;
DoScriptText(SAY_AGGRO, m_creature);
if (m_pInstance)
m_pInstance->SetData(TYPE_MAJORDOMO, IN_PROGRESS);
}
void JustReachedHome() override
{
if (!m_bHasEncounterFinished) // Normal reached home, FAIL
{
if (m_pInstance)
m_pInstance->SetData(TYPE_MAJORDOMO, FAIL);
}
else // Finished the encounter, DONE
{
// Exit combat
m_creature->RemoveAllAurasOnEvade();
m_creature->DeleteThreatList();
m_creature->CombatStop(true);
m_creature->SetLootRecipient(nullptr);
// Set friendly
m_creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE);
m_creature->SetFactionTemporary(FACTION_MAJORDOMO_FRIENDLY, TEMPFACTION_RESTORE_RESPAWN);
// Reset orientation
m_creature->SetFacingTo(m_aMajordomoLocations[0].m_fO);
// Start his speech
m_uiSpeechTimer = 1; // At next tick
m_uiSpeech = 1;
m_pInstance->SetData(TYPE_MAJORDOMO, DONE);
}
}
void StartSummonEvent(Player* pPlayer)
{
m_creature->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
// Prevent possible exploits with double summoning
if (m_creature->GetMap()->GetCreature(m_ragnarosGuid))
return;
DoScriptText(SAY_SUMMON_0, m_creature, pPlayer);
m_uiSpeechTimer = 5000;
m_uiSpeech = 10;
}
void JustRespawned() override
{
// Encounter finished, need special treatment
if (m_bHasEncounterFinished)
{
// This needs to be set to be able to resummon Ragnaros
m_creature->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
// Relocate here
debug_log("SD2: boss_majordomo_executus: Relocate to Ragnaros' Lair on respawn");
m_creature->GetMap()->CreatureRelocation(m_creature, m_aMajordomoLocations[1].m_fX, m_aMajordomoLocations[1].m_fY, m_aMajordomoLocations[1].m_fZ, m_aMajordomoLocations[1].m_fO);
m_creature->SetActiveObjectState(false);
}
}
void JustSummoned(Creature* pSummoned) override
{
if (pSummoned->GetEntry() == NPC_FLAMEWAKER_HEALER || pSummoned->GetEntry() == NPC_FLAMEWAKER_ELITE)
{
m_luiMajordomoAddsGUIDs.push_back(pSummoned->GetObjectGuid());
pSummoned->SetRespawnDelay(2 * HOUR);
}
else if (pSummoned->GetEntry() == NPC_RAGNAROS)
{
m_ragnarosGuid = pSummoned->GetObjectGuid();
pSummoned->CastSpell(pSummoned, SPELL_RAGNA_EMERGE, false);
}
}
void JustDied(Unit* pKiller) override
{
if (pKiller->GetTypeId() == TYPEID_UNIT && pKiller->GetEntry() == NPC_RAGNAROS)
DoScriptText(SAY_ARRIVAL4_MAJ, m_creature);
}
void CorpseRemoved(uint32& uiRespawnDelay) override
{
uiRespawnDelay = urand(2 * HOUR, 3 * HOUR);
if (m_bHasEncounterFinished)
{
// Needed for proper respawn handling
debug_log("SD2: boss_majordomo_executus: Set active");
m_creature->SetActiveObjectState(true);
}
}
void SummonedCreatureJustDied(Creature* pSummoned) override
{
if (pSummoned->GetEntry() == NPC_FLAMEWAKER_HEALER || pSummoned->GetEntry() == NPC_FLAMEWAKER_ELITE)
{
m_uiAddsKilled += 1;
// Yell if only one Add alive
if (m_uiAddsKilled == m_luiMajordomoAddsGUIDs.size() - 1)
DoScriptText(SAY_LAST_ADD, m_creature);
if (m_uiAddsKilled == 4)
{
for (GuidList::const_iterator itr = m_luiMajordomoAddsGUIDs.begin(); itr != m_luiMajordomoAddsGUIDs.end(); ++itr)
{
if (Creature* pCreature = m_creature->GetMap()->GetCreature(*itr))
{
if (pCreature->isAlive() && pCreature->GetEntry() == NPC_FLAMEWAKER_HEALER)
{
pCreature->CastSpell(pCreature, SPELL_POLYMORPH_IMMUNE, true);
}
}
}
}
// All adds are killed, retreat
else if (m_uiAddsKilled == m_luiMajordomoAddsGUIDs.size())
{
m_bHasEncounterFinished = true;
m_creature->GetMotionMaster()->MoveTargetedHome();
}
}
}
// Unsummon Majordomo adds
void UnsummonMajordomoAdds()
{
for (GuidList::const_iterator itr = m_luiMajordomoAddsGUIDs.begin(); itr != m_luiMajordomoAddsGUIDs.end(); ++itr)
{
if (Creature* pAdd = m_creature->GetMap()->GetCreature(*itr))
if (pAdd->IsTemporarySummon())
((TemporarySummon*)pAdd)->UnSummon();
}
m_luiMajordomoAddsGUIDs.clear();
}
void DamageTaken(Unit* /*pDealer*/, uint32& uiDamage) override
{
if (uiDamage > m_creature->GetHealth())
{
uiDamage = 0;
DoCastSpellIfCan(m_creature, SPELL_AEGIS, CAST_TRIGGERED);
}
}
void UpdateAI(const uint32 uiDiff) override
{
// Handling of his combat-end speech and Ragnaros summoning
if (m_uiSpeech)
{
if (m_uiSpeechTimer < uiDiff)
{
switch (m_uiSpeech)
{
// Majordomo retreat event
case 1:
DoScriptText(SAY_DEFEAT_1, m_creature);
m_uiSpeechTimer = 7500;
++m_uiSpeech;
break;
case 2:
DoScriptText(SAY_DEFEAT_2, m_creature);
m_uiSpeechTimer = 8000;
++m_uiSpeech;
break;
case 3:
DoScriptText(SAY_DEFEAT_3, m_creature);
m_uiSpeechTimer = 21500;
++m_uiSpeech;
break;
case 4:
DoCastSpellIfCan(m_creature, SPELL_TELEPORT_SELF);
// TODO - when should they be unsummoned?
// TODO - also unclear how this should be handled, as of range issues
m_uiSpeechTimer = 900;
++m_uiSpeech;
break;
case 5:
// Majordomo is away now, remove his adds
UnsummonMajordomoAdds();
m_uiSpeech = 0;
break;
// Ragnaros Summon Event
case 10:
DoScriptText(SAY_SUMMON_1, m_creature);
++m_uiSpeech;
m_uiSpeechTimer = 1000;
break;
case 11:
DoCastSpellIfCan(m_creature, SPELL_SUMMON_RAGNAROS);
// TODO - Move along, this expects to be handled with mmaps
m_creature->GetMotionMaster()->MovePoint(1, 831.079590f, -816.023193f, -229.023270f);
++m_uiSpeech;
m_uiSpeechTimer = 7000;
break;
case 12:
// Reset orientation
if (GameObject* pLavaSteam = m_pInstance->GetSingleGameObjectFromStorage(GO_LAVA_STEAM))
m_creature->SetFacingToObject(pLavaSteam);
m_uiSpeechTimer = 4500;
++m_uiSpeech;
break;
case 13:
DoScriptText(SAY_SUMMON_MAJ, m_creature);
++m_uiSpeech;
m_uiSpeechTimer = 8000;
break;
case 14:
// Summon Ragnaros
if (m_pInstance)
if (GameObject* pGo = m_pInstance->GetSingleGameObjectFromStorage(GO_LAVA_STEAM))
m_creature->SummonCreature(NPC_RAGNAROS, pGo->GetPositionX(), pGo->GetPositionY(), pGo->GetPositionZ(), fmod(m_creature->GetOrientation() + M_PI, 2 * M_PI), TEMPSUMMON_TIMED_OOC_OR_DEAD_DESPAWN, 2 * HOUR * IN_MILLISECONDS);
++m_uiSpeech;
m_uiSpeechTimer = 8700;
break;
case 15:
if (Creature* pRagnaros = m_creature->GetMap()->GetCreature(m_ragnarosGuid))
DoScriptText(SAY_ARRIVAL1_RAG, pRagnaros);
++m_uiSpeech;
m_uiSpeechTimer = 11700;
break;
case 16:
DoScriptText(SAY_ARRIVAL2_MAJ, m_creature);
++m_uiSpeech;
m_uiSpeechTimer = 8700;
break;
case 17:
if (Creature* pRagnaros = m_creature->GetMap()->GetCreature(m_ragnarosGuid))
DoScriptText(SAY_ARRIVAL3_RAG, pRagnaros);
++m_uiSpeech;
m_uiSpeechTimer = 16500;
break;
case 18:
if (Creature* pRagnaros = m_creature->GetMap()->GetCreature(m_ragnarosGuid))
pRagnaros->CastSpell(m_creature, SPELL_ELEMENTAL_FIRE, false);
// Rest of summoning speech is handled by Ragnaros, as Majordomo will be dead
m_uiSpeech = 0;
break;
}
}
else
m_uiSpeechTimer -= uiDiff;
}
// When encounter finished, no need to do anything anymore (important for moving home after victory)
if (m_bHasEncounterFinished)
return;
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
return;
// Cast Ageis to heal self
if (m_uiAegisTimer <= uiDiff)
m_uiAegisTimer = 0;
else
m_uiAegisTimer -= uiDiff;
if (m_creature->GetHealthPercent() < 90.0f && !m_uiAegisTimer)
{
DoCastSpellIfCan(m_creature, SPELL_AEGIS);
m_uiAegisTimer = 10000;
}
// Magic Reflection Timer
if (m_uiMagicReflectionTimer < uiDiff)
{
if (DoCastSpellIfCan(m_creature, SPELL_MAGIC_REFLECTION) == CAST_OK)
m_uiMagicReflectionTimer = 30000;
}
else
m_uiMagicReflectionTimer -= uiDiff;
// Damage Reflection Timer
if (m_uiDamageReflectionTimer < uiDiff)
{
if (DoCastSpellIfCan(m_creature, SPELL_DAMAGE_REFLECTION) == CAST_OK)
m_uiDamageReflectionTimer = 30000;
}
else
m_uiDamageReflectionTimer -= uiDiff;
// Teleports the target to the heated rock in the center of the area
if (m_uiTeleportTimer < uiDiff)
{
if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 1))
{
if (DoCastSpellIfCan(pTarget, SPELL_TELEPORT) == CAST_OK)
m_uiTeleportTimer = 20000;
}
}
else
m_uiTeleportTimer -= uiDiff;
// Blastwave Timer
if (m_uiBlastwaveTimer < uiDiff)
{
if (DoCastSpellIfCan(m_creature, SPELL_BLASTWAVE) == CAST_OK)
m_uiBlastwaveTimer = 10000;
}
else
m_uiBlastwaveTimer -= uiDiff;
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI_boss_majordomo(Creature* pCreature)
{
return new boss_majordomoAI(pCreature);
}
bool GossipHello_boss_majordomo(Player* pPlayer, Creature* pCreature)
{
if (instance_molten_core* pInstance = (instance_molten_core*)pCreature->GetInstanceData())
{
if (pInstance->GetData(TYPE_RAGNAROS) == NOT_STARTED || pInstance->GetData(TYPE_RAGNAROS) == FAIL)
{
pPlayer->ADD_GOSSIP_ITEM_ID(GOSSIP_ICON_CHAT, GOSSIP_ITEM_SUMMON_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1);
pPlayer->SEND_GOSSIP_MENU(TEXT_ID_SUMMON_1, pCreature->GetObjectGuid());
}
}
return true;
}
bool GossipSelect_boss_majordomo(Player* pPlayer, Creature* pCreature, uint32 /*sender*/, uint32 uiAction)
{
switch (uiAction)
{
case GOSSIP_ACTION_INFO_DEF + 1:
pPlayer->ADD_GOSSIP_ITEM_ID(GOSSIP_ICON_CHAT, GOSSIP_ITEM_SUMMON_2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2);
pPlayer->SEND_GOSSIP_MENU(TEXT_ID_SUMMON_2, pCreature->GetObjectGuid());
break;
case GOSSIP_ACTION_INFO_DEF + 2:
pPlayer->ADD_GOSSIP_ITEM_ID(GOSSIP_ICON_CHAT, GOSSIP_ITEM_SUMMON_3, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 3);
pPlayer->SEND_GOSSIP_MENU(TEXT_ID_SUMMON_3, pCreature->GetObjectGuid());
break;
case GOSSIP_ACTION_INFO_DEF + 3:
pPlayer->CLOSE_GOSSIP_MENU();
if (boss_majordomoAI* pMajoAI = dynamic_cast<boss_majordomoAI*>(pCreature->AI()))
pMajoAI->StartSummonEvent(pPlayer);
break;
}
return true;
}
bool EffectDummyCreature_spell_boss_majordomo(Unit* /*pCaster*/, uint32 uiSpellId, SpellEffectIndex uiEffIndex, Creature* pCreatureTarget, ObjectGuid /*originalCasterGuid*/)
{
if (uiSpellId != SPELL_TELEPORT_SELF || uiEffIndex != EFFECT_INDEX_0)
return false;
pCreatureTarget->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
pCreatureTarget->NearTeleportTo(m_aMajordomoLocations[1].m_fX, m_aMajordomoLocations[1].m_fY, m_aMajordomoLocations[1].m_fZ, m_aMajordomoLocations[1].m_fO, true);
// TODO - some visibility update?
return true;
}
void AddSC_boss_majordomo()
{
Script* pNewScript;
pNewScript = new Script;
pNewScript->Name = "boss_majordomo";
pNewScript->pEffectDummyNPC = &EffectDummyCreature_spell_boss_majordomo;
pNewScript->pGossipHello = &GossipHello_boss_majordomo;
pNewScript->pGossipSelect = &GossipSelect_boss_majordomo;
pNewScript->GetAI = &GetAI_boss_majordomo;
pNewScript->RegisterSelf();
}
| gpl-2.0 |
castlecms/castle.cms | castle/cms/tiles/base.py | 10347 | from plone.memoize.view import memoize
from castle.cms.utils import parse_query_from_data
from plone.memoize.view import memoize_contextless
from plone.tiles import Tile
from plone.tiles.interfaces import IPersistentTile
from Products.CMFCore.utils import getToolByName
from urllib import quote_plus
from zope.component import getMultiAdapter
from zope.component.hooks import getSite
from zope.interface import implements
from zope.security import checkPermission
from castle.cms.tiles.views import getTileView
from castle.cms.behaviors.adjustablefont import IAdjustableFontSizeQueryListing
from castle.cms.behaviors.adjustablefont import get_inline_style
import json
import logging
import traceback
logger = logging.getLogger('castle.cms')
def _one(val):
if type(val) in (list, set, tuple):
if len(val) > 0:
return val[0]
return val
class BaseTile(Tile):
global_editable = False
edit_label = 'Tile'
edit_permission = 'cmf.ModifyPortalContent'
wrap = True
font_sizes = {}
adjustable_font_behaviors = [
{
'interface': IAdjustableFontSizeQueryListing,
'tile_type': 'query_listing',
}
]
def get_focal_point(self):
focal = self.data.get('override_focal_point')
if not focal:
return
try:
focal = json.loads(focal)
if len(focal) == 2:
return focal
except Exception:
pass
@property
def title(self):
return self.data.get('title', None)
@property
def more_link(self):
return _one(self.data.get('more_link', None))
@property
def more_text(self):
return self.data.get('more_text', None)
@property
@memoize
def site(self):
return getSite()
@property
@memoize
def catalog(self):
return getToolByName(self.site, 'portal_catalog')
@property
@memoize_contextless
def utils(self):
return getMultiAdapter((self.context, self.request),
name="castle-utils")
@property
def edit_url(self):
url = '%s/@@edit-tile/%s/%s' % (
self.context.absolute_url(), self.__name__, self.id or ''
)
if IPersistentTile.providedBy(self):
url += '?' + self.request.environ.get('QUERY_STRING') or ''
return url
@property
def view_url(self):
url = '%s/@@%s/%s' % (
self.context.absolute_url(), self.__name__, self.id or ''
)
if IPersistentTile.providedBy(self):
if hasattr(self.request, 'tile_data'):
qs = []
for k, v in self.request.tile_data.items():
if not v or k == 'X-Tile-Persistent':
continue
if isinstance(v, list):
for item in v:
if isinstance(item, dict):
for subk, subv in item.items():
qs.append((
'%s.%s:records' % (k, subk),
str(subv)
))
else:
qs.append((
'%s:records' % k,
str(subv)
))
else:
qs.append((k, str(v)))
qs = '&'.join([k + '=' + quote_plus(v) for k, v in qs])
else:
qs = self.request.environ.get('QUERY_STRING') or ''
url += '?' + qs
return url
def __call__(self):
self.request.response.setHeader('X-Theme-Disabled', '1')
for behavior in self.adjustable_font_behaviors:
if behavior['interface'].providedBy(self.context):
self.font_sizes[behavior['tile_type']] = get_inline_style(self.context, behavior['tile_type'])
try:
res = self.render()
if self.global_editable and checkPermission('cmf.ModifyPortalContent', self.context):
# wrap with tile url div
config = json.dumps({
'label': self.edit_label,
'url': self.view_url,
'editUrl': self.edit_url
})
res = """
<div class="castle-tile-wrapper pat-edittile"
data-pat-edittile='%s'>%s</div>""" % (
config, res)
else:
if self.wrap:
res = '<div class="castle-tile-wrapper">%s</div>' % res
return '<html><body>' + res + '</body></html>'
except Exception:
path = ['']
if hasattr(self.context, 'getPhysicalPath'):
path = self.context.getPhysicalPath()
logger.error(
'Error rendering tile on context: %s, url: %s, data: %s,\n%s' % (
'/'.join(path),
self.request.ACTUAL_URL,
repr(self.data),
traceback.format_exc()))
return """<html><body>
<p class="tileerror">
We apologize, there was an error rendering this snippet
</p></body></html>"""
def render(self):
return self.index()
class DisplayTypeTileMixin(object):
display_type_name = ''
display_type_default = 'default'
display_type_fallback_view = None
def render_display(self):
view = getTileView(
self.context, self.request, self.display_type_name,
self.data.get('display_type', self.display_type_default) or self.display_type_default,
default=self.display_type_default)
if view is None:
if self.display_type_fallback_view:
view = self.display_type_fallback_view(self.context, self.request)
else:
return '<div>Warning: No display found</div>'
view.tile = self
return view()
class ContentTile(BaseTile):
implements(IPersistentTile)
default_display_fields = ('title', 'image', 'description')
sort_limit = 1
def render(self):
return self.index()
@property
def content(self):
if self.data.get('use_query') in ('True', True, 'true'):
catalog = getToolByName(self.context, 'portal_catalog')
items = catalog(**self.query)
if len(items) > 0:
return items[0].getObject()
else:
return self.utils.get_object(self.data['content'][0])
@property
def query(self):
parsed = parse_query_from_data(self.data, self.context)
if self.sort_limit:
parsed['sort_limit'] = self.sort_limit
return parsed
@property
def display_fields(self):
df = self.data.get('display_fields', None)
if df is None:
df = self.default_display_fields
return df
class BaseImagesTile(ContentTile):
implements(IPersistentTile)
sort_limit = 0
def get_image_data_from_brain(self, brain):
if brain.has_custom_markup:
return self.get_image_data(brain.getObject())
base_url = brain.getURL()
return {
'high': '%s/@@images/image/high' % base_url,
'large': '%s/@@images/image/large' % base_url,
'medium': '%s/@@images/image/preview' % base_url,
'thumb': '%s/@@images/image/thumb' % base_url,
'original': base_url,
'title': brain.Title,
'description': brain.Description or '',
'link': '%s/view' % base_url,
'custom_markup': False
}
def get_image_data(self, im):
base_url = im.absolute_url()
related = self.get_related(im) or im
return {
'high': '%s/@@images/image/high' % base_url,
'large': '%s/@@images/image/large' % base_url,
'medium': '%s/@@images/image/preview' % base_url,
'thumb': '%s/@@images/image/thumb' % base_url,
'original': base_url,
'title': im.Title(),
'description': im.Description() or '',
'link': '%s/view' % related.absolute_url(),
'custom_markup': im.custom_markup
}
def get_images_in_folder(self, brain):
if brain.portal_type == 'Folder':
# get contents
folder = brain.getObject()
images = folder.getFolderContents()
results = []
for image in images:
if image.portal_type == 'Image':
results.append(self.get_image_data_from_brain(image))
else:
obj = image.getObject()
if hasattr(obj, 'image') and hasattr(obj.image, 'contentType'):
results.append(self.get_image_data(obj))
return results
else:
return [self.get_image_data_from_brain(brain)]
@property
def images(self):
if self.data.get('use_query') in ('True', True, 'true'):
return self.query_images()
else:
return self.get_selected_images()
def query_images(self):
catalog = getToolByName(self.context, 'portal_catalog')
results = []
query = self.query
query['hasImage'] = True
for brain in catalog(**query):
results.append(self.get_image_data_from_brain(brain))
return results
def get_selected_images(self):
results = []
brains = list(self.catalog(UID=self.data.get('images', [])))
# we need to order this since catalog results are not ordered
for uid in self.data.get('images') or []:
found = False
for brain in brains:
if brain.UID == uid:
found = brain
break
if not found:
continue
brains.remove(found)
if found.is_folderish:
results.extend(self.get_images_in_folder(brain))
else:
results.append(self.get_image_data_from_brain(found))
return results
def get_related(self, obj):
try:
return obj.relatedItems[0]
except Exception:
return None
| gpl-2.0 |
alons182/partytime | plugins/k2store/shipping_standard/shipping_standard/tables/shippingmethods.php | 797 | <?php
/** ensure this file is being included by a parent file */
defined( '_JEXEC' ) or die( 'Restricted access' );
class TableShippingMethods extends JTable
{
function TableShippingMethods ( $db )
{
$tbl_key = 'shipping_method_id';
$tbl_suffix = 'shippingmethods';
$this->set( '_suffix', $tbl_suffix );
$name = 'k2store';
parent::__construct( "#__{$name}_{$tbl_suffix}", $tbl_key, $db );
}
function check()
{
if(empty($this->shipping_method_name)) {
throw new Exception(JText::_('K2STORE_SHIPPING_METHOD_NAME_REQUIRED'));
return false;
}
if ((float) $this->subtotal_maximum == (float) '0.00000')
{
$this->subtotal_maximum = '-1';
}
return true;
}
}
| gpl-2.0 |
ljx0305/ice | cpp/test/IceUtil/thread/AliveTest.cpp | 1989 | // **********************************************************************
//
// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
#include <IceUtil/IceUtil.h>
#include <AliveTest.h>
#include <TestCommon.h>
using namespace std;
using namespace IceUtil;
static const string createTestName("thread alive");
class CondVar : public IceUtil::Monitor<IceUtil::RecMutex>
{
public:
CondVar() :
_done(false)
{
}
void waitForSignal()
{
IceUtil::Monitor<IceUtil::RecMutex>::Lock lock(*this);
while(!_done)
{
wait();
}
}
void signal()
{
IceUtil::Monitor<IceUtil::RecMutex>::Lock lock(*this);
_done = true;
notify();
}
private:
bool _done;
};
class AliveTestThread : public Thread
{
public:
AliveTestThread(CondVar& childCreated, CondVar& parentReady) :
_childCreated(childCreated), _parentReady(parentReady)
{
}
virtual void run()
{
try
{
_childCreated.signal();
_parentReady.waitForSignal();
}
catch(const IceUtil::ThreadLockedException&)
{
}
}
private:
CondVar& _childCreated;
CondVar& _parentReady;
};
typedef Handle<AliveTestThread> AliveTestThreadPtr;
AliveTest::AliveTest() :
TestBase(createTestName)
{
}
void
AliveTest::run()
{
//
// Check that calling isAlive() returns the correct result for alive and
// and dead threads.
//
CondVar childCreated;
CondVar parentReady;
AliveTestThreadPtr t = new AliveTestThread(childCreated, parentReady);
IceUtil::ThreadControl c = t->start();
childCreated.waitForSignal();
test(t->isAlive());
parentReady.signal();
c.join();
test(!t->isAlive());
}
| gpl-2.0 |
dusik/realejuventudfan | core/modules/path/path.api.php | 1499 | <?php
/**
* @file
* Hooks provided by the Path module.
*/
/**
* @addtogroup hooks
* @{
*/
/**
* Respond to a path being inserted.
*
* @param $path
* An associative array containing the following keys:
* - source: The internal system path.
* - alias: The URL alias.
* - pid: Unique path alias identifier.
* - langcode: The language code of the alias.
*
* @see path_save()
*/
function hook_path_insert($path) {
db_insert('mytable')
->fields(array(
'alias' => $path['alias'],
'pid' => $path['pid'],
))
->execute();
}
/**
* Respond to a path being updated.
*
* @param $path
* An associative array containing the following keys:
* - source: The internal system path.
* - alias: The URL alias.
* - pid: Unique path alias identifier.
* - langcode: The language code of the alias.
*
* @see path_save()
*/
function hook_path_update($path) {
db_update('mytable')
->fields(array('alias' => $path['alias']))
->condition('pid', $path['pid'])
->execute();
}
/**
* Respond to a path being deleted.
*
* @param $path
* An associative array containing the following keys:
* - source: The internal system path.
* - alias: The URL alias.
* - pid: Unique path alias identifier.
* - langcode: The language code of the alias.
*
* @see path_delete()
*/
function hook_path_delete($path) {
db_delete('mytable')
->condition('pid', $path['pid'])
->execute();
}
/**
* @} End of "addtogroup hooks".
*/
| gpl-2.0 |
leiran/aermodpy | aermod.py | 32889 | #!/usr/bin/env python
"""Python interface to AERMOD modeling system files.
design notes:
+ Bug on POST processing; only processes 996 hours
- proposed fix: in-place averaging, discard hourly data
developed for python 3.x
"""
# docstring metadata
__author__ = "Leiran Biton"
__copyright__ = "Copyright 2015"
__credits__ = []
__license__ = "GPL"
__version__ = "0.11"
__maintainer__ = "Leiran Biton"
__email__ = "leiranbiton@gmail.com"
__status__ = "Production"
# standard library imports
import os.path
import datetime
import numpy
import csv
# internal package imports
from aermodpy.support import pollutant_dict, vars_indices, ordinal
class point(object):
def __init__(self, num, **kwargs):
"""Point object
mandatory arguments:
num - number of points
optional arguments:
Xs - array of x locations for # of points. default = zeros
Ys - array of y locations for # of points. default = zeros
Zs - array of z locations for # of points. default = zeros
XYs - array shape=(num, 2) of x and y locations for # of points. replaces Xs & Ys.
XYZs - array shape=(num, 3) of x, y, and z locations for # of points. replaces Xs, Ys, and Zs.
"""
self.num = num
self.X = kwargs.get("Xs", numpy.zeros(num))
self.Y = kwargs.get("Ys", numpy.zeros(num))
self.Z = kwargs.get("Zs", numpy.zeros(num))
if "XYs" in kwargs:
self.X = kwargs["XYs"][:,0]
self.Y = kwargs["XYs"][:,1]
if "XYZs" in kwargs:
self.X = kwargs["XYZs"][:,0]
self.Y = kwargs["XYZs"][:,1]
self.Z = kwargs["XYZs"][:,2]
class post:
"POST file processor"
verbose = False
DEBUG = False
# default data
formatstring = "(3(1X,F13.5),3(1X,F8.2),3X,A5,2X,A8,2X,A4,6X,A8,2X,I8)"
vars_index = None
def __init__(self
,filename
,directory="."
,receptors=0
,formatstring_override=False
,century=20
,vars_index=vars_indices["post"]
,verbose=True
,DEBUG=False
):
self.POSTfile = self.openfile(filename, directory=directory, mode="rU")
self.century = century
self.datetimes = [] # empty list for datetime objects
self.modeldoc = []
self.datatypes = []
self.POSTdata = {}
self.receptors = point(receptors)
self.formatstring_override = formatstring_override
self.vars_index = vars_index
self.verbose = verbose
self.DEBUG = DEBUG
def decode_format_datastring(self
,formatstring):
"""placeholder function for decoding a string describing POST file dataformat"""
# example format '* FORMAT: (3(1X,F13.5),3(1X,F8.2),3X,A5,2X,A8,2X,A4,6X,A8,2X,I8)'
return formatstring
def decode_data(self
,dataline
#,formatstring=formatstring
):
# example format '* FORMAT: (3(1X,F13.5),3(1X,F8.2),3X,A5,2X,A8,2X,A4,6X,A8,2X,I8)'
# example head '* X Y AVERAGE CONC ZELEV ZHILL ZFLAG AVE GRP HIVAL NET ID DATE(CONC)\n
# example data ' 569830.00000 4909393.00000 3065.99300 494.10 747.20 0.00 1-HR ALL 08033104\n'
#if self.formatstring_override:
# self.decode_format_datastring(self, formatstring)
if all([datetime_part in self.vars_index for datetime_part in ("year","month","day","hour")]):
dt = datetime.datetime(self.vars_index["year"]["type"](dataline[self.vars_index["year"]["start"]:
self.vars_index["year"]["end" ]]) + self.century*100
,self.vars_index["month"]["type"](dataline[self.vars_index["month"]["start"]:
self.vars_index["month"]["end" ]])
,self.vars_index["day"]["type"](dataline[self.vars_index["day"]["start"]:
self.vars_index["day"]["end" ]])
,self.vars_index["hour"]["type"](dataline[self.vars_index["hour"]["start"]:
self.vars_index["hour"]["end" ]]) - 1
)
else:
dt = None
return [self.vars_index[var]["type"](dataline[self.vars_index[var]["start"]:self.vars_index[var]["end"]])
for var in ["x", "y", "zflag","conc"]
], dt
def add_buildings(self
,filename
,directory="."
,nosources=False
):
self.building_vertices = {}
self.sources = {}
if self.verbose: print("--> opening building data file")
self.building_file = self.openfile(filename, directory, "rU")
# throw away header data
[next(self.building_file) for header in range(2)]
units, unit_value = next(self.building_file).split()
if self.DEBUG: print("DEBUG: units / unit_value:", units, unit_value)
utmy, trash = next(self.building_file).split()
num_bldgs = int(next(self.building_file))
if self.DEBUG: print("DEBUG: number of buildings:", num_bldgs)
for building in range(num_bldgs):
try:
name, stories, elev = self.building_header()
self.process_building(name, stories, elev)
except:
raise Exception("No more buildings to process")
if not nosources:
num_srcs = int(next(self.building_file))
for src in range(num_srcs):
try:
raw_source_line = next(self.building_file).strip()
source_descriptors = raw_source_line.replace("'", "").split(sep=None, maxsplit=5)
if len(source_descriptors) == 5:
name, elev, height, x, y = source_descriptors
else:
trash, elev, height, x, y, name = source_descriptors
name = name.strip()
if self.DEBUG: print("DEBUG: source name:", name, x, y)
self.sources[(name)] = \
point(1, Xs=numpy.array(float(x))
, Ys=numpy.array(float(y))
)
if self.verbose: print("adding source:", self.sources[(name)].X, self.sources[(name)].Y)
except:
raise Exception("No more sources to process")
def building_header(self):
"""get building data for new building"""
building_descriptors = next(self.building_file).split(sep=None, maxsplit=3)
if len(building_descriptors) == 3:
name_padded, stories, base_elevation = building_descriptors
else:
trash, stories, base_elevation, name_padded = building_descriptors
if self.verbose: print("adding building: ", name_padded.strip(), stories, base_elevation)
return name_padded.strip().replace("'",""), int(stories), float(base_elevation)
def process_building(self
,name
,stories
,base_elevation
):
"""adds building data to the self.building_vertices dictionary"""
for story in range(stories):
self.process_building_story(name, story+1)
def process_building_story(self
,name
,story
):
"""process a building story"""
vertices, height = next(self.building_file).split()
vertices = int(vertices)
height = float(height)
vs = numpy.array([(float(X), float(Y)) for (X, Y) in \
[next(self.building_file).split() for v in range(vertices)] \
]).reshape(vertices, 2)
self.building_vertices[(name, story)] = point(vertices, XYs=vs)
def openfile(self
,filename
,directory="."
,mode="rU"
):
# files
try:
filepath = directory + os.path.sep + filename
except TypeError:
raise TypeError("Invalid 'directory' or 'filename' inputs!")
if self.verbose: print("Opening file:", filepath)
if self.verbose: print(" mode =", mode)
try: openfile = open(filepath, mode)
except:
raise IOError("Filepath '%s' failed to open. Check the address and mode." % filepath)
return openfile
def getPOSTfileMetaData(self):
"""Get metadata from POSTfile"""
try:
[filetype_doc
,optionsflag_doc
,modeloptions_doc
,datatype_doc
,receptors_doc
,dataformat_doc
] = [next(self.POSTfile) for i in range(6)]
except:
raise Exception("POST file does not contain proper header metadata")
# extract format string from data format documentation
if self.DEBUG: print("DEBUG: filetype_doc =", filetype_doc)
if self.DEBUG: print("DEBUG: dataformat_doc =", dataformat_doc)
dataformat_string = dataformat_doc[dataformat_doc.index(":")+1:].strip()
# decode data format string
dataformat = self.decode_format_datastring(dataformat_string)
if self.formatstring_override:
# function still in development
self.formatstring = dataformat
else:
self.modeldoc.append((filetype_doc
,optionsflag_doc
,modeloptions_doc
,datatype_doc
,receptors_doc
,dataformat_doc
))
datatype_metadata = datatype_doc.split()
r_type = datatype_metadata[datatype_metadata.index("VALUES")-1]
r_form = datatype_metadata[datatype_metadata.index("OF")+1:\
datatype_metadata.index("VALUES")-1]
r_form = " ".join(r_form)
source_group = datatype_metadata[-1]
if self.DEBUG: print("DEBUG:", r_type, r_form, source_group)
self.datatypes.append((r_type, r_form, source_group))
self.POSTdata[(r_type, r_form, source_group)] = numpy.zeros([self.receptors.num, 1])
if len(self.modeldoc) == 1:
n_receptors = [int(s) for s in receptors_doc.split() if s.isdigit()][0]
self.receptors = point(n_receptors)
def getPOSTfileHeader(self):
"""Get metadata from POSTfile"""
self.fileheader = next(self.POSTfile).strip()
next(self.POSTfile) # -------- line
def printResults(self, filename, r_type, **kwargs):
"""print(r_type results data array to outfile as comma separated values)"""
outfile = self.openfile(filename, directory=kwargs.get("directory", "."), mode="w")
self.POSTdata[(r_type, r_form, source_group)].tofile(outfile, sep=",")
outfile.close()
def scalePOSTdata(self, r_type, **kwargs):
"""scales POSTdata result_type using optional "scalar" keyword argument. if omitted, 1.0."""
if self.DEBUG: print("DEBUG: scaling %s results by" % r_type, kwargs.get("scalar", 1.0))
self.POSTdata[(r_type, r_form, source_group)] *= kwargs.get("scalar", 1.0)
def processPOSTData(self
,ranked=1
,annual=False
):
"""Process stored POST file data"""
if self.verbose: print("--> processing open data file")
while True:
try:
self.getPOSTfileMetaData()
self.getPOSTfileHeader()
self.POSTdata[self.datatypes[-1]] = numpy.zeros([self.receptors.num, ranked])
h = 0
if "hour" in self.vars_index:
while True:
try:
self.getPOSTfileData(h=h, annual=annual, ranked=ranked)
h += 1
except Exception as e:
if self.DEBUG:
print("DEBUG: reached exception during file processing")
print("DEBUG:", "Unexpected error:", e)
print(" ", self.datetimes[-1])
return
else:
try:
self.getPOSTfileData(h=h, annual=annual, ranked=ranked)
if self.DEBUG:
print("DEBUG: got 1 instance of POST data")
except:
return
except:
return
def getPOSTfileData(self
,h=0
,annual=False
,ranked=1
):
"""Get data from POSTfile, process for average number of hours"""
if self.verbose: print("--> retrieving data")
if h == 0:
self.POSTdata[self.datatypes[-1]] = numpy.zeros([self.receptors.num, ranked])
if annual:
self.POSTdata[self.datatypes[-1]] = numpy.expand_dims(self.POSTdata[self.datatypes[-1]], axis=2)
for r in range(self.receptors.num):
line = next(self.POSTfile)
# decode data
data4hour, dt = self.decode_data(line)
# build datetime list
if r == 0:
if self.DEBUG: print("DEBUG:", "processing for", dt)
if annual and (h > 0) and (dt.year > self.datetimes[-1].year):
self.POSTdata[self.datatypes[-1]] = numpy.append(self.POSTdata[self.datatypes[-1]]
,numpy.zeros([self.receptors.num, ranked, 1])
,axis=2
)
self.datetimes.append(dt)
# populate receptor location values
if h == 0:
self.receptors.X[r] = data4hour[0]
self.receptors.Y[r] = data4hour[1]
self.receptors.Z[r] = data4hour[2]
if annual:
receptor_data = numpy.append(self.POSTdata[self.datatypes[-1]][r,:,-1], [data4hour[3]], axis=1)
receptor_data.sort()
self.POSTdata[self.datatypes[-1]][r,:,-1] = receptor_data[::-1][:ranked]
else:
receptor_data = numpy.append(self.POSTdata[self.datatypes[-1]][r,:], [data4hour[3]], axis=1)
receptor_data.sort()
self.POSTdata[self.datatypes[-1]][r,:] = receptor_data[::-1][:ranked]
return
def draw_building(self
,building
,story
,axis
,origin=point(1,Xs=[0],Ys=[0])
,**kwargs
):
import matplotlib.patches as patches
from matplotlib.path import Path
"""method for drawing buildings"""
# create polygon using path method
verts = [(x-origin.X, y-origin.Y) \
for (x, y) \
in zip(self.building_vertices[(building, story)].X
,self.building_vertices[(building, story)].Y
)]
verts.append(verts[0]) # add first point to close polygon
codes = [Path.LINETO for coords in verts]
codes[0] = Path.MOVETO
codes[-1] = Path.CLOSEPOLY
path = Path(verts, codes)
patch = patches.PathPatch(path
,facecolor=kwargs.get("color", "white")
,edgecolor='black'
,linewidth=kwargs.get("linewidth", 0.4)
,alpha=kwargs.get("alpha", 1.00)
)
axis.add_patch(patch)
if kwargs.get("building_name", False) and (story == 1):
axis.annotate(str(building)
,xy=((self.building_vertices[(building, story)].X - origin.X).mean()
,(self.building_vertices[(building, story)].Y - origin.Y).mean())
,va="center"
,ha="center"
,color="blue"
,size=kwargs.get("max_textsize", 8)
)
def printdata(self
,r_type
,r_form # datatype key for POSTdata
,source_group
,filename="aermod_results.csv"
,directory="."
,**kwargs
):
with self.openfile(filename, directory, "w") as csvoutfile:
csvoutfile.write(r_type+"\n")
csvoutfile.write(r_form+"\n")
csvoutfile.write(source_group+"\n")
w = csv.writer(csvoutfile)
rank = kwargs.get("ranked_data", 0)
rank_index = 0 if rank == 0 else rank-1
if kwargs.get("exclude_flagpole_receptors", False):
concs = self.POSTdata[(r_type, r_form, source_group)][:,rank_index][self.receptors.Z==0] * kwargs.get("scalar", 1.0) + kwargs.get("add_background", 0.0)
else:
concs = self.POSTdata[(r_type, r_form, source_group)][:,rank_index] * kwargs.get("scalar", 1.0) + kwargs.get("add_background", 0.0)
outlist = [kwargs.get("scale_decimals","%0.0f") % concs.max()]
w.writerow(outlist)
def gridplot(self
,r_type
,r_form # datatype key for POSTdata
,source_group
,levels=[0,10,20,30,40,50,60,70,80,90,100,150,200,250,300]
,**kwargs
):
"""creates an individual grid plot based on input concentration array
kwargs:
contours - width of contour lines to draw. no contour lines if omitted
levels - list of levels to be used in the contour plots
receptor_size - an integer for sizing the receptors to be plotted. default = 15. enter 0 to omit.
plot_max - an integer for sizing the datapoint for the max conc in the domain. enter 0 to omit.
distance_from_origin -
receptor_type - receptor representation as matplotlib marker indicators (default=".")
max_plot - if 0, maximum point omitted.
tickinterval - interval of x and y axes
noticks - if True, omit x-y ticks
labelsize - size of colorbar and x-y tick labels
labelgap - gap between ticks and labels
nocolorbar - if True: colorbar omitted
scale_decimals - colorbar number formatting (e.g. "%0.0f")
filename - string for filename. default: "aermod.png"
colorbar_spacing - "uniform" or "proportional" (default = "proportional")
interpolation_method - linear cubic nearest
contour_colors - list of contour colors to use for contours. if omitted, hot colorscale is used.
colorslevels - colors and levels
scalar - multiplier for concentration data
exclude_flagpole_receptors - Default = False, set to True to exclude flagpole receptors
add_background - Default value = 0.0
ranked_data - use ranked dataset of value n. Default=1.
annual - POSTdata has annual values (default=False)
"""
import matplotlib
import matplotlib.pyplot as plt
#from scipy.interpolate import griddata
from matplotlib.mlab import griddata
if kwargs.get("exclude_flagpole_receptors", False):
if self.DEBUG: print("DEBUG: removing flagpole receptors")
receptor_array = numpy.column_stack((self.receptors.X[self.receptors.Z==0]
,self.receptors.Y[self.receptors.Z==0]
,self.receptors.Z[self.receptors.Z==0]))
else:
receptor_array = numpy.column_stack((self.receptors.X, self.receptors.Y, self.receptors.Z))
receptor_num = len(receptor_array)
receptors = point(receptor_num
,XYZs=receptor_array)
rank = kwargs.get("ranked_data", 0)
rank_index = 0 if rank == 0 else rank-1
if kwargs.get("annual", False):
if self.DEBUG: print("DEBUG: 'annual' flag is on. Averaging all years.")
if kwargs.get("exclude_flagpole_receptors", False):
if self.DEBUG: print("DEBUG: removing flagplot data")
concs = numpy.mean(self.POSTdata[(r_type, r_form, source_group)][:,rank_index,:], axis=1)[self.receptors.Z==0] * kwargs.get("scalar", 1.0) + kwargs.get("add_background", 0.0)
else:
concs = numpy.mean(self.POSTdata[(r_type, r_form, source_group)][:,rank_index,:], axis=1) * kwargs.get("scalar", 1.0) + kwargs.get("add_background", 0.0)
else:
if kwargs.get("exclude_flagpole_receptors", False):
if self.DEBUG: print("DEBUG: removing flagplot data")
concs = self.POSTdata[(r_type, r_form, source_group)][:,rank_index][self.receptors.Z==0] * kwargs.get("scalar", 1.0) + kwargs.get("add_background", 0.0)
else:
concs = self.POSTdata[(r_type, r_form, source_group)][:,rank_index] * kwargs.get("scalar", 1.0) + kwargs.get("add_background", 0.0)
# define grid.
x_range = receptors.X.max() - receptors.X.min()
y_range = receptors.Y.max() - receptors.Y.min()
xi = numpy.linspace(receptors.X.min(), receptors.X.max(), round(receptors.num**0.85))
yi = numpy.linspace(receptors.Y.min(), receptors.Y.max(), round(receptors.num**0.85))
distance_from_origin = kwargs.get("distance_from_origin", max(x_range/2, y_range/2))
if self.DEBUG: print("DEBUG: distance_from_origin -", distance_from_origin)
origin = point(1)
origin.X = (receptors.X.max() + receptors.X.min())/2
origin.Y = (receptors.Y.max() + receptors.Y.min())/2
# instantiate figure
figure = plt.figure(num=None
,figsize=(6.5, 6) if kwargs.get("nocolorbar", False) else (8, 6)
,dpi=80
,facecolor="white"
,edgecolor="black"
)
ax = figure.add_subplot(111
,aspect="equal"
)
# grid the data.
if self.DEBUG: print("DEBUG: receptors.X:", type(receptors.X), receptors.X)
if self.DEBUG: print("DEBUG: receptors.X:", type(receptors.Y), receptors.Y)
zi = griddata(receptors.X - origin.X,
receptors.Y - origin.Y,
concs,
0, 0,
interp = kwargs.get("interpolation_method", "linear"))
if self.DEBUG: print("DEBUG:", zi)
# define contour levels and colors
if kwargs.get("colorslevels", None):
levels = [level for level, color, label in kwargs["colorslevels"]]
kwargs["levels"] = levels
kwargs["contour_colors"] = [color for level, color, label in kwargs["colorslevels"]]
# draw the contours using contour(X,Y,Z,V) formulation (see documentation)
CS = plt.contour(xi - origin.X, # X
yi - origin.Y, # Y
zi, # Z
levels, # V
linewidths=float(kwargs.get("contours", 0)),
colors="black")
# fill the contours
if kwargs.get("contour_colors", None):
cmap, norm = matplotlib.colors.from_levels_and_colors(levels=levels
,colors=kwargs.get("contour_colors", ["white" for level in levels])[:-1]
,extend="neither"
)
else:
cmap = plt.cm.hot_r
norm = matplotlib.colors.Normalize(vmin=0, vmax=1)
CS = plt.contourf(xi - origin.X
,yi - origin.Y
,zi
,levels
,cmap=cmap
,norm=norm
)
# prepare the colorbar
if not kwargs.get("nocolorbar", False):
matplotlib.rcParams['xtick.direction'] = 'out'
matplotlib.rcParams['ytick.direction'] = 'out'
if kwargs.get("colorslevels", False):
if self.DEBUG: print("DEBUG: setting colorbar labels")
labels = [label for level, color, label in kwargs.get("colorslevels", False)]
else:
labels = ["" for level in levels]
colorbar = figure.colorbar(CS
,ax=ax
,format=kwargs.get("scale_decimals", "%0.1f")
,spacing=kwargs.get("colorbar_spacing", "proportional")
,shrink=1.0 # same size as map
)
display_units = pollutant_dict[kwargs["pollutant"]][1]
colorbar.set_label("Concentration (%s)" %display_units
,size=kwargs.get("max_textsize", 10)
)
colorbar.set_ticks(levels)
colorbar.set_ticklabels(labels)
colorbar.ax.tick_params(labelsize=kwargs.get("labelsize", 10)
,colors="black"
,axis="both"
,direction="out"
)
if kwargs.get("tickinterval", None):
tickinterval = kwargs.get("tickinterval", 100)
# build ticks
aticks = ["0m"]
ticks = [0]
j = tickinterval
while j <= distance_from_origin:
aticks = [-j] + aticks + [j]
ticks = [-j] + ticks + [j]
j += tickinterval
ticks = numpy.array(ticks)
CS.ax.set_xticks(ticks)
CS.ax.set_yticks(ticks)
CS.ax.set_xticklabels(aticks, rotation=90)
CS.ax.set_yticklabels(aticks)
else:
if self.DEBUG: print("DEBUG: ticklabels set")
ax.ticklabel_format(axis="both"
,style="plain"
,useOffset=0
)
# set tick interval
ax.set_xlim(-distance_from_origin, distance_from_origin)
ax.set_ylim(-distance_from_origin, distance_from_origin)
# format tick marks
ax.tick_params(axis="both"
,direction="out"
,length=0 if kwargs.get("noticks", False) else 4 # default tick length is 4. Can be omitted if requested using noticks option
,color="grey"
,width=1
,pad=kwargs.get("labelgap",4)
,labelsize=kwargs.get("labelsize", 10)
)
# plot data points.
if kwargs.get("receptor_size", 12):
scat = ax.scatter(receptors.X - origin.X
,receptors.Y - origin.Y
,marker=kwargs.get("receptor_type", "o")
,c=(1,1,1,0) # in place of marker_style which I can't get to work
,s=kwargs.get("receptor_size", 12)
,zorder=10
)
if kwargs.get("max_plot", True):
max_point = point(1
,Xs=numpy.array([receptors.X[concs.argmax()] - origin.X])
,Ys=numpy.array([receptors.Y[concs.argmax()] - origin.Y])
)
if self.DEBUG:
print("DEBUG: max plot:")
print(" X =", max_point.X[0])
print(" Y =", max_point.Y[0])
print(" c =", concs.max())
ax.annotate('+ Maximum Concentration: '+ kwargs.get("scale_decimals","%0.0f") % concs.max()
,(0.5, 0)
,(0, -40 + (kwargs.get("max_textsize", 10)))
,xycoords='axes fraction'
,ha="center"
,va="top"
,textcoords='offset points'
,size=kwargs.get("max_textsize", 10)
)
ax.scatter(max_point.X
,max_point.Y
,marker="+"
,c=(0,0,0) # in place of marker_style which I can't get to work
,s=kwargs.get("max_plot", 50)
,zorder=10
)
if kwargs.get("add_background", False):
ax.annotate('Includes background\nconcentration: '+ kwargs.get("scale_decimals","%0.0f") % kwargs.get("add_background", 0.0)
,(1.05, 0)
,(0, -32 + (kwargs.get("max_textsize", 10)))
,xycoords='axes fraction'
,ha="left"
,va="top"
,textcoords='offset points'
,size=kwargs.get("max_textsize", 10)
)
if kwargs.get("transparent_buildings", False):
if self.DEBUG: print("DEBUG: transparent buildings")
building_color = "#FFFFFF00"
else:
building_color = "white"
if kwargs.get("buildings", False):
for name, story in sorted(self.building_vertices.keys()):
self.draw_building(name, story, ax, origin=origin
,color=kwargs.get("building_color", building_color)
,linewidth=kwargs.get("building_linewidth", 0.4)
,building_name=kwargs.get("building_name", False)
)
if kwargs.get("sources", False):
for name, source in self.sources.items():
if self.DEBUG:
print("DEBUG: source:", name, source.X, source.Y)
ax.scatter(source.X - origin.X
,source.Y - origin.Y
,marker="o"
,c=(0,0,0)
,s=kwargs.get("sources", 10)
,zorder=10
)
if self.DEBUG: print("DEBUG: sources successfully plotted")
ax.set_title(pollutant_dict[kwargs.get("pollutant", "PM2.5")][0] + " " + \
("" if r_form is "CONCURRENT" else r_type )+ "\n" + \
("%s HIGHEST " %(ordinal(rank)) if rank else "") + \
("HOURLY" if (r_form == "CONCURRENT") else r_form)
,size=kwargs.get("title_size", 10)
,loc="left"
,ha="left"
,position=(0.05,1.012)
)
ax.set_title("SOURCE(S): \n"+source_group
,size=kwargs.get("title_size", 10)
,loc="right"
,ha="left"
,position=(0.75,1.012)
)
plt.savefig(kwargs.get("filename", "aermod.png"))
plt.close("all")
| gpl-2.0 |
eareyan/tradedirectionprediction | src/financialpredictor/Exception/FinancialPredictorException.java | 291 | /*
* Generic exception for the finanacialpredictor library
*/
package financialpredictor.Exception;
/**
*
* @author enriqueareyan
*/
public class FinancialPredictorException extends Exception{
public FinancialPredictorException(String string) {
super(string);
}
}
| gpl-2.0 |
fbarthelery/RoomConnect | mobile/src/main/java/com/genymobile/roomconnect/roomengine/ChannelJoinListener.java | 160 | package com.genymobile.roomconnect.roomengine;
public interface ChannelJoinListener {
void onChannelJoinSuccessfull();
void onChannelJoinError();
}
| gpl-2.0 |
hiikezoe/tpkbdctl | tpkbdctl/__init__.py | 8411 | # -*- coding: utf-8 -*-
# vim:set sw=4 ts=4 et:
from os import listdir, sep, access, W_OK
from os.path import isdir, isfile, islink, realpath, normpath, basename
from os.path import join as join_path
from struct import pack
from fcntl import ioctl
import re
class HidrawDevice(object):
can_get = False
def __init__(self, hidraw_dev):
#if not access(hidraw_dev, W_OK):
# raise RuntimeError('No write access. Maybe run as root?')
self.hidraw_dev = hidraw_dev
self._sensitivity = 180
self._press_speed = 180
self._press_to_select = False
self._press_right = False
self._dragging = False
self._release_to_select = False
def __repr__(self):
return '<HidrawDevice "%s">' % self.hidraw_dev
def __str__(self):
return 'hidraw:%s (write-only)' % self.hidraw_dev
def _write_settings(self):
props = 0
props |= 0x01 if self._press_to_select else 0x02
props |= 0x04 if self._dragging else 0x08
props |= 0x10 if self._release_to_select else 0x20
props |= 0x80 if self._press_right else 0x40
with open(self.hidraw_dev, 'w') as fd:
ioctl(fd, 0xc0054806, pack('BBBBB', 4, props, 3, self._sensitivity, self._press_speed))
def get_attr(self):
raise RuntimeError('Cannot get, only set')
def set_sensitivity(self, value):
self._sensitivity = value
self._write_settings()
def set_press_speed(self, value):
self._press_speed = value
self._write_settings()
def set_press_to_select(self, value):
self._press_to_select = value
self._write_settings()
def set_press_right(self, value):
self._press_right = value
self._write_settings()
def set_dragging(self, value):
self._dragging = value
self._write_settings()
def set_release_to_select(self, value):
self._release_to_select = value
self._write_settings()
sensitivity = property(get_attr, set_sensitivity)
press_speed = property(get_attr, set_press_speed)
press_to_select = property(get_attr, set_press_to_select)
press_right = property(get_attr, set_press_right)
dragging = property(get_attr, set_dragging)
release_to_select = property(get_attr, set_release_to_select)
class HidrawDeviceForCompact(object):
can_get = False
def __init__(self, hidraw_dev, device_id):
#if not access(hidraw_dev, W_OK):
# raise RuntimeError('No write access. Maybe run as root?')
self.hidraw_dev = hidraw_dev
self._device_id = device_id
def __repr__(self):
return '<HidrawDeviceForCompact "%s">' % self.hidraw_dev
def __str__(self):
return 'hidraw:%s (write-only)' % self.hidraw_dev
def _write_settings(self, command, value):
magic_number = 0x13 if self._device_id == 0x6047 else 0x18
data = pack('BBB', magic_number, command, value)
with open(self.hidraw_dev, 'w') as fd:
ioctl(fd, 0xc0034806, data) # HIDIOCSFEATURE(3)
def get_attr(self):
raise RuntimeError('Cannot get, only set')
def set_sensitivity(self, value):
sensitivity = int(value / 31) + 1
self._write_settings(0x02, sensitivity)
def set_fn_lock(self, value):
fn_lock = 0x00 if value else 0x01
self._write_settings(0x05, fn_lock)
def set_native_fn(self, value):
native_fn = 0x03 if value else 0x00
self._write_settings(0x01, native_fn)
def set_hardware_wheel_emulation(self, value):
hardware_wheel_emulation = 0x00 if value else 0x01
self._write_settings(0x09, hardware_wheel_emulation)
sensitivity = property(get_attr, set_sensitivity)
fn_lock = property(get_attr, set_fn_lock)
native_fn = property(get_attr, set_native_fn)
hardware_wheel_emulation = property(get_attr, set_hardware_wheel_emulation)
class TpkbdDevice(object):
can_get = True
def __init__(self, hid_path):
#if not access(hid_path, W_OK):
# raise RuntimeError('No write access. Maybe run as root?')
self.hid_path = hid_path
def __repr__(self):
return '<TpkbdDevice "%s">' % basename(self.hid_path)
def __str__(self):
[a,b,c,d] = re.split(':|\.', basename(self.hid_path))
return 'tpkbd:%x:%x' % (int(a, 16), int(d, 16))
def get_sensitivity(self):
return int(open(join_path(self.hid_path, 'sensitivity')).readline())
def set_sensitivity(self, value):
with open(join_path(self.hid_path, 'sensitivity'), 'w') as fd:
fd.write(str(value))
def get_press_speed(self):
return int(open(join_path(self.hid_path, 'press_speed')).readline())
def set_press_speed(self, value):
with open(join_path(self.hid_path, 'press_speed'), 'w') as fd:
fd.write(str(value))
def get_press_to_select(self):
return int(open(join_path(self.hid_path, 'press_to_select')).readline()) == 1
def set_press_to_select(self, value):
with open(join_path(self.hid_path, 'press_to_select'), 'w') as fd:
fd.write('1' if value else '0')
def get_press_right(self):
return int(open(join_path(self.hid_path, 'press_right')).readline()) == 1
def set_press_right(self, value):
with open(join_path(self.hid_path, 'press_right'), 'w') as fd:
fd.write('1' if value else '0')
def get_dragging(self):
return int(open(join_path(self.hid_path, 'dragging')).readline()) == 1
def set_dragging(self, value):
with open(join_path(self.hid_path, 'dragging'), 'w') as fd:
fd.write('1' if value else '0')
def get_release_to_select(self):
return int(open(join_path(self.hid_path, 'release_to_select')).readline()) == 1
def set_release_to_select(self, value):
with open(join_path(self.hid_path, 'release_to_select'), 'w') as fd:
fd.write('1' if value else '0')
sensitivity = property(get_sensitivity, set_sensitivity)
press_speed = property(get_press_speed, set_press_speed)
press_to_select = property(get_press_to_select, set_press_to_select)
press_right = property(get_press_right, set_press_right)
dragging = property(get_dragging, set_dragging)
release_to_select = property(get_release_to_select, set_release_to_select)
class TpkbdCtl(object):
__hid_path__ = '/sys/bus/hid/devices'
__dev_path__ = '/dev'
def __init__(self):
self._check_prereqs()
self.devices = []
def _check_prereqs(self):
pass
def find_devices(self):
self.devices = []
devs = listdir(self.__hid_path__)
for dev in devs:
self.probe_device(dev)
def _check_interface(self, dev):
while not isfile(join_path(dev, 'bInterfaceClass')):
if dev == '/sys/devices' or len(dev) < 2:
raise RuntimeError('USB device info not found in sysfs')
dev = realpath(join_path(dev, '..'))
intclass = open(join_path(dev, 'bInterfaceClass')).readline()
if not re.match(r'^03\s*$', intclass):
return False
intnum = open(join_path(dev, 'bInterfaceNumber')).readline()
if not re.match(r'^01\s*$', intnum):
return False
return True
def probe_device(self, dev):
m = re.match(r'^....:17EF:(6009|6047|6048)\.....$', dev)
if not m:
return False
hid_path = realpath(join_path(self.__hid_path__, dev))
hidraw_path = join_path(hid_path, 'hidraw')
if not isdir(hidraw_path):
return False
hidraw_name = listdir(hidraw_path)[0]
if not isdir(join_path(hidraw_path, hidraw_name)):
return False
if not self._check_interface(hid_path):
return False
if isfile(join_path(hid_path, 'sensitivity')):
self.devices.append(TpkbdDevice(hid_path))
else:
hidraw_dev = join_path(self.__dev_path__, hidraw_name)
device_id = int(m.group(1), 16)
if device_id == 0x6009:
device = HidrawDevice(hidraw_dev)
else:
device = HidrawDeviceForCompact(hidraw_dev, device_id)
self.devices.append(device)
return True
def __repr__(self):
return '<Tpkbdctl>'
| gpl-2.0 |
itkinside/ari | ari/fx/spiral.py | 1882 | #! /usr/bin/env python
#
# Copyright (C) 2006 Vidar Wahlberg
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2
# as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#
# Authors: Vidar Wahlberg <canidae@samfundet.no>
#
import ari.fx.base
import math
class Spiral(ari.fx.base.Base):
"""A spiral!"""
def findxy(self, n):
if n == 0:
self.x = 0
self.y = 0
return
d = (math.sqrt(n) + 1.0) / 2.0
m = int(d) * 2
c = n - (m - 1) * (m - 1)
if c < m:
self.x = int(d)
self.y = 1 - int(d) + c % m
elif c < 2 * m:
self.x = int(d) - 1 - c % m
self.y = int(d)
elif c < 3 * m:
self.x = int(-d)
self.y = int(d) - 1 - c % m
elif c < 4 * m:
self.x = 1 - int(d) + c % m
self.y = int(-d)
def run(self):
# The demo
while self.runnable:
if self.drawable:
for n in xrange(500):
self.findxy(n)
self.image[self.x + 25][self.y + 15] = n % 80 + 20
self.findxy((n + 450) % 500)
self.image[self.x + 25][self.y + 15] = 0
self.canvas.update(self.image)
self.canvas.flush()
# self.sleep()
| gpl-2.0 |
allmyservos/allmyservos | contrib/AllMyServos/TrayIcon/TrayIcon.py | 4996 | #!/usr/bin/python
#######################################################################
# AllMyServos - Fun with PWM
# Copyright (C) 2015 Donate BTC:14rVTppdYQzLrqay5fp2FwP3AXvn3VSZxQ
#
# 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/.
#######################################################################
import os, gtk, Scheduler
from __bootstrap import AmsEnvironment
## System tray icon with context menus
class TrayIcon:
def __init__(self, scheduler = None):
""" Initializes the TrayIcon object
"""
if (scheduler != None):
self.scheduler = scheduler
else:
self.scheduler = Scheduler.Scheduler.GetInstance()
self.enabled = True
try:
icon = gtk.StatusIcon()
except:
self.enabled = False
else:
self.widgets = {
'tray': icon
}
self.initLeftMenu()
self.initRightMenu()
self.widgets['tray'].set_visible(True)
self.widgets['tray'].set_tooltip_text('AllMyServos')
self.widgets['tray'].set_from_file(os.path.join(AmsEnvironment.AppPath(), 'images', 'tray-icon', 'tray-icon.png'))
self.scheduler.addTask('tray_update', self.update, 0.01, False)
def initLeftMenu(self):
""" setup left click menu
"""
self.widgets['left'] = gtk.Window()
self.widgets['left'].set_decorated(False)
self.widgets['left'].set_gravity(gtk.gdk.GRAVITY_NORTH_EAST)
self.widgets['info'] = self.displayAppInfo()
self.widgets['left'].add(self.widgets['info'])
self.widgets['left'].connect('focus-out-event', self.hideLeftMenu)
self.widgets['tray'].connect('activate', self.showLeftMenu)
def initRightMenu(self):
""" setup right click menu
"""
self.widgets['right'] = gtk.Menu()
i = gtk.MenuItem("About...")
i.show()
i.connect("activate", self.showAbout)
self.widgets['right'].append(i)
i = gtk.MenuItem("Exit")
i.show()
i.connect("activate", self.exit)
self.widgets['right'].append(i)
self.widgets['tray'].connect('popup-menu', self.showRightMenu, self.widgets['right'])
def update(self):
""" perform gtk iteration
"""
if (gtk.events_pending()):
gtk.main_iteration_do(False)
def exit(self, widget):
""" run exit callback
"""
if (hasattr(self, 'exitCallback')):
self.exitCallback()
def setExitCallback(self, cb):
""" set the exit callback
"""
self.exitCallback = cb
def showLeftMenu(self, widget):
""" show left menu
"""
if (not self.widgets['left'].get_visible()):
trayPos = self.widgets['tray'].get_geometry()[1]
self.widgets['left'].move(trayPos[0],trayPos[1])
self.widgets['left'].set_skip_taskbar_hint(True)
self.widgets['left'].set_visible(True)
self.widgets['left'].present()
else:
self.widgets['left'].set_visible(False)
def hideLeftMenu(self, widget, event):
""" hide left menu
"""
if (self.widgets['left'].get_visible()):
self.widgets['left'].set_visible(False)
def showRightMenu(self, widget, event_button, event_time, menu):
""" show right menu
auto hides due to popup behaviour
"""
self.widgets['right'].popup(None, None,
gtk.status_icon_position_menu,
event_button,
event_time,
self.widgets['tray']
)
def showAbout(self, widget):
""" show about info
"""
dialog = gtk.MessageDialog(
None,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
gtk.MESSAGE_INFO,
gtk.BUTTONS_OK,
'''
All My Servos - Fun with PWM
Visit:
http://allmyservos.co.uk
''')
dialog.run()
dialog.destroy()
def displayAppInfo(self):
""" display app information
@return gtk.VBox
"""
vbox = gtk.VBox(spacing=3)
vbox.set_visible(True)
info = AmsEnvironment.AppInfo()
if (any(info)):
for k,v in info.items():
if (isinstance(v, str)):
p = self.displayPair(k, v)
vbox.pack_start(p, True, True, 1)
elif (isinstance(v, list)):
p = self.displayPair(k, ''.join(v))
vbox.pack_start(p, True, True, 1)
else:
l = gtk.Label()
l.set_text('App Info Unavailable')
l.set_visible(True)
vbox.pack_start(l, True, True, 6)
return vbox
def displayPair(self, label, value):
""" display label and value
@return gtk.HBox
"""
h = gtk.HBox(spacing=3)
h.set_visible(True)
l = gtk.Label()
l.set_markup('<b>{}</b>'.format(str(label)))
l.set_alignment(xalign=0, yalign=0.5)
l.set_visible(True)
h.pack_start(l, False, False, 3)
l = gtk.Label()
l.set_text(value)
l.set_alignment(xalign=0, yalign=0.5)
l.set_visible(True)
h.pack_start(l, False, False, 3)
return h | gpl-2.0 |
TheTypoMaster/calligra | libs/textlayout/KoTextLayoutNoteArea.cpp | 7036 | /* This file is part of the KDE project
* Copyright (C) 2011 Brijesh Patel <brijesh3105@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "KoTextLayoutNoteArea.h"
#include "FrameIterator.h"
#include "KoStyleManager.h"
#include "KoParagraphStyle.h"
#include "KoTextLayoutObstruction.h"
#include "KoPointedAt.h"
#include <KoOdfNumberDefinition.h>
#include <KoInlineNote.h>
#include <KoTextDocument.h>
#include <QPainter>
#define OVERLAPPREVENTION 1000
class Q_DECL_HIDDEN KoTextLayoutNoteArea::Private
{
public:
Private()
{
}
KoInlineNote *note;
QTextLayout *textLayout;
QTextLayout *postLayout;
qreal labelIndent;
bool isContinuedArea;
qreal labelWidth;
qreal labelHeight;
qreal labelYOffset;
};
KoTextLayoutNoteArea::KoTextLayoutNoteArea(KoInlineNote *note, KoTextLayoutArea *parent, KoTextDocumentLayout *documentLayout)
: KoTextLayoutArea(parent, documentLayout)
, d(new Private)
{
Q_ASSERT(note);
Q_ASSERT(parent);
d->note = note;
d->isContinuedArea = false;
d->postLayout = 0;
}
KoTextLayoutNoteArea::~KoTextLayoutNoteArea()
{
delete d;
}
void KoTextLayoutNoteArea::paint(QPainter *painter, const KoTextDocumentLayout::PaintContext &context)
{
painter->save();
if (d->isContinuedArea) {
painter->translate(0, -OVERLAPPREVENTION);
}
KoTextLayoutArea::paint(painter, context);
if (d->postLayout) {
d->postLayout->draw(painter, QPointF(left() + d->labelIndent, top() + d->labelYOffset));
}
d->textLayout->draw(painter, QPointF(left() + d->labelIndent, top() + d->labelYOffset));
painter->restore();
}
bool KoTextLayoutNoteArea::layout(FrameIterator *cursor)
{
KoOdfNotesConfiguration *notesConfig = 0;
if (d->note->type() == KoInlineNote::Footnote) {
notesConfig = KoTextDocument(d->note->textFrame()->document()).styleManager()->notesConfiguration(KoOdfNotesConfiguration::Footnote);
} else if (d->note->type() == KoInlineNote::Endnote) {
notesConfig = KoTextDocument(d->note->textFrame()->document()).styleManager()->notesConfiguration(KoOdfNotesConfiguration::Endnote);
}
QString label;
if (d->isContinuedArea) {
if (! notesConfig->footnoteContinuationBackward().isEmpty()) {
label = notesConfig->footnoteContinuationBackward() + " " + d->note->label();
}
setReferenceRect(left(), right(), top() + OVERLAPPREVENTION
, maximumAllowedBottom() + OVERLAPPREVENTION);
} else {
label = d->note->label();
}
label.prepend(notesConfig->numberFormat().prefix());
label.append(notesConfig->numberFormat().suffix());
QPaintDevice *pd = documentLayout()->paintDevice();
QTextBlock block = cursor->it.currentBlock();
QTextCharFormat format = block.charFormat();
KoCharacterStyle *style = static_cast<KoCharacterStyle *>(notesConfig->citationTextStyle());
if (style) {
style->applyStyle(format);
}
QFont font(format.font(), pd);
d->textLayout = new QTextLayout(label, font, pd);
QList<QTextLayout::FormatRange> layouts;
QTextLayout::FormatRange range;
range.start = 0;
range.length = label.length();
range.format = format;
layouts.append(range);
d->textLayout->setAdditionalFormats(layouts);
QTextOption option(Qt::AlignLeft | Qt::AlignAbsolute);
d->textLayout->setTextOption(option);
d->textLayout->beginLayout();
QTextLine line = d->textLayout->createLine();
d->textLayout->endLayout();
KoParagraphStyle pStyle(block.blockFormat(), QTextCharFormat());
d->labelIndent = textIndent(d->note->textFrame()->begin().currentBlock(), 0, pStyle);
if (line.naturalTextWidth() > -d->labelIndent) {
KoTextLayoutArea::setExtraTextIndent(line.naturalTextWidth());
} else {
KoTextLayoutArea::setExtraTextIndent(-d->labelIndent);
}
d->labelIndent += pStyle.leftMargin();
d->labelWidth = line.naturalTextWidth();
d->labelHeight = line.naturalTextRect().bottom() - line.naturalTextRect().top();
d->labelYOffset = -line.ascent();
bool contNotNeeded = KoTextLayoutArea::layout(cursor);
d->labelYOffset += block.layout()->lineAt(0).ascent();
if (!contNotNeeded) {
QString contNote = notesConfig->footnoteContinuationForward();
font.setBold(true);
d->postLayout = new QTextLayout(contNote, font, pd);
QList<QTextLayout::FormatRange> contTextLayouts;
QTextLayout::FormatRange contTextRange;
contTextRange.start = 0;
contTextRange.length = contNote.length();
contTextRange.format = block.charFormat();;
contTextLayouts.append(contTextRange);
d->postLayout->setAdditionalFormats(contTextLayouts);
QTextOption contTextOption(Qt::AlignLeft | Qt::AlignAbsolute);
//option.setTextDirection();
d->postLayout->setTextOption(contTextOption);
d->postLayout->beginLayout();
QTextLine contTextLine = d->postLayout->createLine();
d->postLayout->endLayout();
contTextLine.setPosition(QPointF(right() - contTextLine.naturalTextWidth(), bottom() - contTextLine.height()));
documentLayout()->setContinuationObstruction(new
KoTextLayoutObstruction(contTextLine.naturalTextRect(), false));
}
return contNotNeeded;
}
void KoTextLayoutNoteArea::setAsContinuedArea(bool isContinuedArea)
{
d->isContinuedArea = isContinuedArea;
}
KoPointedAt KoTextLayoutNoteArea::hitTest(const QPointF &p, Qt::HitTestAccuracy accuracy) const
{
KoPointedAt pointedAt;
pointedAt.noteReference = -1;
QPointF tmpP(p.x(), p.y() + (d->isContinuedArea ? OVERLAPPREVENTION : 0));
pointedAt = KoTextLayoutArea::hitTest(tmpP, accuracy);
if (tmpP.x() > left() && tmpP.x() < d->labelWidth && tmpP.y() < top() + d->labelYOffset + d->labelHeight)
{
pointedAt.noteReference = d->note->getPosInDocument();
pointedAt.position = tmpP.x();
}
return pointedAt;
}
QRectF KoTextLayoutNoteArea::selectionBoundingBox(QTextCursor &cursor) const
{
return KoTextLayoutArea::selectionBoundingBox(cursor).translated(0
, d->isContinuedArea ? -OVERLAPPREVENTION : 0);
}
| gpl-2.0 |
scs/uclinux | lib/boost/boost_1_38_0/libs/wave/samples/token_statistics/token_statistics.cpp | 9181 | /*=============================================================================
Boost.Wave: A Standard compliant C++ preprocessor library
http://www.boost.org/
Copyright (c) 2001-2009 Hartmut Kaiser. Distributed under the Boost
Software License, Version 1.0. (See accompanying file
LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#include "token_statistics.hpp" // config data
///////////////////////////////////////////////////////////////////////////////
// include required boost libraries
#include <boost/assert.hpp>
#include <boost/program_options.hpp>
///////////////////////////////////////////////////////////////////////////////
// Include Wave itself
#include <boost/wave.hpp>
///////////////////////////////////////////////////////////////////////////////
// Include the lexer stuff
#include <boost/wave/cpplexer/cpp_lex_token.hpp> // token class
#include "xlex_iterator.hpp" // lexer class
#include "collect_token_statistics.hpp"
///////////////////////////////////////////////////////////////////////////////
// import required names
using namespace boost::spirit::classic;
using std::string;
using std::vector;
using std::cout;
using std::cerr;
using std::endl;
using std::ifstream;
using std::ostream;
using std::istreambuf_iterator;
namespace po = boost::program_options;
///////////////////////////////////////////////////////////////////////////////
namespace cmd_line_util {
// predicate to extract all positional arguments from the command line
struct is_argument {
bool operator()(po::option const &opt)
{
return (opt.position_key == -1) ? true : false;
}
};
///////////////////////////////////////////////////////////////////////////////
}
///////////////////////////////////////////////////////////////////////////////
// print the current version
int print_version()
{
// get time of last compilation of this file
boost::wave::util::time_conversion_helper compilation_time(__DATE__ " " __TIME__);
// calculate the number of days since May 9 2005
// (the day the token_statistics project was started)
std::tm first_day;
std::memset (&first_day, 0, sizeof(std::tm));
first_day.tm_mon = 4; // May
first_day.tm_mday = 9; // 09
first_day.tm_year = 105; // 2005
long seconds = long(std::difftime(compilation_time.get_time(),
std::mktime(&first_day)));
cout
<< TOKEN_STATISTICS_VERSION_MAJOR << '.'
<< TOKEN_STATISTICS_VERSION_MINOR << '.'
<< TOKEN_STATISTICS_VERSION_SUBMINOR << '.'
<< seconds/(3600*24); // get number of days from seconds
return 1; // exit app
}
///////////////////////////////////////////////////////////////////////////////
//
int
do_actual_work(vector<string> const &arguments, po::variables_map const &vm)
{
// current file position is saved for exception handling
boost::wave::util::file_position_type current_position;
try {
// this object keeps track of all the statistics
collect_token_statistics stats;
// collect the token statistics for all arguments given
vector<string>::const_iterator lastfile = arguments.end();
for (vector<string>::const_iterator file_it = arguments.begin();
file_it != lastfile; ++file_it)
{
ifstream instream((*file_it).c_str());
string instring;
if (!instream.is_open()) {
cerr << "token_statistics: could not open input file: "
<< *file_it << endl;
continue;
}
instream.unsetf(std::ios::skipws);
instring = string(istreambuf_iterator<char>(instream.rdbuf()),
istreambuf_iterator<char>());
// The template boost::wave::cpplexer::lex_token<> is the token type to be
// used by the Wave library.
typedef boost::wave::cpplexer::xlex::xlex_iterator<
boost::wave::cpplexer::lex_token<> >
lexer_type;
typedef boost::wave::context<
std::string::iterator, lexer_type
> context_type;
// The preprocessor iterator shouldn't be constructed directly. It is
// to be generated through a wave::context<> object. This wave:context<>
// object is additionally to be used to initialize and define different
// parameters of the actual preprocessing.
// The preprocessing of the input stream is done on the fly behind the
// scenes during iteration over the context_type::iterator_type stream.
context_type ctx (instring.begin(), instring.end(), (*file_it).c_str());
// add include directories to the include path
if (vm.count("include")) {
vector<string> const &paths =
vm["include"].as<vector<string> >();
vector<string>::const_iterator end = paths.end();
for (vector<string>::const_iterator cit = paths.begin();
cit != end; ++cit)
{
ctx.add_include_path((*cit).c_str());
}
}
// add system include directories to the include path
if (vm.count("sysinclude")) {
vector<string> const &syspaths =
vm["sysinclude"].as<vector<string> >();
vector<string>::const_iterator end = syspaths.end();
for (vector<string>::const_iterator cit = syspaths.begin();
cit != end; ++cit)
{
ctx.add_sysinclude_path((*cit).c_str());
}
}
// analyze the actual file
context_type::iterator_type first = ctx.begin();
context_type::iterator_type last = ctx.end();
while (first != last) {
current_position = (*first).get_position();
stats(*first);
++first;
}
}
// print out the collected statistics
stats.print();
}
catch (boost::wave::cpp_exception const& e) {
// some preprocessing error
cerr
<< e.file_name() << "(" << e.line_no() << "): "
<< e.description() << endl;
return 2;
}
catch (std::exception const& e) {
// use last recognized token to retrieve the error position
cerr
<< current_position.get_file()
<< "(" << current_position.get_line() << "): "
<< "exception caught: " << e.what()
<< endl;
return 3;
}
catch (...) {
// use last recognized token to retrieve the error position
cerr
<< current_position.get_file()
<< "(" << current_position.get_line() << "): "
<< "unexpected exception caught." << endl;
return 4;
}
return 0;
}
///////////////////////////////////////////////////////////////////////////////
// here we go!
int
main (int argc, char *argv[])
{
try {
// analyze the command line options and arguments
vector<string> syspathes;
po::options_description desc("Usage: token_statistics [options] file ...");
desc.add_options()
("help,h", "print out program usage (this message)")
("version,v", "print the version number")
("include,I", po::value<vector<string> >(),
"specify additional include directory")
("sysinclude,S", po::value<vector<string> >(),
"specify additional system include directory")
;
using namespace boost::program_options::command_line_style;
po::parsed_options opts = po::parse_command_line(argc, argv, desc, unix_style);
po::variables_map vm;
po::store(opts, vm);
po::notify(vm);
if (vm.count("help")) {
cout << desc << endl;
return 1;
}
if (vm.count("version")) {
return print_version();
}
// extract the arguments from the parsed command line
vector<po::option> arguments;
std::remove_copy_if(opts.options.begin(), opts.options.end(),
inserter(arguments, arguments.end()), cmd_line_util::is_argument());
// if there is no input file given, then exit
if (0 == arguments.size() || 0 == arguments[0].value.size()) {
cerr << "token_statistics: No input file given. "
<< "Use --help to get a hint." << endl;
return 5;
}
// iterate over all given input files
return do_actual_work(arguments[0].value , vm);
}
catch (std::exception const& e) {
cout << "token_statistics: exception caught: " << e.what() << endl;
return 6;
}
catch (...) {
cerr << "token_statistics: unexpected exception caught." << endl;
return 7;
}
}
| gpl-2.0 |
mambax7/257 | htdocs/modules/extcal/versions/extcal_2_33.php | 1827 | <?php
/**
* extcal module.
*
* You may not change or alter any portion of this comment or credits
* of supporting developers from this source code or any supporting source code
* which is considered copyrighted (c) material of the original comment or credit authors.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* @copyright XOOPS Project (https://xoops.org)
* @license http://www.fsf.org/copyleft/gpl.html GNU public license
*
* @since 2.2
*
* @author JJDai <http://xoops.kiolo.com>
**/
//----------------------------------------------------
class Extcal_2_33
{
//----------------------------------------------------
/**
* @param XoopsModule $module
* @param $options
*/
public function __construct(\XoopsModule $module, $options)
{
global $xoopsDB;
$this->alterTable_cat();
$this->alterTable_eventmember();
}
//----------------------------------------------------
public function alterTable_cat()
{
global $xoopsDB;
$tbl = $xoopsDB->prefix('extcal_cat');
$sql = <<<__sql__
ALTER TABLE `{$tbl}`
ADD `cat_weight` INT NOT NULL DEFAULT '0';
__sql__;
$xoopsDB->queryF($sql);
}
//----------------------------------------------------
public function alterTable_eventmember()
{
global $xoopsDB;
$tbl = $xoopsDB->prefix('eventmember');
$sql = <<<__sql__
ALTER TABLE `{$tbl}`
ADD `status` INT NOT NULL DEFAULT '0';
__sql__;
$xoopsDB->queryF($sql);
}
//-----------------------------------------------------------------
} // fin de la classe
| gpl-2.0 |
senven/blog | wp-content/themes/sonicbids/content.php | 3423 | <?php
/**
* The default template for displaying content
*
* @package WordPress
* @subpackage Sonicbids CMS
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<?php if ( is_sticky() ) : ?>
<hgroup>
<h2><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyeleven' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
<h3 class="entry-format"><?php _e( 'Featured', 'twentyeleven' ); ?></h3>
</hgroup>
<?php else : ?>
<br>
<h1><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyeleven' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h1>
<?php endif; ?>
<?php if ( 'post' == get_post_type() ) : ?>
<div class="entry-meta">
<?php //sonicbids_posted_on(); ?>
</div><!-- .entry-meta -->
<?php endif; ?>
<?php if ( comments_open() && ! post_password_required() ) : ?>
<div class="comments-link">
<?php //comments_popup_link( '<span class="leave-reply">' . __( 'Reply', 'twentyeleven' ) . '</span>', _x( '1', 'comments number', 'twentyeleven' ), _x( '%', 'comments number', 'twentyeleven' ) ); ?>
</div>
<?php endif; ?>
</header><!-- .entry-header -->
<?php if ( is_search() ) : // Only display Excerpts for Search ?>
<div class="entry-summary">
<?php the_excerpt(); ?>
</div><!-- .entry-summary -->
<?php else : ?>
<div class="entry-content">
<?php the_content( __( 'Continue reading <span class="meta-nav">→</span>', 'twentyeleven' ) ); ?>
<?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'twentyeleven' ) . '</span>', 'after' => '</div>' ) ); ?>
</div><!-- .entry-content -->
<?php endif; ?>
<footer class="entry-meta">
<?php $show_sep = false; ?>
<?php if ( 'post' == get_post_type() ) : // Hide category and tag text for pages on Search ?>
<?php
/* translators: used between list items, there is a space after the comma */
$categories_list = get_the_category_list( __( ', ', 'twentyeleven' ) );
if ( $categories_list ):
?>
<?php endif; // End if categories ?>
<?php
/* translators: used between list items, there is a space after the comma */
$tags_list = get_the_tag_list( '', __( ', ', 'twentyeleven' ) );
if ( $tags_list ):
if ( $show_sep ) : ?>
<span class="sep"> | </span>
<?php endif; // End if $show_sep ?>
<span class="tag-links">
<?php printf( __( '<span class="%1$s">Tagged</span> %2$s', 'twentyeleven' ), 'entry-utility-prep entry-utility-prep-tag-links', $tags_list );
$show_sep = true; ?>
</span>
<?php endif; // End if $tags_list ?>
<?php endif; // End if 'post' == get_post_type() ?>
<?php if ( comments_open() ) : ?>
<?php if ( $show_sep ) : ?>
<span class="sep"> | </span>
<?php endif; // End if $show_sep ?>
<span class="comments-link"><?php //comments_popup_link( '<span class="leave-reply">' . __( 'Leave a reply', 'twentyeleven' ) . '</span>', __( '<b>1</b> Reply', 'twentyeleven' ), __( '<b>%</b> Replies', 'twentyeleven' ) ); ?></span>
<?php endif; // End if comments_open() ?>
<?php edit_post_link( __( 'Edit', 'twentyeleven' ), '<span class="edit-link">', '</span>' ); ?>
</footer><!-- #entry-meta -->
</article><!-- #post-<?php the_ID(); ?> -->
| gpl-2.0 |
srisatish/openjdk | hotspot/src/cpu/sparc/vm/c1_LIRAssembler_sparc.cpp | 113323 | /*
* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
# include "incls/_precompiled.incl"
# include "incls/_c1_LIRAssembler_sparc.cpp.incl"
#define __ _masm->
//------------------------------------------------------------
bool LIR_Assembler::is_small_constant(LIR_Opr opr) {
if (opr->is_constant()) {
LIR_Const* constant = opr->as_constant_ptr();
switch (constant->type()) {
case T_INT: {
jint value = constant->as_jint();
return Assembler::is_simm13(value);
}
default:
return false;
}
}
return false;
}
bool LIR_Assembler::is_single_instruction(LIR_Op* op) {
switch (op->code()) {
case lir_null_check:
return true;
case lir_add:
case lir_ushr:
case lir_shr:
case lir_shl:
// integer shifts and adds are always one instruction
return op->result_opr()->is_single_cpu();
case lir_move: {
LIR_Op1* op1 = op->as_Op1();
LIR_Opr src = op1->in_opr();
LIR_Opr dst = op1->result_opr();
if (src == dst) {
NEEDS_CLEANUP;
// this works around a problem where moves with the same src and dst
// end up in the delay slot and then the assembler swallows the mov
// since it has no effect and then it complains because the delay slot
// is empty. returning false stops the optimizer from putting this in
// the delay slot
return false;
}
// don't put moves involving oops into the delay slot since the VerifyOops code
// will make it much larger than a single instruction.
if (VerifyOops) {
return false;
}
if (src->is_double_cpu() || dst->is_double_cpu() || op1->patch_code() != lir_patch_none ||
((src->is_double_fpu() || dst->is_double_fpu()) && op1->move_kind() != lir_move_normal)) {
return false;
}
if (dst->is_register()) {
if (src->is_address() && Assembler::is_simm13(src->as_address_ptr()->disp())) {
return !PatchALot;
} else if (src->is_single_stack()) {
return true;
}
}
if (src->is_register()) {
if (dst->is_address() && Assembler::is_simm13(dst->as_address_ptr()->disp())) {
return !PatchALot;
} else if (dst->is_single_stack()) {
return true;
}
}
if (dst->is_register() &&
((src->is_register() && src->is_single_word() && src->is_same_type(dst)) ||
(src->is_constant() && LIR_Assembler::is_small_constant(op->as_Op1()->in_opr())))) {
return true;
}
return false;
}
default:
return false;
}
ShouldNotReachHere();
}
LIR_Opr LIR_Assembler::receiverOpr() {
return FrameMap::O0_oop_opr;
}
LIR_Opr LIR_Assembler::incomingReceiverOpr() {
return FrameMap::I0_oop_opr;
}
LIR_Opr LIR_Assembler::osrBufferPointer() {
return FrameMap::I0_opr;
}
int LIR_Assembler::initial_frame_size_in_bytes() {
return in_bytes(frame_map()->framesize_in_bytes());
}
// inline cache check: the inline cached class is in G5_inline_cache_reg(G5);
// we fetch the class of the receiver (O0) and compare it with the cached class.
// If they do not match we jump to slow case.
int LIR_Assembler::check_icache() {
int offset = __ offset();
__ inline_cache_check(O0, G5_inline_cache_reg);
return offset;
}
void LIR_Assembler::osr_entry() {
// On-stack-replacement entry sequence (interpreter frame layout described in interpreter_sparc.cpp):
//
// 1. Create a new compiled activation.
// 2. Initialize local variables in the compiled activation. The expression stack must be empty
// at the osr_bci; it is not initialized.
// 3. Jump to the continuation address in compiled code to resume execution.
// OSR entry point
offsets()->set_value(CodeOffsets::OSR_Entry, code_offset());
BlockBegin* osr_entry = compilation()->hir()->osr_entry();
ValueStack* entry_state = osr_entry->end()->state();
int number_of_locks = entry_state->locks_size();
// Create a frame for the compiled activation.
__ build_frame(initial_frame_size_in_bytes());
// OSR buffer is
//
// locals[nlocals-1..0]
// monitors[number_of_locks-1..0]
//
// locals is a direct copy of the interpreter frame so in the osr buffer
// so first slot in the local array is the last local from the interpreter
// and last slot is local[0] (receiver) from the interpreter
//
// Similarly with locks. The first lock slot in the osr buffer is the nth lock
// from the interpreter frame, the nth lock slot in the osr buffer is 0th lock
// in the interpreter frame (the method lock if a sync method)
// Initialize monitors in the compiled activation.
// I0: pointer to osr buffer
//
// All other registers are dead at this point and the locals will be
// copied into place by code emitted in the IR.
Register OSR_buf = osrBufferPointer()->as_register();
{ assert(frame::interpreter_frame_monitor_size() == BasicObjectLock::size(), "adjust code below");
int monitor_offset = BytesPerWord * method()->max_locals() +
(2 * BytesPerWord) * (number_of_locks - 1);
// SharedRuntime::OSR_migration_begin() packs BasicObjectLocks in
// the OSR buffer using 2 word entries: first the lock and then
// the oop.
for (int i = 0; i < number_of_locks; i++) {
int slot_offset = monitor_offset - ((i * 2) * BytesPerWord);
#ifdef ASSERT
// verify the interpreter's monitor has a non-null object
{
Label L;
__ ld_ptr(OSR_buf, slot_offset + 1*BytesPerWord, O7);
__ cmp(G0, O7);
__ br(Assembler::notEqual, false, Assembler::pt, L);
__ delayed()->nop();
__ stop("locked object is NULL");
__ bind(L);
}
#endif // ASSERT
// Copy the lock field into the compiled activation.
__ ld_ptr(OSR_buf, slot_offset + 0, O7);
__ st_ptr(O7, frame_map()->address_for_monitor_lock(i));
__ ld_ptr(OSR_buf, slot_offset + 1*BytesPerWord, O7);
__ st_ptr(O7, frame_map()->address_for_monitor_object(i));
}
}
}
// Optimized Library calls
// This is the fast version of java.lang.String.compare; it has not
// OSR-entry and therefore, we generate a slow version for OSR's
void LIR_Assembler::emit_string_compare(LIR_Opr left, LIR_Opr right, LIR_Opr dst, CodeEmitInfo* info) {
Register str0 = left->as_register();
Register str1 = right->as_register();
Label Ldone;
Register result = dst->as_register();
{
// Get a pointer to the first character of string0 in tmp0 and get string0.count in str0
// Get a pointer to the first character of string1 in tmp1 and get string1.count in str1
// Also, get string0.count-string1.count in o7 and get the condition code set
// Note: some instructions have been hoisted for better instruction scheduling
Register tmp0 = L0;
Register tmp1 = L1;
Register tmp2 = L2;
int value_offset = java_lang_String:: value_offset_in_bytes(); // char array
int offset_offset = java_lang_String::offset_offset_in_bytes(); // first character position
int count_offset = java_lang_String:: count_offset_in_bytes();
__ ld_ptr(str0, value_offset, tmp0);
__ ld(str0, offset_offset, tmp2);
__ add(tmp0, arrayOopDesc::base_offset_in_bytes(T_CHAR), tmp0);
__ ld(str0, count_offset, str0);
__ sll(tmp2, exact_log2(sizeof(jchar)), tmp2);
// str1 may be null
add_debug_info_for_null_check_here(info);
__ ld_ptr(str1, value_offset, tmp1);
__ add(tmp0, tmp2, tmp0);
__ ld(str1, offset_offset, tmp2);
__ add(tmp1, arrayOopDesc::base_offset_in_bytes(T_CHAR), tmp1);
__ ld(str1, count_offset, str1);
__ sll(tmp2, exact_log2(sizeof(jchar)), tmp2);
__ subcc(str0, str1, O7);
__ add(tmp1, tmp2, tmp1);
}
{
// Compute the minimum of the string lengths, scale it and store it in limit
Register count0 = I0;
Register count1 = I1;
Register limit = L3;
Label Lskip;
__ sll(count0, exact_log2(sizeof(jchar)), limit); // string0 is shorter
__ br(Assembler::greater, true, Assembler::pt, Lskip);
__ delayed()->sll(count1, exact_log2(sizeof(jchar)), limit); // string1 is shorter
__ bind(Lskip);
// If either string is empty (or both of them) the result is the difference in lengths
__ cmp(limit, 0);
__ br(Assembler::equal, true, Assembler::pn, Ldone);
__ delayed()->mov(O7, result); // result is difference in lengths
}
{
// Neither string is empty
Label Lloop;
Register base0 = L0;
Register base1 = L1;
Register chr0 = I0;
Register chr1 = I1;
Register limit = L3;
// Shift base0 and base1 to the end of the arrays, negate limit
__ add(base0, limit, base0);
__ add(base1, limit, base1);
__ neg(limit); // limit = -min{string0.count, strin1.count}
__ lduh(base0, limit, chr0);
__ bind(Lloop);
__ lduh(base1, limit, chr1);
__ subcc(chr0, chr1, chr0);
__ br(Assembler::notZero, false, Assembler::pn, Ldone);
assert(chr0 == result, "result must be pre-placed");
__ delayed()->inccc(limit, sizeof(jchar));
__ br(Assembler::notZero, true, Assembler::pt, Lloop);
__ delayed()->lduh(base0, limit, chr0);
}
// If strings are equal up to min length, return the length difference.
__ mov(O7, result);
// Otherwise, return the difference between the first mismatched chars.
__ bind(Ldone);
}
// --------------------------------------------------------------------------------------------
void LIR_Assembler::monitorexit(LIR_Opr obj_opr, LIR_Opr lock_opr, Register hdr, int monitor_no) {
if (!GenerateSynchronizationCode) return;
Register obj_reg = obj_opr->as_register();
Register lock_reg = lock_opr->as_register();
Address mon_addr = frame_map()->address_for_monitor_lock(monitor_no);
Register reg = mon_addr.base();
int offset = mon_addr.disp();
// compute pointer to BasicLock
if (mon_addr.is_simm13()) {
__ add(reg, offset, lock_reg);
}
else {
__ set(offset, lock_reg);
__ add(reg, lock_reg, lock_reg);
}
// unlock object
MonitorAccessStub* slow_case = new MonitorExitStub(lock_opr, UseFastLocking, monitor_no);
// _slow_case_stubs->append(slow_case);
// temporary fix: must be created after exceptionhandler, therefore as call stub
_slow_case_stubs->append(slow_case);
if (UseFastLocking) {
// try inlined fast unlocking first, revert to slow locking if it fails
// note: lock_reg points to the displaced header since the displaced header offset is 0!
assert(BasicLock::displaced_header_offset_in_bytes() == 0, "lock_reg must point to the displaced header");
__ unlock_object(hdr, obj_reg, lock_reg, *slow_case->entry());
} else {
// always do slow unlocking
// note: the slow unlocking code could be inlined here, however if we use
// slow unlocking, speed doesn't matter anyway and this solution is
// simpler and requires less duplicated code - additionally, the
// slow unlocking code is the same in either case which simplifies
// debugging
__ br(Assembler::always, false, Assembler::pt, *slow_case->entry());
__ delayed()->nop();
}
// done
__ bind(*slow_case->continuation());
}
int LIR_Assembler::emit_exception_handler() {
// if the last instruction is a call (typically to do a throw which
// is coming at the end after block reordering) the return address
// must still point into the code area in order to avoid assertion
// failures when searching for the corresponding bci => add a nop
// (was bug 5/14/1999 - gri)
__ nop();
// generate code for exception handler
ciMethod* method = compilation()->method();
address handler_base = __ start_a_stub(exception_handler_size);
if (handler_base == NULL) {
// not enough space left for the handler
bailout("exception handler overflow");
return -1;
}
int offset = code_offset();
__ call(Runtime1::entry_for(Runtime1::handle_exception_id), relocInfo::runtime_call_type);
__ delayed()->nop();
debug_only(__ stop("should have gone to the caller");)
assert(code_offset() - offset <= exception_handler_size, "overflow");
__ end_a_stub();
return offset;
}
// Emit the code to remove the frame from the stack in the exception
// unwind path.
int LIR_Assembler::emit_unwind_handler() {
#ifndef PRODUCT
if (CommentedAssembly) {
_masm->block_comment("Unwind handler");
}
#endif
int offset = code_offset();
// Fetch the exception from TLS and clear out exception related thread state
__ ld_ptr(G2_thread, in_bytes(JavaThread::exception_oop_offset()), O0);
__ st_ptr(G0, G2_thread, in_bytes(JavaThread::exception_oop_offset()));
__ st_ptr(G0, G2_thread, in_bytes(JavaThread::exception_pc_offset()));
__ bind(_unwind_handler_entry);
__ verify_not_null_oop(O0);
if (method()->is_synchronized() || compilation()->env()->dtrace_method_probes()) {
__ mov(O0, I0); // Preserve the exception
}
// Preform needed unlocking
MonitorExitStub* stub = NULL;
if (method()->is_synchronized()) {
monitor_address(0, FrameMap::I1_opr);
stub = new MonitorExitStub(FrameMap::I1_opr, true, 0);
__ unlock_object(I3, I2, I1, *stub->entry());
__ bind(*stub->continuation());
}
if (compilation()->env()->dtrace_method_probes()) {
__ mov(G2_thread, O0);
jobject2reg(method()->constant_encoding(), O1);
__ call(CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit), relocInfo::runtime_call_type);
__ delayed()->nop();
}
if (method()->is_synchronized() || compilation()->env()->dtrace_method_probes()) {
__ mov(I0, O0); // Restore the exception
}
// dispatch to the unwind logic
__ call(Runtime1::entry_for(Runtime1::unwind_exception_id), relocInfo::runtime_call_type);
__ delayed()->nop();
// Emit the slow path assembly
if (stub != NULL) {
stub->emit_code(this);
}
return offset;
}
int LIR_Assembler::emit_deopt_handler() {
// if the last instruction is a call (typically to do a throw which
// is coming at the end after block reordering) the return address
// must still point into the code area in order to avoid assertion
// failures when searching for the corresponding bci => add a nop
// (was bug 5/14/1999 - gri)
__ nop();
// generate code for deopt handler
ciMethod* method = compilation()->method();
address handler_base = __ start_a_stub(deopt_handler_size);
if (handler_base == NULL) {
// not enough space left for the handler
bailout("deopt handler overflow");
return -1;
}
int offset = code_offset();
AddressLiteral deopt_blob(SharedRuntime::deopt_blob()->unpack());
__ JUMP(deopt_blob, G3_scratch, 0); // sethi;jmp
__ delayed()->nop();
assert(code_offset() - offset <= deopt_handler_size, "overflow");
debug_only(__ stop("should have gone to the caller");)
__ end_a_stub();
return offset;
}
void LIR_Assembler::jobject2reg(jobject o, Register reg) {
if (o == NULL) {
__ set(NULL_WORD, reg);
} else {
int oop_index = __ oop_recorder()->find_index(o);
RelocationHolder rspec = oop_Relocation::spec(oop_index);
__ set(NULL_WORD, reg, rspec); // Will be set when the nmethod is created
}
}
void LIR_Assembler::jobject2reg_with_patching(Register reg, CodeEmitInfo *info) {
// Allocate a new index in oop table to hold the oop once it's been patched
int oop_index = __ oop_recorder()->allocate_index((jobject)NULL);
PatchingStub* patch = new PatchingStub(_masm, PatchingStub::load_klass_id, oop_index);
AddressLiteral addrlit(NULL, oop_Relocation::spec(oop_index));
assert(addrlit.rspec().type() == relocInfo::oop_type, "must be an oop reloc");
// It may not seem necessary to use a sethi/add pair to load a NULL into dest, but the
// NULL will be dynamically patched later and the patched value may be large. We must
// therefore generate the sethi/add as a placeholders
__ patchable_set(addrlit, reg);
patching_epilog(patch, lir_patch_normal, reg, info);
}
void LIR_Assembler::emit_op3(LIR_Op3* op) {
Register Rdividend = op->in_opr1()->as_register();
Register Rdivisor = noreg;
Register Rscratch = op->in_opr3()->as_register();
Register Rresult = op->result_opr()->as_register();
int divisor = -1;
if (op->in_opr2()->is_register()) {
Rdivisor = op->in_opr2()->as_register();
} else {
divisor = op->in_opr2()->as_constant_ptr()->as_jint();
assert(Assembler::is_simm13(divisor), "can only handle simm13");
}
assert(Rdividend != Rscratch, "");
assert(Rdivisor != Rscratch, "");
assert(op->code() == lir_idiv || op->code() == lir_irem, "Must be irem or idiv");
if (Rdivisor == noreg && is_power_of_2(divisor)) {
// convert division by a power of two into some shifts and logical operations
if (op->code() == lir_idiv) {
if (divisor == 2) {
__ srl(Rdividend, 31, Rscratch);
} else {
__ sra(Rdividend, 31, Rscratch);
__ and3(Rscratch, divisor - 1, Rscratch);
}
__ add(Rdividend, Rscratch, Rscratch);
__ sra(Rscratch, log2_intptr(divisor), Rresult);
return;
} else {
if (divisor == 2) {
__ srl(Rdividend, 31, Rscratch);
} else {
__ sra(Rdividend, 31, Rscratch);
__ and3(Rscratch, divisor - 1,Rscratch);
}
__ add(Rdividend, Rscratch, Rscratch);
__ andn(Rscratch, divisor - 1,Rscratch);
__ sub(Rdividend, Rscratch, Rresult);
return;
}
}
__ sra(Rdividend, 31, Rscratch);
__ wry(Rscratch);
if (!VM_Version::v9_instructions_work()) {
// v9 doesn't require these nops
__ nop();
__ nop();
__ nop();
__ nop();
}
add_debug_info_for_div0_here(op->info());
if (Rdivisor != noreg) {
__ sdivcc(Rdividend, Rdivisor, (op->code() == lir_idiv ? Rresult : Rscratch));
} else {
assert(Assembler::is_simm13(divisor), "can only handle simm13");
__ sdivcc(Rdividend, divisor, (op->code() == lir_idiv ? Rresult : Rscratch));
}
Label skip;
__ br(Assembler::overflowSet, true, Assembler::pn, skip);
__ delayed()->Assembler::sethi(0x80000000, (op->code() == lir_idiv ? Rresult : Rscratch));
__ bind(skip);
if (op->code() == lir_irem) {
if (Rdivisor != noreg) {
__ smul(Rscratch, Rdivisor, Rscratch);
} else {
__ smul(Rscratch, divisor, Rscratch);
}
__ sub(Rdividend, Rscratch, Rresult);
}
}
void LIR_Assembler::emit_opBranch(LIR_OpBranch* op) {
#ifdef ASSERT
assert(op->block() == NULL || op->block()->label() == op->label(), "wrong label");
if (op->block() != NULL) _branch_target_blocks.append(op->block());
if (op->ublock() != NULL) _branch_target_blocks.append(op->ublock());
#endif
assert(op->info() == NULL, "shouldn't have CodeEmitInfo");
if (op->cond() == lir_cond_always) {
__ br(Assembler::always, false, Assembler::pt, *(op->label()));
} else if (op->code() == lir_cond_float_branch) {
assert(op->ublock() != NULL, "must have unordered successor");
bool is_unordered = (op->ublock() == op->block());
Assembler::Condition acond;
switch (op->cond()) {
case lir_cond_equal: acond = Assembler::f_equal; break;
case lir_cond_notEqual: acond = Assembler::f_notEqual; break;
case lir_cond_less: acond = (is_unordered ? Assembler::f_unorderedOrLess : Assembler::f_less); break;
case lir_cond_greater: acond = (is_unordered ? Assembler::f_unorderedOrGreater : Assembler::f_greater); break;
case lir_cond_lessEqual: acond = (is_unordered ? Assembler::f_unorderedOrLessOrEqual : Assembler::f_lessOrEqual); break;
case lir_cond_greaterEqual: acond = (is_unordered ? Assembler::f_unorderedOrGreaterOrEqual: Assembler::f_greaterOrEqual); break;
default : ShouldNotReachHere();
};
if (!VM_Version::v9_instructions_work()) {
__ nop();
}
__ fb( acond, false, Assembler::pn, *(op->label()));
} else {
assert (op->code() == lir_branch, "just checking");
Assembler::Condition acond;
switch (op->cond()) {
case lir_cond_equal: acond = Assembler::equal; break;
case lir_cond_notEqual: acond = Assembler::notEqual; break;
case lir_cond_less: acond = Assembler::less; break;
case lir_cond_lessEqual: acond = Assembler::lessEqual; break;
case lir_cond_greaterEqual: acond = Assembler::greaterEqual; break;
case lir_cond_greater: acond = Assembler::greater; break;
case lir_cond_aboveEqual: acond = Assembler::greaterEqualUnsigned; break;
case lir_cond_belowEqual: acond = Assembler::lessEqualUnsigned; break;
default: ShouldNotReachHere();
};
// sparc has different condition codes for testing 32-bit
// vs. 64-bit values. We could always test xcc is we could
// guarantee that 32-bit loads always sign extended but that isn't
// true and since sign extension isn't free, it would impose a
// slight cost.
#ifdef _LP64
if (op->type() == T_INT) {
__ br(acond, false, Assembler::pn, *(op->label()));
} else
#endif
__ brx(acond, false, Assembler::pn, *(op->label()));
}
// The peephole pass fills the delay slot
}
void LIR_Assembler::emit_opConvert(LIR_OpConvert* op) {
Bytecodes::Code code = op->bytecode();
LIR_Opr dst = op->result_opr();
switch(code) {
case Bytecodes::_i2l: {
Register rlo = dst->as_register_lo();
Register rhi = dst->as_register_hi();
Register rval = op->in_opr()->as_register();
#ifdef _LP64
__ sra(rval, 0, rlo);
#else
__ mov(rval, rlo);
__ sra(rval, BitsPerInt-1, rhi);
#endif
break;
}
case Bytecodes::_i2d:
case Bytecodes::_i2f: {
bool is_double = (code == Bytecodes::_i2d);
FloatRegister rdst = is_double ? dst->as_double_reg() : dst->as_float_reg();
FloatRegisterImpl::Width w = is_double ? FloatRegisterImpl::D : FloatRegisterImpl::S;
FloatRegister rsrc = op->in_opr()->as_float_reg();
if (rsrc != rdst) {
__ fmov(FloatRegisterImpl::S, rsrc, rdst);
}
__ fitof(w, rdst, rdst);
break;
}
case Bytecodes::_f2i:{
FloatRegister rsrc = op->in_opr()->as_float_reg();
Address addr = frame_map()->address_for_slot(dst->single_stack_ix());
Label L;
// result must be 0 if value is NaN; test by comparing value to itself
__ fcmp(FloatRegisterImpl::S, Assembler::fcc0, rsrc, rsrc);
if (!VM_Version::v9_instructions_work()) {
__ nop();
}
__ fb(Assembler::f_unordered, true, Assembler::pn, L);
__ delayed()->st(G0, addr); // annuled if contents of rsrc is not NaN
__ ftoi(FloatRegisterImpl::S, rsrc, rsrc);
// move integer result from float register to int register
__ stf(FloatRegisterImpl::S, rsrc, addr.base(), addr.disp());
__ bind (L);
break;
}
case Bytecodes::_l2i: {
Register rlo = op->in_opr()->as_register_lo();
Register rhi = op->in_opr()->as_register_hi();
Register rdst = dst->as_register();
#ifdef _LP64
__ sra(rlo, 0, rdst);
#else
__ mov(rlo, rdst);
#endif
break;
}
case Bytecodes::_d2f:
case Bytecodes::_f2d: {
bool is_double = (code == Bytecodes::_f2d);
assert((!is_double && dst->is_single_fpu()) || (is_double && dst->is_double_fpu()), "check");
LIR_Opr val = op->in_opr();
FloatRegister rval = (code == Bytecodes::_d2f) ? val->as_double_reg() : val->as_float_reg();
FloatRegister rdst = is_double ? dst->as_double_reg() : dst->as_float_reg();
FloatRegisterImpl::Width vw = is_double ? FloatRegisterImpl::S : FloatRegisterImpl::D;
FloatRegisterImpl::Width dw = is_double ? FloatRegisterImpl::D : FloatRegisterImpl::S;
__ ftof(vw, dw, rval, rdst);
break;
}
case Bytecodes::_i2s:
case Bytecodes::_i2b: {
Register rval = op->in_opr()->as_register();
Register rdst = dst->as_register();
int shift = (code == Bytecodes::_i2b) ? (BitsPerInt - T_BYTE_aelem_bytes * BitsPerByte) : (BitsPerInt - BitsPerShort);
__ sll (rval, shift, rdst);
__ sra (rdst, shift, rdst);
break;
}
case Bytecodes::_i2c: {
Register rval = op->in_opr()->as_register();
Register rdst = dst->as_register();
int shift = BitsPerInt - T_CHAR_aelem_bytes * BitsPerByte;
__ sll (rval, shift, rdst);
__ srl (rdst, shift, rdst);
break;
}
default: ShouldNotReachHere();
}
}
void LIR_Assembler::align_call(LIR_Code) {
// do nothing since all instructions are word aligned on sparc
}
void LIR_Assembler::call(LIR_OpJavaCall* op, relocInfo::relocType rtype) {
__ call(op->addr(), rtype);
// The peephole pass fills the delay slot, add_call_info is done in
// LIR_Assembler::emit_delay.
}
void LIR_Assembler::ic_call(LIR_OpJavaCall* op) {
RelocationHolder rspec = virtual_call_Relocation::spec(pc());
__ set_oop((jobject)Universe::non_oop_word(), G5_inline_cache_reg);
__ relocate(rspec);
__ call(op->addr(), relocInfo::none);
// The peephole pass fills the delay slot, add_call_info is done in
// LIR_Assembler::emit_delay.
}
void LIR_Assembler::vtable_call(LIR_OpJavaCall* op) {
add_debug_info_for_null_check_here(op->info());
__ ld_ptr(O0, oopDesc::klass_offset_in_bytes(), G3_scratch);
if (__ is_simm13(op->vtable_offset())) {
__ ld_ptr(G3_scratch, op->vtable_offset(), G5_method);
} else {
// This will generate 2 instructions
__ set(op->vtable_offset(), G5_method);
// ld_ptr, set_hi, set
__ ld_ptr(G3_scratch, G5_method, G5_method);
}
__ ld_ptr(G5_method, methodOopDesc::from_compiled_offset(), G3_scratch);
__ callr(G3_scratch, G0);
// the peephole pass fills the delay slot
}
// load with 32-bit displacement
int LIR_Assembler::load(Register s, int disp, Register d, BasicType ld_type, CodeEmitInfo *info) {
int load_offset = code_offset();
if (Assembler::is_simm13(disp)) {
if (info != NULL) add_debug_info_for_null_check_here(info);
switch(ld_type) {
case T_BOOLEAN: // fall through
case T_BYTE : __ ldsb(s, disp, d); break;
case T_CHAR : __ lduh(s, disp, d); break;
case T_SHORT : __ ldsh(s, disp, d); break;
case T_INT : __ ld(s, disp, d); break;
case T_ADDRESS:// fall through
case T_ARRAY : // fall through
case T_OBJECT: __ ld_ptr(s, disp, d); break;
default : ShouldNotReachHere();
}
} else {
__ set(disp, O7);
if (info != NULL) add_debug_info_for_null_check_here(info);
load_offset = code_offset();
switch(ld_type) {
case T_BOOLEAN: // fall through
case T_BYTE : __ ldsb(s, O7, d); break;
case T_CHAR : __ lduh(s, O7, d); break;
case T_SHORT : __ ldsh(s, O7, d); break;
case T_INT : __ ld(s, O7, d); break;
case T_ADDRESS:// fall through
case T_ARRAY : // fall through
case T_OBJECT: __ ld_ptr(s, O7, d); break;
default : ShouldNotReachHere();
}
}
if (ld_type == T_ARRAY || ld_type == T_OBJECT) __ verify_oop(d);
return load_offset;
}
// store with 32-bit displacement
void LIR_Assembler::store(Register value, Register base, int offset, BasicType type, CodeEmitInfo *info) {
if (Assembler::is_simm13(offset)) {
if (info != NULL) add_debug_info_for_null_check_here(info);
switch (type) {
case T_BOOLEAN: // fall through
case T_BYTE : __ stb(value, base, offset); break;
case T_CHAR : __ sth(value, base, offset); break;
case T_SHORT : __ sth(value, base, offset); break;
case T_INT : __ stw(value, base, offset); break;
case T_ADDRESS:// fall through
case T_ARRAY : // fall through
case T_OBJECT: __ st_ptr(value, base, offset); break;
default : ShouldNotReachHere();
}
} else {
__ set(offset, O7);
if (info != NULL) add_debug_info_for_null_check_here(info);
switch (type) {
case T_BOOLEAN: // fall through
case T_BYTE : __ stb(value, base, O7); break;
case T_CHAR : __ sth(value, base, O7); break;
case T_SHORT : __ sth(value, base, O7); break;
case T_INT : __ stw(value, base, O7); break;
case T_ADDRESS:// fall through
case T_ARRAY : //fall through
case T_OBJECT: __ st_ptr(value, base, O7); break;
default : ShouldNotReachHere();
}
}
// Note: Do the store before verification as the code might be patched!
if (type == T_ARRAY || type == T_OBJECT) __ verify_oop(value);
}
// load float with 32-bit displacement
void LIR_Assembler::load(Register s, int disp, FloatRegister d, BasicType ld_type, CodeEmitInfo *info) {
FloatRegisterImpl::Width w;
switch(ld_type) {
case T_FLOAT : w = FloatRegisterImpl::S; break;
case T_DOUBLE: w = FloatRegisterImpl::D; break;
default : ShouldNotReachHere();
}
if (Assembler::is_simm13(disp)) {
if (info != NULL) add_debug_info_for_null_check_here(info);
if (disp % BytesPerLong != 0 && w == FloatRegisterImpl::D) {
__ ldf(FloatRegisterImpl::S, s, disp + BytesPerWord, d->successor());
__ ldf(FloatRegisterImpl::S, s, disp , d);
} else {
__ ldf(w, s, disp, d);
}
} else {
__ set(disp, O7);
if (info != NULL) add_debug_info_for_null_check_here(info);
__ ldf(w, s, O7, d);
}
}
// store float with 32-bit displacement
void LIR_Assembler::store(FloatRegister value, Register base, int offset, BasicType type, CodeEmitInfo *info) {
FloatRegisterImpl::Width w;
switch(type) {
case T_FLOAT : w = FloatRegisterImpl::S; break;
case T_DOUBLE: w = FloatRegisterImpl::D; break;
default : ShouldNotReachHere();
}
if (Assembler::is_simm13(offset)) {
if (info != NULL) add_debug_info_for_null_check_here(info);
if (w == FloatRegisterImpl::D && offset % BytesPerLong != 0) {
__ stf(FloatRegisterImpl::S, value->successor(), base, offset + BytesPerWord);
__ stf(FloatRegisterImpl::S, value , base, offset);
} else {
__ stf(w, value, base, offset);
}
} else {
__ set(offset, O7);
if (info != NULL) add_debug_info_for_null_check_here(info);
__ stf(w, value, O7, base);
}
}
int LIR_Assembler::store(LIR_Opr from_reg, Register base, int offset, BasicType type, bool unaligned) {
int store_offset;
if (!Assembler::is_simm13(offset + (type == T_LONG) ? wordSize : 0)) {
assert(!unaligned, "can't handle this");
// for offsets larger than a simm13 we setup the offset in O7
__ set(offset, O7);
store_offset = store(from_reg, base, O7, type);
} else {
if (type == T_ARRAY || type == T_OBJECT) __ verify_oop(from_reg->as_register());
store_offset = code_offset();
switch (type) {
case T_BOOLEAN: // fall through
case T_BYTE : __ stb(from_reg->as_register(), base, offset); break;
case T_CHAR : __ sth(from_reg->as_register(), base, offset); break;
case T_SHORT : __ sth(from_reg->as_register(), base, offset); break;
case T_INT : __ stw(from_reg->as_register(), base, offset); break;
case T_LONG :
#ifdef _LP64
if (unaligned || PatchALot) {
__ srax(from_reg->as_register_lo(), 32, O7);
__ stw(from_reg->as_register_lo(), base, offset + lo_word_offset_in_bytes);
__ stw(O7, base, offset + hi_word_offset_in_bytes);
} else {
__ stx(from_reg->as_register_lo(), base, offset);
}
#else
assert(Assembler::is_simm13(offset + 4), "must be");
__ stw(from_reg->as_register_lo(), base, offset + lo_word_offset_in_bytes);
__ stw(from_reg->as_register_hi(), base, offset + hi_word_offset_in_bytes);
#endif
break;
case T_ADDRESS:// fall through
case T_ARRAY : // fall through
case T_OBJECT: __ st_ptr(from_reg->as_register(), base, offset); break;
case T_FLOAT : __ stf(FloatRegisterImpl::S, from_reg->as_float_reg(), base, offset); break;
case T_DOUBLE:
{
FloatRegister reg = from_reg->as_double_reg();
// split unaligned stores
if (unaligned || PatchALot) {
assert(Assembler::is_simm13(offset + 4), "must be");
__ stf(FloatRegisterImpl::S, reg->successor(), base, offset + 4);
__ stf(FloatRegisterImpl::S, reg, base, offset);
} else {
__ stf(FloatRegisterImpl::D, reg, base, offset);
}
break;
}
default : ShouldNotReachHere();
}
}
return store_offset;
}
int LIR_Assembler::store(LIR_Opr from_reg, Register base, Register disp, BasicType type) {
if (type == T_ARRAY || type == T_OBJECT) __ verify_oop(from_reg->as_register());
int store_offset = code_offset();
switch (type) {
case T_BOOLEAN: // fall through
case T_BYTE : __ stb(from_reg->as_register(), base, disp); break;
case T_CHAR : __ sth(from_reg->as_register(), base, disp); break;
case T_SHORT : __ sth(from_reg->as_register(), base, disp); break;
case T_INT : __ stw(from_reg->as_register(), base, disp); break;
case T_LONG :
#ifdef _LP64
__ stx(from_reg->as_register_lo(), base, disp);
#else
assert(from_reg->as_register_hi()->successor() == from_reg->as_register_lo(), "must match");
__ std(from_reg->as_register_hi(), base, disp);
#endif
break;
case T_ADDRESS:// fall through
case T_ARRAY : // fall through
case T_OBJECT: __ st_ptr(from_reg->as_register(), base, disp); break;
case T_FLOAT : __ stf(FloatRegisterImpl::S, from_reg->as_float_reg(), base, disp); break;
case T_DOUBLE: __ stf(FloatRegisterImpl::D, from_reg->as_double_reg(), base, disp); break;
default : ShouldNotReachHere();
}
return store_offset;
}
int LIR_Assembler::load(Register base, int offset, LIR_Opr to_reg, BasicType type, bool unaligned) {
int load_offset;
if (!Assembler::is_simm13(offset + (type == T_LONG) ? wordSize : 0)) {
assert(base != O7, "destroying register");
assert(!unaligned, "can't handle this");
// for offsets larger than a simm13 we setup the offset in O7
__ set(offset, O7);
load_offset = load(base, O7, to_reg, type);
} else {
load_offset = code_offset();
switch(type) {
case T_BOOLEAN: // fall through
case T_BYTE : __ ldsb(base, offset, to_reg->as_register()); break;
case T_CHAR : __ lduh(base, offset, to_reg->as_register()); break;
case T_SHORT : __ ldsh(base, offset, to_reg->as_register()); break;
case T_INT : __ ld(base, offset, to_reg->as_register()); break;
case T_LONG :
if (!unaligned) {
#ifdef _LP64
__ ldx(base, offset, to_reg->as_register_lo());
#else
assert(to_reg->as_register_hi()->successor() == to_reg->as_register_lo(),
"must be sequential");
__ ldd(base, offset, to_reg->as_register_hi());
#endif
} else {
#ifdef _LP64
assert(base != to_reg->as_register_lo(), "can't handle this");
assert(O7 != to_reg->as_register_lo(), "can't handle this");
__ ld(base, offset + hi_word_offset_in_bytes, to_reg->as_register_lo());
__ lduw(base, offset + lo_word_offset_in_bytes, O7); // in case O7 is base or offset, use it last
__ sllx(to_reg->as_register_lo(), 32, to_reg->as_register_lo());
__ or3(to_reg->as_register_lo(), O7, to_reg->as_register_lo());
#else
if (base == to_reg->as_register_lo()) {
__ ld(base, offset + hi_word_offset_in_bytes, to_reg->as_register_hi());
__ ld(base, offset + lo_word_offset_in_bytes, to_reg->as_register_lo());
} else {
__ ld(base, offset + lo_word_offset_in_bytes, to_reg->as_register_lo());
__ ld(base, offset + hi_word_offset_in_bytes, to_reg->as_register_hi());
}
#endif
}
break;
case T_ADDRESS:// fall through
case T_ARRAY : // fall through
case T_OBJECT: __ ld_ptr(base, offset, to_reg->as_register()); break;
case T_FLOAT: __ ldf(FloatRegisterImpl::S, base, offset, to_reg->as_float_reg()); break;
case T_DOUBLE:
{
FloatRegister reg = to_reg->as_double_reg();
// split unaligned loads
if (unaligned || PatchALot) {
__ ldf(FloatRegisterImpl::S, base, offset + 4, reg->successor());
__ ldf(FloatRegisterImpl::S, base, offset, reg);
} else {
__ ldf(FloatRegisterImpl::D, base, offset, to_reg->as_double_reg());
}
break;
}
default : ShouldNotReachHere();
}
if (type == T_ARRAY || type == T_OBJECT) __ verify_oop(to_reg->as_register());
}
return load_offset;
}
int LIR_Assembler::load(Register base, Register disp, LIR_Opr to_reg, BasicType type) {
int load_offset = code_offset();
switch(type) {
case T_BOOLEAN: // fall through
case T_BYTE : __ ldsb(base, disp, to_reg->as_register()); break;
case T_CHAR : __ lduh(base, disp, to_reg->as_register()); break;
case T_SHORT : __ ldsh(base, disp, to_reg->as_register()); break;
case T_INT : __ ld(base, disp, to_reg->as_register()); break;
case T_ADDRESS:// fall through
case T_ARRAY : // fall through
case T_OBJECT: __ ld_ptr(base, disp, to_reg->as_register()); break;
case T_FLOAT: __ ldf(FloatRegisterImpl::S, base, disp, to_reg->as_float_reg()); break;
case T_DOUBLE: __ ldf(FloatRegisterImpl::D, base, disp, to_reg->as_double_reg()); break;
case T_LONG :
#ifdef _LP64
__ ldx(base, disp, to_reg->as_register_lo());
#else
assert(to_reg->as_register_hi()->successor() == to_reg->as_register_lo(),
"must be sequential");
__ ldd(base, disp, to_reg->as_register_hi());
#endif
break;
default : ShouldNotReachHere();
}
if (type == T_ARRAY || type == T_OBJECT) __ verify_oop(to_reg->as_register());
return load_offset;
}
// load/store with an Address
void LIR_Assembler::load(const Address& a, Register d, BasicType ld_type, CodeEmitInfo *info, int offset) {
load(a.base(), a.disp() + offset, d, ld_type, info);
}
void LIR_Assembler::store(Register value, const Address& dest, BasicType type, CodeEmitInfo *info, int offset) {
store(value, dest.base(), dest.disp() + offset, type, info);
}
// loadf/storef with an Address
void LIR_Assembler::load(const Address& a, FloatRegister d, BasicType ld_type, CodeEmitInfo *info, int offset) {
load(a.base(), a.disp() + offset, d, ld_type, info);
}
void LIR_Assembler::store(FloatRegister value, const Address& dest, BasicType type, CodeEmitInfo *info, int offset) {
store(value, dest.base(), dest.disp() + offset, type, info);
}
// load/store with an Address
void LIR_Assembler::load(LIR_Address* a, Register d, BasicType ld_type, CodeEmitInfo *info) {
load(as_Address(a), d, ld_type, info);
}
void LIR_Assembler::store(Register value, LIR_Address* dest, BasicType type, CodeEmitInfo *info) {
store(value, as_Address(dest), type, info);
}
// loadf/storef with an Address
void LIR_Assembler::load(LIR_Address* a, FloatRegister d, BasicType ld_type, CodeEmitInfo *info) {
load(as_Address(a), d, ld_type, info);
}
void LIR_Assembler::store(FloatRegister value, LIR_Address* dest, BasicType type, CodeEmitInfo *info) {
store(value, as_Address(dest), type, info);
}
void LIR_Assembler::const2stack(LIR_Opr src, LIR_Opr dest) {
LIR_Const* c = src->as_constant_ptr();
switch (c->type()) {
case T_INT:
case T_FLOAT:
case T_ADDRESS: {
Register src_reg = O7;
int value = c->as_jint_bits();
if (value == 0) {
src_reg = G0;
} else {
__ set(value, O7);
}
Address addr = frame_map()->address_for_slot(dest->single_stack_ix());
__ stw(src_reg, addr.base(), addr.disp());
break;
}
case T_OBJECT: {
Register src_reg = O7;
jobject2reg(c->as_jobject(), src_reg);
Address addr = frame_map()->address_for_slot(dest->single_stack_ix());
__ st_ptr(src_reg, addr.base(), addr.disp());
break;
}
case T_LONG:
case T_DOUBLE: {
Address addr = frame_map()->address_for_double_slot(dest->double_stack_ix());
Register tmp = O7;
int value_lo = c->as_jint_lo_bits();
if (value_lo == 0) {
tmp = G0;
} else {
__ set(value_lo, O7);
}
__ stw(tmp, addr.base(), addr.disp() + lo_word_offset_in_bytes);
int value_hi = c->as_jint_hi_bits();
if (value_hi == 0) {
tmp = G0;
} else {
__ set(value_hi, O7);
}
__ stw(tmp, addr.base(), addr.disp() + hi_word_offset_in_bytes);
break;
}
default:
Unimplemented();
}
}
void LIR_Assembler::const2mem(LIR_Opr src, LIR_Opr dest, BasicType type, CodeEmitInfo* info ) {
LIR_Const* c = src->as_constant_ptr();
LIR_Address* addr = dest->as_address_ptr();
Register base = addr->base()->as_pointer_register();
if (info != NULL) {
add_debug_info_for_null_check_here(info);
}
switch (c->type()) {
case T_INT:
case T_FLOAT:
case T_ADDRESS: {
LIR_Opr tmp = FrameMap::O7_opr;
int value = c->as_jint_bits();
if (value == 0) {
tmp = FrameMap::G0_opr;
} else if (Assembler::is_simm13(value)) {
__ set(value, O7);
}
if (addr->index()->is_valid()) {
assert(addr->disp() == 0, "must be zero");
store(tmp, base, addr->index()->as_pointer_register(), type);
} else {
assert(Assembler::is_simm13(addr->disp()), "can't handle larger addresses");
store(tmp, base, addr->disp(), type);
}
break;
}
case T_LONG:
case T_DOUBLE: {
assert(!addr->index()->is_valid(), "can't handle reg reg address here");
assert(Assembler::is_simm13(addr->disp()) &&
Assembler::is_simm13(addr->disp() + 4), "can't handle larger addresses");
Register tmp = O7;
int value_lo = c->as_jint_lo_bits();
if (value_lo == 0) {
tmp = G0;
} else {
__ set(value_lo, O7);
}
store(tmp, base, addr->disp() + lo_word_offset_in_bytes, T_INT);
int value_hi = c->as_jint_hi_bits();
if (value_hi == 0) {
tmp = G0;
} else {
__ set(value_hi, O7);
}
store(tmp, base, addr->disp() + hi_word_offset_in_bytes, T_INT);
break;
}
case T_OBJECT: {
jobject obj = c->as_jobject();
LIR_Opr tmp;
if (obj == NULL) {
tmp = FrameMap::G0_opr;
} else {
tmp = FrameMap::O7_opr;
jobject2reg(c->as_jobject(), O7);
}
// handle either reg+reg or reg+disp address
if (addr->index()->is_valid()) {
assert(addr->disp() == 0, "must be zero");
store(tmp, base, addr->index()->as_pointer_register(), type);
} else {
assert(Assembler::is_simm13(addr->disp()), "can't handle larger addresses");
store(tmp, base, addr->disp(), type);
}
break;
}
default:
Unimplemented();
}
}
void LIR_Assembler::const2reg(LIR_Opr src, LIR_Opr dest, LIR_PatchCode patch_code, CodeEmitInfo* info) {
LIR_Const* c = src->as_constant_ptr();
LIR_Opr to_reg = dest;
switch (c->type()) {
case T_INT:
case T_ADDRESS:
{
jint con = c->as_jint();
if (to_reg->is_single_cpu()) {
assert(patch_code == lir_patch_none, "no patching handled here");
__ set(con, to_reg->as_register());
} else {
ShouldNotReachHere();
assert(to_reg->is_single_fpu(), "wrong register kind");
__ set(con, O7);
Address temp_slot(SP, (frame::register_save_words * wordSize) + STACK_BIAS);
__ st(O7, temp_slot);
__ ldf(FloatRegisterImpl::S, temp_slot, to_reg->as_float_reg());
}
}
break;
case T_LONG:
{
jlong con = c->as_jlong();
if (to_reg->is_double_cpu()) {
#ifdef _LP64
__ set(con, to_reg->as_register_lo());
#else
__ set(low(con), to_reg->as_register_lo());
__ set(high(con), to_reg->as_register_hi());
#endif
#ifdef _LP64
} else if (to_reg->is_single_cpu()) {
__ set(con, to_reg->as_register());
#endif
} else {
ShouldNotReachHere();
assert(to_reg->is_double_fpu(), "wrong register kind");
Address temp_slot_lo(SP, ((frame::register_save_words ) * wordSize) + STACK_BIAS);
Address temp_slot_hi(SP, ((frame::register_save_words) * wordSize) + (longSize/2) + STACK_BIAS);
__ set(low(con), O7);
__ st(O7, temp_slot_lo);
__ set(high(con), O7);
__ st(O7, temp_slot_hi);
__ ldf(FloatRegisterImpl::D, temp_slot_lo, to_reg->as_double_reg());
}
}
break;
case T_OBJECT:
{
if (patch_code == lir_patch_none) {
jobject2reg(c->as_jobject(), to_reg->as_register());
} else {
jobject2reg_with_patching(to_reg->as_register(), info);
}
}
break;
case T_FLOAT:
{
address const_addr = __ float_constant(c->as_jfloat());
if (const_addr == NULL) {
bailout("const section overflow");
break;
}
RelocationHolder rspec = internal_word_Relocation::spec(const_addr);
AddressLiteral const_addrlit(const_addr, rspec);
if (to_reg->is_single_fpu()) {
__ patchable_sethi(const_addrlit, O7);
__ relocate(rspec);
__ ldf(FloatRegisterImpl::S, O7, const_addrlit.low10(), to_reg->as_float_reg());
} else {
assert(to_reg->is_single_cpu(), "Must be a cpu register.");
__ set(const_addrlit, O7);
load(O7, 0, to_reg->as_register(), T_INT);
}
}
break;
case T_DOUBLE:
{
address const_addr = __ double_constant(c->as_jdouble());
if (const_addr == NULL) {
bailout("const section overflow");
break;
}
RelocationHolder rspec = internal_word_Relocation::spec(const_addr);
if (to_reg->is_double_fpu()) {
AddressLiteral const_addrlit(const_addr, rspec);
__ patchable_sethi(const_addrlit, O7);
__ relocate(rspec);
__ ldf (FloatRegisterImpl::D, O7, const_addrlit.low10(), to_reg->as_double_reg());
} else {
assert(to_reg->is_double_cpu(), "Must be a long register.");
#ifdef _LP64
__ set(jlong_cast(c->as_jdouble()), to_reg->as_register_lo());
#else
__ set(low(jlong_cast(c->as_jdouble())), to_reg->as_register_lo());
__ set(high(jlong_cast(c->as_jdouble())), to_reg->as_register_hi());
#endif
}
}
break;
default:
ShouldNotReachHere();
}
}
Address LIR_Assembler::as_Address(LIR_Address* addr) {
Register reg = addr->base()->as_register();
return Address(reg, addr->disp());
}
void LIR_Assembler::stack2stack(LIR_Opr src, LIR_Opr dest, BasicType type) {
switch (type) {
case T_INT:
case T_FLOAT: {
Register tmp = O7;
Address from = frame_map()->address_for_slot(src->single_stack_ix());
Address to = frame_map()->address_for_slot(dest->single_stack_ix());
__ lduw(from.base(), from.disp(), tmp);
__ stw(tmp, to.base(), to.disp());
break;
}
case T_OBJECT: {
Register tmp = O7;
Address from = frame_map()->address_for_slot(src->single_stack_ix());
Address to = frame_map()->address_for_slot(dest->single_stack_ix());
__ ld_ptr(from.base(), from.disp(), tmp);
__ st_ptr(tmp, to.base(), to.disp());
break;
}
case T_LONG:
case T_DOUBLE: {
Register tmp = O7;
Address from = frame_map()->address_for_double_slot(src->double_stack_ix());
Address to = frame_map()->address_for_double_slot(dest->double_stack_ix());
__ lduw(from.base(), from.disp(), tmp);
__ stw(tmp, to.base(), to.disp());
__ lduw(from.base(), from.disp() + 4, tmp);
__ stw(tmp, to.base(), to.disp() + 4);
break;
}
default:
ShouldNotReachHere();
}
}
Address LIR_Assembler::as_Address_hi(LIR_Address* addr) {
Address base = as_Address(addr);
return Address(base.base(), base.disp() + hi_word_offset_in_bytes);
}
Address LIR_Assembler::as_Address_lo(LIR_Address* addr) {
Address base = as_Address(addr);
return Address(base.base(), base.disp() + lo_word_offset_in_bytes);
}
void LIR_Assembler::mem2reg(LIR_Opr src_opr, LIR_Opr dest, BasicType type,
LIR_PatchCode patch_code, CodeEmitInfo* info, bool unaligned) {
LIR_Address* addr = src_opr->as_address_ptr();
LIR_Opr to_reg = dest;
Register src = addr->base()->as_pointer_register();
Register disp_reg = noreg;
int disp_value = addr->disp();
bool needs_patching = (patch_code != lir_patch_none);
if (addr->base()->type() == T_OBJECT) {
__ verify_oop(src);
}
PatchingStub* patch = NULL;
if (needs_patching) {
patch = new PatchingStub(_masm, PatchingStub::access_field_id);
assert(!to_reg->is_double_cpu() ||
patch_code == lir_patch_none ||
patch_code == lir_patch_normal, "patching doesn't match register");
}
if (addr->index()->is_illegal()) {
if (!Assembler::is_simm13(disp_value) && (!unaligned || Assembler::is_simm13(disp_value + 4))) {
if (needs_patching) {
__ patchable_set(0, O7);
} else {
__ set(disp_value, O7);
}
disp_reg = O7;
}
} else if (unaligned || PatchALot) {
__ add(src, addr->index()->as_register(), O7);
src = O7;
} else {
disp_reg = addr->index()->as_pointer_register();
assert(disp_value == 0, "can't handle 3 operand addresses");
}
// remember the offset of the load. The patching_epilog must be done
// before the call to add_debug_info, otherwise the PcDescs don't get
// entered in increasing order.
int offset = code_offset();
assert(disp_reg != noreg || Assembler::is_simm13(disp_value), "should have set this up");
if (disp_reg == noreg) {
offset = load(src, disp_value, to_reg, type, unaligned);
} else {
assert(!unaligned, "can't handle this");
offset = load(src, disp_reg, to_reg, type);
}
if (patch != NULL) {
patching_epilog(patch, patch_code, src, info);
}
if (info != NULL) add_debug_info_for_null_check(offset, info);
}
void LIR_Assembler::prefetchr(LIR_Opr src) {
LIR_Address* addr = src->as_address_ptr();
Address from_addr = as_Address(addr);
if (VM_Version::has_v9()) {
__ prefetch(from_addr, Assembler::severalReads);
}
}
void LIR_Assembler::prefetchw(LIR_Opr src) {
LIR_Address* addr = src->as_address_ptr();
Address from_addr = as_Address(addr);
if (VM_Version::has_v9()) {
__ prefetch(from_addr, Assembler::severalWritesAndPossiblyReads);
}
}
void LIR_Assembler::stack2reg(LIR_Opr src, LIR_Opr dest, BasicType type) {
Address addr;
if (src->is_single_word()) {
addr = frame_map()->address_for_slot(src->single_stack_ix());
} else if (src->is_double_word()) {
addr = frame_map()->address_for_double_slot(src->double_stack_ix());
}
bool unaligned = (addr.disp() - STACK_BIAS) % 8 != 0;
load(addr.base(), addr.disp(), dest, dest->type(), unaligned);
}
void LIR_Assembler::reg2stack(LIR_Opr from_reg, LIR_Opr dest, BasicType type, bool pop_fpu_stack) {
Address addr;
if (dest->is_single_word()) {
addr = frame_map()->address_for_slot(dest->single_stack_ix());
} else if (dest->is_double_word()) {
addr = frame_map()->address_for_slot(dest->double_stack_ix());
}
bool unaligned = (addr.disp() - STACK_BIAS) % 8 != 0;
store(from_reg, addr.base(), addr.disp(), from_reg->type(), unaligned);
}
void LIR_Assembler::reg2reg(LIR_Opr from_reg, LIR_Opr to_reg) {
if (from_reg->is_float_kind() && to_reg->is_float_kind()) {
if (from_reg->is_double_fpu()) {
// double to double moves
assert(to_reg->is_double_fpu(), "should match");
__ fmov(FloatRegisterImpl::D, from_reg->as_double_reg(), to_reg->as_double_reg());
} else {
// float to float moves
assert(to_reg->is_single_fpu(), "should match");
__ fmov(FloatRegisterImpl::S, from_reg->as_float_reg(), to_reg->as_float_reg());
}
} else if (!from_reg->is_float_kind() && !to_reg->is_float_kind()) {
if (from_reg->is_double_cpu()) {
#ifdef _LP64
__ mov(from_reg->as_pointer_register(), to_reg->as_pointer_register());
#else
assert(to_reg->is_double_cpu() &&
from_reg->as_register_hi() != to_reg->as_register_lo() &&
from_reg->as_register_lo() != to_reg->as_register_hi(),
"should both be long and not overlap");
// long to long moves
__ mov(from_reg->as_register_hi(), to_reg->as_register_hi());
__ mov(from_reg->as_register_lo(), to_reg->as_register_lo());
#endif
#ifdef _LP64
} else if (to_reg->is_double_cpu()) {
// int to int moves
__ mov(from_reg->as_register(), to_reg->as_register_lo());
#endif
} else {
// int to int moves
__ mov(from_reg->as_register(), to_reg->as_register());
}
} else {
ShouldNotReachHere();
}
if (to_reg->type() == T_OBJECT || to_reg->type() == T_ARRAY) {
__ verify_oop(to_reg->as_register());
}
}
void LIR_Assembler::reg2mem(LIR_Opr from_reg, LIR_Opr dest, BasicType type,
LIR_PatchCode patch_code, CodeEmitInfo* info, bool pop_fpu_stack,
bool unaligned) {
LIR_Address* addr = dest->as_address_ptr();
Register src = addr->base()->as_pointer_register();
Register disp_reg = noreg;
int disp_value = addr->disp();
bool needs_patching = (patch_code != lir_patch_none);
if (addr->base()->is_oop_register()) {
__ verify_oop(src);
}
PatchingStub* patch = NULL;
if (needs_patching) {
patch = new PatchingStub(_masm, PatchingStub::access_field_id);
assert(!from_reg->is_double_cpu() ||
patch_code == lir_patch_none ||
patch_code == lir_patch_normal, "patching doesn't match register");
}
if (addr->index()->is_illegal()) {
if (!Assembler::is_simm13(disp_value) && (!unaligned || Assembler::is_simm13(disp_value + 4))) {
if (needs_patching) {
__ patchable_set(0, O7);
} else {
__ set(disp_value, O7);
}
disp_reg = O7;
}
} else if (unaligned || PatchALot) {
__ add(src, addr->index()->as_register(), O7);
src = O7;
} else {
disp_reg = addr->index()->as_pointer_register();
assert(disp_value == 0, "can't handle 3 operand addresses");
}
// remember the offset of the store. The patching_epilog must be done
// before the call to add_debug_info_for_null_check, otherwise the PcDescs don't get
// entered in increasing order.
int offset;
assert(disp_reg != noreg || Assembler::is_simm13(disp_value), "should have set this up");
if (disp_reg == noreg) {
offset = store(from_reg, src, disp_value, type, unaligned);
} else {
assert(!unaligned, "can't handle this");
offset = store(from_reg, src, disp_reg, type);
}
if (patch != NULL) {
patching_epilog(patch, patch_code, src, info);
}
if (info != NULL) add_debug_info_for_null_check(offset, info);
}
void LIR_Assembler::return_op(LIR_Opr result) {
// the poll may need a register so just pick one that isn't the return register
#ifdef TIERED
if (result->type_field() == LIR_OprDesc::long_type) {
// Must move the result to G1
// Must leave proper result in O0,O1 and G1 (TIERED only)
__ sllx(I0, 32, G1); // Shift bits into high G1
__ srl (I1, 0, I1); // Zero extend O1 (harmless?)
__ or3 (I1, G1, G1); // OR 64 bits into G1
}
#endif // TIERED
__ set((intptr_t)os::get_polling_page(), L0);
__ relocate(relocInfo::poll_return_type);
__ ld_ptr(L0, 0, G0);
__ ret();
__ delayed()->restore();
}
int LIR_Assembler::safepoint_poll(LIR_Opr tmp, CodeEmitInfo* info) {
__ set((intptr_t)os::get_polling_page(), tmp->as_register());
if (info != NULL) {
add_debug_info_for_branch(info);
} else {
__ relocate(relocInfo::poll_type);
}
int offset = __ offset();
__ ld_ptr(tmp->as_register(), 0, G0);
return offset;
}
void LIR_Assembler::emit_static_call_stub() {
address call_pc = __ pc();
address stub = __ start_a_stub(call_stub_size);
if (stub == NULL) {
bailout("static call stub overflow");
return;
}
int start = __ offset();
__ relocate(static_stub_Relocation::spec(call_pc));
__ set_oop(NULL, G5);
// must be set to -1 at code generation time
AddressLiteral addrlit(-1);
__ jump_to(addrlit, G3);
__ delayed()->nop();
assert(__ offset() - start <= call_stub_size, "stub too big");
__ end_a_stub();
}
void LIR_Assembler::comp_op(LIR_Condition condition, LIR_Opr opr1, LIR_Opr opr2, LIR_Op2* op) {
if (opr1->is_single_fpu()) {
__ fcmp(FloatRegisterImpl::S, Assembler::fcc0, opr1->as_float_reg(), opr2->as_float_reg());
} else if (opr1->is_double_fpu()) {
__ fcmp(FloatRegisterImpl::D, Assembler::fcc0, opr1->as_double_reg(), opr2->as_double_reg());
} else if (opr1->is_single_cpu()) {
if (opr2->is_constant()) {
switch (opr2->as_constant_ptr()->type()) {
case T_INT:
{ jint con = opr2->as_constant_ptr()->as_jint();
if (Assembler::is_simm13(con)) {
__ cmp(opr1->as_register(), con);
} else {
__ set(con, O7);
__ cmp(opr1->as_register(), O7);
}
}
break;
case T_OBJECT:
// there are only equal/notequal comparisions on objects
{ jobject con = opr2->as_constant_ptr()->as_jobject();
if (con == NULL) {
__ cmp(opr1->as_register(), 0);
} else {
jobject2reg(con, O7);
__ cmp(opr1->as_register(), O7);
}
}
break;
default:
ShouldNotReachHere();
break;
}
} else {
if (opr2->is_address()) {
LIR_Address * addr = opr2->as_address_ptr();
BasicType type = addr->type();
if ( type == T_OBJECT ) __ ld_ptr(as_Address(addr), O7);
else __ ld(as_Address(addr), O7);
__ cmp(opr1->as_register(), O7);
} else {
__ cmp(opr1->as_register(), opr2->as_register());
}
}
} else if (opr1->is_double_cpu()) {
Register xlo = opr1->as_register_lo();
Register xhi = opr1->as_register_hi();
if (opr2->is_constant() && opr2->as_jlong() == 0) {
assert(condition == lir_cond_equal || condition == lir_cond_notEqual, "only handles these cases");
#ifdef _LP64
__ orcc(xhi, G0, G0);
#else
__ orcc(xhi, xlo, G0);
#endif
} else if (opr2->is_register()) {
Register ylo = opr2->as_register_lo();
Register yhi = opr2->as_register_hi();
#ifdef _LP64
__ cmp(xlo, ylo);
#else
__ subcc(xlo, ylo, xlo);
__ subccc(xhi, yhi, xhi);
if (condition == lir_cond_equal || condition == lir_cond_notEqual) {
__ orcc(xhi, xlo, G0);
}
#endif
} else {
ShouldNotReachHere();
}
} else if (opr1->is_address()) {
LIR_Address * addr = opr1->as_address_ptr();
BasicType type = addr->type();
assert (opr2->is_constant(), "Checking");
if ( type == T_OBJECT ) __ ld_ptr(as_Address(addr), O7);
else __ ld(as_Address(addr), O7);
__ cmp(O7, opr2->as_constant_ptr()->as_jint());
} else {
ShouldNotReachHere();
}
}
void LIR_Assembler::comp_fl2i(LIR_Code code, LIR_Opr left, LIR_Opr right, LIR_Opr dst, LIR_Op2* op){
if (code == lir_cmp_fd2i || code == lir_ucmp_fd2i) {
bool is_unordered_less = (code == lir_ucmp_fd2i);
if (left->is_single_fpu()) {
__ float_cmp(true, is_unordered_less ? -1 : 1, left->as_float_reg(), right->as_float_reg(), dst->as_register());
} else if (left->is_double_fpu()) {
__ float_cmp(false, is_unordered_less ? -1 : 1, left->as_double_reg(), right->as_double_reg(), dst->as_register());
} else {
ShouldNotReachHere();
}
} else if (code == lir_cmp_l2i) {
#ifdef _LP64
__ lcmp(left->as_register_lo(), right->as_register_lo(), dst->as_register());
#else
__ lcmp(left->as_register_hi(), left->as_register_lo(),
right->as_register_hi(), right->as_register_lo(),
dst->as_register());
#endif
} else {
ShouldNotReachHere();
}
}
void LIR_Assembler::cmove(LIR_Condition condition, LIR_Opr opr1, LIR_Opr opr2, LIR_Opr result) {
Assembler::Condition acond;
switch (condition) {
case lir_cond_equal: acond = Assembler::equal; break;
case lir_cond_notEqual: acond = Assembler::notEqual; break;
case lir_cond_less: acond = Assembler::less; break;
case lir_cond_lessEqual: acond = Assembler::lessEqual; break;
case lir_cond_greaterEqual: acond = Assembler::greaterEqual; break;
case lir_cond_greater: acond = Assembler::greater; break;
case lir_cond_aboveEqual: acond = Assembler::greaterEqualUnsigned; break;
case lir_cond_belowEqual: acond = Assembler::lessEqualUnsigned; break;
default: ShouldNotReachHere();
};
if (opr1->is_constant() && opr1->type() == T_INT) {
Register dest = result->as_register();
// load up first part of constant before branch
// and do the rest in the delay slot.
if (!Assembler::is_simm13(opr1->as_jint())) {
__ sethi(opr1->as_jint(), dest);
}
} else if (opr1->is_constant()) {
const2reg(opr1, result, lir_patch_none, NULL);
} else if (opr1->is_register()) {
reg2reg(opr1, result);
} else if (opr1->is_stack()) {
stack2reg(opr1, result, result->type());
} else {
ShouldNotReachHere();
}
Label skip;
__ br(acond, false, Assembler::pt, skip);
if (opr1->is_constant() && opr1->type() == T_INT) {
Register dest = result->as_register();
if (Assembler::is_simm13(opr1->as_jint())) {
__ delayed()->or3(G0, opr1->as_jint(), dest);
} else {
// the sethi has been done above, so just put in the low 10 bits
__ delayed()->or3(dest, opr1->as_jint() & 0x3ff, dest);
}
} else {
// can't do anything useful in the delay slot
__ delayed()->nop();
}
if (opr2->is_constant()) {
const2reg(opr2, result, lir_patch_none, NULL);
} else if (opr2->is_register()) {
reg2reg(opr2, result);
} else if (opr2->is_stack()) {
stack2reg(opr2, result, result->type());
} else {
ShouldNotReachHere();
}
__ bind(skip);
}
void LIR_Assembler::arith_op(LIR_Code code, LIR_Opr left, LIR_Opr right, LIR_Opr dest, CodeEmitInfo* info, bool pop_fpu_stack) {
assert(info == NULL, "unused on this code path");
assert(left->is_register(), "wrong items state");
assert(dest->is_register(), "wrong items state");
if (right->is_register()) {
if (dest->is_float_kind()) {
FloatRegister lreg, rreg, res;
FloatRegisterImpl::Width w;
if (right->is_single_fpu()) {
w = FloatRegisterImpl::S;
lreg = left->as_float_reg();
rreg = right->as_float_reg();
res = dest->as_float_reg();
} else {
w = FloatRegisterImpl::D;
lreg = left->as_double_reg();
rreg = right->as_double_reg();
res = dest->as_double_reg();
}
switch (code) {
case lir_add: __ fadd(w, lreg, rreg, res); break;
case lir_sub: __ fsub(w, lreg, rreg, res); break;
case lir_mul: // fall through
case lir_mul_strictfp: __ fmul(w, lreg, rreg, res); break;
case lir_div: // fall through
case lir_div_strictfp: __ fdiv(w, lreg, rreg, res); break;
default: ShouldNotReachHere();
}
} else if (dest->is_double_cpu()) {
#ifdef _LP64
Register dst_lo = dest->as_register_lo();
Register op1_lo = left->as_pointer_register();
Register op2_lo = right->as_pointer_register();
switch (code) {
case lir_add:
__ add(op1_lo, op2_lo, dst_lo);
break;
case lir_sub:
__ sub(op1_lo, op2_lo, dst_lo);
break;
default: ShouldNotReachHere();
}
#else
Register op1_lo = left->as_register_lo();
Register op1_hi = left->as_register_hi();
Register op2_lo = right->as_register_lo();
Register op2_hi = right->as_register_hi();
Register dst_lo = dest->as_register_lo();
Register dst_hi = dest->as_register_hi();
switch (code) {
case lir_add:
__ addcc(op1_lo, op2_lo, dst_lo);
__ addc (op1_hi, op2_hi, dst_hi);
break;
case lir_sub:
__ subcc(op1_lo, op2_lo, dst_lo);
__ subc (op1_hi, op2_hi, dst_hi);
break;
default: ShouldNotReachHere();
}
#endif
} else {
assert (right->is_single_cpu(), "Just Checking");
Register lreg = left->as_register();
Register res = dest->as_register();
Register rreg = right->as_register();
switch (code) {
case lir_add: __ add (lreg, rreg, res); break;
case lir_sub: __ sub (lreg, rreg, res); break;
case lir_mul: __ mult (lreg, rreg, res); break;
default: ShouldNotReachHere();
}
}
} else {
assert (right->is_constant(), "must be constant");
if (dest->is_single_cpu()) {
Register lreg = left->as_register();
Register res = dest->as_register();
int simm13 = right->as_constant_ptr()->as_jint();
switch (code) {
case lir_add: __ add (lreg, simm13, res); break;
case lir_sub: __ sub (lreg, simm13, res); break;
case lir_mul: __ mult (lreg, simm13, res); break;
default: ShouldNotReachHere();
}
} else {
Register lreg = left->as_pointer_register();
Register res = dest->as_register_lo();
long con = right->as_constant_ptr()->as_jlong();
assert(Assembler::is_simm13(con), "must be simm13");
switch (code) {
case lir_add: __ add (lreg, (int)con, res); break;
case lir_sub: __ sub (lreg, (int)con, res); break;
case lir_mul: __ mult (lreg, (int)con, res); break;
default: ShouldNotReachHere();
}
}
}
}
void LIR_Assembler::fpop() {
// do nothing
}
void LIR_Assembler::intrinsic_op(LIR_Code code, LIR_Opr value, LIR_Opr thread, LIR_Opr dest, LIR_Op* op) {
switch (code) {
case lir_sin:
case lir_tan:
case lir_cos: {
assert(thread->is_valid(), "preserve the thread object for performance reasons");
assert(dest->as_double_reg() == F0, "the result will be in f0/f1");
break;
}
case lir_sqrt: {
assert(!thread->is_valid(), "there is no need for a thread_reg for dsqrt");
FloatRegister src_reg = value->as_double_reg();
FloatRegister dst_reg = dest->as_double_reg();
__ fsqrt(FloatRegisterImpl::D, src_reg, dst_reg);
break;
}
case lir_abs: {
assert(!thread->is_valid(), "there is no need for a thread_reg for fabs");
FloatRegister src_reg = value->as_double_reg();
FloatRegister dst_reg = dest->as_double_reg();
__ fabs(FloatRegisterImpl::D, src_reg, dst_reg);
break;
}
default: {
ShouldNotReachHere();
break;
}
}
}
void LIR_Assembler::logic_op(LIR_Code code, LIR_Opr left, LIR_Opr right, LIR_Opr dest) {
if (right->is_constant()) {
if (dest->is_single_cpu()) {
int simm13 = right->as_constant_ptr()->as_jint();
switch (code) {
case lir_logic_and: __ and3 (left->as_register(), simm13, dest->as_register()); break;
case lir_logic_or: __ or3 (left->as_register(), simm13, dest->as_register()); break;
case lir_logic_xor: __ xor3 (left->as_register(), simm13, dest->as_register()); break;
default: ShouldNotReachHere();
}
} else {
long c = right->as_constant_ptr()->as_jlong();
assert(c == (int)c && Assembler::is_simm13(c), "out of range");
int simm13 = (int)c;
switch (code) {
case lir_logic_and:
#ifndef _LP64
__ and3 (left->as_register_hi(), 0, dest->as_register_hi());
#endif
__ and3 (left->as_register_lo(), simm13, dest->as_register_lo());
break;
case lir_logic_or:
#ifndef _LP64
__ or3 (left->as_register_hi(), 0, dest->as_register_hi());
#endif
__ or3 (left->as_register_lo(), simm13, dest->as_register_lo());
break;
case lir_logic_xor:
#ifndef _LP64
__ xor3 (left->as_register_hi(), 0, dest->as_register_hi());
#endif
__ xor3 (left->as_register_lo(), simm13, dest->as_register_lo());
break;
default: ShouldNotReachHere();
}
}
} else {
assert(right->is_register(), "right should be in register");
if (dest->is_single_cpu()) {
switch (code) {
case lir_logic_and: __ and3 (left->as_register(), right->as_register(), dest->as_register()); break;
case lir_logic_or: __ or3 (left->as_register(), right->as_register(), dest->as_register()); break;
case lir_logic_xor: __ xor3 (left->as_register(), right->as_register(), dest->as_register()); break;
default: ShouldNotReachHere();
}
} else {
#ifdef _LP64
Register l = (left->is_single_cpu() && left->is_oop_register()) ? left->as_register() :
left->as_register_lo();
Register r = (right->is_single_cpu() && right->is_oop_register()) ? right->as_register() :
right->as_register_lo();
switch (code) {
case lir_logic_and: __ and3 (l, r, dest->as_register_lo()); break;
case lir_logic_or: __ or3 (l, r, dest->as_register_lo()); break;
case lir_logic_xor: __ xor3 (l, r, dest->as_register_lo()); break;
default: ShouldNotReachHere();
}
#else
switch (code) {
case lir_logic_and:
__ and3 (left->as_register_hi(), right->as_register_hi(), dest->as_register_hi());
__ and3 (left->as_register_lo(), right->as_register_lo(), dest->as_register_lo());
break;
case lir_logic_or:
__ or3 (left->as_register_hi(), right->as_register_hi(), dest->as_register_hi());
__ or3 (left->as_register_lo(), right->as_register_lo(), dest->as_register_lo());
break;
case lir_logic_xor:
__ xor3 (left->as_register_hi(), right->as_register_hi(), dest->as_register_hi());
__ xor3 (left->as_register_lo(), right->as_register_lo(), dest->as_register_lo());
break;
default: ShouldNotReachHere();
}
#endif
}
}
}
int LIR_Assembler::shift_amount(BasicType t) {
int elem_size = type2aelembytes(t);
switch (elem_size) {
case 1 : return 0;
case 2 : return 1;
case 4 : return 2;
case 8 : return 3;
}
ShouldNotReachHere();
return -1;
}
void LIR_Assembler::throw_op(LIR_Opr exceptionPC, LIR_Opr exceptionOop, CodeEmitInfo* info) {
assert(exceptionOop->as_register() == Oexception, "should match");
assert(exceptionPC->as_register() == Oissuing_pc, "should match");
info->add_register_oop(exceptionOop);
// reuse the debug info from the safepoint poll for the throw op itself
address pc_for_athrow = __ pc();
int pc_for_athrow_offset = __ offset();
RelocationHolder rspec = internal_word_Relocation::spec(pc_for_athrow);
__ set(pc_for_athrow, Oissuing_pc, rspec);
add_call_info(pc_for_athrow_offset, info); // for exception handler
__ call(Runtime1::entry_for(Runtime1::handle_exception_id), relocInfo::runtime_call_type);
__ delayed()->nop();
}
void LIR_Assembler::unwind_op(LIR_Opr exceptionOop) {
assert(exceptionOop->as_register() == Oexception, "should match");
__ br(Assembler::always, false, Assembler::pt, _unwind_handler_entry);
__ delayed()->nop();
}
void LIR_Assembler::emit_arraycopy(LIR_OpArrayCopy* op) {
Register src = op->src()->as_register();
Register dst = op->dst()->as_register();
Register src_pos = op->src_pos()->as_register();
Register dst_pos = op->dst_pos()->as_register();
Register length = op->length()->as_register();
Register tmp = op->tmp()->as_register();
Register tmp2 = O7;
int flags = op->flags();
ciArrayKlass* default_type = op->expected_type();
BasicType basic_type = default_type != NULL ? default_type->element_type()->basic_type() : T_ILLEGAL;
if (basic_type == T_ARRAY) basic_type = T_OBJECT;
// set up the arraycopy stub information
ArrayCopyStub* stub = op->stub();
// always do stub if no type information is available. it's ok if
// the known type isn't loaded since the code sanity checks
// in debug mode and the type isn't required when we know the exact type
// also check that the type is an array type.
// We also, for now, always call the stub if the barrier set requires a
// write_ref_pre barrier (which the stub does, but none of the optimized
// cases currently does).
if (op->expected_type() == NULL ||
Universe::heap()->barrier_set()->has_write_ref_pre_barrier()) {
__ mov(src, O0);
__ mov(src_pos, O1);
__ mov(dst, O2);
__ mov(dst_pos, O3);
__ mov(length, O4);
__ call_VM_leaf(tmp, CAST_FROM_FN_PTR(address, Runtime1::arraycopy));
__ br_zero(Assembler::less, false, Assembler::pn, O0, *stub->entry());
__ delayed()->nop();
__ bind(*stub->continuation());
return;
}
assert(default_type != NULL && default_type->is_array_klass(), "must be true at this point");
// make sure src and dst are non-null and load array length
if (flags & LIR_OpArrayCopy::src_null_check) {
__ tst(src);
__ br(Assembler::equal, false, Assembler::pn, *stub->entry());
__ delayed()->nop();
}
if (flags & LIR_OpArrayCopy::dst_null_check) {
__ tst(dst);
__ br(Assembler::equal, false, Assembler::pn, *stub->entry());
__ delayed()->nop();
}
if (flags & LIR_OpArrayCopy::src_pos_positive_check) {
// test src_pos register
__ tst(src_pos);
__ br(Assembler::less, false, Assembler::pn, *stub->entry());
__ delayed()->nop();
}
if (flags & LIR_OpArrayCopy::dst_pos_positive_check) {
// test dst_pos register
__ tst(dst_pos);
__ br(Assembler::less, false, Assembler::pn, *stub->entry());
__ delayed()->nop();
}
if (flags & LIR_OpArrayCopy::length_positive_check) {
// make sure length isn't negative
__ tst(length);
__ br(Assembler::less, false, Assembler::pn, *stub->entry());
__ delayed()->nop();
}
if (flags & LIR_OpArrayCopy::src_range_check) {
__ ld(src, arrayOopDesc::length_offset_in_bytes(), tmp2);
__ add(length, src_pos, tmp);
__ cmp(tmp2, tmp);
__ br(Assembler::carrySet, false, Assembler::pn, *stub->entry());
__ delayed()->nop();
}
if (flags & LIR_OpArrayCopy::dst_range_check) {
__ ld(dst, arrayOopDesc::length_offset_in_bytes(), tmp2);
__ add(length, dst_pos, tmp);
__ cmp(tmp2, tmp);
__ br(Assembler::carrySet, false, Assembler::pn, *stub->entry());
__ delayed()->nop();
}
if (flags & LIR_OpArrayCopy::type_check) {
__ ld_ptr(src, oopDesc::klass_offset_in_bytes(), tmp);
__ ld_ptr(dst, oopDesc::klass_offset_in_bytes(), tmp2);
__ cmp(tmp, tmp2);
__ br(Assembler::notEqual, false, Assembler::pt, *stub->entry());
__ delayed()->nop();
}
#ifdef ASSERT
if (basic_type != T_OBJECT || !(flags & LIR_OpArrayCopy::type_check)) {
// Sanity check the known type with the incoming class. For the
// primitive case the types must match exactly with src.klass and
// dst.klass each exactly matching the default type. For the
// object array case, if no type check is needed then either the
// dst type is exactly the expected type and the src type is a
// subtype which we can't check or src is the same array as dst
// but not necessarily exactly of type default_type.
Label known_ok, halt;
jobject2reg(op->expected_type()->constant_encoding(), tmp);
__ ld_ptr(dst, oopDesc::klass_offset_in_bytes(), tmp2);
if (basic_type != T_OBJECT) {
__ cmp(tmp, tmp2);
__ br(Assembler::notEqual, false, Assembler::pn, halt);
__ delayed()->ld_ptr(src, oopDesc::klass_offset_in_bytes(), tmp2);
__ cmp(tmp, tmp2);
__ br(Assembler::equal, false, Assembler::pn, known_ok);
__ delayed()->nop();
} else {
__ cmp(tmp, tmp2);
__ br(Assembler::equal, false, Assembler::pn, known_ok);
__ delayed()->cmp(src, dst);
__ br(Assembler::equal, false, Assembler::pn, known_ok);
__ delayed()->nop();
}
__ bind(halt);
__ stop("incorrect type information in arraycopy");
__ bind(known_ok);
}
#endif
int shift = shift_amount(basic_type);
Register src_ptr = O0;
Register dst_ptr = O1;
Register len = O2;
__ add(src, arrayOopDesc::base_offset_in_bytes(basic_type), src_ptr);
LP64_ONLY(__ sra(src_pos, 0, src_pos);) //higher 32bits must be null
if (shift == 0) {
__ add(src_ptr, src_pos, src_ptr);
} else {
__ sll(src_pos, shift, tmp);
__ add(src_ptr, tmp, src_ptr);
}
__ add(dst, arrayOopDesc::base_offset_in_bytes(basic_type), dst_ptr);
LP64_ONLY(__ sra(dst_pos, 0, dst_pos);) //higher 32bits must be null
if (shift == 0) {
__ add(dst_ptr, dst_pos, dst_ptr);
} else {
__ sll(dst_pos, shift, tmp);
__ add(dst_ptr, tmp, dst_ptr);
}
if (basic_type != T_OBJECT) {
if (shift == 0) {
__ mov(length, len);
} else {
__ sll(length, shift, len);
}
__ call_VM_leaf(tmp, CAST_FROM_FN_PTR(address, Runtime1::primitive_arraycopy));
} else {
// oop_arraycopy takes a length in number of elements, so don't scale it.
__ mov(length, len);
__ call_VM_leaf(tmp, CAST_FROM_FN_PTR(address, Runtime1::oop_arraycopy));
}
__ bind(*stub->continuation());
}
void LIR_Assembler::shift_op(LIR_Code code, LIR_Opr left, LIR_Opr count, LIR_Opr dest, LIR_Opr tmp) {
if (dest->is_single_cpu()) {
#ifdef _LP64
if (left->type() == T_OBJECT) {
switch (code) {
case lir_shl: __ sllx (left->as_register(), count->as_register(), dest->as_register()); break;
case lir_shr: __ srax (left->as_register(), count->as_register(), dest->as_register()); break;
case lir_ushr: __ srl (left->as_register(), count->as_register(), dest->as_register()); break;
default: ShouldNotReachHere();
}
} else
#endif
switch (code) {
case lir_shl: __ sll (left->as_register(), count->as_register(), dest->as_register()); break;
case lir_shr: __ sra (left->as_register(), count->as_register(), dest->as_register()); break;
case lir_ushr: __ srl (left->as_register(), count->as_register(), dest->as_register()); break;
default: ShouldNotReachHere();
}
} else {
#ifdef _LP64
switch (code) {
case lir_shl: __ sllx (left->as_register_lo(), count->as_register(), dest->as_register_lo()); break;
case lir_shr: __ srax (left->as_register_lo(), count->as_register(), dest->as_register_lo()); break;
case lir_ushr: __ srlx (left->as_register_lo(), count->as_register(), dest->as_register_lo()); break;
default: ShouldNotReachHere();
}
#else
switch (code) {
case lir_shl: __ lshl (left->as_register_hi(), left->as_register_lo(), count->as_register(), dest->as_register_hi(), dest->as_register_lo(), G3_scratch); break;
case lir_shr: __ lshr (left->as_register_hi(), left->as_register_lo(), count->as_register(), dest->as_register_hi(), dest->as_register_lo(), G3_scratch); break;
case lir_ushr: __ lushr (left->as_register_hi(), left->as_register_lo(), count->as_register(), dest->as_register_hi(), dest->as_register_lo(), G3_scratch); break;
default: ShouldNotReachHere();
}
#endif
}
}
void LIR_Assembler::shift_op(LIR_Code code, LIR_Opr left, jint count, LIR_Opr dest) {
#ifdef _LP64
if (left->type() == T_OBJECT) {
count = count & 63; // shouldn't shift by more than sizeof(intptr_t)
Register l = left->as_register();
Register d = dest->as_register_lo();
switch (code) {
case lir_shl: __ sllx (l, count, d); break;
case lir_shr: __ srax (l, count, d); break;
case lir_ushr: __ srlx (l, count, d); break;
default: ShouldNotReachHere();
}
return;
}
#endif
if (dest->is_single_cpu()) {
count = count & 0x1F; // Java spec
switch (code) {
case lir_shl: __ sll (left->as_register(), count, dest->as_register()); break;
case lir_shr: __ sra (left->as_register(), count, dest->as_register()); break;
case lir_ushr: __ srl (left->as_register(), count, dest->as_register()); break;
default: ShouldNotReachHere();
}
} else if (dest->is_double_cpu()) {
count = count & 63; // Java spec
switch (code) {
case lir_shl: __ sllx (left->as_pointer_register(), count, dest->as_pointer_register()); break;
case lir_shr: __ srax (left->as_pointer_register(), count, dest->as_pointer_register()); break;
case lir_ushr: __ srlx (left->as_pointer_register(), count, dest->as_pointer_register()); break;
default: ShouldNotReachHere();
}
} else {
ShouldNotReachHere();
}
}
void LIR_Assembler::emit_alloc_obj(LIR_OpAllocObj* op) {
assert(op->tmp1()->as_register() == G1 &&
op->tmp2()->as_register() == G3 &&
op->tmp3()->as_register() == G4 &&
op->obj()->as_register() == O0 &&
op->klass()->as_register() == G5, "must be");
if (op->init_check()) {
__ ld(op->klass()->as_register(),
instanceKlass::init_state_offset_in_bytes() + sizeof(oopDesc),
op->tmp1()->as_register());
add_debug_info_for_null_check_here(op->stub()->info());
__ cmp(op->tmp1()->as_register(), instanceKlass::fully_initialized);
__ br(Assembler::notEqual, false, Assembler::pn, *op->stub()->entry());
__ delayed()->nop();
}
__ allocate_object(op->obj()->as_register(),
op->tmp1()->as_register(),
op->tmp2()->as_register(),
op->tmp3()->as_register(),
op->header_size(),
op->object_size(),
op->klass()->as_register(),
*op->stub()->entry());
__ bind(*op->stub()->continuation());
__ verify_oop(op->obj()->as_register());
}
void LIR_Assembler::emit_alloc_array(LIR_OpAllocArray* op) {
assert(op->tmp1()->as_register() == G1 &&
op->tmp2()->as_register() == G3 &&
op->tmp3()->as_register() == G4 &&
op->tmp4()->as_register() == O1 &&
op->klass()->as_register() == G5, "must be");
if (UseSlowPath ||
(!UseFastNewObjectArray && (op->type() == T_OBJECT || op->type() == T_ARRAY)) ||
(!UseFastNewTypeArray && (op->type() != T_OBJECT && op->type() != T_ARRAY))) {
__ br(Assembler::always, false, Assembler::pt, *op->stub()->entry());
__ delayed()->nop();
} else {
__ allocate_array(op->obj()->as_register(),
op->len()->as_register(),
op->tmp1()->as_register(),
op->tmp2()->as_register(),
op->tmp3()->as_register(),
arrayOopDesc::header_size(op->type()),
type2aelembytes(op->type()),
op->klass()->as_register(),
*op->stub()->entry());
}
__ bind(*op->stub()->continuation());
}
void LIR_Assembler::emit_opTypeCheck(LIR_OpTypeCheck* op) {
LIR_Code code = op->code();
if (code == lir_store_check) {
Register value = op->object()->as_register();
Register array = op->array()->as_register();
Register k_RInfo = op->tmp1()->as_register();
Register klass_RInfo = op->tmp2()->as_register();
Register Rtmp1 = op->tmp3()->as_register();
__ verify_oop(value);
CodeStub* stub = op->stub();
Label done;
__ cmp(value, 0);
__ br(Assembler::equal, false, Assembler::pn, done);
__ delayed()->nop();
load(array, oopDesc::klass_offset_in_bytes(), k_RInfo, T_OBJECT, op->info_for_exception());
load(value, oopDesc::klass_offset_in_bytes(), klass_RInfo, T_OBJECT, NULL);
// get instance klass
load(k_RInfo, objArrayKlass::element_klass_offset_in_bytes() + sizeof(oopDesc), k_RInfo, T_OBJECT, NULL);
// perform the fast part of the checking logic
__ check_klass_subtype_fast_path(klass_RInfo, k_RInfo, Rtmp1, O7, &done, stub->entry(), NULL);
// call out-of-line instance of __ check_klass_subtype_slow_path(...):
assert(klass_RInfo == G3 && k_RInfo == G1, "incorrect call setup");
__ call(Runtime1::entry_for(Runtime1::slow_subtype_check_id), relocInfo::runtime_call_type);
__ delayed()->nop();
__ cmp(G3, 0);
__ br(Assembler::equal, false, Assembler::pn, *stub->entry());
__ delayed()->nop();
__ bind(done);
} else if (op->code() == lir_checkcast) {
// we always need a stub for the failure case.
CodeStub* stub = op->stub();
Register obj = op->object()->as_register();
Register k_RInfo = op->tmp1()->as_register();
Register klass_RInfo = op->tmp2()->as_register();
Register dst = op->result_opr()->as_register();
Register Rtmp1 = op->tmp3()->as_register();
ciKlass* k = op->klass();
if (obj == k_RInfo) {
k_RInfo = klass_RInfo;
klass_RInfo = obj;
}
if (op->profiled_method() != NULL) {
ciMethod* method = op->profiled_method();
int bci = op->profiled_bci();
// We need two temporaries to perform this operation on SPARC,
// so to keep things simple we perform a redundant test here
Label profile_done;
__ cmp(obj, 0);
__ br(Assembler::notEqual, false, Assembler::pn, profile_done);
__ delayed()->nop();
// Object is null; update methodDataOop
ciMethodData* md = method->method_data();
if (md == NULL) {
bailout("out of memory building methodDataOop");
return;
}
ciProfileData* data = md->bci_to_data(bci);
assert(data != NULL, "need data for checkcast");
assert(data->is_BitData(), "need BitData for checkcast");
Register mdo = k_RInfo;
Register data_val = Rtmp1;
jobject2reg(md->constant_encoding(), mdo);
int mdo_offset_bias = 0;
if (!Assembler::is_simm13(md->byte_offset_of_slot(data, DataLayout::header_offset()) + data->size_in_bytes())) {
// The offset is large so bias the mdo by the base of the slot so
// that the ld can use simm13s to reference the slots of the data
mdo_offset_bias = md->byte_offset_of_slot(data, DataLayout::header_offset());
__ set(mdo_offset_bias, data_val);
__ add(mdo, data_val, mdo);
}
Address flags_addr(mdo, md->byte_offset_of_slot(data, DataLayout::flags_offset()) - mdo_offset_bias);
__ ldub(flags_addr, data_val);
__ or3(data_val, BitData::null_seen_byte_constant(), data_val);
__ stb(data_val, flags_addr);
__ bind(profile_done);
}
Label done;
// patching may screw with our temporaries on sparc,
// so let's do it before loading the class
if (k->is_loaded()) {
jobject2reg(k->constant_encoding(), k_RInfo);
} else {
jobject2reg_with_patching(k_RInfo, op->info_for_patch());
}
assert(obj != k_RInfo, "must be different");
__ cmp(obj, 0);
__ br(Assembler::equal, false, Assembler::pn, done);
__ delayed()->nop();
// get object class
// not a safepoint as obj null check happens earlier
load(obj, oopDesc::klass_offset_in_bytes(), klass_RInfo, T_OBJECT, NULL);
if (op->fast_check()) {
assert_different_registers(klass_RInfo, k_RInfo);
__ cmp(k_RInfo, klass_RInfo);
__ br(Assembler::notEqual, false, Assembler::pt, *stub->entry());
__ delayed()->nop();
__ bind(done);
} else {
bool need_slow_path = true;
if (k->is_loaded()) {
if (k->super_check_offset() != sizeof(oopDesc) + Klass::secondary_super_cache_offset_in_bytes())
need_slow_path = false;
// perform the fast part of the checking logic
__ check_klass_subtype_fast_path(klass_RInfo, k_RInfo, Rtmp1, noreg,
(need_slow_path ? &done : NULL),
stub->entry(), NULL,
RegisterOrConstant(k->super_check_offset()));
} else {
// perform the fast part of the checking logic
__ check_klass_subtype_fast_path(klass_RInfo, k_RInfo, Rtmp1, O7,
&done, stub->entry(), NULL);
}
if (need_slow_path) {
// call out-of-line instance of __ check_klass_subtype_slow_path(...):
assert(klass_RInfo == G3 && k_RInfo == G1, "incorrect call setup");
__ call(Runtime1::entry_for(Runtime1::slow_subtype_check_id), relocInfo::runtime_call_type);
__ delayed()->nop();
__ cmp(G3, 0);
__ br(Assembler::equal, false, Assembler::pn, *stub->entry());
__ delayed()->nop();
}
__ bind(done);
}
__ mov(obj, dst);
} else if (code == lir_instanceof) {
Register obj = op->object()->as_register();
Register k_RInfo = op->tmp1()->as_register();
Register klass_RInfo = op->tmp2()->as_register();
Register dst = op->result_opr()->as_register();
Register Rtmp1 = op->tmp3()->as_register();
ciKlass* k = op->klass();
Label done;
if (obj == k_RInfo) {
k_RInfo = klass_RInfo;
klass_RInfo = obj;
}
// patching may screw with our temporaries on sparc,
// so let's do it before loading the class
if (k->is_loaded()) {
jobject2reg(k->constant_encoding(), k_RInfo);
} else {
jobject2reg_with_patching(k_RInfo, op->info_for_patch());
}
assert(obj != k_RInfo, "must be different");
__ cmp(obj, 0);
__ br(Assembler::equal, true, Assembler::pn, done);
__ delayed()->set(0, dst);
// get object class
// not a safepoint as obj null check happens earlier
load(obj, oopDesc::klass_offset_in_bytes(), klass_RInfo, T_OBJECT, NULL);
if (op->fast_check()) {
__ cmp(k_RInfo, klass_RInfo);
__ br(Assembler::equal, true, Assembler::pt, done);
__ delayed()->set(1, dst);
__ set(0, dst);
__ bind(done);
} else {
bool need_slow_path = true;
if (k->is_loaded()) {
if (k->super_check_offset() != sizeof(oopDesc) + Klass::secondary_super_cache_offset_in_bytes())
need_slow_path = false;
// perform the fast part of the checking logic
__ check_klass_subtype_fast_path(klass_RInfo, k_RInfo, O7, noreg,
(need_slow_path ? &done : NULL),
(need_slow_path ? &done : NULL), NULL,
RegisterOrConstant(k->super_check_offset()),
dst);
} else {
assert(dst != klass_RInfo && dst != k_RInfo, "need 3 registers");
// perform the fast part of the checking logic
__ check_klass_subtype_fast_path(klass_RInfo, k_RInfo, O7, dst,
&done, &done, NULL,
RegisterOrConstant(-1),
dst);
}
if (need_slow_path) {
// call out-of-line instance of __ check_klass_subtype_slow_path(...):
assert(klass_RInfo == G3 && k_RInfo == G1, "incorrect call setup");
__ call(Runtime1::entry_for(Runtime1::slow_subtype_check_id), relocInfo::runtime_call_type);
__ delayed()->nop();
__ mov(G3, dst);
}
__ bind(done);
}
} else {
ShouldNotReachHere();
}
}
void LIR_Assembler::emit_compare_and_swap(LIR_OpCompareAndSwap* op) {
if (op->code() == lir_cas_long) {
assert(VM_Version::supports_cx8(), "wrong machine");
Register addr = op->addr()->as_pointer_register();
Register cmp_value_lo = op->cmp_value()->as_register_lo();
Register cmp_value_hi = op->cmp_value()->as_register_hi();
Register new_value_lo = op->new_value()->as_register_lo();
Register new_value_hi = op->new_value()->as_register_hi();
Register t1 = op->tmp1()->as_register();
Register t2 = op->tmp2()->as_register();
#ifdef _LP64
__ mov(cmp_value_lo, t1);
__ mov(new_value_lo, t2);
#else
// move high and low halves of long values into single registers
__ sllx(cmp_value_hi, 32, t1); // shift high half into temp reg
__ srl(cmp_value_lo, 0, cmp_value_lo); // clear upper 32 bits of low half
__ or3(t1, cmp_value_lo, t1); // t1 holds 64-bit compare value
__ sllx(new_value_hi, 32, t2);
__ srl(new_value_lo, 0, new_value_lo);
__ or3(t2, new_value_lo, t2); // t2 holds 64-bit value to swap
#endif
// perform the compare and swap operation
__ casx(addr, t1, t2);
// generate condition code - if the swap succeeded, t2 ("new value" reg) was
// overwritten with the original value in "addr" and will be equal to t1.
__ cmp(t1, t2);
} else if (op->code() == lir_cas_int || op->code() == lir_cas_obj) {
Register addr = op->addr()->as_pointer_register();
Register cmp_value = op->cmp_value()->as_register();
Register new_value = op->new_value()->as_register();
Register t1 = op->tmp1()->as_register();
Register t2 = op->tmp2()->as_register();
__ mov(cmp_value, t1);
__ mov(new_value, t2);
#ifdef _LP64
if (op->code() == lir_cas_obj) {
__ casx(addr, t1, t2);
} else
#endif
{
__ cas(addr, t1, t2);
}
__ cmp(t1, t2);
} else {
Unimplemented();
}
}
void LIR_Assembler::set_24bit_FPU() {
Unimplemented();
}
void LIR_Assembler::reset_FPU() {
Unimplemented();
}
void LIR_Assembler::breakpoint() {
__ breakpoint_trap();
}
void LIR_Assembler::push(LIR_Opr opr) {
Unimplemented();
}
void LIR_Assembler::pop(LIR_Opr opr) {
Unimplemented();
}
void LIR_Assembler::monitor_address(int monitor_no, LIR_Opr dst_opr) {
Address mon_addr = frame_map()->address_for_monitor_lock(monitor_no);
Register dst = dst_opr->as_register();
Register reg = mon_addr.base();
int offset = mon_addr.disp();
// compute pointer to BasicLock
if (mon_addr.is_simm13()) {
__ add(reg, offset, dst);
} else {
__ set(offset, dst);
__ add(dst, reg, dst);
}
}
void LIR_Assembler::emit_lock(LIR_OpLock* op) {
Register obj = op->obj_opr()->as_register();
Register hdr = op->hdr_opr()->as_register();
Register lock = op->lock_opr()->as_register();
// obj may not be an oop
if (op->code() == lir_lock) {
MonitorEnterStub* stub = (MonitorEnterStub*)op->stub();
if (UseFastLocking) {
assert(BasicLock::displaced_header_offset_in_bytes() == 0, "lock_reg must point to the displaced header");
// add debug info for NullPointerException only if one is possible
if (op->info() != NULL) {
add_debug_info_for_null_check_here(op->info());
}
__ lock_object(hdr, obj, lock, op->scratch_opr()->as_register(), *op->stub()->entry());
} else {
// always do slow locking
// note: the slow locking code could be inlined here, however if we use
// slow locking, speed doesn't matter anyway and this solution is
// simpler and requires less duplicated code - additionally, the
// slow locking code is the same in either case which simplifies
// debugging
__ br(Assembler::always, false, Assembler::pt, *op->stub()->entry());
__ delayed()->nop();
}
} else {
assert (op->code() == lir_unlock, "Invalid code, expected lir_unlock");
if (UseFastLocking) {
assert(BasicLock::displaced_header_offset_in_bytes() == 0, "lock_reg must point to the displaced header");
__ unlock_object(hdr, obj, lock, *op->stub()->entry());
} else {
// always do slow unlocking
// note: the slow unlocking code could be inlined here, however if we use
// slow unlocking, speed doesn't matter anyway and this solution is
// simpler and requires less duplicated code - additionally, the
// slow unlocking code is the same in either case which simplifies
// debugging
__ br(Assembler::always, false, Assembler::pt, *op->stub()->entry());
__ delayed()->nop();
}
}
__ bind(*op->stub()->continuation());
}
void LIR_Assembler::emit_profile_call(LIR_OpProfileCall* op) {
ciMethod* method = op->profiled_method();
int bci = op->profiled_bci();
// Update counter for all call types
ciMethodData* md = method->method_data();
if (md == NULL) {
bailout("out of memory building methodDataOop");
return;
}
ciProfileData* data = md->bci_to_data(bci);
assert(data->is_CounterData(), "need CounterData for calls");
assert(op->mdo()->is_single_cpu(), "mdo must be allocated");
assert(op->tmp1()->is_single_cpu(), "tmp1 must be allocated");
Register mdo = op->mdo()->as_register();
Register tmp1 = op->tmp1()->as_register();
jobject2reg(md->constant_encoding(), mdo);
int mdo_offset_bias = 0;
if (!Assembler::is_simm13(md->byte_offset_of_slot(data, CounterData::count_offset()) +
data->size_in_bytes())) {
// The offset is large so bias the mdo by the base of the slot so
// that the ld can use simm13s to reference the slots of the data
mdo_offset_bias = md->byte_offset_of_slot(data, CounterData::count_offset());
__ set(mdo_offset_bias, O7);
__ add(mdo, O7, mdo);
}
Address counter_addr(mdo, md->byte_offset_of_slot(data, CounterData::count_offset()) - mdo_offset_bias);
Bytecodes::Code bc = method->java_code_at_bci(bci);
// Perform additional virtual call profiling for invokevirtual and
// invokeinterface bytecodes
if ((bc == Bytecodes::_invokevirtual || bc == Bytecodes::_invokeinterface) &&
Tier1ProfileVirtualCalls) {
assert(op->recv()->is_single_cpu(), "recv must be allocated");
Register recv = op->recv()->as_register();
assert_different_registers(mdo, tmp1, recv);
assert(data->is_VirtualCallData(), "need VirtualCallData for virtual calls");
ciKlass* known_klass = op->known_holder();
if (Tier1OptimizeVirtualCallProfiling && known_klass != NULL) {
// We know the type that will be seen at this call site; we can
// statically update the methodDataOop rather than needing to do
// dynamic tests on the receiver type
// NOTE: we should probably put a lock around this search to
// avoid collisions by concurrent compilations
ciVirtualCallData* vc_data = (ciVirtualCallData*) data;
uint i;
for (i = 0; i < VirtualCallData::row_limit(); i++) {
ciKlass* receiver = vc_data->receiver(i);
if (known_klass->equals(receiver)) {
Address data_addr(mdo, md->byte_offset_of_slot(data,
VirtualCallData::receiver_count_offset(i)) -
mdo_offset_bias);
__ lduw(data_addr, tmp1);
__ add(tmp1, DataLayout::counter_increment, tmp1);
__ stw(tmp1, data_addr);
return;
}
}
// Receiver type not found in profile data; select an empty slot
// Note that this is less efficient than it should be because it
// always does a write to the receiver part of the
// VirtualCallData rather than just the first time
for (i = 0; i < VirtualCallData::row_limit(); i++) {
ciKlass* receiver = vc_data->receiver(i);
if (receiver == NULL) {
Address recv_addr(mdo, md->byte_offset_of_slot(data, VirtualCallData::receiver_offset(i)) -
mdo_offset_bias);
jobject2reg(known_klass->constant_encoding(), tmp1);
__ st_ptr(tmp1, recv_addr);
Address data_addr(mdo, md->byte_offset_of_slot(data, VirtualCallData::receiver_count_offset(i)) -
mdo_offset_bias);
__ lduw(data_addr, tmp1);
__ add(tmp1, DataLayout::counter_increment, tmp1);
__ stw(tmp1, data_addr);
return;
}
}
} else {
load(Address(recv, oopDesc::klass_offset_in_bytes()), recv, T_OBJECT);
Label update_done;
uint i;
for (i = 0; i < VirtualCallData::row_limit(); i++) {
Label next_test;
// See if the receiver is receiver[n].
Address receiver_addr(mdo, md->byte_offset_of_slot(data, VirtualCallData::receiver_offset(i)) -
mdo_offset_bias);
__ ld_ptr(receiver_addr, tmp1);
__ verify_oop(tmp1);
__ cmp(recv, tmp1);
__ brx(Assembler::notEqual, false, Assembler::pt, next_test);
__ delayed()->nop();
Address data_addr(mdo, md->byte_offset_of_slot(data, VirtualCallData::receiver_count_offset(i)) -
mdo_offset_bias);
__ lduw(data_addr, tmp1);
__ add(tmp1, DataLayout::counter_increment, tmp1);
__ stw(tmp1, data_addr);
__ br(Assembler::always, false, Assembler::pt, update_done);
__ delayed()->nop();
__ bind(next_test);
}
// Didn't find receiver; find next empty slot and fill it in
for (i = 0; i < VirtualCallData::row_limit(); i++) {
Label next_test;
Address recv_addr(mdo, md->byte_offset_of_slot(data, VirtualCallData::receiver_offset(i)) -
mdo_offset_bias);
load(recv_addr, tmp1, T_OBJECT);
__ tst(tmp1);
__ brx(Assembler::notEqual, false, Assembler::pt, next_test);
__ delayed()->nop();
__ st_ptr(recv, recv_addr);
__ set(DataLayout::counter_increment, tmp1);
__ st_ptr(tmp1, mdo, md->byte_offset_of_slot(data, VirtualCallData::receiver_count_offset(i)) -
mdo_offset_bias);
__ br(Assembler::always, false, Assembler::pt, update_done);
__ delayed()->nop();
__ bind(next_test);
}
// Receiver did not match any saved receiver and there is no empty row for it.
// Increment total counter to indicate polymorphic case.
__ lduw(counter_addr, tmp1);
__ add(tmp1, DataLayout::counter_increment, tmp1);
__ stw(tmp1, counter_addr);
__ bind(update_done);
}
} else {
// Static call
__ lduw(counter_addr, tmp1);
__ add(tmp1, DataLayout::counter_increment, tmp1);
__ stw(tmp1, counter_addr);
}
}
void LIR_Assembler::align_backward_branch_target() {
__ align(OptoLoopAlignment);
}
void LIR_Assembler::emit_delay(LIR_OpDelay* op) {
// make sure we are expecting a delay
// this has the side effect of clearing the delay state
// so we can use _masm instead of _masm->delayed() to do the
// code generation.
__ delayed();
// make sure we only emit one instruction
int offset = code_offset();
op->delay_op()->emit_code(this);
#ifdef ASSERT
if (code_offset() - offset != NativeInstruction::nop_instruction_size) {
op->delay_op()->print();
}
assert(code_offset() - offset == NativeInstruction::nop_instruction_size,
"only one instruction can go in a delay slot");
#endif
// we may also be emitting the call info for the instruction
// which we are the delay slot of.
CodeEmitInfo* call_info = op->call_info();
if (call_info) {
add_call_info(code_offset(), call_info);
}
if (VerifyStackAtCalls) {
_masm->sub(FP, SP, O7);
_masm->cmp(O7, initial_frame_size_in_bytes());
_masm->trap(Assembler::notEqual, Assembler::ptr_cc, G0, ST_RESERVED_FOR_USER_0+2 );
}
}
void LIR_Assembler::negate(LIR_Opr left, LIR_Opr dest) {
assert(left->is_register(), "can only handle registers");
if (left->is_single_cpu()) {
__ neg(left->as_register(), dest->as_register());
} else if (left->is_single_fpu()) {
__ fneg(FloatRegisterImpl::S, left->as_float_reg(), dest->as_float_reg());
} else if (left->is_double_fpu()) {
__ fneg(FloatRegisterImpl::D, left->as_double_reg(), dest->as_double_reg());
} else {
assert (left->is_double_cpu(), "Must be a long");
Register Rlow = left->as_register_lo();
Register Rhi = left->as_register_hi();
#ifdef _LP64
__ sub(G0, Rlow, dest->as_register_lo());
#else
__ subcc(G0, Rlow, dest->as_register_lo());
__ subc (G0, Rhi, dest->as_register_hi());
#endif
}
}
void LIR_Assembler::fxch(int i) {
Unimplemented();
}
void LIR_Assembler::fld(int i) {
Unimplemented();
}
void LIR_Assembler::ffree(int i) {
Unimplemented();
}
void LIR_Assembler::rt_call(LIR_Opr result, address dest,
const LIR_OprList* args, LIR_Opr tmp, CodeEmitInfo* info) {
// if tmp is invalid, then the function being called doesn't destroy the thread
if (tmp->is_valid()) {
__ save_thread(tmp->as_register());
}
__ call(dest, relocInfo::runtime_call_type);
__ delayed()->nop();
if (info != NULL) {
add_call_info_here(info);
}
if (tmp->is_valid()) {
__ restore_thread(tmp->as_register());
}
#ifdef ASSERT
__ verify_thread();
#endif // ASSERT
}
void LIR_Assembler::volatile_move_op(LIR_Opr src, LIR_Opr dest, BasicType type, CodeEmitInfo* info) {
#ifdef _LP64
ShouldNotReachHere();
#endif
NEEDS_CLEANUP;
if (type == T_LONG) {
LIR_Address* mem_addr = dest->is_address() ? dest->as_address_ptr() : src->as_address_ptr();
// (extended to allow indexed as well as constant displaced for JSR-166)
Register idx = noreg; // contains either constant offset or index
int disp = mem_addr->disp();
if (mem_addr->index() == LIR_OprFact::illegalOpr) {
if (!Assembler::is_simm13(disp)) {
idx = O7;
__ set(disp, idx);
}
} else {
assert(disp == 0, "not both indexed and disp");
idx = mem_addr->index()->as_register();
}
int null_check_offset = -1;
Register base = mem_addr->base()->as_register();
if (src->is_register() && dest->is_address()) {
// G4 is high half, G5 is low half
if (VM_Version::v9_instructions_work()) {
// clear the top bits of G5, and scale up G4
__ srl (src->as_register_lo(), 0, G5);
__ sllx(src->as_register_hi(), 32, G4);
// combine the two halves into the 64 bits of G4
__ or3(G4, G5, G4);
null_check_offset = __ offset();
if (idx == noreg) {
__ stx(G4, base, disp);
} else {
__ stx(G4, base, idx);
}
} else {
__ mov (src->as_register_hi(), G4);
__ mov (src->as_register_lo(), G5);
null_check_offset = __ offset();
if (idx == noreg) {
__ std(G4, base, disp);
} else {
__ std(G4, base, idx);
}
}
} else if (src->is_address() && dest->is_register()) {
null_check_offset = __ offset();
if (VM_Version::v9_instructions_work()) {
if (idx == noreg) {
__ ldx(base, disp, G5);
} else {
__ ldx(base, idx, G5);
}
__ srax(G5, 32, dest->as_register_hi()); // fetch the high half into hi
__ mov (G5, dest->as_register_lo()); // copy low half into lo
} else {
if (idx == noreg) {
__ ldd(base, disp, G4);
} else {
__ ldd(base, idx, G4);
}
// G4 is high half, G5 is low half
__ mov (G4, dest->as_register_hi());
__ mov (G5, dest->as_register_lo());
}
} else {
Unimplemented();
}
if (info != NULL) {
add_debug_info_for_null_check(null_check_offset, info);
}
} else {
// use normal move for all other volatiles since they don't need
// special handling to remain atomic.
move_op(src, dest, type, lir_patch_none, info, false, false);
}
}
void LIR_Assembler::membar() {
// only StoreLoad membars are ever explicitly needed on sparcs in TSO mode
__ membar( Assembler::Membar_mask_bits(Assembler::StoreLoad) );
}
void LIR_Assembler::membar_acquire() {
// no-op on TSO
}
void LIR_Assembler::membar_release() {
// no-op on TSO
}
// Macro to Pack two sequential registers containing 32 bit values
// into a single 64 bit register.
// rs and rs->successor() are packed into rd
// rd and rs may be the same register.
// Note: rs and rs->successor() are destroyed.
void LIR_Assembler::pack64( Register rs, Register rd ) {
__ sllx(rs, 32, rs);
__ srl(rs->successor(), 0, rs->successor());
__ or3(rs, rs->successor(), rd);
}
// Macro to unpack a 64 bit value in a register into
// two sequential registers.
// rd is unpacked into rd and rd->successor()
void LIR_Assembler::unpack64( Register rd ) {
__ mov(rd, rd->successor());
__ srax(rd, 32, rd);
__ sra(rd->successor(), 0, rd->successor());
}
void LIR_Assembler::leal(LIR_Opr addr_opr, LIR_Opr dest) {
LIR_Address* addr = addr_opr->as_address_ptr();
assert(addr->index()->is_illegal() && addr->scale() == LIR_Address::times_1 && Assembler::is_simm13(addr->disp()), "can't handle complex addresses yet");
__ add(addr->base()->as_register(), addr->disp(), dest->as_register());
}
void LIR_Assembler::get_thread(LIR_Opr result_reg) {
assert(result_reg->is_register(), "check");
__ mov(G2_thread, result_reg->as_register());
}
void LIR_Assembler::peephole(LIR_List* lir) {
LIR_OpList* inst = lir->instructions_list();
for (int i = 0; i < inst->length(); i++) {
LIR_Op* op = inst->at(i);
switch (op->code()) {
case lir_cond_float_branch:
case lir_branch: {
LIR_OpBranch* branch = op->as_OpBranch();
assert(branch->info() == NULL, "shouldn't be state on branches anymore");
LIR_Op* delay_op = NULL;
// we'd like to be able to pull following instructions into
// this slot but we don't know enough to do it safely yet so
// only optimize block to block control flow.
if (LIRFillDelaySlots && branch->block()) {
LIR_Op* prev = inst->at(i - 1);
if (prev && LIR_Assembler::is_single_instruction(prev) && prev->info() == NULL) {
// swap previous instruction into delay slot
inst->at_put(i - 1, op);
inst->at_put(i, new LIR_OpDelay(prev, op->info()));
#ifndef PRODUCT
if (LIRTracePeephole) {
tty->print_cr("delayed");
inst->at(i - 1)->print();
inst->at(i)->print();
tty->cr();
}
#endif
continue;
}
}
if (!delay_op) {
delay_op = new LIR_OpDelay(new LIR_Op0(lir_nop), NULL);
}
inst->insert_before(i + 1, delay_op);
break;
}
case lir_static_call:
case lir_virtual_call:
case lir_icvirtual_call:
case lir_optvirtual_call:
case lir_dynamic_call: {
LIR_Op* prev = inst->at(i - 1);
if (LIRFillDelaySlots && prev && prev->code() == lir_move && prev->info() == NULL &&
(op->code() != lir_virtual_call ||
!prev->result_opr()->is_single_cpu() ||
prev->result_opr()->as_register() != O0) &&
LIR_Assembler::is_single_instruction(prev)) {
// Only moves without info can be put into the delay slot.
// Also don't allow the setup of the receiver in the delay
// slot for vtable calls.
inst->at_put(i - 1, op);
inst->at_put(i, new LIR_OpDelay(prev, op->info()));
#ifndef PRODUCT
if (LIRTracePeephole) {
tty->print_cr("delayed");
inst->at(i - 1)->print();
inst->at(i)->print();
tty->cr();
}
#endif
continue;
}
LIR_Op* delay_op = new LIR_OpDelay(new LIR_Op0(lir_nop), op->as_OpJavaCall()->info());
inst->insert_before(i + 1, delay_op);
break;
}
}
}
}
#undef __
| gpl-2.0 |
uannight/reposan | plugin.video.tvalacarta/channels/rtspan.py | 9055 | # -*- coding: utf-8 -*-
#------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Canal para rtspan
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os, sys
from core import logger
from core import config
from core import scrapertools
from core.item import Item
from servers import servertools
__channel__ = "rtspan"
__category__ = "F"
__type__ = "generic"
__title__ = "rtspan"
__language__ = "ES"
__creationdate__ = "20121212"
__vfanart__ = ""
PROGRAMAS_URL = "http://actualidad.rt.com/programas"
VIDEOS_URL = "http://actualidad.rt.com/video"
DEBUG = config.get_setting("debug")
def isGeneric():
return True
def mainlist(item):
logger.info("tvalacarta.channels.rtspan mainlist")
itemlist = []
itemlist.append( Item(channel=__channel__, title="Todos los programas", action="programas", url=PROGRAMAS_URL, fanart = __vfanart__))
itemlist.append( Item(channel=__channel__, title="Últimos vídeos", action="episodios", url=VIDEOS_URL, fanart = __vfanart__))
return itemlist
def programas(item):
logger.info("tvalacarta.channels.rtspan programas")
itemlist = []
# Descarga la lista de canales
if item.url=="":
item.url = PROGRAMAS_URL
data = scrapertools.cache_page(item.url)
#logger.info("data="+data)
'''
<a href="/programas/zoom" class="ration_16-9 bg-img " style="background-image: url('https://esp.rt.com/actualidad/public_images/2015.08/original/55c0cba3c46188265e8b458a.jpg');">
</a>
</div>
<p class="watches watches_bg-black">
<span class="watches__counter" data-component="CounterEye" onclick=" return {
publicId: '182111'
};"></span>
</p>
<div class="summary js-programs-summary">
<div class="summary-wrapper">
<h3 class="header">
<a href="/programas/zoom">
El Zoom
</a>
</h3>
<p>
<a href="/programas/zoom">
¿Qué nos pretenden enseñar las fotos del actual escenario internacional? ¿Están retocadas, trucadas o desenfocadas? ¿Qué imagen nos quieren mostrar?...
</a>
</p>
</div>
</div>
<span class="js-programs-info icon-i">
i
</span>
</div>
'''
patron = '<a href="([^"]+)" class="ration_16-9[^"]+" style="background-image: url\('
patron += "'([^']+)'\)[^<]+"
patron += '</a[^<]+'
patron += '</div[^<]+'
patron += '<p class="watches watches_bg-black"[^<]+'
patron += '<span[^<]+</span[^<]+'
patron += '</p[^<]+'
patron += '<div class="summary js-programs-summary"[^<]+'
patron += '<div class="summary-wrapper"[^<]+'
patron += '<h3 class="header"[^<]+'
patron += '<a[^>]+>([^<]+)</a[^<]+'
patron += '</h3[^<]+'
patron += '<p[^<]+'
patron += '<a[^>]+>([^<]+)</a>'
matches = re.compile(patron,re.DOTALL).findall(data)
if DEBUG: scrapertools.printMatches(matches)
for scrapedurl,scrapedthumbnail,scrapedtitle,scrapedplot in matches:
title = scrapedtitle.strip()
url = urlparse.urljoin(item.url,scrapedurl)
thumbnail = scrapedthumbnail
plot = scrapertools.htmlclean(scrapedplot).strip()
if (DEBUG): logger.info("title=["+title+"], url=["+url+"], thumbnail=["+thumbnail+"]")
itemlist.append( Item(channel=__channel__, title=title , action="videos" , url=url, thumbnail=thumbnail, fanart=thumbnail, plot=plot , show = title , viewmode="movie_with_plot" , folder=True) )
return itemlist
def episodios(item):
logger.info("tvalacarta.channels.rtspan episodios")
itemlist = []
data = scrapertools.cachePage(item.url)
patron = '<figure class="media">.*?'
patron += '<a href="([^"]+)".*?'
patron += '<img src="([^"]+)".*?'
patron += '<time class="date">([^<]+)</time.*?'
patron += '<h3[^<]+'
patron += '<a[^>]+>([^<]+)</a'
matches = re.compile(patron,re.DOTALL).findall(data)
if DEBUG: scrapertools.printMatches(matches)
for scrapedurl,scrapedthumbnail,fecha,scrapedtitle in matches:
scrapedday = scrapertools.find_single_match(fecha,'(\d+)\.\d+\.\d+')
scrapedmonth = scrapertools.find_single_match(fecha,'\d+\.(\d+)\.\d+')
scrapedyear = scrapertools.find_single_match(fecha,'\d+\.\d+\.(\d+)')
scrapeddate = scrapedyear + "-" + scrapedmonth + "-" + scrapedday
title = fecha.strip() + " - " + scrapedtitle.strip()
url = urlparse.urljoin(item.url,scrapedurl)
thumbnail = scrapedthumbnail
itemlist.append( Item(channel=__channel__, action="play", title=title, url=url, thumbnail=thumbnail, aired_date=scrapeddate, folder=False) )
next_page_url = scrapertools.find_single_match(data,'<button class="button-grey js-listing-more".*?data-href="([^"]+)">')
if next_page_url!="":
itemlist.append( Item(channel=__channel__, action="episodios", title=">> Página siguiente" , url=urlparse.urljoin(item.url,next_page_url) , folder=True) )
return itemlist
def detalle_episodio(item):
data = scrapertools.cache_page(item.url)
item.plot = scrapertools.htmlclean(scrapertools.find_single_match(data,'<meta property="og:description" content="([^"]+)"')).strip()
item.thumbnail = scrapertools.find_single_match(data,'<meta property="og:image" content="([^"]+)"')
item.geolocked = "0"
item.aired_date = scrapertools.find_single_match(data,'<meta name="publish-date" content="([^\s]+)')
media_item = play(item)
try:
item.media_url = media_item[0].url
except:
import traceback
print traceback.format_exc()
item.media_url = ""
return item
def videos(item, load_all_pages=False):
logger.info("tvalacarta.channels.rtspan videos")
itemlist = []
'''
<div class="cover">
<a href="/programas/keiser_report/223832-eeuu-estado-puerto-rico" class="cover__media bg-img cover__media_ratio cover__image_type_video-normal"
style="background-image: url('https://esp.rt.com/actualidad/public_images/2016.11/thumbnail/582d9f22c461884a098b45b3.jpg');">
</a>
</div>
</div>
<div class="card__heading card__heading_all-news">
<a class="link " href="/programas/keiser_report/223832-eeuu-estado-puerto-rico">
¿Tendrá pronto EE. UU. un 51.º estado?
</a></div><div class="card__date-time card__date-time_all-news"><time class="date ">
17 noviembre 2016 | 14:19
</time>
'''
data = scrapertools.cachePage(item.url)
patron = '<div class="cover"[^<]+'
patron += '<a href="([^"]+)".*?'
patron += "url\('([^']+)'.*?"
patron += '<a class="link[^>]+>([^<]+)</a'
matches = re.compile(patron,re.DOTALL).findall(data)
if DEBUG: scrapertools.printMatches(matches)
for scrapedurl,scrapedthumbnail,scrapedtitle in matches:
title = scrapedtitle.strip()
url = urlparse.urljoin(item.url,scrapedurl)
thumbnail = scrapedthumbnail
plot = ""
itemlist.append( Item(channel=__channel__, action="play", title=title, url=url, thumbnail=thumbnail, show=item.show, folder=False) )
next_page_url = scrapertools.find_single_match(data,'<div class="listing__button listing__button_all-news listing__button_js" data-href="([^"]+)"')
if next_page_url!="":
next_page_item = Item(channel=__channel__, action="videos", title=">> Página siguiente" , url=urlparse.urljoin(item.url,next_page_url) , show=item.show, folder=True)
if load_all_pages:
itemlist.extend(videos(next_page_item,load_all_pages))
else:
itemlist.append(next_page_item)
return itemlist
def play(item):
logger.info("tvalacarta.channels.rtspan play")
itemlist = []
data = scrapertools.cachePage(item.url)
video_url = scrapertools.find_single_match(data,'www.youtube.com/embed/([^"]+)"')
if video_url!="":
itemlist.append( Item(channel=__channel__, action="play", server="youtube", title=item.title , url="http://www.youtube.com/watch?v="+video_url , folder=False) )
else:
video_url = scrapertools.find_single_match(data,'href="([^"]+)">Descargar video</a>')
if video_url!="":
itemlist.append( Item(channel=__channel__, action="play", server="directo", title=item.title , url=video_url , folder=False) )
else:
video_url = scrapertools.find_single_match(data,'file\:\s+"([^"]+)"')
itemlist.append( Item(channel=__channel__, action="play", server="directo", title=item.title , url=video_url , folder=False) )
return itemlist
def test():
# Al entrar sale una lista de programas
programas_items = mainlist(Item())
if len(programas_items)==0:
print "No devuelve programas"
return False
videos_items = videos(programas_items[0])
if len(videos_items)==1:
print "No devuelve videos en "+programas_items[0].title
return False
return True
| gpl-2.0 |
koalakoker/PGap | TextBuffer2HTMLConvert.py | 3852 | '''
Created on 02/giu/2015
@author: koala
'''
import os
typeTag = {"Bold": 0, "Underline": 1, "Italic": 2}
statusTag = [False, False, False]
HTMLTagsOpen = ["<b>","<u>","<i>"]
HTMLTagsClose = ["</b>", "</u>" ,"</i>"]
XML_SEPARATOR = "##@@##"
def getTagNames(tags):
currentTag = []
for t in tags:
currentTag.append(t.get_property("name"))
return currentTag
def iterNext(textBuffer, start, end, istr):
# print ("iter start = " + str(start.get_offset()) + " end = " + str(end.get_offset()))
if (start.get_offset() >= end.get_offset()):
return istr
tags = getTagNames(start.get_tags())
for tag in typeTag:
if (statusTag[typeTag[tag]]):
if not tag in tags:
istr += HTMLTagsClose[typeTag[tag]] #"</" + tag + ">"
statusTag[typeTag[tag]] = False
for name in tags:
if not (statusTag[typeTag[name]]):
istr += HTMLTagsOpen[typeTag[name]] # "<" + name + ">"
statusTag[typeTag[name]] = True
pnext = start.copy()
pnext.forward_to_tag_toggle(None)
istr += start.get_text(pnext)
return iterNext(textBuffer, pnext, end, istr)
def toHTML(textBuffer, start = None, end = None):
if (start == None):
start = textBuffer.get_start_iter()
if (end == None):
end = textBuffer.get_end_iter()
outStr = """ <!DOCTYPE HTML>
<html>
<head>
<title>Generated HTM file</title>
</head>
<body>"""
outStr += iterNext(textBuffer, start, end, "").replace(os.linesep, '<br>')
outStr += """</body>
</html> """
return outStr
def serialize(textBuffer, start = None, end = None):
if (start == None):
start = textBuffer.get_start_iter()
if (end == None):
end = textBuffer.get_end_iter()
myFormat = textBuffer.register_serialize_tagset('my-tagset')
exported = textBuffer.serialize(textBuffer, myFormat, start, end)
preambleTxt = exported[:26]
#lenTxt = strToInt(exported[26:30])
#skip exported[26:29] beacuse it is binay = len of text
text = exported[30:]
exported = preambleTxt + XML_SEPARATOR + text
return exported
def deserialize(retTextBuffer, data, start = None):
dataSplitted = data.split(XML_SEPARATOR,1)
preambleTxt = dataSplitted[0]
text = dataSplitted[1]
data = preambleTxt + intToStr(len(text)) + text
if (start == None):
start = retTextBuffer.get_start_iter()
myFormat = retTextBuffer.register_deserialize_tagset('my-tagset')
retTextBuffer.deserialize(retTextBuffer, myFormat, start, data)
return retTextBuffer
def formatting(textBuffer, start = None, end = None):
if (start == None):
start = textBuffer.get_start_iter()
if (end == None):
end = textBuffer.get_end_iter()
exported = start.get_text(end)
exported = exported.replace('<br>', os.linesep)
exported = exported.replace('<i>', '"')
exported = exported.replace('</i>', '"')
exported = exported.replace('!', '!')
out_file = open("converted","w")
out_file.write(exported)
out_file.close()
def strToInt(istr):
# return the value of istr that is a 4 char string with coded binary 32bit int. ex. 0x00 00 00 1c => 28
retVal = None
if (len(istr) == 4):
retVal = (ord(istr[0]) << 24) + (ord(istr[1]) << 16) + (ord(istr[2]) << 8) + ord(istr[3])
return retVal
def intToStr(value):
# return the coded binary 32bit int. Value is integer input. Returned value is a string. ex 28 => 0x00 00 00 1c
return chr((value >> 24) & 0xFF) + chr((value >> 16) & 0xFF) + chr((value >> 8) & 0xFF) + chr(value & 0xFF)
def prtHex(istr):
i = 0
for c in istr:
h = format(ord(c), '02x')
hi = format(i, '02x')
print (i,hi, c, h)
i = i + 1
| gpl-2.0 |
wiktorm/projekt-awr | components/com_phocadownload/views/category/view.html.php | 9818 | <?php
/*
* @package Joomla 1.5
* @copyright Copyright (C) 2005 Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
*
* @component Phoca Component
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();
jimport( 'joomla.application.component.view');
class PhocaDownloadViewCategory extends JView
{
function display($tpl = null)
{
global $mainframe;
jimport( 'joomla.filesystem.folder' );
jimport( 'joomla.filesystem.file' );
$params = &$mainframe->getParams();
$tmpl = array();
$tmpl['user'] = &JFactory::getUser();
$uri = &JFactory::getURI();
$model = &$this->getModel();
$document = &JFactory::getDocument();
$categoryId = JRequest::getVar('id', 0, '', 'int');
$limitStart = JRequest::getVar( 'limitstart', 0, '', 'int');
$section = $model->getSection($categoryId, $params);
$category = $model->getCategory($categoryId, $params);
$documentList = $model->getDocumentList($categoryId, $params);
$tmpl['pagination'] = $model->getPagination($categoryId, $params);
// Limit start
if ($limitStart > 0 ) {
$tmpl['limitstarturl'] = '&start='.$limitStart;
} else {
$tmpl['limitstarturl'] = '';
}
$css = $params->get( 'theme', 'phocadownload-grey' );
$document->addStyleSheet(JURI::base(true).'/components/com_phocadownload/assets/'.$css.'.css');
$document->addCustomTag('<script type="text/javascript" src="'.JURI::root().'includes/js/overlib_mini.js"></script>');
switch($css) {
case 'phocadownload-blue':
$ol['fgColor'] = '#E5E5FF';
$ol['bgColor'] = '#CCCCFF';
break;
case 'phocadownload-red':
$ol['fgColor'] = '#E5E5FF';
$ol['bgColor'] = '#FFB3C6';
break;
default:
$ol['fgColor'] = '#f0f0f0';
$ol['bgColor'] = '#D6D6D6';
break;
}
// Overlib
$ol['textColor'] = '#000000';
$ol['capColor'] = '#000000';
$ol['closeColor'] = '#000000';
// PARAMS
$tmpl['download_external_link'] = $params->get( 'download_external_link', '_self' );
$tmpl['filename_or_name'] = $params->get( 'filename_or_name', 'filename' );
$tmpl['display_downloads'] = $params->get( 'display_downloads', 0 );
$tmpl['display_description'] = $params->get( 'display_description', 3 );
$tmpl['display_detail'] = $params->get( 'display_detail', 1 );
$tmpl['display_play'] = $params->get( 'display_play', 0 );
$tmpl['playerwidth'] = $params->get( 'player_width', 328 );
$tmpl['playerheight'] = $params->get( 'player_height', 200 );
$tmpl['playermp3height'] = $params->get( 'player_mp3_height', 30 );
$tmpl['previewwidth'] = $params->get( 'preview_width', 640 );
$tmpl['previewheight'] = $params->get( 'preview_height', 480 );
$tmpl['display_preview'] = $params->get( 'display_preview', 0 );
$tmpl['play_popup_window'] = $params->get( 'play_popup_window', 0 );
$tmpl['preview_popup_window'] = $params->get( 'preview_popup_window', 0 );
$tmpl['file_icon_size'] = $params->get( 'file_icon_size', 16 );
$tmpl['button_style'] = $params->get( 'button_style', '' );
$tmpl['displaynew'] = $params->get( 'display_new', 0 );
$tmpl['displayhot'] = $params->get( 'display_hot', 0 );
$tmpl['display_up_icon'] = $params->get( 'display_up_icon', 1 );
$tmpl['allowed_file_types'] = PhocaDownloadHelper::getSettings( 'allowed_file_types', '' );
$tmpl['disallowed_file_types'] = PhocaDownloadHelper::getSettings( 'disallowed_file_types', '' );
$tmpl['enable_user_statistics'] = PhocaDownloadHelper::getSettings( 'enable_user_statistics', 1 );
$tmpl['display_category_comments']= $params->get( 'display_category_comments', 0 );
$tmpl['display_date_type'] = $params->get( 'display_date_type', 0 );
$tmpl['display_file_view'] = $params->get('display_file_view', 0);
$tmpl['phoca_download'] = PhocaDownloadHelper::renderPhocaDownload();
$tmpl['download_metakey'] = $params->get( 'download_metakey', '' );
$tmpl['download_metadesc'] = $params->get( 'download_metadesc', '' );
$tmpl['send_mail_download'] = $params->get( 'send_mail_download', 0 );// not boolean but id of user
//$tmpl['send_mail_upload'] = $params->get( 'send_mail_upload', 0 );
// Meta data
if (isset($category[0]) && $category[0]->metakey != '') {
$mainframe->addMetaTag('keywords', $category[0]->metakey);
} else if ($tmpl['download_metakey'] != '') {
$mainframe->addMetaTag('keywords', $tmpl['download_metakey']);
}
if (isset($category[0]) && $category[0]->metadesc != '') {
$mainframe->addMetaTag('description', $category[0]->metadesc);
} else if ($tmpl['download_metadesc'] != '') {
$mainframe->addMetaTag('description', $tmpl['download_metadesc']);
}
// DOWNLOAD
// - - - - - - - - - - - - - - -
$download = JRequest::getVar( 'download', array(0), 'get', 'array' );
$downloadId = (int) $download[0];
if ($downloadId > 0) {
$currentLink = 'index.php?option=com_phocadownload&view=category&id='.$category[0]->id.':'.$category[0]->alias.$tmpl['limitstarturl'] . '&Itemid='. JRequest::getVar('Itemid', 0, '', 'int');
$fileData = $model->getDownload($downloadId, $currentLink);
PhocaDownloadHelperFront::download($fileData, $downloadId, $currentLink, $tmpl);
}
// - - - - - - - - - - - - - - -
JHTML::_('behavior.modal', 'a.modal-button');
// PLAY - - - - - - - - - - - -
$windowWidthPl = (int)$tmpl['playerwidth'] + 30;
$windowHeightPl = (int)$tmpl['playerheight'] + 30;
$windowHeightPlMP3 = (int)$tmpl['playermp3height'] + 30;
if ($tmpl['play_popup_window'] == 1) {
$buttonPl = new JObject();
$buttonPl->set('methodname', 'js-button');
$buttonPl->set('options', "window.open(this.href,'win2','width=".$windowWidthPl.",height=".$windowHeightPl.",scrollbars=yes,menubar=no,resizable=yes'); return false;");
$buttonPl->set('optionsmp3', "window.open(this.href,'win2','width=".$windowWidthPl.",height=".$windowHeightPlMP3.",scrollbars=yes,menubar=no,resizable=yes'); return false;");
} else {
$document->addCustomTag( "<style type=\"text/css\"> \n"
." #sbox-window.phocadownloadplaywindow {background-color:#fff;padding:2px} \n"
." #sbox-overlay.phocadownloadplayoverlay {background-color:#000;} \n"
." </style> \n");
$buttonPl = new JObject();
$buttonPl->set('name', 'image');
$buttonPl->set('modal', true);
$buttonPl->set('methodname', 'modal-button');
$buttonPl->set('options', "{handler: 'iframe', size: {x: ".$windowWidthPl.", y: ".$windowHeightPl."}, overlayOpacity: 0.7, classWindow: 'phocadownloadplaywindow', classOverlay: 'phocadownloadplayoverlay'}");
$buttonPl->set('optionsmp3', "{handler: 'iframe', size: {x: ".$windowWidthPl.", y: ".$windowHeightPlMP3."}, overlayOpacity: 0.7, classWindow: 'phocadownloadplaywindow', classOverlay: 'phocadownloadplayoverlay'}");
}
// - - - - - - - - - - - - - - -
// PREVIEW - - - - - - - - - - - -
$windowWidthPr = (int)$tmpl['previewwidth'] + 20;
$windowHeightPr = (int)$tmpl['previewheight'] + 20;
if ($tmpl['preview_popup_window'] == 1) {
$buttonPr = new JObject();
$buttonPr->set('methodname', 'js-button');
$buttonPr->set('options', "window.open(this.href,'win2','width=".$windowWidthPr.",height=".$windowHeightPr.",scrollbars=yes,menubar=no,resizable=yes'); return false;");
} else {
$document->addCustomTag( "<style type=\"text/css\"> \n"
." #sbox-window.phocadownloadpreviewwindow {background-color:#fff;padding:2px} \n"
." #sbox-overlay.phocadownloadpreviewoverlay {background-color:#000;} \n"
." </style> \n");
$buttonPr = new JObject();
$buttonPr->set('name', 'image');
$buttonPr->set('modal', true);
$buttonPr->set('methodname', 'modal-button');
$buttonPr->set('options', "{handler: 'iframe', size: {x: ".$windowWidthPr.", y: ".$windowHeightPr."}, overlayOpacity: 0.7, classWindow: 'phocadownloadpreviewwindow', classOverlay: 'phocadownloadpreviewoverlay'}");
$buttonPr->set('optionsimg', "{handler: 'image', size: {x: 200, y: 150}, overlayOpacity: 0.7, classWindow: 'phocadownloadpreviewwindow', classOverlay: 'phocadownloadpreviewoverlay'}");
}
// - - - - - - - - - - - - - - -
// CSS Image Path
$imagePath = PhocaDownloadHelper::getPathSet('icon');
$cssImagePath = str_replace ( '../', JURI::base(true).'/', $imagePath['orig_rel_ds']);
$filePath = PhocaDownloadHelper::getPathSet('file');
// Define image tag attributes
if (!empty($category[0]->image)) {
$attribs['align'] = '"'.$category[0]->image_position.'"';
$attribs['hspace'] = '"6"';
// Use the static HTML library to build the image tag
$tmpl['image'] = JHTML::_('image', 'images/stories/'.$category[0]->image, JText::_('Phoca Download'), $attribs);
} else {
$tmpl['image'] = '';
}
// Breadcrumbs
$pathway =& $mainframe->getPathway();
if (!empty($section[0]->title)) {
$pathway->addItem($section[0]->title, JRoute::_(PhocaDownloadHelperRoute::getSectionRoute($section[0]->id, $section[0]->alias)));
}
if (!empty($category[0]->title)) {
$pathway->addItem($category[0]->title);
}
$this->assignRef('tmpl', $tmpl);
$this->assignRef('section', $section);
$this->assignRef('category', $category);
$this->assignRef('documentlist', $documentList);
$this->assignRef('params', $params);
$this->assignRef('cssimagepath', $cssImagePath);
$this->assignRef('absfilepath', $filePath['orig_abs_ds']);
$this->assignRef('ol', $ol);
$this->assignRef('buttonpl', $buttonPl);
$this->assignRef('buttonpr', $buttonPr);
$this->assignRef('request_url', $uri->toString());
parent::display($tpl);
}
}
?> | gpl-2.0 |
panzi/KDE-Folderview-Translucent-D-n-D-Hack | dolphin/src/kitemviews/kfileitemmodelfilter.cpp | 2633 | /***************************************************************************
* Copyright (C) 2011 by Janardhan Reddy *
* <annapareddyjanardhanreddy@gmail.com> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************/
#include "kfileitemmodelfilter_p.h"
#include <KFileItem>
#include <QRegExp>
KFileItemModelFilter::KFileItemModelFilter() :
m_useRegExp(false),
m_regExp(0),
m_lowerCasePattern(),
m_pattern()
{
}
KFileItemModelFilter::~KFileItemModelFilter()
{
delete m_regExp;
m_regExp = 0;
}
void KFileItemModelFilter::setPattern(const QString& filter)
{
m_pattern = filter;
m_lowerCasePattern = filter.toLower();
m_useRegExp = filter.contains('*') ||
filter.contains('?') ||
filter.contains('[');
if (m_useRegExp) {
if (!m_regExp) {
m_regExp = new QRegExp();
m_regExp->setCaseSensitivity(Qt::CaseInsensitive);
m_regExp->setMinimal(false);
m_regExp->setPatternSyntax(QRegExp::WildcardUnix);
}
m_regExp->setPattern(filter);
}
}
QString KFileItemModelFilter::pattern() const
{
return m_pattern;
}
bool KFileItemModelFilter::matches(const KFileItem& item) const
{
if (m_useRegExp) {
return m_regExp->exactMatch(item.text());
} else {
return item.text().toLower().contains(m_lowerCasePattern);
}
}
| gpl-2.0 |
hildebrandttk/javaee7-petclinic | src/test/graphene/common/src/main/java/org/woehlke/javaee7/petclinic/web/pages/OwnersTableFragment.java | 1015 | package org.woehlke.javaee7.petclinic.web.pages;
import java.util.ArrayList;
import java.util.List;
import org.jboss.arquillian.graphene.fragment.Root;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class OwnersTableFragment {
@Root
private WebElement root;
@FindBy(css = "tbody.rf-dt-b > tr")
private List<OwnersTableRowFragment> rows;
public List<OwnersTableRowFragment> findRowsByParameters(String firstName, String lastName, String address,
String city, String telephone) {
List<OwnersTableRowFragment> matchingRows = new ArrayList<>();
for (OwnersTableRowFragment row : rows) {
if (row.getLastName().equals(lastName) && row.getFirstName().equals(firstName)
&& row.getAddress().equals(address) && row.getCity().equals(city) && row.getTelephone().equals(telephone)) {
matchingRows.add(row);
}
}
return matchingRows;
}
}
| gpl-2.0 |
pbhopalka/AccountingSoftware | accounting/migrations/0004_auto_20150927_2227.py | 407 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('accounting', '0003_auto_20150927_2223'),
]
operations = [
migrations.AlterField(
model_name='c_details',
name='Phone',
field=models.CharField(max_length=10),
),
]
| gpl-2.0 |
drazenzadravec/nequeo | Source/Components/Linq/Nequeo.Linq/Nequeo.Linq/base/DynamicExpression.cs | 111142 | /* Company : Nequeo Pty Ltd, http://www.nequeo.com.au/
* Copyright : Copyright © Nequeo Pty Ltd 2010 http://www.nequeo.com.au/
*
* File :
* Purpose :
*
*/
#region Nequeo Pty Ltd License
/*
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.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using Nequeo.Data.TypeExtenders;
namespace Nequeo.Linq
{
/// <summary>
/// Dynamic expression builder.
/// </summary>
public static class DynamicExpression
{
/// <summary>
/// Parse string to expression.
/// </summary>
/// <param name="resultType">The result type.</param>
/// <param name="expression">The string expression.</param>
/// <param name="values">The values.</param>
/// <returns>The expression.</returns>
public static Expression Parse(Type resultType, string expression, params object[] values)
{
ExpressionParser parser = new ExpressionParser(null, expression, values);
return parser.Parse(resultType);
}
/// <summary>
/// Parse string lambda expression.
/// </summary>
/// <param name="itType">Initial type.</param>
/// <param name="resultType">Result ype.</param>
/// <param name="expression">The string expression.</param>
/// <param name="values">The values.</param>
/// <returns>The lambda expression.</returns>
public static LambdaExpression ParseLambda(Type itType, Type resultType, string expression, params object[] values)
{
return ParseLambda(new ParameterExpression[] { Expression.Parameter(itType, "") }, resultType, expression, values);
}
/// <summary>
/// Parse string lambda expression.
/// </summary>
/// <param name="parameters">The parameter expressions.</param>
/// <param name="resultType">The result ype.</param>
/// <param name="expression">The string expression.</param>
/// <param name="values">The values.</param>
/// <returns>The lambda expression.</returns>
public static LambdaExpression ParseLambda(ParameterExpression[] parameters, Type resultType, string expression, params object[] values)
{
ExpressionParser parser = new ExpressionParser(parameters, expression, values);
return Expression.Lambda(parser.Parse(resultType), parameters);
}
/// <summary>
/// The string to lambda expression.
/// </summary>
/// <typeparam name="T">The source type.</typeparam>
/// <typeparam name="S">The result type.</typeparam>
/// <param name="expression">The string expression.</param>
/// <param name="values">The values.</param>
/// <returns>The lambda expression.</returns>
public static Expression<Func<T, S>> ParseLambda<T, S>(string expression, params object[] values)
{
return (Expression<Func<T, S>>)ParseLambda(typeof(T), typeof(S), expression, values);
}
/// <summary>
/// Create dynamic class type.
/// </summary>
/// <param name="properties">The dynamic properties.</param>
/// <returns>The dynamic class type.</returns>
public static Type CreateClass(params Nequeo.Reflection.DynamicProperty[] properties)
{
return Nequeo.Reflection.DynamicClassBuilder.Instance.GetDynamicClass(properties);
}
/// <summary>
/// Create dynamic class type.
/// </summary>
/// <param name="properties">The dynamic properties.</param>
/// <returns>The dynamic class type.</returns>
public static Type CreateClass(IEnumerable<Nequeo.Reflection.DynamicProperty> properties)
{
return Nequeo.Reflection.DynamicClassBuilder.Instance.GetDynamicClass(properties);
}
}
/// <summary>
/// Dynamic ordering.
/// </summary>
internal class DynamicOrdering
{
/// <summary>
/// The slector expression.
/// </summary>
public Expression Selector;
/// <summary>
/// Is ascending.
/// </summary>
public bool Ascending;
}
/// <summary>
/// Parse exception.
/// </summary>
public sealed class ParseException : Exception
{
int position;
/// <summary>
/// Parse exception.
/// </summary>
/// <param name="message">THe message.</param>
/// <param name="position">The position.</param>
public ParseException(string message, int position)
: base(message)
{
this.position = position;
}
/// <summary>
/// Gets the position.
/// </summary>
public int Position
{
get { return position; }
}
/// <summary>
/// Gets the message.
/// </summary>
/// <returns>The message.</returns>
public override string ToString()
{
return string.Format(Res.ParseExceptionFormat, Message, position);
}
}
/// <summary>
/// Expression parser.
/// </summary>
internal class ExpressionParser
{
/// <summary>
/// Token structure.
/// </summary>
struct Token
{
/// <summary>
/// Token id.
/// </summary>
public TokenId id;
/// <summary>
/// The text.
/// </summary>
public string text;
/// <summary>
/// The position.
/// </summary>
public int pos;
}
/// <summary>
/// Token id.
/// </summary>
enum TokenId
{
Unknown,
End,
Identifier,
StringLiteral,
IntegerLiteral,
RealLiteral,
Exclamation,
Percent,
Amphersand,
OpenParen,
CloseParen,
Asterisk,
Plus,
Comma,
Minus,
Dot,
Slash,
Colon,
LessThan,
Equal,
GreaterThan,
Question,
OpenBracket,
CloseBracket,
Bar,
ExclamationEqual,
DoubleAmphersand,
LessThanEqual,
LessGreater,
DoubleEqual,
GreaterThanEqual,
DoubleBar
}
/// <summary>
/// Logical signatures interface.
/// </summary>
interface ILogicalSignatures
{
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(bool x, bool y);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(bool? x, bool? y);
}
/// <summary>
/// Arithmetic signatures interface.
/// </summary>
interface IArithmeticSignatures
{
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(int x, int y);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(uint x, uint y);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(long x, long y);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(ulong x, ulong y);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(float x, float y);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(double x, double y);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(decimal x, decimal y);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(int? x, int? y);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(uint? x, uint? y);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(long? x, long? y);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(ulong? x, ulong? y);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(float? x, float? y);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(double? x, double? y);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(decimal? x, decimal? y);
}
/// <summary>
/// Relational signatures interface.
/// </summary>
interface IRelationalSignatures : IArithmeticSignatures
{
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(string x, string y);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(char x, char y);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(DateTime x, DateTime y);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(TimeSpan x, TimeSpan y);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(char? x, char? y);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(DateTime? x, DateTime? y);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(TimeSpan? x, TimeSpan? y);
}
/// <summary>
/// Equality signatures interface.
/// </summary>
interface IEqualitySignatures : IRelationalSignatures
{
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(bool x, bool y);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(bool? x, bool? y);
}
/// <summary>
/// Add signatures interface.
/// </summary>
interface IAddSignatures : IArithmeticSignatures
{
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(DateTime x, TimeSpan y);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(TimeSpan x, TimeSpan y);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(DateTime? x, TimeSpan? y);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(TimeSpan? x, TimeSpan? y);
}
/// <summary>
/// Subtract signatures interface.
/// </summary>
interface ISubtractSignatures : IAddSignatures
{
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(DateTime x, DateTime y);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
/// <param name="y">The y value.</param>
void F(DateTime? x, DateTime? y);
}
/// <summary>
/// Negation signatures interace.
/// </summary>
interface INegationSignatures
{
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
void F(int x);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
void F(long x);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
void F(float x);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
void F(double x);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
void F(decimal x);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
void F(int? x);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
void F(long? x);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
void F(float? x);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
void F(double? x);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
void F(decimal? x);
}
/// <summary>
/// Not signatures interface.
/// </summary>
interface INotSignatures
{
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
void F(bool x);
/// <summary>
/// Compare.
/// </summary>
/// <param name="x">The x value.</param>
void F(bool? x);
}
/// <summary>
/// Enumerable signatures interface.
/// </summary>
interface IEnumerableSignatures
{
/// <summary>
/// Where
/// </summary>
/// <param name="predicate">Predicate.</param>
void Where(bool predicate);
/// <summary>
/// Any
/// </summary>
void Any();
/// <summary>
/// Any
/// </summary>
/// <param name="predicate">Predicate.</param>
void Any(bool predicate);
/// <summary>
/// All
/// </summary>
/// <param name="predicate">Predicate.</param>
void All(bool predicate);
/// <summary>
/// Count
/// </summary>
void Count();
/// <summary>
/// Count
/// </summary>
/// <param name="predicate">Predicate.</param>
void Count(bool predicate);
/// <summary>
/// Min
/// </summary>
/// <param name="selector">Selector.</param>
void Min(object selector);
/// <summary>
/// Max
/// </summary>
/// <param name="selector">Selector.</param>
void Max(object selector);
/// <summary>
/// Sum
/// </summary>
/// <param name="selector">Selector.</param>
void Sum(int selector);
/// <summary>
/// Sum
/// </summary>
/// <param name="selector">Selector.</param>
void Sum(int? selector);
/// <summary>
/// Sum
/// </summary>
/// <param name="selector">Selector.</param>
void Sum(long selector);
/// <summary>
/// Sum
/// </summary>
/// <param name="selector">Selector.</param>
void Sum(long? selector);
/// <summary>
/// Sum
/// </summary>
/// <param name="selector">Selector.</param>
void Sum(float selector);
/// <summary>
/// Sum
/// </summary>
/// <param name="selector">Selector.</param>
void Sum(float? selector);
/// <summary>
/// Sum
/// </summary>
/// <param name="selector">Selector.</param>
void Sum(double selector);
/// <summary>
/// Sum
/// </summary>
/// <param name="selector">Selector.</param>
void Sum(double? selector);
/// <summary>
/// Sum
/// </summary>
/// <param name="selector">Selector.</param>
void Sum(decimal selector);
/// <summary>
/// Sum
/// </summary>
/// <param name="selector">Selector.</param>
void Sum(decimal? selector);
/// <summary>
/// Average
/// </summary>
/// <param name="selector">Selector.</param>
void Average(int selector);
/// <summary>
/// Average
/// </summary>
/// <param name="selector">Selector.</param>
void Average(int? selector);
/// <summary>
/// Average
/// </summary>
/// <param name="selector">Selector.</param>
void Average(long selector);
/// <summary>
/// Average
/// </summary>
/// <param name="selector">Selector.</param>
void Average(long? selector);
/// <summary>
/// Average
/// </summary>
/// <param name="selector">Selector.</param>
void Average(float selector);
/// <summary>
/// Average
/// </summary>
/// <param name="selector">Selector.</param>
void Average(float? selector);
/// <summary>
/// Average
/// </summary>
/// <param name="selector">Selector.</param>
void Average(double selector);
/// <summary>
/// Average
/// </summary>
/// <param name="selector">Selector.</param>
void Average(double? selector);
/// <summary>
/// Average
/// </summary>
/// <param name="selector">Selector.</param>
void Average(decimal selector);
/// <summary>
/// Average
/// </summary>
/// <param name="selector">Selector.</param>
void Average(decimal? selector);
}
/// <summary>
/// Predefined types.
/// </summary>
static readonly Type[] predefinedTypes = {
typeof(Object),
typeof(Boolean),
typeof(Char),
typeof(String),
typeof(SByte),
typeof(Byte),
typeof(Int16),
typeof(UInt16),
typeof(Int32),
typeof(UInt32),
typeof(Int64),
typeof(UInt64),
typeof(Single),
typeof(Double),
typeof(Decimal),
typeof(DateTime),
typeof(TimeSpan),
typeof(Guid),
typeof(Math),
typeof(Convert),
typeof(SqlQueryMethods)
};
static readonly Expression trueLiteral = Expression.Constant(true);
static readonly Expression falseLiteral = Expression.Constant(false);
static readonly Expression nullLiteral = Expression.Constant(null);
static readonly string keywordIt = "it";
static readonly string keywordIif = "iif";
static readonly string keywordNew = "new";
static Dictionary<string, object> keywords;
Dictionary<string, object> symbols;
IDictionary<string, object> externals;
Dictionary<Expression, string> literals;
ParameterExpression it;
string text;
int textPos;
int textLen;
char ch;
Token token;
/// <summary>
/// Expression Parser.
/// </summary>
/// <param name="parameters">The expression parameters.</param>
/// <param name="expression">The string expression.</param>
/// <param name="values">The values.</param>
public ExpressionParser(ParameterExpression[] parameters, string expression, object[] values)
{
if (expression == null) throw new ArgumentNullException("expression");
if (keywords == null) keywords = CreateKeywords();
symbols = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
literals = new Dictionary<Expression, string>();
if (parameters != null) ProcessParameters(parameters);
if (values != null) ProcessValues(values);
text = expression;
textLen = text.Length;
SetTextPos(0);
NextToken();
}
/// <summary>
/// Process parameters.
/// </summary>
/// <param name="parameters">The expression parameters.</param>
void ProcessParameters(ParameterExpression[] parameters)
{
foreach (ParameterExpression pe in parameters)
if (!String.IsNullOrEmpty(pe.Name))
AddSymbol(pe.Name, pe);
if (parameters.Length == 1 && String.IsNullOrEmpty(parameters[0].Name))
it = parameters[0];
}
/// <summary>
/// Process values.
/// </summary>
/// <param name="values">The values.</param>
void ProcessValues(object[] values)
{
for (int i = 0; i < values.Length; i++)
{
object value = values[i];
if (i == values.Length - 1 && value is IDictionary<string, object>)
{
externals = (IDictionary<string, object>)value;
}
else
{
AddSymbol("@" + i.ToString(System.Globalization.CultureInfo.InvariantCulture), value);
}
}
}
/// <summary>
/// Add symbol
/// </summary>
/// <param name="name">The name.</param>
/// <param name="value">The value.</param>
void AddSymbol(string name, object value)
{
if (symbols.ContainsKey(name))
throw ParseError(Res.DuplicateIdentifier, name);
symbols.Add(name, value);
}
/// <summary>
/// Parse.
/// </summary>
/// <param name="resultType">Result type.</param>
/// <returns>The expression.</returns>
public Expression Parse(Type resultType)
{
int exprPos = token.pos;
Expression expr = ParseExpression();
if (resultType != null)
if ((expr = PromoteExpression(expr, resultType, true)) == null)
throw ParseError(exprPos, Res.ExpressionTypeMismatch, GetTypeName(resultType));
ValidateToken(TokenId.End, Res.SyntaxError);
return expr;
}
#pragma warning disable 0219
/// <summary>
/// Parse ordering.
/// </summary>
/// <returns>Dynamic ordering list.</returns>
public IEnumerable<DynamicOrdering> ParseOrdering()
{
List<DynamicOrdering> orderings = new List<DynamicOrdering>();
while (true)
{
Expression expr = ParseExpression();
bool ascending = true;
if (TokenIdentifierIs("asc") || TokenIdentifierIs("ascending"))
{
NextToken();
}
else if (TokenIdentifierIs("desc") || TokenIdentifierIs("descending"))
{
NextToken();
ascending = false;
}
orderings.Add(new DynamicOrdering { Selector = expr, Ascending = ascending });
if (token.id != TokenId.Comma) break;
NextToken();
}
ValidateToken(TokenId.End, Res.SyntaxError);
return orderings;
}
#pragma warning restore 0219
/// <summary>
/// Parse expression.
/// </summary>
/// <returns>The expression.</returns>
Expression ParseExpression()
{
int errorPos = token.pos;
Expression expr = ParseLogicalOr();
if (token.id == TokenId.Question)
{
NextToken();
Expression expr1 = ParseExpression();
ValidateToken(TokenId.Colon, Res.ColonExpected);
NextToken();
Expression expr2 = ParseExpression();
expr = GenerateConditional(expr, expr1, expr2, errorPos);
}
return expr;
}
/// <summary>
/// Parse logical Or.
/// </summary>
/// <returns>The expression.</returns>
Expression ParseLogicalOr()
{
Expression left = ParseLogicalAnd();
while (token.id == TokenId.DoubleBar || TokenIdentifierIs("or"))
{
Token op = token;
NextToken();
Expression right = ParseLogicalAnd();
CheckAndPromoteOperands(typeof(ILogicalSignatures), op.text, ref left, ref right, op.pos);
left = Expression.OrElse(left, right);
}
return left;
}
/// <summary>
/// Parse logical And.
/// </summary>
/// <returns>The expression.</returns>
Expression ParseLogicalAnd()
{
//&&, and operator
Expression left = ParseComparison();
while (token.id == TokenId.DoubleAmphersand || TokenIdentifierIs("and"))
{
Token op = token;
NextToken();
Expression right = ParseComparison();
CheckAndPromoteOperands(typeof(ILogicalSignatures), op.text, ref left, ref right, op.pos);
left = Expression.AndAlso(left, right);
}
return left;
}
/// <summary>
/// Parse comparison.
/// </summary>
/// <returns>The expression.</returns>
Expression ParseComparison()
{
// =, ==, !=, <>, >, >=, <, <= operators
Expression left = ParseAdditive();
while (token.id == TokenId.Equal || token.id == TokenId.DoubleEqual ||
token.id == TokenId.ExclamationEqual || token.id == TokenId.LessGreater ||
token.id == TokenId.GreaterThan || token.id == TokenId.GreaterThanEqual ||
token.id == TokenId.LessThan || token.id == TokenId.LessThanEqual)
{
Token op = token;
NextToken();
Expression right = ParseAdditive();
bool isEquality = op.id == TokenId.Equal || op.id == TokenId.DoubleEqual ||
op.id == TokenId.ExclamationEqual || op.id == TokenId.LessGreater;
if (isEquality && !left.Type.IsValueType && !right.Type.IsValueType)
{
if (left.Type != right.Type)
{
if (left.Type.IsAssignableFrom(right.Type))
{
right = Expression.Convert(right, left.Type);
}
else if (right.Type.IsAssignableFrom(left.Type))
{
left = Expression.Convert(left, right.Type);
}
else
{
throw IncompatibleOperandsError(op.text, left, right, op.pos);
}
}
}
else if (IsEnumType(left.Type) || IsEnumType(right.Type))
{
if (left.Type != right.Type)
{
Expression e;
if ((e = PromoteExpression(right, left.Type, true)) != null)
{
right = e;
}
else if ((e = PromoteExpression(left, right.Type, true)) != null)
{
left = e;
}
else
{
throw IncompatibleOperandsError(op.text, left, right, op.pos);
}
}
}
else
{
CheckAndPromoteOperands(isEquality ? typeof(IEqualitySignatures) : typeof(IRelationalSignatures),
op.text, ref left, ref right, op.pos);
}
switch (op.id)
{
case TokenId.Equal:
case TokenId.DoubleEqual:
left = GenerateEqual(left, right);
break;
case TokenId.ExclamationEqual:
case TokenId.LessGreater:
left = GenerateNotEqual(left, right);
break;
case TokenId.GreaterThan:
left = GenerateGreaterThan(left, right);
break;
case TokenId.GreaterThanEqual:
left = GenerateGreaterThanEqual(left, right);
break;
case TokenId.LessThan:
left = GenerateLessThan(left, right);
break;
case TokenId.LessThanEqual:
left = GenerateLessThanEqual(left, right);
break;
}
}
return left;
}
/// <summary>
/// Parse additive.
/// </summary>
/// <returns>The expression.</returns>
Expression ParseAdditive()
{
// +, -, & operators
Expression left = ParseMultiplicative();
while (token.id == TokenId.Plus || token.id == TokenId.Minus ||
token.id == TokenId.Amphersand)
{
Token op = token;
NextToken();
Expression right = ParseMultiplicative();
switch (op.id)
{
case TokenId.Plus:
if (left.Type == typeof(string) || right.Type == typeof(string))
goto case TokenId.Amphersand;
CheckAndPromoteOperands(typeof(IAddSignatures), op.text, ref left, ref right, op.pos);
left = GenerateAdd(left, right);
break;
case TokenId.Minus:
CheckAndPromoteOperands(typeof(ISubtractSignatures), op.text, ref left, ref right, op.pos);
left = GenerateSubtract(left, right);
break;
case TokenId.Amphersand:
left = GenerateStringConcat(left, right);
break;
}
}
return left;
}
/// <summary>
/// Parse multiplicative.
/// </summary>
/// <returns>The expression.</returns>
Expression ParseMultiplicative()
{
Expression left = ParseUnary();
while (token.id == TokenId.Asterisk || token.id == TokenId.Slash ||
token.id == TokenId.Percent || TokenIdentifierIs("mod"))
{
Token op = token;
NextToken();
Expression right = ParseUnary();
CheckAndPromoteOperands(typeof(IArithmeticSignatures), op.text, ref left, ref right, op.pos);
switch (op.id)
{
case TokenId.Asterisk:
left = Expression.Multiply(left, right);
break;
case TokenId.Slash:
left = Expression.Divide(left, right);
break;
case TokenId.Percent:
case TokenId.Identifier:
left = Expression.Modulo(left, right);
break;
}
}
return left;
}
/// <summary>
/// Parse -, !, not unary operators
/// </summary>
/// <returns>The expression.</returns>
Expression ParseUnary()
{
if (token.id == TokenId.Minus || token.id == TokenId.Exclamation ||
TokenIdentifierIs("not"))
{
Token op = token;
NextToken();
if (op.id == TokenId.Minus && (token.id == TokenId.IntegerLiteral ||
token.id == TokenId.RealLiteral))
{
token.text = "-" + token.text;
token.pos = op.pos;
return ParsePrimary();
}
Expression expr = ParseUnary();
if (op.id == TokenId.Minus)
{
CheckAndPromoteOperand(typeof(INegationSignatures), op.text, ref expr, op.pos);
expr = Expression.Negate(expr);
}
else
{
CheckAndPromoteOperand(typeof(INotSignatures), op.text, ref expr, op.pos);
expr = Expression.Not(expr);
}
return expr;
}
return ParsePrimary();
}
/// <summary>
/// Parse primary.
/// </summary>
/// <returns>The expression.</returns>
Expression ParsePrimary()
{
Expression expr = ParsePrimaryStart();
while (true)
{
if (token.id == TokenId.Dot)
{
NextToken();
expr = ParseMemberAccess(null, expr);
}
else if (token.id == TokenId.OpenBracket)
{
expr = ParseElementAccess(expr);
}
else
{
break;
}
}
return expr;
}
/// <summary>
/// Parse primary start.
/// </summary>
/// <returns>The expression.</returns>
Expression ParsePrimaryStart()
{
switch (token.id)
{
case TokenId.Identifier:
return ParseIdentifier();
case TokenId.StringLiteral:
return ParseStringLiteral();
case TokenId.IntegerLiteral:
return ParseIntegerLiteral();
case TokenId.RealLiteral:
return ParseRealLiteral();
case TokenId.OpenParen:
return ParseParenExpression();
default:
throw ParseError(Res.ExpressionExpected);
}
}
/// <summary>
/// Parse string literal.
/// </summary>
/// <returns>The expression.</returns>
Expression ParseStringLiteral()
{
ValidateToken(TokenId.StringLiteral);
char quote = token.text[0];
string s = token.text.Substring(1, token.text.Length - 2);
int start = 0;
while (true)
{
int i = s.IndexOf(quote, start);
if (i < 0) break;
s = s.Remove(i, 1);
start = i + 1;
}
if (quote == '\'')
{
if (s.Length != 1)
throw ParseError(Res.InvalidCharacterLiteral);
NextToken();
return CreateLiteral(s[0], s);
}
NextToken();
return CreateLiteral(s, s);
}
/// <summary>
/// Parse integer literal.
/// </summary>
/// <returns>The expression.</returns>
Expression ParseIntegerLiteral()
{
ValidateToken(TokenId.IntegerLiteral);
string text = token.text;
if (text[0] != '-')
{
ulong value;
if (!UInt64.TryParse(text, out value))
throw ParseError(Res.InvalidIntegerLiteral, text);
NextToken();
if (value <= (ulong)Int32.MaxValue) return CreateLiteral((int)value, text);
if (value <= (ulong)UInt32.MaxValue) return CreateLiteral((uint)value, text);
if (value <= (ulong)Int64.MaxValue) return CreateLiteral((long)value, text);
return CreateLiteral(value, text);
}
else
{
long value;
if (!Int64.TryParse(text, out value))
throw ParseError(Res.InvalidIntegerLiteral, text);
NextToken();
if (value >= Int32.MinValue && value <= Int32.MaxValue)
return CreateLiteral((int)value, text);
return CreateLiteral(value, text);
}
}
/// <summary>
/// Parse real literal.
/// </summary>
/// <returns>The expression.</returns>
Expression ParseRealLiteral()
{
ValidateToken(TokenId.RealLiteral);
string text = token.text;
object value = null;
char last = text[text.Length - 1];
if (last == 'F' || last == 'f')
{
float f;
if (Single.TryParse(text.Substring(0, text.Length - 1), out f)) value = f;
}
else
{
double d;
if (Double.TryParse(text, out d)) value = d;
}
if (value == null) throw ParseError(Res.InvalidRealLiteral, text);
NextToken();
return CreateLiteral(value, text);
}
/// <summary>
/// Create literal.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="text">The text.</param>
/// <returns>The expression.</returns>
Expression CreateLiteral(object value, string text)
{
ConstantExpression expr = Expression.Constant(value);
literals.Add(expr, text);
return expr;
}
/// <summary>
/// Parse paren expression.
/// </summary>
/// <returns>The expression.</returns>
Expression ParseParenExpression()
{
ValidateToken(TokenId.OpenParen, Res.OpenParenExpected);
NextToken();
Expression e = ParseExpression();
ValidateToken(TokenId.CloseParen, Res.CloseParenOrOperatorExpected);
NextToken();
return e;
}
/// <summary>
/// Parse identifier.
/// </summary>
/// <returns>The expression.</returns>
Expression ParseIdentifier()
{
ValidateToken(TokenId.Identifier);
object value;
if (keywords.TryGetValue(token.text, out value))
{
if (value is Type) return ParseTypeAccess((Type)value);
if (value == (object)keywordIt) return ParseIt();
if (value == (object)keywordIif) return ParseIif();
if (value == (object)keywordNew) return ParseNew();
NextToken();
return (Expression)value;
}
if (symbols.TryGetValue(token.text, out value) ||
externals != null && externals.TryGetValue(token.text, out value))
{
Expression expr = value as Expression;
if (expr == null)
{
expr = Expression.Constant(value);
}
else
{
LambdaExpression lambda = expr as LambdaExpression;
if (lambda != null) return ParseLambdaInvocation(lambda);
}
NextToken();
return expr;
}
if (it != null) return ParseMemberAccess(null, it);
throw ParseError(Res.UnknownIdentifier, token.text);
}
/// <summary>
/// Parse It.
/// </summary>
/// <returns>The expression.</returns>
Expression ParseIt()
{
if (it == null)
throw ParseError(Res.NoItInScope);
NextToken();
return it;
}
/// <summary>
/// Parse Iif.
/// </summary>
/// <returns>The expression.</returns>
Expression ParseIif()
{
int errorPos = token.pos;
NextToken();
Expression[] args = ParseArgumentList();
if (args.Length != 3)
throw ParseError(errorPos, Res.IifRequiresThreeArgs);
return GenerateConditional(args[0], args[1], args[2], errorPos);
}
/// <summary>
/// Generate conditional.
/// </summary>
/// <param name="test">The test expression.</param>
/// <param name="expr1">Expression</param>
/// <param name="expr2">Expression</param>
/// <param name="errorPos">Error position.</param>
/// <returns>The expression.</returns>
Expression GenerateConditional(Expression test, Expression expr1, Expression expr2, int errorPos)
{
if (test.Type != typeof(bool))
throw ParseError(errorPos, Res.FirstExprMustBeBool);
if (expr1.Type != expr2.Type)
{
Expression expr1as2 = expr2 != nullLiteral ? PromoteExpression(expr1, expr2.Type, true) : null;
Expression expr2as1 = expr1 != nullLiteral ? PromoteExpression(expr2, expr1.Type, true) : null;
if (expr1as2 != null && expr2as1 == null)
{
expr1 = expr1as2;
}
else if (expr2as1 != null && expr1as2 == null)
{
expr2 = expr2as1;
}
else
{
string type1 = expr1 != nullLiteral ? expr1.Type.Name : "null";
string type2 = expr2 != nullLiteral ? expr2.Type.Name : "null";
if (expr1as2 != null && expr2as1 != null)
throw ParseError(errorPos, Res.BothTypesConvertToOther, type1, type2);
throw ParseError(errorPos, Res.NeitherTypeConvertsToOther, type1, type2);
}
}
return Expression.Condition(test, expr1, expr2);
}
/// <summary>
/// Parse new.
/// </summary>
/// <returns>The expression.</returns>
Expression ParseNew()
{
NextToken();
ValidateToken(TokenId.OpenParen, Res.OpenParenExpected);
NextToken();
List<Nequeo.Reflection.DynamicProperty> properties = new List<Nequeo.Reflection.DynamicProperty>();
List<Expression> expressions = new List<Expression>();
while (true)
{
int exprPos = token.pos;
Expression expr = ParseExpression();
string propName;
if (TokenIdentifierIs("as"))
{
NextToken();
propName = GetIdentifier();
NextToken();
}
else
{
MemberExpression me = expr as MemberExpression;
if (me == null) throw ParseError(exprPos, Res.MissingAsClause);
propName = me.Member.Name;
}
expressions.Add(expr);
properties.Add(new Nequeo.Reflection.DynamicProperty(propName, expr.Type));
if (token.id != TokenId.Comma) break;
NextToken();
}
ValidateToken(TokenId.CloseParen, Res.CloseParenOrCommaExpected);
NextToken();
Type type = DynamicExpression.CreateClass(properties);
MemberBinding[] bindings = new MemberBinding[properties.Count];
for (int i = 0; i < bindings.Length; i++)
bindings[i] = Expression.Bind(type.GetProperty(properties[i].Name), expressions[i]);
return Expression.MemberInit(Expression.New(type), bindings);
}
/// <summary>
/// Parse lambda invocation.
/// </summary>
/// <param name="lambda"></param>
/// <returns>The expression.</returns>
Expression ParseLambdaInvocation(LambdaExpression lambda)
{
int errorPos = token.pos;
NextToken();
Expression[] args = ParseArgumentList();
MethodBase method;
if (FindMethod(lambda.Type, "Invoke", false, args, out method) != 1)
throw ParseError(errorPos, Res.ArgsIncompatibleWithLambda);
return Expression.Invoke(lambda, args);
}
/// <summary>
/// Parse type access.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The expression.</returns>
Expression ParseTypeAccess(Type type)
{
int errorPos = token.pos;
NextToken();
if (token.id == TokenId.Question)
{
if (!type.IsValueType || IsNullableType(type))
throw ParseError(errorPos, Res.TypeHasNoNullableForm, GetTypeName(type));
type = typeof(Nullable<>).MakeGenericType(type);
NextToken();
}
if (token.id == TokenId.OpenParen)
{
Expression[] args = ParseArgumentList();
MethodBase method;
switch (FindBestMethod(type.GetConstructors(), args, out method))
{
case 0:
if (args.Length == 1)
return GenerateConversion(args[0], type, errorPos);
throw ParseError(errorPos, Res.NoMatchingConstructor, GetTypeName(type));
case 1:
return Expression.New((ConstructorInfo)method, args);
default:
throw ParseError(errorPos, Res.AmbiguousConstructorInvocation, GetTypeName(type));
}
}
ValidateToken(TokenId.Dot, Res.DotOrOpenParenExpected);
NextToken();
return ParseMemberAccess(type, null);
}
/// <summary>
/// Generate conversion.
/// </summary>
/// <param name="expr">Expression.</param>
/// <param name="type">The type.</param>
/// <param name="errorPos">Error position.</param>
/// <returns>The expression.</returns>
Expression GenerateConversion(Expression expr, Type type, int errorPos)
{
Type exprType = expr.Type;
if (exprType == type) return expr;
if (exprType.IsValueType && type.IsValueType)
{
if ((IsNullableType(exprType) || IsNullableType(type)) &&
GetNonNullableType(exprType) == GetNonNullableType(type))
return Expression.Convert(expr, type);
if ((IsNumericType(exprType) || IsEnumType(exprType)) &&
(IsNumericType(type)) || IsEnumType(type))
return Expression.ConvertChecked(expr, type);
}
if (exprType.IsAssignableFrom(type) || type.IsAssignableFrom(exprType) ||
exprType.IsInterface || type.IsInterface)
return Expression.Convert(expr, type);
throw ParseError(errorPos, Res.CannotConvertValue,
GetTypeName(exprType), GetTypeName(type));
}
/// <summary>
/// Parse member access.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="instance">Expression.</param>
/// <returns>The expression.</returns>
Expression ParseMemberAccess(Type type, Expression instance)
{
if (instance != null) type = instance.Type;
int errorPos = token.pos;
string id = GetIdentifier();
NextToken();
if (token.id == TokenId.OpenParen)
{
if (instance != null && type != typeof(string))
{
Type enumerableType = FindGenericType(typeof(IEnumerable<>), type);
if (enumerableType != null)
{
Type elementType = enumerableType.GetGenericArguments()[0];
return ParseAggregate(instance, elementType, id, errorPos);
}
}
Expression[] args = ParseArgumentList();
MethodBase mb;
switch (FindMethod(type, id, instance == null, args, out mb))
{
case 0:
throw ParseError(errorPos, Res.NoApplicableMethod,
id, GetTypeName(type));
case 1:
MethodInfo method = (MethodInfo)mb;
if (!IsPredefinedType(method.DeclaringType))
throw ParseError(errorPos, Res.MethodsAreInaccessible, GetTypeName(method.DeclaringType));
if (method.ReturnType == typeof(void))
throw ParseError(errorPos, Res.MethodIsVoid,
id, GetTypeName(method.DeclaringType));
return Expression.Call(instance, (MethodInfo)method, args);
default:
throw ParseError(errorPos, Res.AmbiguousMethodInvocation,
id, GetTypeName(type));
}
}
else
{
MemberInfo member = FindPropertyOrField(type, id, instance == null);
if (member == null)
throw ParseError(errorPos, Res.UnknownPropertyOrField,
id, GetTypeName(type));
return member is PropertyInfo ?
Expression.Property(instance, (PropertyInfo)member) :
Expression.Field(instance, (FieldInfo)member);
}
}
/// <summary>
/// Find generic type.
/// </summary>
/// <param name="generic">The generic type.</param>
/// <param name="type">The type.</param>
/// <returns>The type.</returns>
static Type FindGenericType(Type generic, Type type)
{
while (type != null && type != typeof(object))
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == generic) return type;
if (generic.IsInterface)
{
foreach (Type intfType in type.GetInterfaces())
{
Type found = FindGenericType(generic, intfType);
if (found != null) return found;
}
}
type = type.BaseType;
}
return null;
}
/// <summary>
/// Parse aggregate.
/// </summary>
/// <param name="instance">Expression.</param>
/// <param name="elementType">The element ype.</param>
/// <param name="methodName">The method name.</param>
/// <param name="errorPos">Error position.</param>
/// <returns>The expression.</returns>
Expression ParseAggregate(Expression instance, Type elementType, string methodName, int errorPos)
{
ParameterExpression outerIt = it;
ParameterExpression innerIt = Expression.Parameter(elementType, "");
it = innerIt;
Expression[] args = ParseArgumentList();
it = outerIt;
MethodBase signature;
if (FindMethod(typeof(IEnumerableSignatures), methodName, false, args, out signature) != 1)
throw ParseError(errorPos, Res.NoApplicableAggregate, methodName);
Type[] typeArgs;
if (signature.Name == "Min" || signature.Name == "Max")
{
typeArgs = new Type[] { elementType, args[0].Type };
}
else
{
typeArgs = new Type[] { elementType };
}
if (args.Length == 0)
{
args = new Expression[] { instance };
}
else
{
args = new Expression[] { instance, Expression.Lambda(args[0], innerIt) };
}
return Expression.Call(typeof(Enumerable), signature.Name, typeArgs, args);
}
/// <summary>
/// Parse argument list.
/// </summary>
/// <returns>The expressions.</returns>
Expression[] ParseArgumentList()
{
ValidateToken(TokenId.OpenParen, Res.OpenParenExpected);
NextToken();
Expression[] args = token.id != TokenId.CloseParen ? ParseArguments() : new Expression[0];
ValidateToken(TokenId.CloseParen, Res.CloseParenOrCommaExpected);
NextToken();
return args;
}
/// <summary>
/// Parse arguments.
/// </summary>
/// <returns>The expressions.</returns>
Expression[] ParseArguments()
{
List<Expression> argList = new List<Expression>();
while (true)
{
argList.Add(ParseExpression());
if (token.id != TokenId.Comma) break;
NextToken();
}
return argList.ToArray();
}
/// <summary>
/// Parse element access.
/// </summary>
/// <param name="expr">Expression.</param>
/// <returns>The expression.</returns>
Expression ParseElementAccess(Expression expr)
{
int errorPos = token.pos;
ValidateToken(TokenId.OpenBracket, Res.OpenParenExpected);
NextToken();
Expression[] args = ParseArguments();
ValidateToken(TokenId.CloseBracket, Res.CloseBracketOrCommaExpected);
NextToken();
if (expr.Type.IsArray)
{
if (expr.Type.GetArrayRank() != 1 || args.Length != 1)
throw ParseError(errorPos, Res.CannotIndexMultiDimArray);
Expression index = PromoteExpression(args[0], typeof(int), true);
if (index == null)
throw ParseError(errorPos, Res.InvalidIndex);
return Expression.ArrayIndex(expr, index);
}
else
{
MethodBase mb;
switch (FindIndexer(expr.Type, args, out mb))
{
case 0:
throw ParseError(errorPos, Res.NoApplicableIndexer,
GetTypeName(expr.Type));
case 1:
return Expression.Call(expr, (MethodInfo)mb, args);
default:
throw ParseError(errorPos, Res.AmbiguousIndexerInvocation,
GetTypeName(expr.Type));
}
}
}
/// <summary>
/// Is predefined type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>True if predfined type; else false.</returns>
static bool IsPredefinedType(Type type)
{
foreach (Type t in predefinedTypes) if (t == type) return true;
return false;
}
/// <summary>
/// Is nullable type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>True if nullable type; else false.</returns>
static bool IsNullableType(Type type)
{
return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
/// <summary>
/// Get non nullable type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The type.</returns>
static Type GetNonNullableType(Type type)
{
return IsNullableType(type) ? type.GetGenericArguments()[0] : type;
}
/// <summary>
/// Get type name.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The type name.</returns>
static string GetTypeName(Type type)
{
Type baseType = GetNonNullableType(type);
string s = baseType.Name;
if (type != baseType) s += '?';
return s;
}
/// <summary>
/// Is numeric type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>True if numeric type; else false.</returns>
static bool IsNumericType(Type type)
{
return GetNumericTypeKind(type) != 0;
}
/// <summary>
/// Is signed integral type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>True if signed integral type; else false.</returns>
static bool IsSignedIntegralType(Type type)
{
return GetNumericTypeKind(type) == 2;
}
/// <summary>
/// Is unsigned integral type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>True if unsigned integral type; else false.</returns>
static bool IsUnsignedIntegralType(Type type)
{
return GetNumericTypeKind(type) == 3;
}
/// <summary>
/// Get numeric type kind.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The numeric kind value.</returns>
static int GetNumericTypeKind(Type type)
{
type = GetNonNullableType(type);
if (type.IsEnum) return 0;
switch (Type.GetTypeCode(type))
{
case TypeCode.Char:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return 1;
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
return 2;
case TypeCode.Byte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return 3;
default:
return 0;
}
}
/// <summary>
/// Is enum type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>True if enum type; else false.</returns>
static bool IsEnumType(Type type)
{
return GetNonNullableType(type).IsEnum;
}
/// <summary>
/// Check and promote operand.
/// </summary>
/// <param name="signatures">The signatures type.</param>
/// <param name="opName">OP name.</param>
/// <param name="expr">Expression.</param>
/// <param name="errorPos">Error position.</param>
void CheckAndPromoteOperand(Type signatures, string opName, ref Expression expr, int errorPos)
{
Expression[] args = new Expression[] { expr };
MethodBase method;
if (FindMethod(signatures, "F", false, args, out method) != 1)
throw ParseError(errorPos, Res.IncompatibleOperand,
opName, GetTypeName(args[0].Type));
expr = args[0];
}
/// <summary>
/// Check and promote operands.
/// </summary>
/// <param name="signatures">The signatures type.</param>
/// <param name="opName">OP name.</param>
/// <param name="left">Expression</param>
/// <param name="right">Expression</param>
/// <param name="errorPos">Error position.</param>
void CheckAndPromoteOperands(Type signatures, string opName, ref Expression left, ref Expression right, int errorPos)
{
Expression[] args = new Expression[] { left, right };
MethodBase method;
if (FindMethod(signatures, "F", false, args, out method) != 1)
throw IncompatibleOperandsError(opName, left, right, errorPos);
left = args[0];
right = args[1];
}
/// <summary>
/// Incompatible operands error.
/// </summary>
/// <param name="opName">OP name.</param>
/// <param name="left">Expression</param>
/// <param name="right">Expression</param>
/// <param name="pos">The position.</param>
/// <returns>The exception.</returns>
Exception IncompatibleOperandsError(string opName, Expression left, Expression right, int pos)
{
return ParseError(pos, Res.IncompatibleOperands,
opName, GetTypeName(left.Type), GetTypeName(right.Type));
}
/// <summary>
/// Find property or field.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="memberName">Member name.</param>
/// <param name="staticAccess">Static access.</param>
/// <returns>The member info.</returns>
MemberInfo FindPropertyOrField(Type type, string memberName, bool staticAccess)
{
BindingFlags flags = BindingFlags.Public | BindingFlags.DeclaredOnly |
(staticAccess ? BindingFlags.Static : BindingFlags.Instance);
foreach (Type t in SelfAndBaseTypes(type))
{
MemberInfo[] members = t.FindMembers(MemberTypes.Property | MemberTypes.Field,
flags, Type.FilterNameIgnoreCase, memberName);
if (members.Length != 0) return members[0];
}
return null;
}
/// <summary>
/// Find method.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="methodName">Method name.</param>
/// <param name="staticAccess">Static access.</param>
/// <param name="args">Expression arguments.</param>
/// <param name="method">Method base.</param>
/// <returns>The method index.</returns>
int FindMethod(Type type, string methodName, bool staticAccess, Expression[] args, out MethodBase method)
{
BindingFlags flags = BindingFlags.Public | BindingFlags.DeclaredOnly |
(staticAccess ? BindingFlags.Static : BindingFlags.Instance);
foreach (Type t in SelfAndBaseTypes(type))
{
MemberInfo[] members = t.FindMembers(MemberTypes.Method,
flags, Type.FilterNameIgnoreCase, methodName);
int count = FindBestMethod(members.Cast<MethodBase>(), args, out method);
if (count != 0) return count;
}
method = null;
return 0;
}
/// <summary>
/// Find indexer.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="args">Expression arguments.</param>
/// <param name="method">Method base.</param>
/// <returns>The indexer.</returns>
int FindIndexer(Type type, Expression[] args, out MethodBase method)
{
foreach (Type t in SelfAndBaseTypes(type))
{
MemberInfo[] members = t.GetDefaultMembers();
if (members.Length != 0)
{
IEnumerable<MethodBase> methods = members.
OfType<PropertyInfo>().
Select(p => (MethodBase)p.GetGetMethod()).
Where(m => m != null);
int count = FindBestMethod(methods, args, out method);
if (count != 0) return count;
}
}
method = null;
return 0;
}
/// <summary>
/// Self and base types.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>Array of types.</returns>
static IEnumerable<Type> SelfAndBaseTypes(Type type)
{
if (type.IsInterface)
{
List<Type> types = new List<Type>();
AddInterface(types, type);
return types;
}
return SelfAndBaseClasses(type);
}
/// <summary>
/// Self and base classes.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>Array of types.</returns>
static IEnumerable<Type> SelfAndBaseClasses(Type type)
{
while (type != null)
{
yield return type;
type = type.BaseType;
}
}
/// <summary>
/// Add interface.
/// </summary>
/// <param name="types">The array of types.</param>
/// <param name="type">The type.</param>
static void AddInterface(List<Type> types, Type type)
{
if (!types.Contains(type))
{
types.Add(type);
foreach (Type t in type.GetInterfaces()) AddInterface(types, t);
}
}
/// <summary>
/// Method data.
/// </summary>
class MethodData
{
/// <summary>
/// Mathod base.
/// </summary>
public MethodBase MethodBase;
/// <summary>
/// Parameters.
/// </summary>
public ParameterInfo[] Parameters;
/// <summary>
/// Expression arguments.
/// </summary>
public Expression[] Args;
}
/// <summary>
/// Find best method.
/// </summary>
/// <param name="methods">Methods.</param>
/// <param name="args">Expression arguments.</param>
/// <param name="method">Method base.</param>
/// <returns>The method index.</returns>
int FindBestMethod(IEnumerable<MethodBase> methods, Expression[] args, out MethodBase method)
{
MethodData[] applicable = methods.
Select(m => new MethodData { MethodBase = m, Parameters = m.GetParameters() }).
Where(m => IsApplicable(m, args)).
ToArray();
if (applicable.Length > 1)
{
applicable = applicable.
Where(m => applicable.All(n => m == n || IsBetterThan(args, m, n))).
ToArray();
}
if (applicable.Length == 1)
{
MethodData md = applicable[0];
for (int i = 0; i < args.Length; i++) args[i] = md.Args[i];
method = md.MethodBase;
}
else
{
method = null;
}
return applicable.Length;
}
/// <summary>
/// Is applicable.
/// </summary>
/// <param name="method">Method data.</param>
/// <param name="args">Expression arguments.</param>
/// <returns>True if applicable; else false.</returns>
bool IsApplicable(MethodData method, Expression[] args)
{
if (method.Parameters.Length != args.Length) return false;
Expression[] promotedArgs = new Expression[args.Length];
for (int i = 0; i < args.Length; i++)
{
ParameterInfo pi = method.Parameters[i];
if (pi.IsOut) return false;
Expression promoted = PromoteExpression(args[i], pi.ParameterType, false);
if (promoted == null) return false;
promotedArgs[i] = promoted;
}
method.Args = promotedArgs;
return true;
}
/// <summary>
/// Promote expression.
/// </summary>
/// <param name="expr">Expression</param>
/// <param name="type">The type.</param>
/// <param name="exact">Exact.</param>
/// <returns>The expression.</returns>
Expression PromoteExpression(Expression expr, Type type, bool exact)
{
if (expr.Type == type) return expr;
if (expr is ConstantExpression)
{
ConstantExpression ce = (ConstantExpression)expr;
if (ce == nullLiteral)
{
if (!type.IsValueType || IsNullableType(type))
return Expression.Constant(null, type);
}
else
{
string text;
if (literals.TryGetValue(ce, out text))
{
Type target = GetNonNullableType(type);
Object value = null;
switch (Type.GetTypeCode(ce.Type))
{
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
value = ParseNumber(text, target);
break;
case TypeCode.Double:
if (target == typeof(decimal)) value = ParseNumber(text, target);
break;
case TypeCode.String:
value = ParseEnum(text, target);
break;
}
if (value != null)
return Expression.Constant(value, type);
}
}
}
if (IsCompatibleWith(expr.Type, type))
{
if (type.IsValueType || exact) return Expression.Convert(expr, type);
return expr;
}
return null;
}
/// <summary>
/// Parse number.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="type">The type.</param>
/// <returns>The object value.</returns>
static object ParseNumber(string text, Type type)
{
switch (Type.GetTypeCode(GetNonNullableType(type)))
{
case TypeCode.SByte:
sbyte sb;
if (sbyte.TryParse(text, out sb)) return sb;
break;
case TypeCode.Byte:
byte b;
if (byte.TryParse(text, out b)) return b;
break;
case TypeCode.Int16:
short s;
if (short.TryParse(text, out s)) return s;
break;
case TypeCode.UInt16:
ushort us;
if (ushort.TryParse(text, out us)) return us;
break;
case TypeCode.Int32:
int i;
if (int.TryParse(text, out i)) return i;
break;
case TypeCode.UInt32:
uint ui;
if (uint.TryParse(text, out ui)) return ui;
break;
case TypeCode.Int64:
long l;
if (long.TryParse(text, out l)) return l;
break;
case TypeCode.UInt64:
ulong ul;
if (ulong.TryParse(text, out ul)) return ul;
break;
case TypeCode.Single:
float f;
if (float.TryParse(text, out f)) return f;
break;
case TypeCode.Double:
double d;
if (double.TryParse(text, out d)) return d;
break;
case TypeCode.Decimal:
decimal e;
if (decimal.TryParse(text, out e)) return e;
break;
}
return null;
}
/// <summary>
/// Parse enum.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="type">The type.</param>
/// <returns>The object value.</returns>
static object ParseEnum(string name, Type type)
{
if (type.IsEnum)
{
MemberInfo[] memberInfos = type.FindMembers(MemberTypes.Field,
BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Static,
Type.FilterNameIgnoreCase, name);
if (memberInfos.Length != 0) return ((FieldInfo)memberInfos[0]).GetValue(null);
}
return null;
}
/// <summary>
/// Is compatible with.
/// </summary>
/// <param name="source">The source type.</param>
/// <param name="target">The target type.</param>
/// <returns>True if compatible with; else false.</returns>
static bool IsCompatibleWith(Type source, Type target)
{
if (source == target) return true;
if (!target.IsValueType) return target.IsAssignableFrom(source);
Type st = GetNonNullableType(source);
Type tt = GetNonNullableType(target);
if (st != source && tt == target) return false;
TypeCode sc = st.IsEnum ? TypeCode.Object : Type.GetTypeCode(st);
TypeCode tc = tt.IsEnum ? TypeCode.Object : Type.GetTypeCode(tt);
switch (sc)
{
case TypeCode.SByte:
switch (tc)
{
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Byte:
switch (tc)
{
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Int16:
switch (tc)
{
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.UInt16:
switch (tc)
{
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Int32:
switch (tc)
{
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.UInt32:
switch (tc)
{
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Int64:
switch (tc)
{
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.UInt64:
switch (tc)
{
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
}
break;
case TypeCode.Single:
switch (tc)
{
case TypeCode.Single:
case TypeCode.Double:
return true;
}
break;
default:
if (st == tt) return true;
break;
}
return false;
}
/// <summary>
/// Is better than.
/// </summary>
/// <param name="args">Expression arguments.</param>
/// <param name="m1">Method data.</param>
/// <param name="m2">Method data.</param>
/// <returns>True if is better than; else false.</returns>
static bool IsBetterThan(Expression[] args, MethodData m1, MethodData m2)
{
bool better = false;
for (int i = 0; i < args.Length; i++)
{
int c = CompareConversions(args[i].Type,
m1.Parameters[i].ParameterType,
m2.Parameters[i].ParameterType);
if (c < 0) return false;
if (c > 0) better = true;
}
return better;
}
/// <summary>
/// Return 1 if s -> t1 is a better conversion than s -> t2
/// Return -1 if s -> t2 is a better conversion than s -> t1
/// Return 0 if neither conversion is better
/// </summary>
/// <param name="s">The s type.</param>
/// <param name="t1">The type.</param>
/// <param name="t2">The type.</param>
/// <returns>The conversion index.</returns>
static int CompareConversions(Type s, Type t1, Type t2)
{
if (t1 == t2) return 0;
if (s == t1) return 1;
if (s == t2) return -1;
bool t1t2 = IsCompatibleWith(t1, t2);
bool t2t1 = IsCompatibleWith(t2, t1);
if (t1t2 && !t2t1) return 1;
if (t2t1 && !t1t2) return -1;
if (IsSignedIntegralType(t1) && IsUnsignedIntegralType(t2)) return 1;
if (IsSignedIntegralType(t2) && IsUnsignedIntegralType(t1)) return -1;
return 0;
}
/// <summary>
/// Generate equal.
/// </summary>
/// <param name="left">Expression</param>
/// <param name="right">Expression</param>
/// <returns>The expression.</returns>
Expression GenerateEqual(Expression left, Expression right)
{
return Expression.Equal(left, right);
}
/// <summary>
/// Generate not equal.
/// </summary>
/// <param name="left">Expression</param>
/// <param name="right">Expression</param>
/// <returns>The expression.</returns>
Expression GenerateNotEqual(Expression left, Expression right)
{
return Expression.NotEqual(left, right);
}
/// <summary>
/// Generate greater than.
/// </summary>
/// <param name="left">Expression</param>
/// <param name="right">Expression</param>
/// <returns>The expression.</returns>
Expression GenerateGreaterThan(Expression left, Expression right)
{
if (left.Type == typeof(string))
{
return Expression.GreaterThan(
GenerateStaticMethodCall("Compare", left, right),
Expression.Constant(0)
);
}
return Expression.GreaterThan(left, right);
}
/// <summary>
/// Generate greater than equal.
/// </summary>
/// <param name="left">Expression</param>
/// <param name="right">Expression</param>
/// <returns>The expression.</returns>
Expression GenerateGreaterThanEqual(Expression left, Expression right)
{
if (left.Type == typeof(string))
{
return Expression.GreaterThanOrEqual(
GenerateStaticMethodCall("Compare", left, right),
Expression.Constant(0)
);
}
return Expression.GreaterThanOrEqual(left, right);
}
/// <summary>
/// Generate less than.
/// </summary>
/// <param name="left">Expression</param>
/// <param name="right">Expression</param>
/// <returns>The expression.</returns>
Expression GenerateLessThan(Expression left, Expression right)
{
if (left.Type == typeof(string))
{
return Expression.LessThan(
GenerateStaticMethodCall("Compare", left, right),
Expression.Constant(0)
);
}
return Expression.LessThan(left, right);
}
/// <summary>
/// Generate less than equal.
/// </summary>
/// <param name="left">Expression</param>
/// <param name="right">Expression</param>
/// <returns>The expression.</returns>
Expression GenerateLessThanEqual(Expression left, Expression right)
{
if (left.Type == typeof(string))
{
return Expression.LessThanOrEqual(
GenerateStaticMethodCall("Compare", left, right),
Expression.Constant(0)
);
}
return Expression.LessThanOrEqual(left, right);
}
/// <summary>
/// Generate add.
/// </summary>
/// <param name="left">Expression</param>
/// <param name="right">Expression</param>
/// <returns>The expression.</returns>
Expression GenerateAdd(Expression left, Expression right)
{
if (left.Type == typeof(string) && right.Type == typeof(string))
{
return GenerateStaticMethodCall("Concat", left, right);
}
return Expression.Add(left, right);
}
/// <summary>
/// Generate subtract.
/// </summary>
/// <param name="left">Expression</param>
/// <param name="right">Expression</param>
/// <returns>The expression.</returns>
Expression GenerateSubtract(Expression left, Expression right)
{
return Expression.Subtract(left, right);
}
/// <summary>
/// Generate string concat.
/// </summary>
/// <param name="left">Expression</param>
/// <param name="right">Expression</param>
/// <returns>The expression.</returns>
Expression GenerateStringConcat(Expression left, Expression right)
{
return Expression.Call(
null,
typeof(string).GetMethod("Concat", new[] { typeof(object), typeof(object) }),
new[] { left, right });
}
/// <summary>
/// Get static method.
/// </summary>
/// <param name="methodName">Method name.</param>
/// <param name="left">Expression</param>
/// <param name="right">Expression</param>
/// <returns>The expression.</returns>
MethodInfo GetStaticMethod(string methodName, Expression left, Expression right)
{
return left.Type.GetMethod(methodName, new[] { left.Type, right.Type });
}
/// <summary>
/// Generate static method call.
/// </summary>
/// <param name="methodName">Method name.</param>
/// <param name="left">Expression</param>
/// <param name="right">Expression</param>
/// <returns>The expression.</returns>
Expression GenerateStaticMethodCall(string methodName, Expression left, Expression right)
{
return Expression.Call(null, GetStaticMethod(methodName, left, right), new[] { left, right });
}
/// <summary>
/// Set text position.
/// </summary>
/// <param name="pos">The position.</param>
void SetTextPos(int pos)
{
textPos = pos;
ch = textPos < textLen ? text[textPos] : '\0';
}
/// <summary>
/// Next char.
/// </summary>
void NextChar()
{
if (textPos < textLen) textPos++;
ch = textPos < textLen ? text[textPos] : '\0';
}
/// <summary>
/// Next token.
/// </summary>
void NextToken()
{
while (Char.IsWhiteSpace(ch)) NextChar();
TokenId t;
int tokenPos = textPos;
switch (ch)
{
case '!':
NextChar();
if (ch == '=')
{
NextChar();
t = TokenId.ExclamationEqual;
}
else
{
t = TokenId.Exclamation;
}
break;
case '%':
NextChar();
t = TokenId.Percent;
break;
case '&':
NextChar();
if (ch == '&')
{
NextChar();
t = TokenId.DoubleAmphersand;
}
else
{
t = TokenId.Amphersand;
}
break;
case '(':
NextChar();
t = TokenId.OpenParen;
break;
case ')':
NextChar();
t = TokenId.CloseParen;
break;
case '*':
NextChar();
t = TokenId.Asterisk;
break;
case '+':
NextChar();
t = TokenId.Plus;
break;
case ',':
NextChar();
t = TokenId.Comma;
break;
case '-':
NextChar();
t = TokenId.Minus;
break;
case '.':
NextChar();
t = TokenId.Dot;
break;
case '/':
NextChar();
t = TokenId.Slash;
break;
case ':':
NextChar();
t = TokenId.Colon;
break;
case '<':
NextChar();
if (ch == '=')
{
NextChar();
t = TokenId.LessThanEqual;
}
else if (ch == '>')
{
NextChar();
t = TokenId.LessGreater;
}
else
{
t = TokenId.LessThan;
}
break;
case '=':
NextChar();
if (ch == '=')
{
NextChar();
t = TokenId.DoubleEqual;
}
else
{
t = TokenId.Equal;
}
break;
case '>':
NextChar();
if (ch == '=')
{
NextChar();
t = TokenId.GreaterThanEqual;
}
else
{
t = TokenId.GreaterThan;
}
break;
case '?':
NextChar();
t = TokenId.Question;
break;
case '[':
NextChar();
t = TokenId.OpenBracket;
break;
case ']':
NextChar();
t = TokenId.CloseBracket;
break;
case '|':
NextChar();
if (ch == '|')
{
NextChar();
t = TokenId.DoubleBar;
}
else
{
t = TokenId.Bar;
}
break;
case '"':
case '\'':
char quote = ch;
do
{
NextChar();
while (textPos < textLen && ch != quote) NextChar();
if (textPos == textLen)
throw ParseError(textPos, Res.UnterminatedStringLiteral);
NextChar();
} while (ch == quote);
t = TokenId.StringLiteral;
break;
default:
if (Char.IsLetter(ch) || ch == '@' || ch == '_')
{
do
{
NextChar();
} while (Char.IsLetterOrDigit(ch) || ch == '_');
t = TokenId.Identifier;
break;
}
if (Char.IsDigit(ch))
{
t = TokenId.IntegerLiteral;
do
{
NextChar();
} while (Char.IsDigit(ch));
if (ch == '.')
{
t = TokenId.RealLiteral;
NextChar();
ValidateDigit();
do
{
NextChar();
} while (Char.IsDigit(ch));
}
if (ch == 'E' || ch == 'e')
{
t = TokenId.RealLiteral;
NextChar();
if (ch == '+' || ch == '-') NextChar();
ValidateDigit();
do
{
NextChar();
} while (Char.IsDigit(ch));
}
if (ch == 'F' || ch == 'f') NextChar();
break;
}
if (textPos == textLen)
{
t = TokenId.End;
break;
}
throw ParseError(textPos, Res.InvalidCharacter, ch);
}
token.id = t;
token.text = text.Substring(tokenPos, textPos - tokenPos);
token.pos = tokenPos;
}
/// <summary>
/// Token identifier is.
/// </summary>
/// <param name="id">The identifier id.</param>
/// <returns>True if token identifier is; else false.</returns>
bool TokenIdentifierIs(string id)
{
return token.id == TokenId.Identifier && String.Equals(id, token.text, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Get identifier.
/// </summary>
/// <returns>The identifier.</returns>
string GetIdentifier()
{
ValidateToken(TokenId.Identifier, Res.IdentifierExpected);
string id = token.text;
if (id.Length > 1 && id[0] == '@') id = id.Substring(1);
return id;
}
/// <summary>
/// Validate digit.
/// </summary>
void ValidateDigit()
{
if (!Char.IsDigit(ch)) throw ParseError(textPos, Res.DigitExpected);
}
/// <summary>
/// Validate token.
/// </summary>
/// <param name="t">The token id.</param>
/// <param name="errorMessage">Error message.</param>
void ValidateToken(TokenId t, string errorMessage)
{
if (token.id != t) throw ParseError(errorMessage);
}
/// <summary>
/// Validate token.
/// </summary>
/// <param name="t">The token id.</param>
void ValidateToken(TokenId t)
{
if (token.id != t) throw ParseError(Res.SyntaxError);
}
/// <summary>
/// Parse error.
/// </summary>
/// <param name="format">The format.</param>
/// <param name="args">The arguments.</param>
/// <returns>Exception</returns>
Exception ParseError(string format, params object[] args)
{
return ParseError(token.pos, format, args);
}
/// <summary>
/// Parse error.
/// </summary>
/// <param name="pos">The position.</param>
/// <param name="format">The format.</param>
/// <param name="args">The arguments.</param>
/// <returns>Exception</returns>
Exception ParseError(int pos, string format, params object[] args)
{
return new ParseException(string.Format(System.Globalization.CultureInfo.CurrentCulture, format, args), pos);
}
/// <summary>
/// Create keywords.
/// </summary>
/// <returns>The list of keywords.</returns>
static Dictionary<string, object> CreateKeywords()
{
Dictionary<string, object> d = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
d.Add("true", trueLiteral);
d.Add("false", falseLiteral);
d.Add("null", nullLiteral);
d.Add(keywordIt, keywordIt);
d.Add(keywordIif, keywordIif);
d.Add(keywordNew, keywordNew);
foreach (Type type in predefinedTypes) d.Add(type.Name, type);
return d;
}
}
/// <summary>
/// REsource string.
/// </summary>
internal static class Res
{
/// <summary>
/// DuplicateIdentifier
/// </summary>
public const string DuplicateIdentifier = "The identifier '{0}' was defined more than once";
/// <summary>
/// ExpressionTypeMismatch
/// </summary>
public const string ExpressionTypeMismatch = "Expression of type '{0}' expected";
/// <summary>
/// ExpressionExpected
/// </summary>
public const string ExpressionExpected = "Expression expected";
/// <summary>
/// InvalidCharacterLiteral
/// </summary>
public const string InvalidCharacterLiteral = "Character literal must contain exactly one character";
/// <summary>
/// InvalidIntegerLiteral
/// </summary>
public const string InvalidIntegerLiteral = "Invalid integer literal '{0}'";
/// <summary>
/// InvalidRealLiteral
/// </summary>
public const string InvalidRealLiteral = "Invalid real literal '{0}'";
/// <summary>
/// UnknownIdentifier
/// </summary>
public const string UnknownIdentifier = "Unknown identifier '{0}'";
/// <summary>
/// NoItInScope
/// </summary>
public const string NoItInScope = "No 'it' is in scope";
/// <summary>
/// IifRequiresThreeArgs
/// </summary>
public const string IifRequiresThreeArgs = "The 'iif' function requires three arguments";
/// <summary>
/// FirstExprMustBeBool
/// </summary>
public const string FirstExprMustBeBool = "The first expression must be of type 'Boolean'";
/// <summary>
/// BothTypesConvertToOther
/// </summary>
public const string BothTypesConvertToOther = "Both of the types '{0}' and '{1}' convert to the other";
/// <summary>
/// NeitherTypeConvertsToOther
/// </summary>
public const string NeitherTypeConvertsToOther = "Neither of the types '{0}' and '{1}' converts to the other";
/// <summary>
/// MissingAsClause
/// </summary>
public const string MissingAsClause = "Expression is missing an 'as' clause";
/// <summary>
/// ArgsIncompatibleWithLambda
/// </summary>
public const string ArgsIncompatibleWithLambda = "Argument list incompatible with lambda expression";
/// <summary>
/// TypeHasNoNullableForm
/// </summary>
public const string TypeHasNoNullableForm = "Type '{0}' has no nullable form";
/// <summary>
/// NoMatchingConstructor
/// </summary>
public const string NoMatchingConstructor = "No matching constructor in type '{0}'";
/// <summary>
/// AmbiguousConstructorInvocation
/// </summary>
public const string AmbiguousConstructorInvocation = "Ambiguous invocation of '{0}' constructor";
/// <summary>
/// CannotConvertValue
/// </summary>
public const string CannotConvertValue = "A value of type '{0}' cannot be converted to type '{1}'";
/// <summary>
/// NoApplicableMethod
/// </summary>
public const string NoApplicableMethod = "No applicable method '{0}' exists in type '{1}'";
/// <summary>
/// MethodsAreInaccessible
/// </summary>
public const string MethodsAreInaccessible = "Methods on type '{0}' are not accessible";
/// <summary>
/// MethodIsVoid
/// </summary>
public const string MethodIsVoid = "Method '{0}' in type '{1}' does not return a value";
/// <summary>
/// AmbiguousMethodInvocation
/// </summary>
public const string AmbiguousMethodInvocation = "Ambiguous invocation of method '{0}' in type '{1}'";
/// <summary>
/// UnknownPropertyOrField
/// </summary>
public const string UnknownPropertyOrField = "No property or field '{0}' exists in type '{1}'";
/// <summary>
/// NoApplicableAggregate
/// </summary>
public const string NoApplicableAggregate = "No applicable aggregate method '{0}' exists";
/// <summary>
/// CannotIndexMultiDimArray
/// </summary>
public const string CannotIndexMultiDimArray = "Indexing of multi-dimensional arrays is not supported";
/// <summary>
/// InvalidIndex
/// </summary>
public const string InvalidIndex = "Array index must be an integer expression";
/// <summary>
/// NoApplicableIndexer
/// </summary>
public const string NoApplicableIndexer = "No applicable indexer exists in type '{0}'";
/// <summary>
/// AmbiguousIndexerInvocation
/// </summary>
public const string AmbiguousIndexerInvocation = "Ambiguous invocation of indexer in type '{0}'";
/// <summary>
/// IncompatibleOperand
/// </summary>
public const string IncompatibleOperand = "Operator '{0}' incompatible with operand type '{1}'";
/// <summary>
/// IncompatibleOperands
/// </summary>
public const string IncompatibleOperands = "Operator '{0}' incompatible with operand types '{1}' and '{2}'";
/// <summary>
/// UnterminatedStringLiteral
/// </summary>
public const string UnterminatedStringLiteral = "Unterminated string literal";
/// <summary>
/// InvalidCharacter
/// </summary>
public const string InvalidCharacter = "Syntax error '{0}'";
/// <summary>
/// DigitExpected
/// </summary>
public const string DigitExpected = "Digit expected";
/// <summary>
/// SyntaxError
/// </summary>
public const string SyntaxError = "Syntax error";
/// <summary>
/// TokenExpected
/// </summary>
public const string TokenExpected = "{0} expected";
/// <summary>
/// ParseExceptionFormat
/// </summary>
public const string ParseExceptionFormat = "{0} (at index {1})";
/// <summary>
/// ColonExpected
/// </summary>
public const string ColonExpected = "':' expected";
/// <summary>
/// OpenParenExpected
/// </summary>
public const string OpenParenExpected = "'(' expected";
/// <summary>
/// CloseParenOrOperatorExpected
/// </summary>
public const string CloseParenOrOperatorExpected = "')' or operator expected";
/// <summary>
/// CloseParenOrCommaExpected
/// </summary>
public const string CloseParenOrCommaExpected = "')' or ',' expected";
/// <summary>
/// DotOrOpenParenExpected
/// </summary>
public const string DotOrOpenParenExpected = "'.' or '(' expected";
/// <summary>
/// OpenBracketExpected
/// </summary>
public const string OpenBracketExpected = "'[' expected";
/// <summary>
/// CloseBracketOrCommaExpected
/// </summary>
public const string CloseBracketOrCommaExpected = "']' or ',' expected";
/// <summary>
/// IdentifierExpected
/// </summary>
public const string IdentifierExpected = "Identifier expected";
}
}
| gpl-2.0 |
niloc132/mauve-gwt | src/main/java/gnu/testlet/java/lang/Error/classInfo/getModifiers.java | 2227 | // Test for method java.lang.Error.getClass().getModifiers()
// Copyright (C) 2012 Pavel Tisnovsky <ptisnovs@redhat.com>
// This file is part of Mauve.
// Mauve 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.
// Mauve 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 Mauve; see the file COPYING. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street,
// Fifth Floor, Boston, MA 02110-1301 USA.
package gnu.testlet.java.lang.Error.classInfo;
import gnu.testlet.TestHarness;
import gnu.testlet.Testlet;
import java.lang.Error;
import java.lang.reflect.Modifier;
/**
* Test for method java.lang.Error.getClass().getModifiers()
*/
public class getModifiers implements Testlet
{
/**
* Runs the test using the specified harness.
*
* @param harness the test harness (<code>null</code> not permitted).
*/
public void test(TestHarness harness)
{
// create instance of a class Double
Object o = new Error("Error");
// get a runtime class of an object "o"
Class c = o.getClass();
int modifiers = c.getModifiers();
harness.check( Modifier.isPublic(modifiers));
harness.check(!Modifier.isPrivate(modifiers));
harness.check(!Modifier.isProtected(modifiers));
harness.check(!Modifier.isAbstract(modifiers));
harness.check(!Modifier.isFinal(modifiers));
harness.check(!Modifier.isInterface(modifiers));
harness.check(!Modifier.isNative(modifiers));
harness.check(!Modifier.isStatic(modifiers));
harness.check(!Modifier.isStrict(modifiers));
harness.check(!Modifier.isSynchronized(modifiers));
harness.check(!Modifier.isTransient(modifiers));
harness.check(!Modifier.isVolatile(modifiers));
}
}
| gpl-2.0 |
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247972723/samba/dcerpc/drsuapi/DsReplicaModRequest1.py | 1298 | # encoding: utf-8
# module samba.dcerpc.drsuapi
# from /usr/lib/python2.7/dist-packages/samba/dcerpc/drsuapi.so
# by generator 1.135
""" drsuapi DCE/RPC """
# imports
import dcerpc as __dcerpc
import talloc as __talloc
class DsReplicaModRequest1(__talloc.Object):
# no doc
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
modify_fields = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
naming_context = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
options = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
replica_flags = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
schedule = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
source_dra = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
source_dra_address = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
| gpl-2.0 |
freddiegar/zerocodigo | zc/plantilla/js/jsLlamadosCrearAjax.js | 1569 | // Definicion de la accion {_nombreAccion_}
if (nombreAccion === '{_nombreAccion_}' && $('#{_idFormulario_}').parsley().validate()) {
$.ajax({
// A la accion se le concatena la palabra cliente, asi se llama en la funcion
url: URLControlador + '{_nombreAccion_}/',
method: 'POST',
dataType: 'JSON',
data: $('#{_idFormulario_}').serialize()+'&accion='+nombreAccion,
beforeSend: function(){
// Inactivar los campos para evitar modificaciones antes del envio
desactivarCampos();
},
success: function(rpta){
if (ZCRespuestaConError(rpta)) {
// Muestra mensaje de error
ZCAsignarErrores(rpta);
} else {
// Establece el id devuelto durante el proceso de insercion
$('#zc-id-{_idFormulario_}').val(rpta.info);
// Carga el listado con el registro insertado
window.location.assign(URLControlador + 'listar/' + rpta.info);
}
},
complete: function(){
// Activar los campos cuando se completa la solicitud, con error o sin error
activarCampos();
},
error: function(rpta){
ZCAsignarErrores('Error en el servicio');
}
});
}
| gpl-2.0 |
ehzil/light-injector | LightInjector/LightInjector.Annotations/ReferAttribute.cs | 1220 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LightInjector.Annotations
{
/// <summary>
/// Inject an instance from LightInjector.
/// </summary>
[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class ReferAttribute : Attribute
{
/// <summary>
/// Managed name
/// </summary>
public string Name { get; set; }
/// <summary>
/// Whether the instance is necessary
/// </summary>
public bool Required { get; set; }
/// <summary>
/// Constructor
/// </summary>
public ReferAttribute() : this(string.Empty) { }
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">Managed name. If this value is not been set, a default value will be generate.</param>
public ReferAttribute(string name) : this(name, true) { }
public ReferAttribute(string name, bool required)
{
this.Name = name;
this.Required = required;
}
}
}
| gpl-2.0 |
lv-code/mywordpress | wp-content/themes/steam/functions/shortcodes/toggles.php | 4233 | <?php
/**
*
*/
class itToggles {
/**
*
*/
public static function toggles( $atts = null, $content = null, $code = null ) {
if( $atts == 'generator' ) {
$numbers = range(1,100);
$option = array(
'name' => __( 'Toggle', IT_TEXTDOMAIN ),
'value' => 'toggles',
'options' => array(
array(
'name' => __( 'Behavior', IT_TEXTDOMAIN ),
'desc' => __( 'Should the toggles be individual or grouped together as an accordion style.', IT_TEXTDOMAIN ),
'id' => 'behavior',
'default' => '',
'options' => array(
'toggle' => __('Toggle', IT_TEXTDOMAIN ),
'accordion' => __('Accordion', IT_TEXTDOMAIN ),
),
'type' => 'select',
'target' => '',
'shortcode_dont_multiply' => true
),
array(
'name' => __( 'Number of toggles', IT_TEXTDOMAIN ),
'desc' => __( 'Select the number of toggles you wish to display.', IT_TEXTDOMAIN ),
'id' => 'multiply',
'default' => '',
'options' => $numbers,
'type' => 'select',
'target' => '',
'shortcode_multiplier' => true
),
array(
'name' => __( 'Toggle 1 Title', IT_TEXTDOMAIN ),
'desc' => __( 'The text to use for the toggle selector', IT_TEXTDOMAIN ),
'id' => 'title',
'default' => '',
'type' => 'text',
'shortcode_multiply' => true
),
array(
'name' => __( 'Toggle 1 Content', IT_TEXTDOMAIN ),
'desc' => __( 'The content of the toggle container. Shortcodes are accepted.', IT_TEXTDOMAIN ),
'id' => 'content',
'default' => '',
'type' => 'textarea',
'shortcode_multiply' => true
),
array(
'name' => __( 'Toggle 1 Default State', IT_TEXTDOMAIN ),
'desc' => __( 'Should this toggle be expanded or collapsed by default.', IT_TEXTDOMAIN ),
'id' => 'expanded',
'default' => '',
'options' => array(
'' => __('Collapsed', IT_TEXTDOMAIN ),
'in' => __('Expanded', IT_TEXTDOMAIN ),
),
'type' => 'select',
'target' => '',
'shortcode_multiply' => true
),
array(
'value' => 'toggle',
'nested' => true
),
'shortcode_has_atts' => true,
)
);
return $option;
}
extract(shortcode_atts(array(
'behavior' => 'toggle',
), $atts));
if (!preg_match_all("/(.?)\[(toggle)\b(.*?)(?:(\/))?\](?:(.+?)\[\/toggle\])?(.?)/s", $content, $matches)) {
return it_remove_wpautop( $content );
} else {
for($i = 0; $i < count($matches[0]); $i++) {
$matches[3][$i] = shortcode_parse_atts( $matches[3][$i] );
}
$id = rand();
$out = '';
if($behavior=='accordion') {
$accordionid = ' id="accordion_'.$id.'"';
$parent = ' data-parent="#accordion_'.$id.'"';
}
$out .= '<div class="accordion"'.$accordionid.'>';
for($i = 0; $i < count($matches[0]); $i++) {
$expanded = !empty($matches[3][$i]['expanded']) ? $matches[3][$i]['expanded'] : '';
if($behavior=='accordion') {
$collapseid = 'collapse_'.$i.'_'.$id;
} else {
$collapseid = 'toggle_'.$i.'_'.$id;
}
$out .= '<div class="accordion-group">';
$out .= '<div class="accordion-heading">';
$out .= '<a class="accordion-toggle" data-toggle="collapse"'.$parent.' href="#'.$collapseid.'">' . $matches[3][$i]['title'] . '</a>';
$out .= '</div>';
$out .= '<div id="'.$collapseid.'" class="accordion-body collapse '.$expanded.'">';
$out .= '<div class="accordion-inner">' . it_remove_wpautop( $matches[5][$i] ) . '</div>';
$out .= '</div>';
$out .= '</div>';
}
$out .= '</div>';
return $out;
}
}
/**
*
*/
public static function _options($class) {
$shortcode = array();
$class_methods = get_class_methods( $class );
foreach( $class_methods as $method ) {
if( $method[0] != '_' )
$shortcode[] = call_user_func(array( &$class, $method ), $atts = 'generator' );
}
$options = array(
'name' => __( 'Toggles & Accordions', IT_TEXTDOMAIN ),
'value' => 'toggles',
'options' => $shortcode,
);
return $options;
}
}
?>
| gpl-2.0 |
nagerenxiong/ChromeExtension | shangzheng/node_modules/zrender/lib/container/Group.js | 8050 | /**
* Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
* @module zrender/graphic/Group
* @example
* var Group = require('zrender/lib/container/Group');
* var Circle = require('zrender/lib/graphic/shape/Circle');
* var g = new Group();
* g.position[0] = 100;
* g.position[1] = 100;
* g.add(new Circle({
* style: {
* x: 100,
* y: 100,
* r: 20,
* }
* }));
* zr.add(g);
*/
var zrUtil = require('../core/util');
var Element = require('../Element');
var BoundingRect = require('../core/BoundingRect');
/**
* @alias module:zrender/graphic/Group
* @constructor
* @extends module:zrender/mixin/Transformable
* @extends module:zrender/mixin/Eventful
*/
var Group = function (opts) {
opts = opts || {};
Element.call(this, opts);
for (var key in opts) {
this[key] = opts[key];
}
this._children = [];
this.__storage = null;
this.__dirty = true;
};
Group.prototype = {
constructor: Group,
/**
* @type {string}
*/
type: 'group',
/**
* @return {Array.<module:zrender/Element>}
*/
children: function () {
return this._children.slice();
},
/**
* 获取指定 index 的儿子节点
* @param {number} idx
* @return {module:zrender/Element}
*/
childAt: function (idx) {
return this._children[idx];
},
/**
* 获取指定名字的儿子节点
* @param {string} name
* @return {module:zrender/Element}
*/
childOfName: function (name) {
var children = this._children;
for (var i = 0; i < children.length; i++) {
if (children[i].name === name) {
return children[i];
}
}
},
/**
* @return {number}
*/
childCount: function () {
return this._children.length;
},
/**
* 添加子节点到最后
* @param {module:zrender/Element} child
*/
add: function (child) {
if (child && child !== this && child.parent !== this) {
this._children.push(child);
this._doAdd(child);
}
return this;
},
/**
* 添加子节点在 nextSibling 之前
* @param {module:zrender/Element} child
* @param {module:zrender/Element} nextSibling
*/
addBefore: function (child, nextSibling) {
if (child && child !== this && child.parent !== this
&& nextSibling && nextSibling.parent === this) {
var children = this._children;
var idx = children.indexOf(nextSibling);
if (idx >= 0) {
children.splice(idx, 0, child);
this._doAdd(child);
}
}
return this;
},
_doAdd: function (child) {
if (child.parent) {
child.parent.remove(child);
}
child.parent = this;
var storage = this.__storage;
var zr = this.__zr;
if (storage && storage !== child.__storage) {
storage.addToMap(child);
if (child instanceof Group) {
child.addChildrenToStorage(storage);
}
}
zr && zr.refresh();
},
/**
* 移除子节点
* @param {module:zrender/Element} child
*/
remove: function (child) {
var zr = this.__zr;
var storage = this.__storage;
var children = this._children;
var idx = zrUtil.indexOf(children, child);
if (idx < 0) {
return this;
}
children.splice(idx, 1);
child.parent = null;
if (storage) {
storage.delFromMap(child.id);
if (child instanceof Group) {
child.delChildrenFromStorage(storage);
}
}
zr && zr.refresh();
return this;
},
/**
* 移除所有子节点
*/
removeAll: function () {
var children = this._children;
var storage = this.__storage;
var child;
var i;
for (i = 0; i < children.length; i++) {
child = children[i];
if (storage) {
storage.delFromMap(child.id);
if (child instanceof Group) {
child.delChildrenFromStorage(storage);
}
}
child.parent = null;
}
children.length = 0;
return this;
},
/**
* 遍历所有子节点
* @param {Function} cb
* @param {} context
*/
eachChild: function (cb, context) {
var children = this._children;
for (var i = 0; i < children.length; i++) {
var child = children[i];
cb.call(context, child, i);
}
return this;
},
/**
* 深度优先遍历所有子孙节点
* @param {Function} cb
* @param {} context
*/
traverse: function (cb, context) {
for (var i = 0; i < this._children.length; i++) {
var child = this._children[i];
cb.call(context, child);
if (child.type === 'group') {
child.traverse(cb, context);
}
}
return this;
},
addChildrenToStorage: function (storage) {
for (var i = 0; i < this._children.length; i++) {
var child = this._children[i];
storage.addToMap(child);
if (child instanceof Group) {
child.addChildrenToStorage(storage);
}
}
},
delChildrenFromStorage: function (storage) {
for (var i = 0; i < this._children.length; i++) {
var child = this._children[i];
storage.delFromMap(child.id);
if (child instanceof Group) {
child.delChildrenFromStorage(storage);
}
}
},
dirty: function () {
this.__dirty = true;
this.__zr && this.__zr.refresh();
return this;
},
/**
* @return {module:zrender/core/BoundingRect}
*/
getBoundingRect: function (includeChildren) {
// TODO Caching
// TODO Transform
var rect = null;
var tmpRect = new BoundingRect(0, 0, 0, 0);
var children = includeChildren || this._children;
var tmpMat = [];
for (var i = 0; i < children.length; i++) {
var child = children[i];
if (child.ignore || child.invisible) {
continue;
}
var childRect = child.getBoundingRect();
var transform = child.getLocalTransform(tmpMat);
if (transform) {
tmpRect.copy(childRect);
tmpRect.applyTransform(transform);
rect = rect || tmpRect.clone();
rect.union(tmpRect);
}
else {
rect = rect || childRect.clone();
rect.union(childRect);
}
}
return rect || tmpRect;
}
};
zrUtil.inherits(Group, Element);
module.exports = Group;
| gpl-2.0 |
v7fasttrack/virtuoso-opensource | binsrc/tests/biftest/java/Restricted.java | 1765 | /*
*
* This file is part of the OpenLink Software Virtuoso Open-Source (VOS)
* project.
*
* Copyright (C) 1998-2014 OpenLink Software
*
* This project is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; only version 2 of the License, dated June 1991.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
import java.io.*;
import java.lang.*;
import java.net.*;
public class Restricted
{
public static int ret_1 ()
{
return 1;
}
public static void write_file () throws Exception
{
String myFile = "foo";
File f = new File(myFile);
DataOutputStream dos;
try
{
dos = new DataOutputStream (new BufferedOutputStream(new FileOutputStream (myFile),128));
dos.writeBytes("Cats can hypnotize you when you least expect it.\n");
dos.flush();
dos.close();
}
catch (Exception e)
{
throw new Exception (e.getMessage());
}
}
public static void listen () throws Exception
{
ServerSocket demoSocket = null;
try
{
demoSocket = new ServerSocket(144);
}
catch (Exception e)
{
throw new Exception (e.getMessage());
}
}
public static String get_prop()
{
return System.getProperty("user.home", "not specified");
}
}
| gpl-2.0 |
kunj1988/Magento2 | app/code/Magento/Catalog/view/adminhtml/web/js/components/new-attribute-form.js | 2364 | /**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'jquery',
'Magento_Ui/js/form/form',
'Magento_Ui/js/modal/prompt',
'Magento_Ui/js/modal/alert'
], function ($, Form, prompt, alert) {
'use strict';
return Form.extend({
defaults: {
newSetPromptMessage: '',
listens: {
responseData: 'processResponseData'
},
modules: {
productForm: 'product_form.product_form'
}
},
/**
* Process response data
*
* @param {Object} data
*/
processResponseData: function (data) {
if (data.params['new_attribute_set_id']) {
this.productForm().params = {
set: data.params['new_attribute_set_id']
};
}
},
/**
* Process Save In New Attribute Set prompt
*/
saveAttributeInNewSet: function () {
var self = this;
prompt({
content: this.newSetPromptMessage,
actions: {
/**
* @param {String} val
* @this {actions}
*/
confirm: function (val) {
var rules = ['required-entry', 'validate-no-html-tags'],
editForm = self,
newAttributeSetName = val,
i,
params = {};
if (!newAttributeSetName) {
return;
}
for (i = 0; i < rules.length; i++) {
if (!$.validator.methods[rules[i]](newAttributeSetName)) {
alert({
content: $.validator.messages[rules[i]]
});
return;
}
}
params['new_attribute_set_name'] = newAttributeSetName;
editForm.setAdditionalData(params);
editForm.save();
}
}
});
}
});
});
| gpl-2.0 |
pypingou/pagure | alembic/versions/317a285e04a8_delete_hooks.py | 1538 | """Delete hooks
Revision ID: 317a285e04a8
Revises: 2aa7b3958bc5
Create Date: 2016-05-30 11:28:48.512577
"""
# revision identifiers, used by Alembic.
revision = '317a285e04a8'
down_revision = '2aa7b3958bc5'
from alembic import op
import sqlalchemy as sa
def upgrade():
""" Alter the hooks table to update the foreign key to cascade on delete.
"""
for table in [
'hook_fedmsg', 'hook_irc', 'hook_mail',
'hook_pagure_force_commit', 'hook_pagure', 'hook_pagure_requests',
'hook_pagure_tickets', 'hook_pagure_unsigned_commit', 'hook_rtd',
]:
op.drop_constraint(
'%s_project_id_fkey' % table,
table,
type_='foreignkey')
op. create_foreign_key(
name='%s_project_id_fkey' % table,
source_table=table,
referent_table='projects',
local_cols=['project_id'],
remote_cols=['id'],
onupdate='cascade',
ondelete='cascade',
)
op.drop_constraint(
'projects_groups_project_id_fkey',
'projects_groups',
type_='foreignkey')
op. create_foreign_key(
name='projects_groups_project_id_fkey',
source_table='projects_groups',
referent_table='projects',
local_cols=['project_id'],
remote_cols=['id'],
onupdate='cascade',
ondelete='cascade',
)
def downgrade():
""" Alter the hooks table to update the foreign key to undo the cascade
on delete.
"""
| gpl-2.0 |
HankTheDrunk/ultimaonlinemapcreator | REF/JB-dotPeek/DLL/Ultima/TileFlag.cs | 1047 | // Decompiled with JetBrains decompiler
// Type: Ultima.TileFlag
// Assembly: Ultima, Version=1.0.1472.37576, Culture=neutral, PublicKeyToken=null
// MVID: 46638872-DE1F-4F9F-8E8D-1BE44A131A9D
// Assembly location: W:\JetBrains\UOLandscaper\Ultima.dll
using System;
namespace Ultima
{
[Flags]
public enum TileFlag
{
None = 0,
Background = 1,
Weapon = 2,
Transparent = 4,
Translucent = 8,
Wall = 16,
Damaging = 32,
Impassable = 64,
Wet = 128,
Unknown1 = 256,
Surface = 512,
Bridge = 1024,
Generic = 2048,
Window = 4096,
NoShoot = 8192,
ArticleA = 16384,
ArticleAn = 32768,
Internal = 65536,
Foliage = 131072,
PartialHue = 262144,
Unknown2 = 524288,
Map = 1048576,
Container = 2097152,
Wearable = 4194304,
LightSource = 8388608,
Animation = 16777216,
NoDiagonal = 33554432,
Unknown3 = 67108864,
Armor = 134217728,
Roof = 268435456,
Door = 536870912,
StairBack = 1073741824,
StairRight = -2147483648,
}
}
| gpl-2.0 |
astridx/joomla-cms | build/media_source/system/js/fields/joomla-field-user.w-c.es6.js | 4274 | (() => {
class JoomlaFieldUser extends HTMLElement {
constructor() {
super();
this.onUserSelect = '';
this.onchangeStr = '';
this.buttonClick = this.buttonClick.bind(this);
this.iframeLoad = this.iframeLoad.bind(this);
}
static get observedAttributes() {
return ['url', 'modal-class', 'modal-width', 'modal-height', 'input', 'input-name', 'button-select'];
}
get url() { return this.getAttribute('url'); }
set url(value) { this.setAttribute('url', value); }
get modalClass() { return this.getAttribute('modal'); }
set modalClass(value) { this.setAttribute('modal', value); }
get modalWidth() { return this.getAttribute('modal-width'); }
set modalWidth(value) { this.setAttribute('modal-width', value); }
get modalHeight() { return this.getAttribute('modal-height'); }
set modalHeight(value) { this.setAttribute('modal-height', value); }
get inputId() { return this.getAttribute('input'); }
set inputId(value) { this.setAttribute('input', value); }
get inputNameClass() { return this.getAttribute('input-name'); }
set inputNameClass(value) { this.setAttribute('input-name', value); }
get buttonSelectClass() { return this.getAttribute('button-select'); }
set buttonSelectClass(value) { this.setAttribute('button-select', value); }
connectedCallback() {
// Set up elements
this.modal = this.querySelector(this.modalClass);
this.modalBody = this.querySelector('.modal-body');
this.input = this.querySelector(this.inputId);
this.inputName = this.querySelector(this.inputNameClass);
this.buttonSelect = this.querySelector(this.buttonSelectClass);
// Bind events
this.modalClose = this.modalClose.bind(this);
this.setValue = this.setValue.bind(this);
if (this.buttonSelect) {
this.buttonSelect.addEventListener('click', this.modalOpen.bind(this));
this.modal.addEventListener('hide', this.removeIframe.bind(this));
// Check for onchange callback,
this.onchangeStr = this.input.getAttribute('data-onchange');
if (this.onchangeStr) {
/* eslint-disable */
this.onUserSelect = new Function(this.onchangeStr);
this.input.addEventListener('change', this.onUserSelect);
/* eslint-enable */
}
}
}
disconnectedCallback() {
if (this.onchangeStr && this.input) {
this.input.removeEventListener('change', this.onUserSelect);
}
if (this.buttonSelect) {
this.buttonSelect.removeEventListener('click', this);
}
if (this.modal) {
this.modal.removeEventListener('hide', this);
}
}
buttonClick(event) {
this.setValue(event.target.getAttribute('data-user-value'), event.target.getAttribute('data-user-name'));
this.modalClose();
}
iframeLoad() {
const iframeDoc = this.iframeEl.contentWindow.document;
const buttons = [].slice.call(iframeDoc.querySelectorAll('.button-select'));
buttons.forEach((button) => {
button.addEventListener('click', this.buttonClick);
});
}
// Opens the modal
modalOpen() {
// Reconstruct the iframe
this.removeIframe();
const iframe = document.createElement('iframe');
iframe.setAttribute('name', 'field-user-modal');
iframe.src = this.url.replace('{field-user-id}', this.input.getAttribute('id'));
iframe.setAttribute('width', this.modalWidth);
iframe.setAttribute('height', this.modalHeight);
this.modalBody.appendChild(iframe);
this.modal.open();
this.iframeEl = this.modalBody.querySelector('iframe');
// handle the selection on the iframe
this.iframeEl.addEventListener('load', this.iframeLoad);
}
// Closes the modal
modalClose() {
Joomla.Modal.getCurrent().close();
this.modalBody.innerHTML = '';
}
// Remove the iframe
removeIframe() {
this.modalBody.innerHTML = '';
}
// Sets the value
setValue(value, name) {
this.input.setAttribute('value', value);
this.inputName.setAttribute('value', name || value);
}
}
customElements.define('joomla-field-user', JoomlaFieldUser);
})();
| gpl-2.0 |
bkhurram/advance-history-chrome | components/angular/angular.min.js | 104906 | /*
AngularJS v1.3.0-build.2498+sha.ccba305
(c) 2010-2014 Google, Inc. http://angularjs.org
License: MIT
*/
(function(Q,T,s){'use strict';function C(b){return function(){var a=arguments[0],c,a="["+(b?b+":":"")+a+"] http://errors.angularjs.org/1.3.0-build.2498+sha.ccba305/"+(b?b+"/":"")+a;for(c=1;c<arguments.length;c++)a=a+(1==c?"?":"&")+"p"+(c-1)+"="+encodeURIComponent("function"==typeof arguments[c]?arguments[c].toString().replace(/ \{[\s\S]*$/,""):"undefined"==typeof arguments[c]?"undefined":"string"!=typeof arguments[c]?JSON.stringify(arguments[c]):arguments[c]);return Error(a)}}function cb(b){if(null==
b||Ba(b))return!1;var a=b.length;return 1===b.nodeType&&a?!0:A(b)||J(b)||0===a||"number"===typeof a&&0<a&&a-1 in b}function r(b,a,c){var d;if(b)if(F(b))for(d in b)"prototype"==d||("length"==d||"name"==d||b.hasOwnProperty&&!b.hasOwnProperty(d))||a.call(c,b[d],d);else if(b.forEach&&b.forEach!==r)b.forEach(a,c);else if(cb(b))for(d=0;d<b.length;d++)a.call(c,b[d],d);else for(d in b)b.hasOwnProperty(d)&&a.call(c,b[d],d);return b}function Sb(b){var a=[],c;for(c in b)b.hasOwnProperty(c)&&a.push(c);return a.sort()}
function Zc(b,a,c){for(var d=Sb(b),e=0;e<d.length;e++)a.call(c,b[d[e]],d[e]);return d}function Tb(b){return function(a,c){b(c,a)}}function db(){for(var b=ia.length,a;b;){b--;a=ia[b].charCodeAt(0);if(57==a)return ia[b]="A",ia.join("");if(90==a)ia[b]="0";else return ia[b]=String.fromCharCode(a+1),ia.join("")}ia.unshift("0");return ia.join("")}function Ub(b,a){a?b.$$hashKey=a:delete b.$$hashKey}function t(b){var a=b.$$hashKey;r(arguments,function(a){a!==b&&r(a,function(a,c){b[c]=a})});Ub(b,a);return b}
function P(b){return parseInt(b,10)}function Vb(b,a){return t(new (t(function(){},{prototype:b})),a)}function z(){}function Ca(b){return b}function Y(b){return function(){return b}}function D(b){return"undefined"===typeof b}function w(b){return"undefined"!==typeof b}function W(b){return null!=b&&"object"===typeof b}function A(b){return"string"===typeof b}function zb(b){return"number"===typeof b}function oa(b){return"[object Date]"===ua.call(b)}function J(b){return"[object Array]"===ua.call(b)}function F(b){return"function"===
typeof b}function eb(b){return"[object RegExp]"===ua.call(b)}function Ba(b){return b&&b.document&&b.location&&b.alert&&b.setInterval}function $c(b){return!(!b||!(b.nodeName||b.prop&&b.attr&&b.find))}function ad(b,a,c){var d=[];r(b,function(b,f,h){d.push(a.call(c,b,f,h))});return d}function fb(b,a){if(b.indexOf)return b.indexOf(a);for(var c=0;c<b.length;c++)if(a===b[c])return c;return-1}function Da(b,a){var c=fb(b,a);0<=c&&b.splice(c,1);return a}function $(b,a){if(Ba(b)||b&&b.$evalAsync&&b.$watch)throw Na("cpws");
if(a){if(b===a)throw Na("cpi");if(J(b))for(var c=a.length=0;c<b.length;c++)a.push($(b[c]));else{c=a.$$hashKey;r(a,function(b,c){delete a[c]});for(var d in b)a[d]=$(b[d]);Ub(a,c)}}else(a=b)&&(J(b)?a=$(b,[]):oa(b)?a=new Date(b.getTime()):eb(b)?a=RegExp(b.source):W(b)&&(a=$(b,{})));return a}function Wb(b,a){a=a||{};for(var c in b)!b.hasOwnProperty(c)||"$"===c.charAt(0)&&"$"===c.charAt(1)||(a[c]=b[c]);return a}function va(b,a){if(b===a)return!0;if(null===b||null===a)return!1;if(b!==b&&a!==a)return!0;
var c=typeof b,d;if(c==typeof a&&"object"==c)if(J(b)){if(!J(a))return!1;if((c=b.length)==a.length){for(d=0;d<c;d++)if(!va(b[d],a[d]))return!1;return!0}}else{if(oa(b))return oa(a)&&b.getTime()==a.getTime();if(eb(b)&&eb(a))return b.toString()==a.toString();if(b&&b.$evalAsync&&b.$watch||a&&a.$evalAsync&&a.$watch||Ba(b)||Ba(a)||J(a))return!1;c={};for(d in b)if("$"!==d.charAt(0)&&!F(b[d])){if(!va(b[d],a[d]))return!1;c[d]=!0}for(d in a)if(!c.hasOwnProperty(d)&&"$"!==d.charAt(0)&&a[d]!==s&&!F(a[d]))return!1;
return!0}return!1}function Xb(){return T.securityPolicy&&T.securityPolicy.isActive||T.querySelector&&!(!T.querySelector("[ng-csp]")&&!T.querySelector("[data-ng-csp]"))}function gb(b,a){var c=2<arguments.length?wa.call(arguments,2):[];return!F(a)||a instanceof RegExp?a:c.length?function(){return arguments.length?a.apply(b,c.concat(wa.call(arguments,0))):a.apply(b,c)}:function(){return arguments.length?a.apply(b,arguments):a.call(b)}}function bd(b,a){var c=a;"string"===typeof b&&"$"===b.charAt(0)?c=
s:Ba(a)?c="$WINDOW":a&&T===a?c="$DOCUMENT":a&&(a.$evalAsync&&a.$watch)&&(c="$SCOPE");return c}function pa(b,a){return"undefined"===typeof b?s:JSON.stringify(b,bd,a?" ":null)}function Yb(b){return A(b)?JSON.parse(b):b}function Oa(b){"function"===typeof b?b=!0:b&&0!==b.length?(b=O(""+b),b=!("f"==b||"0"==b||"false"==b||"no"==b||"n"==b||"[]"==b)):b=!1;return b}function fa(b){b=v(b).clone();try{b.empty()}catch(a){}var c=v("<div>").append(b).html();try{return 3===b[0].nodeType?O(c):c.match(/^(<[^>]+>)/)[1].replace(/^<([\w\-]+)/,
function(a,b){return"<"+O(b)})}catch(d){return O(c)}}function Zb(b){try{return decodeURIComponent(b)}catch(a){}}function $b(b){var a={},c,d;r((b||"").split("&"),function(b){b&&(c=b.split("="),d=Zb(c[0]),w(d)&&(b=w(c[1])?Zb(c[1]):!0,a[d]?J(a[d])?a[d].push(b):a[d]=[a[d],b]:a[d]=b))});return a}function ac(b){var a=[];r(b,function(b,d){J(b)?r(b,function(b){a.push(xa(d,!0)+(!0===b?"":"="+xa(b,!0)))}):a.push(xa(d,!0)+(!0===b?"":"="+xa(b,!0)))});return a.length?a.join("&"):""}function Ab(b){return xa(b,
!0).replace(/%26/gi,"&").replace(/%3D/gi,"=").replace(/%2B/gi,"+")}function xa(b,a){return encodeURIComponent(b).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,a?"%20":"+")}function cd(b,a){function c(a){a&&d.push(a)}var d=[b],e,f,h=["ng:app","ng-app","x-ng-app","data-ng-app"],g=/\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;r(h,function(a){h[a]=!0;c(T.getElementById(a));a=a.replace(":","\\:");b.querySelectorAll&&(r(b.querySelectorAll("."+a),c),r(b.querySelectorAll("."+
a+"\\:"),c),r(b.querySelectorAll("["+a+"]"),c))});r(d,function(a){if(!e){var b=g.exec(" "+a.className+" ");b?(e=a,f=(b[2]||"").replace(/\s+/g,",")):r(a.attributes,function(b){!e&&h[b.name]&&(e=a,f=b.value)})}});e&&a(e,f?[f]:[])}function bc(b,a){var c=function(){b=v(b);if(b.injector()){var c=b[0]===T?"document":fa(b);throw Na("btstrpd",c);}a=a||[];a.unshift(["$provide",function(a){a.value("$rootElement",b)}]);a.unshift("ng");c=cc(a);c.invoke(["$rootScope","$rootElement","$compile","$injector","$animate",
function(a,b,c,d,e){a.$apply(function(){b.data("$injector",d);c(b)(a)})}]);return c},d=/^NG_DEFER_BOOTSTRAP!/;if(Q&&!d.test(Q.name))return c();Q.name=Q.name.replace(d,"");Pa.resumeBootstrap=function(b){r(b,function(b){a.push(b)});c()}}function hb(b,a){a=a||"_";return b.replace(dd,function(b,d){return(d?a:"")+b.toLowerCase()})}function Bb(b,a,c){if(!b)throw Na("areq",a||"?",c||"required");return b}function Qa(b,a,c){c&&J(b)&&(b=b[b.length-1]);Bb(F(b),a,"not a function, got "+(b&&"object"==typeof b?
b.constructor.name||"Object":typeof b));return b}function ya(b,a){if("hasOwnProperty"===b)throw Na("badname",a);}function dc(b,a,c){if(!a)return b;a=a.split(".");for(var d,e=b,f=a.length,h=0;h<f;h++)d=a[h],b&&(b=(e=b)[d]);return!c&&F(b)?gb(e,b):b}function Cb(b){var a=b[0];b=b[b.length-1];if(a===b)return v(a);var c=[a];do{a=a.nextSibling;if(!a)break;c.push(a)}while(a!==b);return v(c)}function ed(b){var a=C("$injector"),c=C("ng");b=b.angular||(b.angular={});b.$$minErr=b.$$minErr||C;return b.module||
(b.module=function(){var b={};return function(e,f,h){if("hasOwnProperty"===e)throw c("badname","module");f&&b.hasOwnProperty(e)&&(b[e]=null);return b[e]||(b[e]=function(){function b(a,d,e){return function(){c[e||"push"]([a,d,arguments]);return n}}if(!f)throw a("nomod",e);var c=[],d=[],l=b("$injector","invoke"),n={_invokeQueue:c,_runBlocks:d,requires:f,name:e,provider:b("$provide","provider"),factory:b("$provide","factory"),service:b("$provide","service"),value:b("$provide","value"),constant:b("$provide",
"constant","unshift"),animation:b("$animateProvider","register"),filter:b("$filterProvider","register"),controller:b("$controllerProvider","register"),directive:b("$compileProvider","directive"),config:l,run:function(a){d.push(a);return this}};h&&l(h);return n}())}}())}function fd(b){t(b,{bootstrap:bc,copy:$,extend:t,equals:va,element:v,forEach:r,injector:cc,noop:z,bind:gb,toJson:pa,fromJson:Yb,identity:Ca,isUndefined:D,isDefined:w,isString:A,isFunction:F,isObject:W,isNumber:zb,isElement:$c,isArray:J,
version:gd,isDate:oa,lowercase:O,uppercase:Ea,callbacks:{counter:0},$$minErr:C,$$csp:Xb});Ra=ed(Q);try{Ra("ngLocale")}catch(a){Ra("ngLocale",[]).provider("$locale",hd)}Ra("ng",["ngLocale"],["$provide",function(a){a.provider({$$sanitizeUri:id});a.provider("$compile",ec).directive({a:jd,input:fc,textarea:fc,form:kd,script:ld,select:md,style:nd,option:od,ngBind:pd,ngBindHtml:qd,ngBindTemplate:rd,ngClass:sd,ngClassEven:td,ngClassOdd:ud,ngCloak:vd,ngController:wd,ngForm:xd,ngHide:yd,ngIf:zd,ngInclude:Ad,
ngInit:Bd,ngNonBindable:Cd,ngPluralize:Dd,ngRepeat:Ed,ngShow:Fd,ngStyle:Gd,ngSwitch:Hd,ngSwitchWhen:Id,ngSwitchDefault:Jd,ngOptions:Kd,ngTransclude:Ld,ngModel:Md,ngList:Nd,ngChange:Od,required:gc,ngRequired:gc,ngValue:Pd}).directive({ngInclude:Qd}).directive(Db).directive(hc);a.provider({$anchorScroll:Rd,$animate:Sd,$browser:Td,$cacheFactory:Ud,$controller:Vd,$document:Wd,$exceptionHandler:Xd,$filter:ic,$interpolate:Yd,$interval:Zd,$http:$d,$httpBackend:ae,$location:be,$log:ce,$parse:de,$rootScope:ee,
$q:fe,$sce:ge,$sceDelegate:he,$sniffer:ie,$templateCache:je,$timeout:ke,$window:le,$$rAF:me,$$asyncCallback:ne})}])}function Sa(b){return b.replace(oe,function(a,b,d,e){return e?d.toUpperCase():d}).replace(pe,"Moz$1")}function Eb(b,a,c,d){function e(b){var e=c&&b?[this.filter(b)]:[this],m=a,k,l,n,q,p,u;if(!d||null!=b)for(;e.length;)for(k=e.shift(),l=0,n=k.length;l<n;l++)for(q=v(k[l]),m?q.triggerHandler("$destroy"):m=!m,p=0,q=(u=q.children()).length;p<q;p++)e.push(Fa(u[p]));return f.apply(this,arguments)}
var f=Fa.fn[b],f=f.$original||f;e.$original=f;Fa.fn[b]=e}function N(b){if(b instanceof N)return b;A(b)&&(b=aa(b));if(!(this instanceof N)){if(A(b)&&"<"!=b.charAt(0))throw Fb("nosel");return new N(b)}if(A(b)){var a=T.createElement("div");a.innerHTML="<div> </div>"+b;a.removeChild(a.firstChild);Gb(this,a.childNodes);v(T.createDocumentFragment()).append(this)}else Gb(this,b)}function Hb(b){return b.cloneNode(!0)}function Ga(b){jc(b);var a=0;for(b=b.childNodes||[];a<b.length;a++)Ga(b[a])}function kc(b,
a,c,d){if(w(d))throw Fb("offargs");var e=ja(b,"events");ja(b,"handle")&&(D(a)?r(e,function(a,c){Ta(b,c,a);delete e[c]}):r(a.split(" "),function(a){D(c)?(Ta(b,a,e[a]),delete e[a]):Da(e[a]||[],c)}))}function jc(b,a){var c=b[ib],d=Ua[c];d&&(a?delete Ua[c].data[a]:(d.handle&&(d.events.$destroy&&d.handle({},"$destroy"),kc(b)),delete Ua[c],b[ib]=s))}function ja(b,a,c){var d=b[ib],d=Ua[d||-1];if(w(c))d||(b[ib]=d=++qe,d=Ua[d]={}),d[a]=c;else return d&&d[a]}function lc(b,a,c){var d=ja(b,"data"),e=w(c),f=!e&&
w(a),h=f&&!W(a);d||h||ja(b,"data",d={});if(e)d[a]=c;else if(f){if(h)return d&&d[a];t(d,a)}else return d}function Ib(b,a){return b.getAttribute?-1<(" "+(b.getAttribute("class")||"")+" ").replace(/[\n\t]/g," ").indexOf(" "+a+" "):!1}function jb(b,a){a&&b.setAttribute&&r(a.split(" "),function(a){b.setAttribute("class",aa((" "+(b.getAttribute("class")||"")+" ").replace(/[\n\t]/g," ").replace(" "+aa(a)+" "," ")))})}function kb(b,a){if(a&&b.setAttribute){var c=(" "+(b.getAttribute("class")||"")+" ").replace(/[\n\t]/g,
" ");r(a.split(" "),function(a){a=aa(a);-1===c.indexOf(" "+a+" ")&&(c+=a+" ")});b.setAttribute("class",aa(c))}}function Gb(b,a){if(a){a=a.nodeName||!w(a.length)||Ba(a)?[a]:a;for(var c=0;c<a.length;c++)b.push(a[c])}}function mc(b,a){return lb(b,"$"+(a||"ngController")+"Controller")}function lb(b,a,c){b=v(b);9==b[0].nodeType&&(b=b.find("html"));for(a=J(a)?a:[a];b.length;){for(var d=b[0],e=0,f=a.length;e<f;e++)if((c=b.data(a[e]))!==s)return c;b=v(d.parentNode||11===d.nodeType&&d.host)}}function nc(b){for(var a=
0,c=b.childNodes;a<c.length;a++)Ga(c[a]);for(;b.firstChild;)b.removeChild(b.firstChild)}function oc(b,a){var c=mb[a.toLowerCase()];return c&&pc[b.nodeName]&&c}function re(b,a){var c=function(c,e){c.preventDefault||(c.preventDefault=function(){c.returnValue=!1});c.stopPropagation||(c.stopPropagation=function(){c.cancelBubble=!0});c.target||(c.target=c.srcElement||T);if(D(c.defaultPrevented)){var f=c.preventDefault;c.preventDefault=function(){c.defaultPrevented=!0;f.call(c)};c.defaultPrevented=!1}c.isDefaultPrevented=
function(){return c.defaultPrevented||!1===c.returnValue};var h=Wb(a[e||c.type]||[]);r(h,function(a){a.call(b,c)});8>=V?(c.preventDefault=null,c.stopPropagation=null,c.isDefaultPrevented=null):(delete c.preventDefault,delete c.stopPropagation,delete c.isDefaultPrevented)};c.elem=b;return c}function Ha(b){var a=typeof b,c;"object"==a&&null!==b?"function"==typeof(c=b.$$hashKey)?c=b.$$hashKey():c===s&&(c=b.$$hashKey=db()):c=b;return a+":"+c}function Va(b){r(b,this.put,this)}function qc(b){var a,c;"function"==
typeof b?(a=b.$inject)||(a=[],b.length&&(c=b.toString().replace(se,""),c=c.match(te),r(c[1].split(ue),function(b){b.replace(ve,function(b,c,d){a.push(d)})})),b.$inject=a):J(b)?(c=b.length-1,Qa(b[c],"fn"),a=b.slice(0,c)):Qa(b,"fn",!0);return a}function cc(b){function a(a){return function(b,c){if(W(b))r(b,Tb(a));else return a(b,c)}}function c(a,b){ya(a,"service");if(F(b)||J(b))b=n.instantiate(b);if(!b.$get)throw Wa("pget",a);return l[a+g]=b}function d(a,b){return c(a,{$get:b})}function e(a){var b=[],
c,d,f,g;r(a,function(a){if(!k.get(a)){k.put(a,!0);try{if(A(a))for(c=Ra(a),b=b.concat(e(c.requires)).concat(c._runBlocks),d=c._invokeQueue,f=0,g=d.length;f<g;f++){var h=d[f],m=n.get(h[0]);m[h[1]].apply(m,h[2])}else F(a)?b.push(n.invoke(a)):J(a)?b.push(n.invoke(a)):Qa(a,"module")}catch(l){throw J(a)&&(a=a[a.length-1]),l.message&&(l.stack&&-1==l.stack.indexOf(l.message))&&(l=l.message+"\n"+l.stack),Wa("modulerr",a,l.stack||l.message||l);}}});return b}function f(a,b){function c(d){if(a.hasOwnProperty(d)){if(a[d]===
h)throw Wa("cdep",m.join(" <- "));return a[d]}try{return m.unshift(d),a[d]=h,a[d]=b(d)}catch(e){throw a[d]===h&&delete a[d],e;}finally{m.shift()}}function d(a,b,e){var f=[],g=qc(a),h,m,k;m=0;for(h=g.length;m<h;m++){k=g[m];if("string"!==typeof k)throw Wa("itkn",k);f.push(e&&e.hasOwnProperty(k)?e[k]:c(k))}a.$inject||(a=a[h]);return a.apply(b,f)}return{invoke:d,instantiate:function(a,b){var c=function(){},e;c.prototype=(J(a)?a[a.length-1]:a).prototype;c=new c;e=d(a,c,b);return W(e)||F(e)?e:c},get:c,
annotate:qc,has:function(b){return l.hasOwnProperty(b+g)||a.hasOwnProperty(b)}}}var h={},g="Provider",m=[],k=new Va,l={$provide:{provider:a(c),factory:a(d),service:a(function(a,b){return d(a,["$injector",function(a){return a.instantiate(b)}])}),value:a(function(a,b){return d(a,Y(b))}),constant:a(function(a,b){ya(a,"constant");l[a]=b;q[a]=b}),decorator:function(a,b){var c=n.get(a+g),d=c.$get;c.$get=function(){var a=p.invoke(d,c);return p.invoke(b,null,{$delegate:a})}}}},n=l.$injector=f(l,function(){throw Wa("unpr",
m.join(" <- "));}),q={},p=q.$injector=f(q,function(a){a=n.get(a+g);return p.invoke(a.$get,a)});r(e(b),function(a){p.invoke(a||z)});return p}function Rd(){var b=!0;this.disableAutoScrolling=function(){b=!1};this.$get=["$window","$location","$rootScope",function(a,c,d){function e(a){var b=null;r(a,function(a){b||"a"!==O(a.nodeName)||(b=a)});return b}function f(){var b=c.hash(),d;b?(d=h.getElementById(b))?d.scrollIntoView():(d=e(h.getElementsByName(b)))?d.scrollIntoView():"top"===b&&a.scrollTo(0,0):
a.scrollTo(0,0)}var h=a.document;b&&d.$watch(function(){return c.hash()},function(){d.$evalAsync(f)});return f}]}function ne(){this.$get=["$$rAF","$timeout",function(b,a){return b.supported?function(a){return b(a)}:function(b){return a(b,0,!1)}}]}function we(b,a,c,d){function e(a){try{a.apply(null,wa.call(arguments,1))}finally{if(u--,0===u)for(;I.length;)try{I.pop()()}catch(b){c.error(b)}}}function f(a,b){(function nb(){r(E,function(a){a()});y=b(nb,a)})()}function h(){x=null;H!=g.url()&&(H=g.url(),
r(ba,function(a){a(g.url())}))}var g=this,m=a[0],k=b.location,l=b.history,n=b.setTimeout,q=b.clearTimeout,p={};g.isMock=!1;var u=0,I=[];g.$$completeOutstandingRequest=e;g.$$incOutstandingRequestCount=function(){u++};g.notifyWhenNoOutstandingRequests=function(a){r(E,function(a){a()});0===u?a():I.push(a)};var E=[],y;g.addPollFn=function(a){D(y)&&f(100,n);E.push(a);return a};var H=k.href,K=a.find("base"),x=null;g.url=function(a,c){k!==b.location&&(k=b.location);l!==b.history&&(l=b.history);if(a){if(H!=
a)return H=a,d.history?c?l.replaceState(null,"",a):(l.pushState(null,"",a),K.attr("href",K.attr("href"))):(x=a,c?k.replace(a):k.href=a),g}else return x||k.href.replace(/%27/g,"'")};var ba=[],R=!1;g.onUrlChange=function(a){if(!R){if(d.history)v(b).on("popstate",h);if(d.hashchange)v(b).on("hashchange",h);else g.addPollFn(h);R=!0}ba.push(a);return a};g.baseHref=function(){var a=K.attr("href");return a?a.replace(/^(https?\:)?\/\/[^\/]*/,""):""};var M={},Z="",U=g.baseHref();g.cookies=function(a,b){var d,
e,f,g;if(a)b===s?m.cookie=escape(a)+"=;path="+U+";expires=Thu, 01 Jan 1970 00:00:00 GMT":A(b)&&(d=(m.cookie=escape(a)+"="+escape(b)+";path="+U).length+1,4096<d&&c.warn("Cookie '"+a+"' possibly not set or overflowed because it was too large ("+d+" > 4096 bytes)!"));else{if(m.cookie!==Z)for(Z=m.cookie,d=Z.split("; "),M={},f=0;f<d.length;f++)e=d[f],g=e.indexOf("="),0<g&&(a=unescape(e.substring(0,g)),M[a]===s&&(M[a]=unescape(e.substring(g+1))));return M}};g.defer=function(a,b){var c;u++;c=n(function(){delete p[c];
e(a)},b||0);p[c]=!0;return c};g.defer.cancel=function(a){return p[a]?(delete p[a],q(a),e(z),!0):!1}}function Td(){this.$get=["$window","$log","$sniffer","$document",function(b,a,c,d){return new we(b,d,a,c)}]}function Ud(){this.$get=function(){function b(b,d){function e(a){a!=n&&(q?q==a&&(q=a.n):q=a,f(a.n,a.p),f(a,n),n=a,n.n=null)}function f(a,b){a!=b&&(a&&(a.p=b),b&&(b.n=a))}if(b in a)throw C("$cacheFactory")("iid",b);var h=0,g=t({},d,{id:b}),m={},k=d&&d.capacity||Number.MAX_VALUE,l={},n=null,q=null;
return a[b]={put:function(a,b){if(k<Number.MAX_VALUE){var c=l[a]||(l[a]={key:a});e(c)}if(!D(b))return a in m||h++,m[a]=b,h>k&&this.remove(q.key),b},get:function(a){if(k<Number.MAX_VALUE){var b=l[a];if(!b)return;e(b)}return m[a]},remove:function(a){if(k<Number.MAX_VALUE){var b=l[a];if(!b)return;b==n&&(n=b.p);b==q&&(q=b.n);f(b.n,b.p);delete l[a]}delete m[a];h--},removeAll:function(){m={};h=0;l={};n=q=null},destroy:function(){l=g=m=null;delete a[b]},info:function(){return t({},g,{size:h})}}}var a={};
b.info=function(){var b={};r(a,function(a,e){b[e]=a.info()});return b};b.get=function(b){return a[b]};return b}}function je(){this.$get=["$cacheFactory",function(b){return b("templates")}]}function ec(b,a){var c={},d="Directive",e=/^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,f=/(([\d\w\-_]+)(?:\:([^;]+))?;?)/,h=/^<\s*(tr|th|td|thead|tbody|tfoot)(\s+[^>]*)?>/i,g=/^(on[a-z]+|formaction)$/;this.directive=function k(a,e){ya(a,"directive");A(a)?(Bb(e,"directiveFactory"),c.hasOwnProperty(a)||(c[a]=[],b.factory(a+
d,["$injector","$exceptionHandler",function(b,d){var e=[];r(c[a],function(c,f){try{var g=b.invoke(c);F(g)?g={compile:Y(g)}:!g.compile&&g.link&&(g.compile=Y(g.link));g.priority=g.priority||0;g.index=f;g.name=g.name||a;g.require=g.require||g.controller&&g.name;g.restrict=g.restrict||"A";e.push(g)}catch(h){d(h)}});return e}])),c[a].push(e)):r(a,Tb(k));return this};this.aHrefSanitizationWhitelist=function(b){return w(b)?(a.aHrefSanitizationWhitelist(b),this):a.aHrefSanitizationWhitelist()};this.imgSrcSanitizationWhitelist=
function(b){return w(b)?(a.imgSrcSanitizationWhitelist(b),this):a.imgSrcSanitizationWhitelist()};this.$get=["$injector","$interpolate","$exceptionHandler","$http","$templateCache","$parse","$controller","$rootScope","$document","$sce","$animate","$$sanitizeUri",function(a,b,n,q,p,u,I,E,y,H,K,x){function ba(a,b,c,d,e){a instanceof v||(a=v(a));r(a,function(b,c){3==b.nodeType&&b.nodeValue.match(/\S+/)&&(a[c]=v(b).wrap("<span></span>").parent()[0])});var f=M(a,b,a,c,d,e);R(a,"ng-scope");return function(b,
c,d){Bb(b,"scope");var e=c?Ia.clone.call(a):a;r(d,function(a,b){e.data("$"+b+"Controller",a)});d=0;for(var g=e.length;d<g;d++){var h=e[d].nodeType;1!==h&&9!==h||e.eq(d).data("$scope",b)}c&&c(e,b);f&&f(b,e,e);return e}}function R(a,b){try{a.addClass(b)}catch(c){}}function M(a,b,c,d,e,f){function g(a,c,d,e){var f,k,l,n,p,q,u;f=c.length;var ca=Array(f);for(p=0;p<f;p++)ca[p]=c[p];u=p=0;for(q=h.length;p<q;u++)k=ca[u],c=h[p++],f=h[p++],l=v(k),c?(c.scope?(n=a.$new(),l.data("$scope",n)):n=a,(l=c.transclude)||
!e&&b?c(f,n,k,d,Z(a,l||b)):c(f,n,k,d,e)):f&&f(a,k.childNodes,s,e)}for(var h=[],k,l,n,p,q=0;q<a.length;q++)k=new Jb,l=U(a[q],[],k,0===q?d:s,e),(f=l.length?Xa(l,a[q],k,b,c,null,[],[],f):null)&&f.scope&&R(v(a[q]),"ng-scope"),k=f&&f.terminal||!(n=a[q].childNodes)||!n.length?null:M(n,f?f.transclude:b),h.push(f,k),p=p||f||k,f=null;return p?g:null}function Z(a,b){return function(c,d,e){var f=!1;c||(c=a.$new(),f=c.$$transcluded=!0);d=b(c,d,e);if(f)d.on("$destroy",gb(c,c.$destroy));return d}}function U(a,
b,c,d,g){var h=c.$attr,k;switch(a.nodeType){case 1:w(b,ka(Ja(a).toLowerCase()),"E",d,g);var l,n,p;k=a.attributes;for(var q=0,u=k&&k.length;q<u;q++){var I=!1,E=!1;l=k[q];if(!V||8<=V||l.specified){n=l.name;p=ka(n);la.test(p)&&(n=hb(p.substr(6),"-"));var H=p.replace(/(Start|End)$/,"");p===H+"Start"&&(I=n,E=n.substr(0,n.length-5)+"end",n=n.substr(0,n.length-6));p=ka(n.toLowerCase());h[p]=n;c[p]=l=aa(l.value);oc(a,p)&&(c[p]=!0);ga(a,b,l,p);w(b,p,"A",d,g,I,E)}}a=a.className;if(A(a)&&""!==a)for(;k=f.exec(a);)p=
ka(k[2]),w(b,p,"C",d,g)&&(c[p]=aa(k[3])),a=a.substr(k.index+k[0].length);break;case 3:N(b,a.nodeValue);break;case 8:try{if(k=e.exec(a.nodeValue))p=ka(k[1]),w(b,p,"M",d,g)&&(c[p]=aa(k[2]))}catch(x){}}b.sort(C);return b}function B(a,b,c){var d=[],e=0;if(b&&a.hasAttribute&&a.hasAttribute(b)){do{if(!a)throw ha("uterdir",b,c);1==a.nodeType&&(a.hasAttribute(b)&&e++,a.hasAttribute(c)&&e--);d.push(a);a=a.nextSibling}while(0<e)}else d.push(a);return v(d)}function za(a,b,c){return function(d,e,f,g,h){e=B(e[0],
b,c);return a(d,e,f,g,h)}}function Xa(a,c,d,e,f,g,h,k,p){function q(a,b,c,d){if(a){c&&(a=za(a,c,d));a.require=G.require;if(M===G||G.$$isolateScope)a=rc(a,{isolateScope:!0});h.push(a)}if(b){c&&(b=za(b,c,d));b.require=G.require;if(M===G||G.$$isolateScope)b=rc(b,{isolateScope:!0});k.push(b)}}function E(a,b,c){var d,e="data",f=!1;if(A(a)){for(;"^"==(d=a.charAt(0))||"?"==d;)a=a.substr(1),"^"==d&&(e="inheritedData"),f=f||"?"==d;d=null;c&&"data"===e&&(d=c[a]);d=d||b[e]("$"+a+"Controller");if(!d&&!f)throw ha("ctreq",
a,ga);}else J(a)&&(d=[],r(a,function(a){d.push(E(a,b,c))}));return d}function H(a,e,f,g,p){function q(a,b){var c;2>arguments.length&&(b=a,a=s);Ka&&(c=za);return p(a,b,c)}var x,ca,y,B,ba,U,za={},w;x=c===f?d:Wb(d,new Jb(v(f),d.$attr));ca=x.$$element;if(M){var xe=/^\s*([@=&])(\??)\s*(\w*)\s*$/;g=v(f);U=e.$new(!0);Z&&Z===M.$$originalDirective?g.data("$isolateScope",U):g.data("$isolateScopeNoTemplate",U);R(g,"ng-isolate-scope");r(M.scope,function(a,c){var d=a.match(xe)||[],f=d[3]||c,g="?"==d[2],d=d[1],
h,k,n,p;U.$$isolateBindings[c]=d+f;switch(d){case "@":x.$observe(f,function(a){U[c]=a});x.$$observers[f].$$scope=e;x[f]&&(U[c]=b(x[f])(e));break;case "=":if(g&&!x[f])break;k=u(x[f]);p=k.literal?va:function(a,b){return a===b};n=k.assign||function(){h=U[c]=k(e);throw ha("nonassign",x[f],M.name);};h=U[c]=k(e);U.$watch(function(){var a=k(e);p(a,U[c])||(p(a,h)?n(e,a=U[c]):U[c]=a);return h=a},null,k.literal);break;case "&":k=u(x[f]);U[c]=function(a){return k(e,a)};break;default:throw ha("iscp",M.name,c,
a);}})}w=p&&q;K&&r(K,function(a){var b={$scope:a===M||a.$$isolateScope?U:e,$element:ca,$attrs:x,$transclude:w},c;ba=a.controller;"@"==ba&&(ba=x[a.name]);c=I(ba,b);za[a.name]=c;Ka||ca.data("$"+a.name+"Controller",c);a.controllerAs&&(b.$scope[a.controllerAs]=c)});g=0;for(y=h.length;g<y;g++)try{B=h[g],B(B.isolateScope?U:e,ca,x,B.require&&E(B.require,ca,za),w)}catch(t){n(t,fa(ca))}g=e;M&&(M.template||null===M.templateUrl)&&(g=U);a&&a(g,f.childNodes,s,p);for(g=k.length-1;0<=g;g--)try{B=k[g],B(B.isolateScope?
U:e,ca,x,B.require&&E(B.require,ca,za),w)}catch(L){n(L,fa(ca))}}p=p||{};for(var x=-Number.MAX_VALUE,y,K=p.controllerDirectives,M=p.newIsolateScopeDirective,Z=p.templateDirective,w=p.nonTlbTranscludeDirective,Xa=!1,Ka=p.hasElementTranscludeDirective,L=d.$$element=v(c),G,ga,t,C=e,N,la=0,P=a.length;la<P;la++){G=a[la];var S=G.$$start,V=G.$$end;S&&(L=B(c,S,V));t=s;if(x>G.priority)break;if(t=G.scope)y=y||G,G.templateUrl||(Q("new/isolated scope",M,G,L),W(t)&&(M=G));ga=G.name;!G.templateUrl&&G.controller&&
(t=G.controller,K=K||{},Q("'"+ga+"' controller",K[ga],G,L),K[ga]=G);if(t=G.transclude)Xa=!0,G.$$tlb||(Q("transclusion",w,G,L),w=G),"element"==t?(Ka=!0,x=G.priority,t=B(c,S,V),L=d.$$element=v(T.createComment(" "+ga+": "+d[ga]+" ")),c=L[0],ob(f,v(wa.call(t,0)),c),C=ba(t,e,x,g&&g.name,{nonTlbTranscludeDirective:w})):(t=v(Hb(c)).contents(),L.empty(),C=ba(t,e));if(G.template)if(Q("template",Z,G,L),Z=G,t=F(G.template)?G.template(L,d):G.template,t=sc(t),G.replace){g=G;t=D(t);c=t[0];if(1!=t.length||1!==c.nodeType)throw ha("tplrt",
ga,"");ob(f,L,c);P={$attr:{}};t=U(c,[],P);var X=a.splice(la+1,a.length-(la+1));M&&nb(t);a=a.concat(t).concat(X);z(d,P);P=a.length}else L.html(t);if(G.templateUrl)Q("template",Z,G,L),Z=G,G.replace&&(g=G),H=O(a.splice(la,a.length-la),L,d,f,C,h,k,{controllerDirectives:K,newIsolateScopeDirective:M,templateDirective:Z,nonTlbTranscludeDirective:w}),P=a.length;else if(G.compile)try{N=G.compile(L,d,C),F(N)?q(null,N,S,V):N&&q(N.pre,N.post,S,V)}catch(Y){n(Y,fa(L))}G.terminal&&(H.terminal=!0,x=Math.max(x,G.priority))}H.scope=
y&&!0===y.scope;H.transclude=Xa&&C;p.hasElementTranscludeDirective=Ka;return H}function nb(a){for(var b=0,c=a.length;b<c;b++)a[b]=Vb(a[b],{$$isolateScope:!0})}function w(b,e,f,g,h,l,p){if(e===h)return null;h=null;if(c.hasOwnProperty(e)){var q;e=a.get(e+d);for(var u=0,I=e.length;u<I;u++)try{q=e[u],(g===s||g>q.priority)&&-1!=q.restrict.indexOf(f)&&(l&&(q=Vb(q,{$$start:l,$$end:p})),b.push(q),h=q)}catch(x){n(x)}}return h}function z(a,b){var c=b.$attr,d=a.$attr,e=a.$$element;r(a,function(d,e){"$"!=e.charAt(0)&&
(b[e]&&(d+=("style"===e?";":" ")+b[e]),a.$set(e,d,!0,c[e]))});r(b,function(b,f){"class"==f?(R(e,b),a["class"]=(a["class"]?a["class"]+" ":"")+b):"style"==f?(e.attr("style",e.attr("style")+";"+b),a.style=(a.style?a.style+";":"")+b):"$"==f.charAt(0)||a.hasOwnProperty(f)||(a[f]=b,d[f]=c[f])})}function D(a){var b;a=aa(a);if(b=h.exec(a)){b=b[1].toLowerCase();a=v("<table>"+a+"</table>");if(/(thead|tbody|tfoot)/.test(b))return a.children(b);a=a.children("tbody");return"tr"===b?a.children("tr"):a.children("tr").contents()}return v("<div>"+
a+"</div>").contents()}function O(a,b,c,d,e,f,g,h){var k=[],l,n,u=b[0],I=a.shift(),x=t({},I,{templateUrl:null,transclude:null,replace:null,$$originalDirective:I}),E=F(I.templateUrl)?I.templateUrl(b,c):I.templateUrl;b.empty();q.get(H.getTrustedResourceUrl(E),{cache:p}).success(function(p){var q,H;p=sc(p);if(I.replace){p=D(p);q=p[0];if(1!=p.length||1!==q.nodeType)throw ha("tplrt",I.name,E);p={$attr:{}};ob(d,b,q);var y=U(q,[],p);W(I.scope)&&nb(y);a=y.concat(a);z(c,p)}else q=u,b.html(p);a.unshift(x);
l=Xa(a,q,c,e,b,I,f,g,h);r(d,function(a,c){a==q&&(d[c]=b[0])});for(n=M(b[0].childNodes,e);k.length;){p=k.shift();H=k.shift();var B=k.shift(),K=k.shift(),y=b[0];if(H!==u){var ba=H.className;h.hasElementTranscludeDirective&&I.replace||(y=Hb(q));ob(B,v(H),y);R(v(y),ba)}H=l.transclude?Z(p,l.transclude):K;l(n,p,y,d,H)}k=null}).error(function(a,b,c,d){throw ha("tpload",d.url);});return function(a,b,c,d,e){k?(k.push(b),k.push(c),k.push(d),k.push(e)):l(n,b,c,d,e)}}function C(a,b){var c=b.priority-a.priority;
return 0!==c?c:a.name!==b.name?a.name<b.name?-1:1:a.index-b.index}function Q(a,b,c,d){if(b)throw ha("multidir",b.name,c.name,a,fa(d));}function N(a,c){var d=b(c,!0);d&&a.push({priority:0,compile:Y(function(a,b){var c=b.parent(),e=c.data("$binding")||[];e.push(d);R(c.data("$binding",e),"ng-binding");a.$watch(d,function(a){b[0].nodeValue=a})})})}function Ka(a,b){if("srcdoc"==b)return H.HTML;var c=Ja(a);if("xlinkHref"==b||"FORM"==c&&"action"==b||"IMG"!=c&&("src"==b||"ngSrc"==b))return H.RESOURCE_URL}
function ga(a,c,d,e){var f=b(d,!0);if(f){if("multiple"===e&&"SELECT"===Ja(a))throw ha("selmulti",fa(a));c.push({priority:100,compile:function(){return{pre:function(c,d,h){d=h.$$observers||(h.$$observers={});if(g.test(e))throw ha("nodomevents");if(f=b(h[e],!0,Ka(a,e)))h[e]=f(c),(d[e]||(d[e]=[])).$$inter=!0,(h.$$observers&&h.$$observers[e].$$scope||c).$watch(f,function(a,b){"class"===e&&a!=b?h.$updateClass(a,b):h.$set(e,a)})}}}})}}function ob(a,b,c){var d=b[0],e=b.length,f=d.parentNode,g,h;if(a)for(g=
0,h=a.length;g<h;g++)if(a[g]==d){a[g++]=c;h=g+e-1;for(var k=a.length;g<k;g++,h++)h<k?a[g]=a[h]:delete a[g];a.length-=e-1;break}f&&f.replaceChild(c,d);a=T.createDocumentFragment();a.appendChild(d);c[v.expando]=d[v.expando];d=1;for(e=b.length;d<e;d++)f=b[d],v(f).remove(),a.appendChild(f),delete b[d];b[0]=c;b.length=1}function rc(a,b){return t(function(){return a.apply(null,arguments)},a,b)}var Jb=function(a,b){this.$$element=a;this.$attr=b||{}};Jb.prototype={$normalize:ka,$addClass:function(a){a&&0<
a.length&&K.addClass(this.$$element,a)},$removeClass:function(a){a&&0<a.length&&K.removeClass(this.$$element,a)},$updateClass:function(a,b){var c=tc(a,b),d=tc(b,a);0===c.length?K.removeClass(this.$$element,d):0===d.length?K.addClass(this.$$element,c):K.setClass(this.$$element,c,d)},$set:function(a,b,c,d){var e=oc(this.$$element[0],a);e&&(this.$$element.prop(a,b),d=e);this[a]=b;d?this.$attr[a]=d:(d=this.$attr[a])||(this.$attr[a]=d=hb(a,"-"));e=Ja(this.$$element);if("A"===e&&"href"===a||"IMG"===e&&
"src"===a)this[a]=b=x(b,"src"===a);!1!==c&&(null===b||b===s?this.$$element.removeAttr(d):this.$$element.attr(d,b));(c=this.$$observers)&&r(c[a],function(a){try{a(b)}catch(c){n(c)}})},$observe:function(a,b){var c=this,d=c.$$observers||(c.$$observers={}),e=d[a]||(d[a]=[]);e.push(b);E.$evalAsync(function(){e.$$inter||b(c[a])});return function(){Da(e,b)}}};var P=b.startSymbol(),S=b.endSymbol(),sc="{{"==P||"}}"==S?Ca:function(a){return a.replace(/\{\{/g,P).replace(/}}/g,S)},la=/^ngAttr[A-Z]/;return ba}]}
function ka(b){return Sa(b.replace(ye,""))}function tc(b,a){var c="",d=b.split(/\s+/),e=a.split(/\s+/),f=0;a:for(;f<d.length;f++){for(var h=d[f],g=0;g<e.length;g++)if(h==e[g])continue a;c+=(0<c.length?" ":"")+h}return c}function Vd(){var b={},a=/^(\S+)(\s+as\s+(\w+))?$/;this.register=function(a,d){ya(a,"controller");W(a)?t(b,a):b[a]=d};this.$get=["$injector","$window",function(c,d){return function(e,f){var h,g,m;A(e)&&(h=e.match(a),g=h[1],m=h[3],e=b.hasOwnProperty(g)?b[g]:dc(f.$scope,g,!0)||dc(d,
g,!0),Qa(e,g,!0));h=c.instantiate(e,f);if(m){if(!f||"object"!=typeof f.$scope)throw C("$controller")("noscp",g||e.name,m);f.$scope[m]=h}return h}}]}function Wd(){this.$get=["$window",function(b){return v(b.document)}]}function Xd(){this.$get=["$log",function(b){return function(a,c){b.error.apply(b,arguments)}}]}function uc(b){var a={},c,d,e;if(!b)return a;r(b.split("\n"),function(b){e=b.indexOf(":");c=O(aa(b.substr(0,e)));d=aa(b.substr(e+1));c&&(a[c]=a[c]?a[c]+(", "+d):d)});return a}function vc(b){var a=
W(b)?b:s;return function(c){a||(a=uc(b));return c?a[O(c)]||null:a}}function wc(b,a,c){if(F(c))return c(b,a);r(c,function(c){b=c(b,a)});return b}function $d(){var b=/^\s*(\[|\{[^\{])/,a=/[\}\]]\s*$/,c=/^\)\]\}',?\n/,d={"Content-Type":"application/json;charset=utf-8"},e=this.defaults={transformResponse:[function(d){A(d)&&(d=d.replace(c,""),b.test(d)&&a.test(d)&&(d=Yb(d)));return d}],transformRequest:[function(a){return W(a)&&"[object File]"!==ua.call(a)&&"[object Blob]"!==ua.call(a)?pa(a):a}],headers:{common:{Accept:"application/json, text/plain, */*"},
post:$(d),put:$(d),patch:$(d)},xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN"},f=this.interceptors=[],h=this.responseInterceptors=[];this.$get=["$httpBackend","$browser","$cacheFactory","$rootScope","$q","$injector",function(a,b,c,d,n,q){function p(a){function c(a){var b=t({},a,{data:wc(a.data,a.headers,d.transformResponse)});return 200<=a.status&&300>a.status?b:n.reject(b)}var d={method:"get",transformRequest:e.transformRequest,transformResponse:e.transformResponse},f=function(a){function b(a){var c;
r(a,function(b,d){F(b)&&(c=b(),null!=c?a[d]=c:delete a[d])})}var c=e.headers,d=t({},a.headers),f,g,c=t({},c.common,c[O(a.method)]);b(c);b(d);a:for(f in c){a=O(f);for(g in d)if(O(g)===a)continue a;d[f]=c[f]}return d}(a);t(d,a);d.headers=f;d.method=Ea(d.method);(a=Kb(d.url)?b.cookies()[d.xsrfCookieName||e.xsrfCookieName]:s)&&(f[d.xsrfHeaderName||e.xsrfHeaderName]=a);var g=[function(a){f=a.headers;var b=wc(a.data,vc(f),a.transformRequest);D(a.data)&&r(f,function(a,b){"content-type"===O(b)&&delete f[b]});
D(a.withCredentials)&&!D(e.withCredentials)&&(a.withCredentials=e.withCredentials);return u(a,b,f).then(c,c)},s],h=n.when(d);for(r(y,function(a){(a.request||a.requestError)&&g.unshift(a.request,a.requestError);(a.response||a.responseError)&&g.push(a.response,a.responseError)});g.length;){a=g.shift();var k=g.shift(),h=h.then(a,k)}h.success=function(a){h.then(function(b){a(b.data,b.status,b.headers,d)});return h};h.error=function(a){h.then(null,function(b){a(b.data,b.status,b.headers,d)});return h};
return h}function u(b,c,f){function h(a,b,c){y&&(200<=a&&300>a?y.put(s,[a,b,uc(c)]):y.remove(s));k(b,a,c);d.$$phase||d.$apply()}function k(a,c,d){c=Math.max(c,0);(200<=c&&300>c?q.resolve:q.reject)({data:a,status:c,headers:vc(d),config:b})}function m(){var a=fb(p.pendingRequests,b);-1!==a&&p.pendingRequests.splice(a,1)}var q=n.defer(),u=q.promise,y,r,s=I(b.url,b.params);p.pendingRequests.push(b);u.then(m,m);(b.cache||e.cache)&&(!1!==b.cache&&"GET"==b.method)&&(y=W(b.cache)?b.cache:W(e.cache)?e.cache:
E);if(y)if(r=y.get(s),w(r)){if(r.then)return r.then(m,m),r;J(r)?k(r[1],r[0],$(r[2])):k(r,200,{})}else y.put(s,u);D(r)&&a(b.method,s,c,h,f,b.timeout,b.withCredentials,b.responseType);return u}function I(a,b){if(!b)return a;var c=[];Zc(b,function(a,b){null===a||D(a)||(J(a)||(a=[a]),r(a,function(a){W(a)&&(a=pa(a));c.push(xa(b)+"="+xa(a))}))});0<c.length&&(a+=(-1==a.indexOf("?")?"?":"&")+c.join("&"));return a}var E=c("$http"),y=[];r(f,function(a){y.unshift(A(a)?q.get(a):q.invoke(a))});r(h,function(a,
b){var c=A(a)?q.get(a):q.invoke(a);y.splice(b,0,{response:function(a){return c(n.when(a))},responseError:function(a){return c(n.reject(a))}})});p.pendingRequests=[];(function(a){r(arguments,function(a){p[a]=function(b,c){return p(t(c||{},{method:a,url:b}))}})})("get","delete","head","jsonp");(function(a){r(arguments,function(a){p[a]=function(b,c,d){return p(t(d||{},{method:a,url:b,data:c}))}})})("post","put");p.defaults=e;return p}]}function ze(b){if(8>=V&&(!b.match(/^(get|post|head|put|delete|options)$/i)||
!Q.XMLHttpRequest))return new Q.ActiveXObject("Microsoft.XMLHTTP");if(Q.XMLHttpRequest)return new Q.XMLHttpRequest;throw C("$httpBackend")("noxhr");}function ae(){this.$get=["$browser","$window","$document",function(b,a,c){return Ae(b,ze,b.defer,a.angular.callbacks,c[0])}]}function Ae(b,a,c,d,e){function f(a,b,c){var f=e.createElement("script"),h=null;f.type="text/javascript";f.src=a;f.async=!0;h=function(a){Ta(f,"load",h);Ta(f,"error",h);e.body.removeChild(f);f=null;var g=-1,u="unknown";a&&("load"!==
a.type||d[b].called||(a={type:"error"}),u=a.type,g="error"===a.type?404:200);c&&c(g,u)};pb(f,"load",h);pb(f,"error",h);e.body.appendChild(f);return h}var h=-1;return function(e,m,k,l,n,q,p,u){function I(){y=h;K&&K();x&&x.abort()}function E(a,d,e,f){R&&c.cancel(R);K=x=null;0===d&&(d=e?200:"file"==qa(m).protocol?404:0);a(1223==d?204:d,e,f);b.$$completeOutstandingRequest(z)}var y;b.$$incOutstandingRequestCount();m=m||b.url();if("jsonp"==O(e)){var H="_"+(d.counter++).toString(36);d[H]=function(a){d[H].data=
a;d[H].called=!0};var K=f(m.replace("JSON_CALLBACK","angular.callbacks."+H),H,function(a,b){E(l,a,d[H].data,"",b);d[H]=z})}else{var x=a(e);x.open(e,m,!0);r(n,function(a,b){w(a)&&x.setRequestHeader(b,a)});x.onreadystatechange=function(){if(x&&4==x.readyState){var a=null,b=null;y!==h&&(a=x.getAllResponseHeaders(),b="response"in x?x.response:x.responseText);E(l,y||x.status,b,a)}};p&&(x.withCredentials=!0);if(u)try{x.responseType=u}catch(s){if("json"!==u)throw s;}x.send(k||null)}if(0<q)var R=c(I,q);else q&&
q.then&&q.then(I)}}function Yd(){var b="{{",a="}}";this.startSymbol=function(a){return a?(b=a,this):b};this.endSymbol=function(b){return b?(a=b,this):a};this.$get=["$parse","$exceptionHandler","$sce",function(c,d,e){function f(f,k,l){for(var n,q,p=0,u=[],I=f.length,E=!1,y=[];p<I;)-1!=(n=f.indexOf(b,p))&&-1!=(q=f.indexOf(a,n+h))?(p!=n&&u.push(f.substring(p,n)),u.push(p=c(E=f.substring(n+h,q))),p.exp=E,p=q+g,E=!0):(p!=I&&u.push(f.substring(p)),p=I);(I=u.length)||(u.push(""),I=1);if(l&&1<u.length)throw xc("noconcat",
f);if(!k||E)return y.length=I,p=function(a){try{for(var b=0,c=I,g;b<c;b++)"function"==typeof(g=u[b])&&(g=g(a),g=l?e.getTrusted(l,g):e.valueOf(g),null===g||D(g)?g="":"string"!=typeof g&&(g=pa(g))),y[b]=g;return y.join("")}catch(h){a=xc("interr",f,h.toString()),d(a)}},p.exp=f,p.parts=u,p}var h=b.length,g=a.length;f.startSymbol=function(){return b};f.endSymbol=function(){return a};return f}]}function Zd(){this.$get=["$rootScope","$window","$q",function(b,a,c){function d(d,h,g,m){var k=a.setInterval,
l=a.clearInterval,n=c.defer(),q=n.promise,p=0,u=w(m)&&!m;g=w(g)?g:0;q.then(null,null,d);q.$$intervalId=k(function(){n.notify(p++);0<g&&p>=g&&(n.resolve(p),l(q.$$intervalId),delete e[q.$$intervalId]);u||b.$apply()},h);e[q.$$intervalId]=n;return q}var e={};d.cancel=function(a){return a&&a.$$intervalId in e?(e[a.$$intervalId].reject("canceled"),clearInterval(a.$$intervalId),delete e[a.$$intervalId],!0):!1};return d}]}function hd(){this.$get=function(){return{id:"en-us",NUMBER_FORMATS:{DECIMAL_SEP:".",
GROUP_SEP:",",PATTERNS:[{minInt:1,minFrac:0,maxFrac:3,posPre:"",posSuf:"",negPre:"-",negSuf:"",gSize:3,lgSize:3},{minInt:1,minFrac:2,maxFrac:2,posPre:"\u00a4",posSuf:"",negPre:"(\u00a4",negSuf:")",gSize:3,lgSize:3}],CURRENCY_SYM:"$"},DATETIME_FORMATS:{MONTH:"January February March April May June July August September October November December".split(" "),SHORTMONTH:"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),DAY:"Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),
SHORTDAY:"Sun Mon Tue Wed Thu Fri Sat".split(" "),AMPMS:["AM","PM"],medium:"MMM d, y h:mm:ss a","short":"M/d/yy h:mm a",fullDate:"EEEE, MMMM d, y",longDate:"MMMM d, y",mediumDate:"MMM d, y",shortDate:"M/d/yy",mediumTime:"h:mm:ss a",shortTime:"h:mm a"},pluralCat:function(b){return 1===b?"one":"other"}}}}function yc(b){b=b.split("/");for(var a=b.length;a--;)b[a]=Ab(b[a]);return b.join("/")}function zc(b,a,c){b=qa(b,c);a.$$protocol=b.protocol;a.$$host=b.hostname;a.$$port=P(b.port)||Be[b.protocol]||null}
function Ac(b,a,c){var d="/"!==b.charAt(0);d&&(b="/"+b);b=qa(b,c);a.$$path=decodeURIComponent(d&&"/"===b.pathname.charAt(0)?b.pathname.substring(1):b.pathname);a.$$search=$b(b.search);a.$$hash=decodeURIComponent(b.hash);a.$$path&&"/"!=a.$$path.charAt(0)&&(a.$$path="/"+a.$$path)}function ma(b,a){if(0===a.indexOf(b))return a.substr(b.length)}function Ya(b){var a=b.indexOf("#");return-1==a?b:b.substr(0,a)}function Lb(b){return b.substr(0,Ya(b).lastIndexOf("/")+1)}function Bc(b,a){this.$$html5=!0;a=a||
"";var c=Lb(b);zc(b,this,b);this.$$parse=function(a){var e=ma(c,a);if(!A(e))throw Mb("ipthprfx",a,c);Ac(e,this,b);this.$$path||(this.$$path="/");this.$$compose()};this.$$compose=function(){var a=ac(this.$$search),b=this.$$hash?"#"+Ab(this.$$hash):"";this.$$url=yc(this.$$path)+(a?"?"+a:"")+b;this.$$absUrl=c+this.$$url.substr(1)};this.$$rewrite=function(d){var e;if((e=ma(b,d))!==s)return d=e,(e=ma(a,e))!==s?c+(ma("/",e)||e):b+d;if((e=ma(c,d))!==s)return c+e;if(c==d+"/")return c}}function Nb(b,a){var c=
Lb(b);zc(b,this,b);this.$$parse=function(d){var e=ma(b,d)||ma(c,d),e="#"==e.charAt(0)?ma(a,e):this.$$html5?e:"";if(!A(e))throw Mb("ihshprfx",d,a);Ac(e,this,b);d=this.$$path;var f=/^\/?.*?:(\/.*)/;0===e.indexOf(b)&&(e=e.replace(b,""));f.exec(e)||(d=(e=f.exec(d))?e[1]:d);this.$$path=d;this.$$compose()};this.$$compose=function(){var c=ac(this.$$search),e=this.$$hash?"#"+Ab(this.$$hash):"";this.$$url=yc(this.$$path)+(c?"?"+c:"")+e;this.$$absUrl=b+(this.$$url?a+this.$$url:"")};this.$$rewrite=function(a){if(Ya(b)==
Ya(a))return a}}function Cc(b,a){this.$$html5=!0;Nb.apply(this,arguments);var c=Lb(b);this.$$rewrite=function(d){var e;if(b==Ya(d))return d;if(e=ma(c,d))return b+a+e;if(c===d+"/")return c}}function qb(b){return function(){return this[b]}}function Dc(b,a){return function(c){if(D(c))return this[b];this[b]=a(c);this.$$compose();return this}}function be(){var b="",a=!1;this.hashPrefix=function(a){return w(a)?(b=a,this):b};this.html5Mode=function(b){return w(b)?(a=b,this):a};this.$get=["$rootScope","$browser",
"$sniffer","$rootElement",function(c,d,e,f){function h(a){c.$broadcast("$locationChangeSuccess",g.absUrl(),a)}var g,m=d.baseHref(),k=d.url();a?(m=k.substring(0,k.indexOf("/",k.indexOf("//")+2))+(m||"/"),e=e.history?Bc:Cc):(m=Ya(k),e=Nb);g=new e(m,"#"+b);g.$$parse(g.$$rewrite(k));f.on("click",function(a){if(!a.ctrlKey&&!a.metaKey&&2!=a.which){for(var b=v(a.target);"a"!==O(b[0].nodeName);)if(b[0]===f[0]||!(b=b.parent())[0])return;var e=b.prop("href");W(e)&&"[object SVGAnimatedString]"===e.toString()&&
(e=qa(e.animVal).href);var h=g.$$rewrite(e);e&&(!b.attr("target")&&h&&!a.isDefaultPrevented())&&(a.preventDefault(),h!=d.url()&&(g.$$parse(h),c.$apply(),Q.angular["ff-684208-preventDefault"]=!0))}});g.absUrl()!=k&&d.url(g.absUrl(),!0);d.onUrlChange(function(a){g.absUrl()!=a&&(c.$evalAsync(function(){var b=g.absUrl();g.$$parse(a);c.$broadcast("$locationChangeStart",a,b).defaultPrevented?(g.$$parse(b),d.url(b)):h(b)}),c.$$phase||c.$digest())});var l=0;c.$watch(function(){var a=d.url(),b=g.$$replace;
l&&a==g.absUrl()||(l++,c.$evalAsync(function(){c.$broadcast("$locationChangeStart",g.absUrl(),a).defaultPrevented?g.$$parse(a):(d.url(g.absUrl(),b),h(a))}));g.$$replace=!1;return l});return g}]}function ce(){var b=!0,a=this;this.debugEnabled=function(a){return w(a)?(b=a,this):b};this.$get=["$window",function(c){function d(a){a instanceof Error&&(a.stack?a=a.message&&-1===a.stack.indexOf(a.message)?"Error: "+a.message+"\n"+a.stack:a.stack:a.sourceURL&&(a=a.message+"\n"+a.sourceURL+":"+a.line));return a}
function e(a){var b=c.console||{},e=b[a]||b.log||z;a=!1;try{a=!!e.apply}catch(m){}return a?function(){var a=[];r(arguments,function(b){a.push(d(b))});return e.apply(b,a)}:function(a,b){e(a,null==b?"":b)}}return{log:e("log"),info:e("info"),warn:e("warn"),error:e("error"),debug:function(){var c=e("debug");return function(){b&&c.apply(a,arguments)}}()}}]}function da(b,a){if("constructor"===b)throw Aa("isecfld",a);return b}function Za(b,a){if(b){if(b.constructor===b)throw Aa("isecfn",a);if(b.document&&
b.location&&b.alert&&b.setInterval)throw Aa("isecwindow",a);if(b.children&&(b.nodeName||b.prop&&b.attr&&b.find))throw Aa("isecdom",a);}return b}function rb(b,a,c,d,e){e=e||{};a=a.split(".");for(var f,h=0;1<a.length;h++){f=da(a.shift(),d);var g=b[f];g||(g={},b[f]=g);b=g;b.then&&e.unwrapPromises&&(ra(d),"$$v"in b||function(a){a.then(function(b){a.$$v=b})}(b),b.$$v===s&&(b.$$v={}),b=b.$$v)}f=da(a.shift(),d);return b[f]=c}function Ec(b,a,c,d,e,f,h){da(b,f);da(a,f);da(c,f);da(d,f);da(e,f);return h.unwrapPromises?
function(g,h){var k=h&&h.hasOwnProperty(b)?h:g,l;if(null==k)return k;(k=k[b])&&k.then&&(ra(f),"$$v"in k||(l=k,l.$$v=s,l.then(function(a){l.$$v=a})),k=k.$$v);if(!a)return k;if(null==k)return s;(k=k[a])&&k.then&&(ra(f),"$$v"in k||(l=k,l.$$v=s,l.then(function(a){l.$$v=a})),k=k.$$v);if(!c)return k;if(null==k)return s;(k=k[c])&&k.then&&(ra(f),"$$v"in k||(l=k,l.$$v=s,l.then(function(a){l.$$v=a})),k=k.$$v);if(!d)return k;if(null==k)return s;(k=k[d])&&k.then&&(ra(f),"$$v"in k||(l=k,l.$$v=s,l.then(function(a){l.$$v=
a})),k=k.$$v);if(!e)return k;if(null==k)return s;(k=k[e])&&k.then&&(ra(f),"$$v"in k||(l=k,l.$$v=s,l.then(function(a){l.$$v=a})),k=k.$$v);return k}:function(f,h){var k=h&&h.hasOwnProperty(b)?h:f;if(null==k)return k;k=k[b];if(!a)return k;if(null==k)return s;k=k[a];if(!c)return k;if(null==k)return s;k=k[c];if(!d)return k;if(null==k)return s;k=k[d];return e?null==k?s:k=k[e]:k}}function Ce(b,a){da(b,a);return function(a,d){return null==a?s:(d&&d.hasOwnProperty(b)?d:a)[b]}}function De(b,a,c){da(b,c);da(a,
c);return function(c,e){if(null==c)return s;c=(e&&e.hasOwnProperty(b)?e:c)[b];return null==c?s:c[a]}}function Fc(b,a,c){if(Ob.hasOwnProperty(b))return Ob[b];var d=b.split("."),e=d.length,f;if(a.unwrapPromises||1!==e)if(a.unwrapPromises||2!==e)if(a.csp)f=6>e?Ec(d[0],d[1],d[2],d[3],d[4],c,a):function(b,f){var g=0,h;do h=Ec(d[g++],d[g++],d[g++],d[g++],d[g++],c,a)(b,f),f=s,b=h;while(g<e);return h};else{var h="var p;\n";r(d,function(b,d){da(b,c);h+="if(s == null) return undefined;\ns="+(d?"s":'((k&&k.hasOwnProperty("'+
b+'"))?k:s)')+'["'+b+'"];\n'+(a.unwrapPromises?'if (s && s.then) {\n pw("'+c.replace(/(["\r\n])/g,"\\$1")+'");\n if (!("$$v" in s)) {\n p=s;\n p.$$v = undefined;\n p.then(function(v) {p.$$v=v;});\n}\n s=s.$$v\n}\n':"")});var h=h+"return s;",g=new Function("s","k","pw",h);g.toString=Y(h);f=a.unwrapPromises?function(a,b){return g(a,b,ra)}:g}else f=De(d[0],d[1],c);else f=Ce(d[0],c);"hasOwnProperty"!==b&&(Ob[b]=f);return f}function de(){var b={},a={csp:!1,unwrapPromises:!1,logPromiseWarnings:!0};this.unwrapPromises=
function(b){return w(b)?(a.unwrapPromises=!!b,this):a.unwrapPromises};this.logPromiseWarnings=function(b){return w(b)?(a.logPromiseWarnings=b,this):a.logPromiseWarnings};this.$get=["$filter","$sniffer","$log",function(c,d,e){a.csp=d.csp;ra=function(b){a.logPromiseWarnings&&!Gc.hasOwnProperty(b)&&(Gc[b]=!0,e.warn("[$parse] Promise found in the expression `"+b+"`. Automatic unwrapping of promises in Angular expressions is deprecated."))};return function(d){var e;switch(typeof d){case "string":if(b.hasOwnProperty(d))return b[d];
e=new Pb(a);e=(new $a(e,c,a)).parse(d,!1);"hasOwnProperty"!==d&&(b[d]=e);return e;case "function":return d;default:return z}}}]}function fe(){this.$get=["$rootScope","$exceptionHandler",function(b,a){return Ee(function(a){b.$evalAsync(a)},a)}]}function Ee(b,a){function c(a){return a}function d(a){return h(a)}var e=function(){var h=[],k,l;return l={resolve:function(a){if(h){var c=h;h=s;k=f(a);c.length&&b(function(){for(var a,b=0,d=c.length;b<d;b++)a=c[b],k.then(a[0],a[1],a[2])})}},reject:function(a){l.resolve(g(a))},
notify:function(a){if(h){var c=h;h.length&&b(function(){for(var b,d=0,e=c.length;d<e;d++)b=c[d],b[2](a)})}},promise:{then:function(b,f,g){var l=e(),I=function(d){try{l.resolve((F(b)?b:c)(d))}catch(e){l.reject(e),a(e)}},E=function(b){try{l.resolve((F(f)?f:d)(b))}catch(c){l.reject(c),a(c)}},y=function(b){try{l.notify((F(g)?g:c)(b))}catch(d){a(d)}};h?h.push([I,E,y]):k.then(I,E,y);return l.promise},"catch":function(a){return this.then(null,a)},"finally":function(a){function b(a,c){var d=e();c?d.resolve(a):
d.reject(a);return d.promise}function d(e,f){var g=null;try{g=(a||c)()}catch(h){return b(h,!1)}return g&&F(g.then)?g.then(function(){return b(e,f)},function(a){return b(a,!1)}):b(e,f)}return this.then(function(a){return d(a,!0)},function(a){return d(a,!1)})}}}},f=function(a){return a&&F(a.then)?a:{then:function(c){var d=e();b(function(){d.resolve(c(a))});return d.promise}}},h=function(a){var b=e();b.reject(a);return b.promise},g=function(c){return{then:function(f,g){var h=e();b(function(){try{h.resolve((F(g)?
g:d)(c))}catch(b){h.reject(b),a(b)}});return h.promise}}};return{defer:e,reject:h,when:function(g,k,l,n){var q=e(),p,u=function(b){try{return(F(k)?k:c)(b)}catch(d){return a(d),h(d)}},I=function(b){try{return(F(l)?l:d)(b)}catch(c){return a(c),h(c)}},E=function(b){try{return(F(n)?n:c)(b)}catch(d){a(d)}};b(function(){f(g).then(function(a){p||(p=!0,q.resolve(f(a).then(u,I,E)))},function(a){p||(p=!0,q.resolve(I(a)))},function(a){p||q.notify(E(a))})});return q.promise},all:function(a){var b=e(),c=0,d=J(a)?
[]:{};r(a,function(a,e){c++;f(a).then(function(a){d.hasOwnProperty(e)||(d[e]=a,--c||b.resolve(d))},function(a){d.hasOwnProperty(e)||b.reject(a)})});0===c&&b.resolve(d);return b.promise}}}function me(){this.$get=["$window","$timeout",function(b,a){var c=b.requestAnimationFrame||b.webkitRequestAnimationFrame||b.mozRequestAnimationFrame,d=b.cancelAnimationFrame||b.webkitCancelAnimationFrame||b.mozCancelAnimationFrame||b.webkitCancelRequestAnimationFrame,e=!!c,f=e?function(a){var b=c(a);return function(){d(b)}}:
function(b){var c=a(b,16.66,!1);return function(){a.cancel(c)}};f.supported=e;return f}]}function ee(){var b=10,a=C("$rootScope"),c=null;this.digestTtl=function(a){arguments.length&&(b=a);return b};this.$get=["$injector","$exceptionHandler","$parse","$browser",function(d,e,f,h){function g(){this.$id=db();this.$$phase=this.$parent=this.$$watchers=this.$$nextSibling=this.$$prevSibling=this.$$childHead=this.$$childTail=null;this["this"]=this.$root=this;this.$$destroyed=!1;this.$$asyncQueue=[];this.$$postDigestQueue=
[];this.$$listeners={};this.$$listenerCount={};this.$$isolateBindings={}}function m(b){if(q.$$phase)throw a("inprog",q.$$phase);q.$$phase=b}function k(a,b){var c=f(a);Qa(c,b);return c}function l(a,b,c){do a.$$listenerCount[c]-=b,0===a.$$listenerCount[c]&&delete a.$$listenerCount[c];while(a=a.$parent)}function n(){}g.prototype={constructor:g,$new:function(a){a?(a=new g,a.$root=this.$root,a.$$asyncQueue=this.$$asyncQueue,a.$$postDigestQueue=this.$$postDigestQueue):(a=function(){},a.prototype=this,a=
new a,a.$id=db());a["this"]=a;a.$$listeners={};a.$$listenerCount={};a.$parent=this;a.$$watchers=a.$$nextSibling=a.$$childHead=a.$$childTail=null;a.$$prevSibling=this.$$childTail;this.$$childHead?this.$$childTail=this.$$childTail.$$nextSibling=a:this.$$childHead=this.$$childTail=a;return a},$watch:function(a,b,d){var e=k(a,"watch"),f=this.$$watchers,g={fn:b,last:n,get:e,exp:a,eq:!!d};c=null;if(!F(b)){var h=k(b||z,"listener");g.fn=function(a,b,c){h(c)}}if("string"==typeof a&&e.constant){var m=g.fn;
g.fn=function(a,b,c){m.call(this,a,b,c);Da(f,g)}}f||(f=this.$$watchers=[]);f.unshift(g);return function(){Da(f,g);c=null}},$watchCollection:function(a,b){var c=this,d,e,g,h=1<b.length,k=0,m=f(a),l=[],n={},q=!0,r=0;return this.$watch(function(){d=m(c);var a,b;if(W(d))if(cb(d))for(e!==l&&(e=l,r=e.length=0,k++),a=d.length,r!==a&&(k++,e.length=r=a),b=0;b<a;b++)e[b]!==e[b]&&d[b]!==d[b]||e[b]===d[b]||(k++,e[b]=d[b]);else{e!==n&&(e=n={},r=0,k++);a=0;for(b in d)d.hasOwnProperty(b)&&(a++,e.hasOwnProperty(b)?
e[b]!==d[b]&&(k++,e[b]=d[b]):(r++,e[b]=d[b],k++));if(r>a)for(b in k++,e)e.hasOwnProperty(b)&&!d.hasOwnProperty(b)&&(r--,delete e[b])}else e!==d&&(e=d,k++);return k},function(){q?(q=!1,b(d,d,c)):b(d,g,c);if(h)if(W(d))if(cb(d)){g=Array(d.length);for(var a=0;a<d.length;a++)g[a]=d[a]}else for(a in g={},d)Hc.call(d,a)&&(g[a]=d[a]);else g=d})},$digest:function(){var d,f,g,h,k=this.$$asyncQueue,l=this.$$postDigestQueue,r,x,s=b,R,M=[],w,t,B;m("$digest");c=null;do{x=!1;for(R=this;k.length;){try{B=k.shift(),
B.scope.$eval(B.expression)}catch(v){q.$$phase=null,e(v)}c=null}a:do{if(h=R.$$watchers)for(r=h.length;r--;)try{if(d=h[r])if((f=d.get(R))!==(g=d.last)&&!(d.eq?va(f,g):"number"==typeof f&&"number"==typeof g&&isNaN(f)&&isNaN(g)))x=!0,c=d,d.last=d.eq?$(f):f,d.fn(f,g===n?f:g,R),5>s&&(w=4-s,M[w]||(M[w]=[]),t=F(d.exp)?"fn: "+(d.exp.name||d.exp.toString()):d.exp,t+="; newVal: "+pa(f)+"; oldVal: "+pa(g),M[w].push(t));else if(d===c){x=!1;break a}}catch(A){q.$$phase=null,e(A)}if(!(h=R.$$childHead||R!==this&&
R.$$nextSibling))for(;R!==this&&!(h=R.$$nextSibling);)R=R.$parent}while(R=h);if((x||k.length)&&!s--)throw q.$$phase=null,a("infdig",b,pa(M));}while(x||k.length);for(q.$$phase=null;l.length;)try{l.shift()()}catch(z){e(z)}},$destroy:function(){if(!this.$$destroyed){var a=this.$parent;this.$broadcast("$destroy");this.$$destroyed=!0;this!==q&&(r(this.$$listenerCount,gb(null,l,this)),a.$$childHead==this&&(a.$$childHead=this.$$nextSibling),a.$$childTail==this&&(a.$$childTail=this.$$prevSibling),this.$$prevSibling&&
(this.$$prevSibling.$$nextSibling=this.$$nextSibling),this.$$nextSibling&&(this.$$nextSibling.$$prevSibling=this.$$prevSibling),this.$parent=this.$$nextSibling=this.$$prevSibling=this.$$childHead=this.$$childTail=null)}},$eval:function(a,b){return f(a)(this,b)},$evalAsync:function(a){q.$$phase||q.$$asyncQueue.length||h.defer(function(){q.$$asyncQueue.length&&q.$digest()});this.$$asyncQueue.push({scope:this,expression:a})},$$postDigest:function(a){this.$$postDigestQueue.push(a)},$apply:function(a){try{return m("$apply"),
this.$eval(a)}catch(b){e(b)}finally{q.$$phase=null;try{q.$digest()}catch(c){throw e(c),c;}}},$on:function(a,b){var c=this.$$listeners[a];c||(this.$$listeners[a]=c=[]);c.push(b);var d=this;do d.$$listenerCount[a]||(d.$$listenerCount[a]=0),d.$$listenerCount[a]++;while(d=d.$parent);var e=this;return function(){c[fb(c,b)]=null;l(e,1,a)}},$emit:function(a,b){var c=[],d,f=this,g=!1,h={name:a,targetScope:f,stopPropagation:function(){g=!0},preventDefault:function(){h.defaultPrevented=!0},defaultPrevented:!1},
k=[h].concat(wa.call(arguments,1)),l,m;do{d=f.$$listeners[a]||c;h.currentScope=f;l=0;for(m=d.length;l<m;l++)if(d[l])try{d[l].apply(null,k)}catch(n){e(n)}else d.splice(l,1),l--,m--;if(g)break;f=f.$parent}while(f);return h},$broadcast:function(a,b){for(var c=this,d=this,f={name:a,targetScope:this,preventDefault:function(){f.defaultPrevented=!0},defaultPrevented:!1},g=[f].concat(wa.call(arguments,1)),h,k;c=d;){f.currentScope=c;d=c.$$listeners[a]||[];h=0;for(k=d.length;h<k;h++)if(d[h])try{d[h].apply(null,
g)}catch(l){e(l)}else d.splice(h,1),h--,k--;if(!(d=c.$$listenerCount[a]&&c.$$childHead||c!==this&&c.$$nextSibling))for(;c!==this&&!(d=c.$$nextSibling);)c=c.$parent}return f}};var q=new g;return q}]}function id(){var b=/^\s*(https?|ftp|mailto|tel|file):/,a=/^\s*(https?|ftp|file|blob):|data:image\//;this.aHrefSanitizationWhitelist=function(a){return w(a)?(b=a,this):b};this.imgSrcSanitizationWhitelist=function(b){return w(b)?(a=b,this):a};this.$get=function(){return function(c,d){var e=d?a:b,f;if(!V||
8<=V)if(f=qa(c).href,""!==f&&!f.match(e))return"unsafe:"+f;return c}}}function Fe(b){if("self"===b)return b;if(A(b)){if(-1<b.indexOf("***"))throw sa("iwcard",b);b=b.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1").replace(/\x08/g,"\\x08").replace("\\*\\*",".*").replace("\\*","[^:/.?&;]*");return RegExp("^"+b+"$")}if(eb(b))return RegExp("^"+b.source+"$");throw sa("imatcher");}function Ic(b){var a=[];w(b)&&r(b,function(b){a.push(Fe(b))});return a}function he(){this.SCE_CONTEXTS=ea;var b=["self"],a=[];
this.resourceUrlWhitelist=function(a){arguments.length&&(b=Ic(a));return b};this.resourceUrlBlacklist=function(b){arguments.length&&(a=Ic(b));return a};this.$get=["$injector",function(c){function d(a){var b=function(a){this.$$unwrapTrustedValue=function(){return a}};a&&(b.prototype=new a);b.prototype.valueOf=function(){return this.$$unwrapTrustedValue()};b.prototype.toString=function(){return this.$$unwrapTrustedValue().toString()};return b}var e=function(a){throw sa("unsafe");};c.has("$sanitize")&&
(e=c.get("$sanitize"));var f=d(),h={};h[ea.HTML]=d(f);h[ea.CSS]=d(f);h[ea.URL]=d(f);h[ea.JS]=d(f);h[ea.RESOURCE_URL]=d(h[ea.URL]);return{trustAs:function(a,b){var c=h.hasOwnProperty(a)?h[a]:null;if(!c)throw sa("icontext",a,b);if(null===b||b===s||""===b)return b;if("string"!==typeof b)throw sa("itype",a);return new c(b)},getTrusted:function(c,d){if(null===d||d===s||""===d)return d;var f=h.hasOwnProperty(c)?h[c]:null;if(f&&d instanceof f)return d.$$unwrapTrustedValue();if(c===ea.RESOURCE_URL){var f=
qa(d.toString()),l,n,q=!1;l=0;for(n=b.length;l<n;l++)if("self"===b[l]?Kb(f):b[l].exec(f.href)){q=!0;break}if(q)for(l=0,n=a.length;l<n;l++)if("self"===a[l]?Kb(f):a[l].exec(f.href)){q=!1;break}if(q)return d;throw sa("insecurl",d.toString());}if(c===ea.HTML)return e(d);throw sa("unsafe");},valueOf:function(a){return a instanceof f?a.$$unwrapTrustedValue():a}}}]}function ge(){var b=!0;this.enabled=function(a){arguments.length&&(b=!!a);return b};this.$get=["$parse","$sniffer","$sceDelegate",function(a,
c,d){if(b&&c.msie&&8>c.msieDocumentMode)throw sa("iequirks");var e=$(ea);e.isEnabled=function(){return b};e.trustAs=d.trustAs;e.getTrusted=d.getTrusted;e.valueOf=d.valueOf;b||(e.trustAs=e.getTrusted=function(a,b){return b},e.valueOf=Ca);e.parseAs=function(b,c){var d=a(c);return d.literal&&d.constant?d:function(a,c){return e.getTrusted(b,d(a,c))}};var f=e.parseAs,h=e.getTrusted,g=e.trustAs;r(ea,function(a,b){var c=O(b);e[Sa("parse_as_"+c)]=function(b){return f(a,b)};e[Sa("get_trusted_"+c)]=function(b){return h(a,
b)};e[Sa("trust_as_"+c)]=function(b){return g(a,b)}});return e}]}function ie(){this.$get=["$window","$document",function(b,a){var c={},d=P((/android (\d+)/.exec(O((b.navigator||{}).userAgent))||[])[1]),e=/Boxee/i.test((b.navigator||{}).userAgent),f=a[0]||{},h=f.documentMode,g,m=/^(Moz|webkit|O|ms)(?=[A-Z])/,k=f.body&&f.body.style,l=!1,n=!1;if(k){for(var q in k)if(l=m.exec(q)){g=l[0];g=g.substr(0,1).toUpperCase()+g.substr(1);break}g||(g="WebkitOpacity"in k&&"webkit");l=!!("transition"in k||g+"Transition"in
k);n=!!("animation"in k||g+"Animation"in k);!d||l&&n||(l=A(f.body.style.webkitTransition),n=A(f.body.style.webkitAnimation))}return{history:!(!b.history||!b.history.pushState||4>d||e),hashchange:"onhashchange"in b&&(!h||7<h),hasEvent:function(a){if("input"==a&&9==V)return!1;if(D(c[a])){var b=f.createElement("div");c[a]="on"+a in b}return c[a]},csp:Xb(),vendorPrefix:g,transitions:l,animations:n,android:d,msie:V,msieDocumentMode:h}}]}function ke(){this.$get=["$rootScope","$browser","$q","$exceptionHandler",
function(b,a,c,d){function e(e,g,m){var k=c.defer(),l=k.promise,n=w(m)&&!m;g=a.defer(function(){try{k.resolve(e())}catch(a){k.reject(a),d(a)}finally{delete f[l.$$timeoutId]}n||b.$apply()},g);l.$$timeoutId=g;f[g]=k;return l}var f={};e.cancel=function(b){return b&&b.$$timeoutId in f?(f[b.$$timeoutId].reject("canceled"),delete f[b.$$timeoutId],a.defer.cancel(b.$$timeoutId)):!1};return e}]}function qa(b,a){var c=b;V&&(S.setAttribute("href",c),c=S.href);S.setAttribute("href",c);return{href:S.href,protocol:S.protocol?
S.protocol.replace(/:$/,""):"",host:S.host,search:S.search?S.search.replace(/^\?/,""):"",hash:S.hash?S.hash.replace(/^#/,""):"",hostname:S.hostname,port:S.port,pathname:"/"===S.pathname.charAt(0)?S.pathname:"/"+S.pathname}}function Kb(b){b=A(b)?qa(b):b;return b.protocol===Jc.protocol&&b.host===Jc.host}function le(){this.$get=Y(Q)}function ic(b){function a(d,e){if(W(d)){var f={};r(d,function(b,c){f[c]=a(c,b)});return f}return b.factory(d+c,e)}var c="Filter";this.register=a;this.$get=["$injector",function(a){return function(b){return a.get(b+
c)}}];a("currency",Kc);a("date",Lc);a("filter",Ge);a("json",He);a("limitTo",Ie);a("lowercase",Je);a("number",Mc);a("orderBy",Nc);a("uppercase",Ke)}function Ge(){return function(b,a,c){if(!J(b))return b;var d=typeof c,e=[];e.check=function(a){for(var b=0;b<e.length;b++)if(!e[b](a))return!1;return!0};"function"!==d&&(c="boolean"===d&&c?function(a,b){return Pa.equals(a,b)}:function(a,b){if(a&&b&&"object"===typeof a&&"object"===typeof b){for(var d in a)if("$"!==d.charAt(0)&&Hc.call(a,d)&&c(a[d],b[d]))return!0;
return!1}b=(""+b).toLowerCase();return-1<(""+a).toLowerCase().indexOf(b)});var f=function(a,b){if("string"==typeof b&&"!"===b.charAt(0))return!f(a,b.substr(1));switch(typeof a){case "boolean":case "number":case "string":return c(a,b);case "object":switch(typeof b){case "object":return c(a,b);default:for(var d in a)if("$"!==d.charAt(0)&&f(a[d],b))return!0}return!1;case "array":for(d=0;d<a.length;d++)if(f(a[d],b))return!0;return!1;default:return!1}};switch(typeof a){case "boolean":case "number":case "string":a=
{$:a};case "object":for(var h in a)(function(b){"undefined"!=typeof a[b]&&e.push(function(c){return f("$"==b?c:c&&c[b],a[b])})})(h);break;case "function":e.push(a);break;default:return b}d=[];for(h=0;h<b.length;h++){var g=b[h];e.check(g)&&d.push(g)}return d}}function Kc(b){var a=b.NUMBER_FORMATS;return function(b,d){D(d)&&(d=a.CURRENCY_SYM);return Oc(b,a.PATTERNS[1],a.GROUP_SEP,a.DECIMAL_SEP,2).replace(/\u00A4/g,d)}}function Mc(b){var a=b.NUMBER_FORMATS;return function(b,d){return Oc(b,a.PATTERNS[0],
a.GROUP_SEP,a.DECIMAL_SEP,d)}}function Oc(b,a,c,d,e){if(null==b||!isFinite(b)||W(b))return"";var f=0>b;b=Math.abs(b);var h=b+"",g="",m=[],k=!1;if(-1!==h.indexOf("e")){var l=h.match(/([\d\.]+)e(-?)(\d+)/);l&&"-"==l[2]&&l[3]>e+1?h="0":(g=h,k=!0)}if(k)0<e&&(-1<b&&1>b)&&(g=b.toFixed(e));else{h=(h.split(Pc)[1]||"").length;D(e)&&(e=Math.min(Math.max(a.minFrac,h),a.maxFrac));h=Math.pow(10,e);b=Math.round(b*h)/h;b=(""+b).split(Pc);h=b[0];b=b[1]||"";var l=0,n=a.lgSize,q=a.gSize;if(h.length>=n+q)for(l=h.length-
n,k=0;k<l;k++)0===(l-k)%q&&0!==k&&(g+=c),g+=h.charAt(k);for(k=l;k<h.length;k++)0===(h.length-k)%n&&0!==k&&(g+=c),g+=h.charAt(k);for(;b.length<e;)b+="0";e&&"0"!==e&&(g+=d+b.substr(0,e))}m.push(f?a.negPre:a.posPre);m.push(g);m.push(f?a.negSuf:a.posSuf);return m.join("")}function sb(b,a,c){var d="";0>b&&(d="-",b=-b);for(b=""+b;b.length<a;)b="0"+b;c&&(b=b.substr(b.length-a));return d+b}function X(b,a,c,d){c=c||0;return function(e){e=e["get"+b]();if(0<c||e>-c)e+=c;0===e&&-12==c&&(e=12);return sb(e,a,d)}}
function tb(b,a){return function(c,d){var e=c["get"+b](),f=Ea(a?"SHORT"+b:b);return d[f][e]}}function Qc(b){var a=(new Date(b,0,1)).getDay();return new Date(b,0,(4>=a?5:12)-a)}function Rc(b){return function(a){var c=Qc(a.getFullYear());a=+new Date(a.getFullYear(),a.getMonth(),a.getDate()+(4-a.getDay()))-+c;a=1+Math.round(a/6048E5);return sb(a,b)}}function Lc(b){function a(a){var b;if(b=a.match(c)){a=new Date(0);var f=0,h=0,g=b[8]?a.setUTCFullYear:a.setFullYear,m=b[8]?a.setUTCHours:a.setHours;b[9]&&
(f=P(b[9]+b[10]),h=P(b[9]+b[11]));g.call(a,P(b[1]),P(b[2])-1,P(b[3]));f=P(b[4]||0)-f;h=P(b[5]||0)-h;g=P(b[6]||0);b=Math.round(1E3*parseFloat("0."+(b[7]||0)));m.call(a,f,h,g,b)}return a}var c=/^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;return function(c,e){var f="",h=[],g,m;e=e||"mediumDate";e=b.DATETIME_FORMATS[e]||e;A(c)&&(c=Le.test(c)?P(c):a(c));zb(c)&&(c=new Date(c));if(!oa(c))return c;for(;e;)(m=Me.exec(e))?(h=h.concat(wa.call(m,1)),e=
h.pop()):(h.push(e),e=null);r(h,function(a){g=Ne[a];f+=g?g(c,b.DATETIME_FORMATS):a.replace(/(^'|'$)/g,"").replace(/''/g,"'")});return f}}function He(){return function(b){return pa(b,!0)}}function Ie(){return function(b,a){if(!J(b)&&!A(b))return b;a=P(a);if(A(b))return a?0<=a?b.slice(0,a):b.slice(a,b.length):"";var c=[],d,e;a>b.length?a=b.length:a<-b.length&&(a=-b.length);0<a?(d=0,e=a):(d=b.length+a,e=b.length);for(;d<e;d++)c.push(b[d]);return c}}function Nc(b){return function(a,c,d){function e(a,
b){return Oa(b)?function(b,c){return a(c,b)}:a}function f(a,b){var c=typeof a,d=typeof b;return c==d?("string"==c&&(a=a.toLowerCase(),b=b.toLowerCase()),a===b?0:a<b?-1:1):c<d?-1:1}if(!J(a)||!c)return a;c=J(c)?c:[c];c=ad(c,function(a){var c=!1,d=a||Ca;if(A(a)){if("+"==a.charAt(0)||"-"==a.charAt(0))c="-"==a.charAt(0),a=a.substring(1);d=b(a);if(d.constant){var g=d();return e(function(a,b){return f(a[g],b[g])},c)}}return e(function(a,b){return f(d(a),d(b))},c)});for(var h=[],g=0;g<a.length;g++)h.push(a[g]);
return h.sort(e(function(a,b){for(var d=0;d<c.length;d++){var e=c[d](a,b);if(0!==e)return e}return 0},d))}}function ta(b){F(b)&&(b={link:b});b.restrict=b.restrict||"AC";return Y(b)}function Sc(b,a,c,d){function e(a,c){c=c?"-"+hb(c,"-"):"";d.removeClass(b,(a?ub:vb)+c);d.addClass(b,(a?vb:ub)+c)}var f=this,h=b.parent().controller("form")||wb,g=0,m=f.$error={},k=[];f.$name=a.name||a.ngForm;f.$dirty=!1;f.$pristine=!0;f.$valid=!0;f.$invalid=!1;h.$addControl(f);b.addClass(La);e(!0);f.$addControl=function(a){ya(a.$name,
"input");k.push(a);a.$name&&(f[a.$name]=a)};f.$removeControl=function(a){a.$name&&f[a.$name]===a&&delete f[a.$name];r(m,function(b,c){f.$setValidity(c,!0,a)});Da(k,a)};f.$setValidity=function(a,b,c){var d=m[a];if(b)d&&(Da(d,c),d.length||(g--,g||(e(b),f.$valid=!0,f.$invalid=!1),m[a]=!1,e(!0,a),h.$setValidity(a,!0,f)));else{g||e(b);if(d){if(-1!=fb(d,c))return}else m[a]=d=[],g++,e(!1,a),h.$setValidity(a,!1,f);d.push(c);f.$valid=!1;f.$invalid=!0}};f.$setDirty=function(){d.removeClass(b,La);d.addClass(b,
xb);f.$dirty=!0;f.$pristine=!1;h.$setDirty()};f.$setPristine=function(){d.removeClass(b,xb);d.addClass(b,La);f.$dirty=!1;f.$pristine=!0;r(k,function(a){a.$setPristine()})}}function na(b,a,c,d){b.$setValidity(a,c);return c?d:s}function Oe(b,a,c){var d=c.prop("validity");W(d)&&b.$parsers.push(function(c){if(b.$error[a]||!(d.badInput||d.customError||d.typeMismatch)||d.valueMissing)return c;b.$setValidity(a,!1)})}function ab(b,a,c,d,e,f){var h=a.prop("validity");if(!e.android){var g=!1;a.on("compositionstart",
function(a){g=!0});a.on("compositionend",function(){g=!1;m()})}var m=function(){if(!g){var e=a.val();Oa(c.ngTrim||"T")&&(e=aa(e));if(d.$viewValue!==e||h&&""===e&&!h.valueMissing)b.$$phase?d.$setViewValue(e):b.$apply(function(){d.$setViewValue(e)})}};if(e.hasEvent("input"))a.on("input",m);else{var k,l=function(){k||(k=f.defer(function(){m();k=null}))};a.on("keydown",function(a){a=a.keyCode;91===a||(15<a&&19>a||37<=a&&40>=a)||l()});if(e.hasEvent("paste"))a.on("paste cut",l)}a.on("change",m);d.$render=
function(){a.val(d.$isEmpty(d.$viewValue)?"":d.$viewValue)};var n=c.ngPattern;n&&((e=n.match(/^\/(.*)\/([gim]*)$/))?(n=RegExp(e[1],e[2]),e=function(a){return na(d,"pattern",d.$isEmpty(a)||n.test(a),a)}):e=function(c){var e=b.$eval(n);if(!e||!e.test)throw C("ngPattern")("noregexp",n,e,fa(a));return na(d,"pattern",d.$isEmpty(c)||e.test(c),c)},d.$formatters.push(e),d.$parsers.push(e));if(c.ngMinlength){var q=P(c.ngMinlength);e=function(a){return na(d,"minlength",d.$isEmpty(a)||a.length>=q,a)};d.$parsers.push(e);
d.$formatters.push(e)}if(c.ngMaxlength){var p=P(c.ngMaxlength);e=function(a){return na(d,"maxlength",d.$isEmpty(a)||a.length<=p,a)};d.$parsers.push(e);d.$formatters.push(e)}}function yb(b,a){return function(c){var d;return oa(c)?c:A(c)&&(b.lastIndex=0,c=b.exec(c))?(c.shift(),d={yyyy:0,MM:1,dd:1,HH:0,mm:0},r(c,function(b,c){c<a.length&&(d[a[c]]=+b)}),new Date(d.yyyy,d.MM-1,d.dd,d.HH,d.mm)):NaN}}function bb(b,a,c,d){return function(e,f,h,g,m,k,l){ab(e,f,h,g,m,k);g.$parsers.push(function(d){if(g.$isEmpty(d))return g.$setValidity(b,
!0),null;if(a.test(d))return g.$setValidity(b,!0),c(d);g.$setValidity(b,!1);return s});g.$formatters.push(function(a){return oa(a)?l("date")(a,d):""});h.min&&(e=function(a){var b=g.$isEmpty(a)||c(a)>=c(h.min);g.$setValidity("min",b);return b?a:s},g.$parsers.push(e),g.$formatters.push(e));h.max&&(e=function(a){var b=g.$isEmpty(a)||c(a)<=c(h.max);g.$setValidity("max",b);return b?a:s},g.$parsers.push(e),g.$formatters.push(e))}}function Qb(b,a){b="ngClass"+b;return function(){return{restrict:"AC",link:function(c,
d,e){function f(b){if(!0===a||c.$index%2===a){var d=h(b||"");g?va(b,g)||e.$updateClass(d,h(g)):e.$addClass(d)}g=$(b)}function h(a){if(J(a))return a.join(" ");if(W(a)){var b=[];r(a,function(a,c){a&&b.push(c)});return b.join(" ")}return a}var g;c.$watch(e[b],f,!0);e.$observe("class",function(a){f(c.$eval(e[b]))});"ngClass"!==b&&c.$watch("$index",function(d,f){var g=d&1;if(g!==f&1){var n=h(c.$eval(e[b]));g===a?e.$addClass(n):e.$removeClass(n)}})}}}}var O=function(b){return A(b)?b.toLowerCase():b},Hc=
Object.prototype.hasOwnProperty,Ea=function(b){return A(b)?b.toUpperCase():b},V,v,Fa,wa=[].slice,Pe=[].push,ua=Object.prototype.toString,Na=C("ng"),Pa=Q.angular||(Q.angular={}),Ra,Ja,ia=["0","0","0"];V=P((/msie (\d+)/.exec(O(navigator.userAgent))||[])[1]);isNaN(V)&&(V=P((/trident\/.*; rv:(\d+)/.exec(O(navigator.userAgent))||[])[1]));z.$inject=[];Ca.$inject=[];var aa=function(){return String.prototype.trim?function(b){return A(b)?b.trim():b}:function(b){return A(b)?b.replace(/^\s\s*/,"").replace(/\s\s*$/,
""):b}}();Ja=9>V?function(b){b=b.nodeName?b:b[0];return b.scopeName&&"HTML"!=b.scopeName?Ea(b.scopeName+":"+b.nodeName):b.nodeName}:function(b){return b.nodeName?b.nodeName:b[0].nodeName};var dd=/[A-Z]/g,gd={full:"1.3.0-build.2498+sha.ccba305",major:1,minor:3,dot:0,codeName:"snapshot"},Ua=N.cache={},ib=N.expando="ng-"+(new Date).getTime(),qe=1,pb=Q.document.addEventListener?function(b,a,c){b.addEventListener(a,c,!1)}:function(b,a,c){b.attachEvent("on"+a,c)},Ta=Q.document.removeEventListener?function(b,
a,c){b.removeEventListener(a,c,!1)}:function(b,a,c){b.detachEvent("on"+a,c)};N._data=function(b){return this.cache[b[this.expando]]||{}};var oe=/([\:\-\_]+(.))/g,pe=/^moz([A-Z])/,Fb=C("jqLite"),Ia=N.prototype={ready:function(b){function a(){c||(c=!0,b())}var c=!1;"complete"===T.readyState?setTimeout(a):(this.on("DOMContentLoaded",a),N(Q).on("load",a))},toString:function(){var b=[];r(this,function(a){b.push(""+a)});return"["+b.join(", ")+"]"},eq:function(b){return 0<=b?v(this[b]):v(this[this.length+
b])},length:0,push:Pe,sort:[].sort,splice:[].splice},mb={};r("multiple selected checked disabled readOnly required open".split(" "),function(b){mb[O(b)]=b});var pc={};r("input select option textarea button form details".split(" "),function(b){pc[Ea(b)]=!0});r({data:lc,inheritedData:lb,scope:function(b){return v(b).data("$scope")||lb(b.parentNode||b,["$isolateScope","$scope"])},isolateScope:function(b){return v(b).data("$isolateScope")||v(b).data("$isolateScopeNoTemplate")},controller:mc,injector:function(b){return lb(b,
"$injector")},removeAttr:function(b,a){b.removeAttribute(a)},hasClass:Ib,css:function(b,a,c){a=Sa(a);if(w(c))b.style[a]=c;else{var d;8>=V&&(d=b.currentStyle&&b.currentStyle[a],""===d&&(d="auto"));d=d||b.style[a];8>=V&&(d=""===d?s:d);return d}},attr:function(b,a,c){var d=O(a);if(mb[d])if(w(c))c?(b[a]=!0,b.setAttribute(a,d)):(b[a]=!1,b.removeAttribute(d));else return b[a]||(b.attributes.getNamedItem(a)||z).specified?d:s;else if(w(c))b.setAttribute(a,c);else if(b.getAttribute)return b=b.getAttribute(a,
2),null===b?s:b},prop:function(b,a,c){if(w(c))b[a]=c;else return b[a]},text:function(){function b(b,d){var e=a[b.nodeType];if(D(d))return e?b[e]:"";b[e]=d}var a=[];9>V?(a[1]="innerText",a[3]="nodeValue"):a[1]=a[3]="textContent";b.$dv="";return b}(),val:function(b,a){if(D(a)){if("SELECT"===Ja(b)&&b.multiple){var c=[];r(b.options,function(a){a.selected&&c.push(a.value||a.text)});return 0===c.length?null:c}return b.value}b.value=a},html:function(b,a){if(D(a))return b.innerHTML;for(var c=0,d=b.childNodes;c<
d.length;c++)Ga(d[c]);b.innerHTML=a},empty:nc},function(b,a){N.prototype[a]=function(a,d){var e,f;if(b!==nc&&(2==b.length&&b!==Ib&&b!==mc?a:d)===s){if(W(a)){for(e=0;e<this.length;e++)if(b===lc)b(this[e],a);else for(f in a)b(this[e],f,a[f]);return this}e=b.$dv;f=e===s?Math.min(this.length,1):this.length;for(var h=0;h<f;h++){var g=b(this[h],a,d);e=e?e+g:g}return e}for(e=0;e<this.length;e++)b(this[e],a,d);return this}});r({removeData:jc,dealoc:Ga,on:function a(c,d,e,f){if(w(f))throw Fb("onargs");var h=
ja(c,"events"),g=ja(c,"handle");h||ja(c,"events",h={});g||ja(c,"handle",g=re(c,h));r(d.split(" "),function(d){var f=h[d];if(!f){if("mouseenter"==d||"mouseleave"==d){var l=T.body.contains||T.body.compareDocumentPosition?function(a,c){var d=9===a.nodeType?a.documentElement:a,e=c&&c.parentNode;return a===e||!!(e&&1===e.nodeType&&(d.contains?d.contains(e):a.compareDocumentPosition&&a.compareDocumentPosition(e)&16))}:function(a,c){if(c)for(;c=c.parentNode;)if(c===a)return!0;return!1};h[d]=[];a(c,{mouseleave:"mouseout",
mouseenter:"mouseover"}[d],function(a){var c=a.relatedTarget;c&&(c===this||l(this,c))||g(a,d)})}else pb(c,d,g),h[d]=[];f=h[d]}f.push(e)})},off:kc,one:function(a,c,d){a=v(a);a.on(c,function f(){a.off(c,d);a.off(c,f)});a.on(c,d)},replaceWith:function(a,c){var d,e=a.parentNode;Ga(a);r(new N(c),function(c){d?e.insertBefore(c,d.nextSibling):e.replaceChild(c,a);d=c})},children:function(a){var c=[];r(a.childNodes,function(a){1===a.nodeType&&c.push(a)});return c},contents:function(a){return a.contentDocument||
a.childNodes||[]},append:function(a,c){r(new N(c),function(c){1!==a.nodeType&&11!==a.nodeType||a.appendChild(c)})},prepend:function(a,c){if(1===a.nodeType){var d=a.firstChild;r(new N(c),function(c){a.insertBefore(c,d)})}},wrap:function(a,c){c=v(c)[0];var d=a.parentNode;d&&d.replaceChild(c,a);c.appendChild(a)},remove:function(a){Ga(a);var c=a.parentNode;c&&c.removeChild(a)},after:function(a,c){var d=a,e=a.parentNode;r(new N(c),function(a){e.insertBefore(a,d.nextSibling);d=a})},addClass:kb,removeClass:jb,
toggleClass:function(a,c,d){c&&r(c.split(" "),function(c){var f=d;D(f)&&(f=!Ib(a,c));(f?kb:jb)(a,c)})},parent:function(a){return(a=a.parentNode)&&11!==a.nodeType?a:null},next:function(a){if(a.nextElementSibling)return a.nextElementSibling;for(a=a.nextSibling;null!=a&&1!==a.nodeType;)a=a.nextSibling;return a},find:function(a,c){return a.getElementsByTagName?a.getElementsByTagName(c):[]},clone:Hb,triggerHandler:function(a,c,d){c=(ja(a,"events")||{})[c];d=d||[];var e=[{preventDefault:z,stopPropagation:z}];
r(c,function(c){c.apply(a,e.concat(d))})}},function(a,c){N.prototype[c]=function(c,e,f){for(var h,g=0;g<this.length;g++)D(h)?(h=a(this[g],c,e,f),w(h)&&(h=v(h))):Gb(h,a(this[g],c,e,f));return w(h)?h:this};N.prototype.bind=N.prototype.on;N.prototype.unbind=N.prototype.off});Va.prototype={put:function(a,c){this[Ha(a)]=c},get:function(a){return this[Ha(a)]},remove:function(a){var c=this[a=Ha(a)];delete this[a];return c}};var te=/^function\s*[^\(]*\(\s*([^\)]*)\)/m,ue=/,/,ve=/^\s*(_?)(\S+?)\1\s*$/,se=
/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,Wa=C("$injector"),Qe=C("$animate"),Sd=["$provide",function(a){this.$$selectors={};this.register=function(c,d){var e=c+"-animation";if(c&&"."!=c.charAt(0))throw Qe("notcsel",c);this.$$selectors[c.substr(1)]=e;a.factory(e,d)};this.classNameFilter=function(a){1===arguments.length&&(this.$$classNameFilter=a instanceof RegExp?a:null);return this.$$classNameFilter};this.$get=["$timeout","$$asyncCallback",function(a,d){return{enter:function(a,c,h,g){h?h.after(a):(c&&c[0]||
(c=h.parent()),c.append(a));g&&d(g)},leave:function(a,c){a.remove();c&&d(c)},move:function(a,c,d,g){this.enter(a,c,d,g)},addClass:function(a,c,h){c=A(c)?c:J(c)?c.join(" "):"";r(a,function(a){kb(a,c)});h&&d(h)},removeClass:function(a,c,h){c=A(c)?c:J(c)?c.join(" "):"";r(a,function(a){jb(a,c)});h&&d(h)},setClass:function(a,c,h,g){r(a,function(a){kb(a,c);jb(a,h)});g&&d(g)},enabled:z}}]}],ha=C("$compile");ec.$inject=["$provide","$$sanitizeUriProvider"];var ye=/^(x[\:\-_]|data[\:\-_])/i,xc=C("$interpolate"),
Re=/^([^\?#]*)(\?([^#]*))?(#(.*))?$/,Be={http:80,https:443,ftp:21},Mb=C("$location");Cc.prototype=Nb.prototype=Bc.prototype={$$html5:!1,$$replace:!1,absUrl:qb("$$absUrl"),url:function(a,c){if(D(a))return this.$$url;var d=Re.exec(a);d[1]&&this.path(decodeURIComponent(d[1]));(d[2]||d[1])&&this.search(d[3]||"");this.hash(d[5]||"",c);return this},protocol:qb("$$protocol"),host:qb("$$host"),port:qb("$$port"),path:Dc("$$path",function(a){return"/"==a.charAt(0)?a:"/"+a}),search:function(a,c){switch(arguments.length){case 0:return this.$$search;
case 1:if(A(a))this.$$search=$b(a);else if(W(a))this.$$search=a;else throw Mb("isrcharg");break;default:D(c)||null===c?delete this.$$search[a]:this.$$search[a]=c}this.$$compose();return this},hash:Dc("$$hash",Ca),replace:function(){this.$$replace=!0;return this}};var Aa=C("$parse"),Gc={},ra,Ma={"null":function(){return null},"true":function(){return!0},"false":function(){return!1},undefined:z,"+":function(a,c,d,e){d=d(a,c);e=e(a,c);return w(d)?w(e)?d+e:d:w(e)?e:s},"-":function(a,c,d,e){d=d(a,c);e=
e(a,c);return(w(d)?d:0)-(w(e)?e:0)},"*":function(a,c,d,e){return d(a,c)*e(a,c)},"/":function(a,c,d,e){return d(a,c)/e(a,c)},"%":function(a,c,d,e){return d(a,c)%e(a,c)},"^":function(a,c,d,e){return d(a,c)^e(a,c)},"=":z,"===":function(a,c,d,e){return d(a,c)===e(a,c)},"!==":function(a,c,d,e){return d(a,c)!==e(a,c)},"==":function(a,c,d,e){return d(a,c)==e(a,c)},"!=":function(a,c,d,e){return d(a,c)!=e(a,c)},"<":function(a,c,d,e){return d(a,c)<e(a,c)},">":function(a,c,d,e){return d(a,c)>e(a,c)},"<=":function(a,
c,d,e){return d(a,c)<=e(a,c)},">=":function(a,c,d,e){return d(a,c)>=e(a,c)},"&&":function(a,c,d,e){return d(a,c)&&e(a,c)},"||":function(a,c,d,e){return d(a,c)||e(a,c)},"&":function(a,c,d,e){return d(a,c)&e(a,c)},"|":function(a,c,d,e){return e(a,c)(a,c,d(a,c))},"!":function(a,c,d){return!d(a,c)}},Se={n:"\n",f:"\f",r:"\r",t:"\t",v:"\v","'":"'",'"':'"'},Pb=function(a){this.options=a};Pb.prototype={constructor:Pb,lex:function(a){this.text=a;this.index=0;this.ch=s;this.lastCh=":";this.tokens=[];var c;
for(a=[];this.index<this.text.length;){this.ch=this.text.charAt(this.index);if(this.is("\"'"))this.readString(this.ch);else if(this.isNumber(this.ch)||this.is(".")&&this.isNumber(this.peek()))this.readNumber();else if(this.isIdent(this.ch))this.readIdent(),this.was("{,")&&("{"===a[0]&&(c=this.tokens[this.tokens.length-1]))&&(c.json=-1===c.text.indexOf("."));else if(this.is("(){}[].,;:?"))this.tokens.push({index:this.index,text:this.ch,json:this.was(":[,")&&this.is("{[")||this.is("}]:,")}),this.is("{[")&&
a.unshift(this.ch),this.is("}]")&&a.shift(),this.index++;else if(this.isWhitespace(this.ch)){this.index++;continue}else{var d=this.ch+this.peek(),e=d+this.peek(2),f=Ma[this.ch],h=Ma[d],g=Ma[e];g?(this.tokens.push({index:this.index,text:e,fn:g}),this.index+=3):h?(this.tokens.push({index:this.index,text:d,fn:h}),this.index+=2):f?(this.tokens.push({index:this.index,text:this.ch,fn:f,json:this.was("[,:")&&this.is("+-")}),this.index+=1):this.throwError("Unexpected next character ",this.index,this.index+
1)}this.lastCh=this.ch}return this.tokens},is:function(a){return-1!==a.indexOf(this.ch)},was:function(a){return-1!==a.indexOf(this.lastCh)},peek:function(a){a=a||1;return this.index+a<this.text.length?this.text.charAt(this.index+a):!1},isNumber:function(a){return"0"<=a&&"9">=a},isWhitespace:function(a){return" "===a||"\r"===a||"\t"===a||"\n"===a||"\v"===a||"\u00a0"===a},isIdent:function(a){return"a"<=a&&"z">=a||"A"<=a&&"Z">=a||"_"===a||"$"===a},isExpOperator:function(a){return"-"===a||"+"===a||this.isNumber(a)},
throwError:function(a,c,d){d=d||this.index;c=w(c)?"s "+c+"-"+this.index+" ["+this.text.substring(c,d)+"]":" "+d;throw Aa("lexerr",a,c,this.text);},readNumber:function(){for(var a="",c=this.index;this.index<this.text.length;){var d=O(this.text.charAt(this.index));if("."==d||this.isNumber(d))a+=d;else{var e=this.peek();if("e"==d&&this.isExpOperator(e))a+=d;else if(this.isExpOperator(d)&&e&&this.isNumber(e)&&"e"==a.charAt(a.length-1))a+=d;else if(!this.isExpOperator(d)||e&&this.isNumber(e)||"e"!=a.charAt(a.length-
1))break;else this.throwError("Invalid exponent")}this.index++}a*=1;this.tokens.push({index:c,text:a,json:!0,fn:function(){return a}})},readIdent:function(){for(var a=this,c="",d=this.index,e,f,h,g;this.index<this.text.length;){g=this.text.charAt(this.index);if("."===g||this.isIdent(g)||this.isNumber(g))"."===g&&(e=this.index),c+=g;else break;this.index++}if(e)for(f=this.index;f<this.text.length;){g=this.text.charAt(f);if("("===g){h=c.substr(e-d+1);c=c.substr(0,e-d);this.index=f;break}if(this.isWhitespace(g))f++;
else break}d={index:d,text:c};if(Ma.hasOwnProperty(c))d.fn=Ma[c],d.json=Ma[c];else{var m=Fc(c,this.options,this.text);d.fn=t(function(a,c){return m(a,c)},{assign:function(d,e){return rb(d,c,e,a.text,a.options)}})}this.tokens.push(d);h&&(this.tokens.push({index:e,text:".",json:!1}),this.tokens.push({index:e+1,text:h,json:!1}))},readString:function(a){var c=this.index;this.index++;for(var d="",e=a,f=!1;this.index<this.text.length;){var h=this.text.charAt(this.index),e=e+h;if(f)"u"===h?(h=this.text.substring(this.index+
1,this.index+5),h.match(/[\da-f]{4}/i)||this.throwError("Invalid unicode escape [\\u"+h+"]"),this.index+=4,d+=String.fromCharCode(parseInt(h,16))):d=(f=Se[h])?d+f:d+h,f=!1;else if("\\"===h)f=!0;else{if(h===a){this.index++;this.tokens.push({index:c,text:e,string:d,json:!0,fn:function(){return d}});return}d+=h}this.index++}this.throwError("Unterminated quote",c)}};var $a=function(a,c,d){this.lexer=a;this.$filter=c;this.options=d};$a.ZERO=function(){return 0};$a.prototype={constructor:$a,parse:function(a,
c){this.text=a;this.json=c;this.tokens=this.lexer.lex(a);c&&(this.assignment=this.logicalOR,this.functionCall=this.fieldAccess=this.objectIndex=this.filterChain=function(){this.throwError("is not valid json",{text:a,index:0})});var d=c?this.primary():this.statements();0!==this.tokens.length&&this.throwError("is an unexpected token",this.tokens[0]);d.literal=!!d.literal;d.constant=!!d.constant;return d},primary:function(){var a;if(this.expect("("))a=this.filterChain(),this.consume(")");else if(this.expect("["))a=
this.arrayDeclaration();else if(this.expect("{"))a=this.object();else{var c=this.expect();(a=c.fn)||this.throwError("not a primary expression",c);c.json&&(a.constant=!0,a.literal=!0)}for(var d;c=this.expect("(","[",".");)"("===c.text?(a=this.functionCall(a,d),d=null):"["===c.text?(d=a,a=this.objectIndex(a)):"."===c.text?(d=a,a=this.fieldAccess(a)):this.throwError("IMPOSSIBLE");return a},throwError:function(a,c){throw Aa("syntax",c.text,a,c.index+1,this.text,this.text.substring(c.index));},peekToken:function(){if(0===
this.tokens.length)throw Aa("ueoe",this.text);return this.tokens[0]},peek:function(a,c,d,e){if(0<this.tokens.length){var f=this.tokens[0],h=f.text;if(h===a||h===c||h===d||h===e||!(a||c||d||e))return f}return!1},expect:function(a,c,d,e){return(a=this.peek(a,c,d,e))?(this.json&&!a.json&&this.throwError("is not valid json",a),this.tokens.shift(),a):!1},consume:function(a){this.expect(a)||this.throwError("is unexpected, expecting ["+a+"]",this.peek())},unaryFn:function(a,c){return t(function(d,e){return a(d,
e,c)},{constant:c.constant})},ternaryFn:function(a,c,d){return t(function(e,f){return a(e,f)?c(e,f):d(e,f)},{constant:a.constant&&c.constant&&d.constant})},binaryFn:function(a,c,d){return t(function(e,f){return c(e,f,a,d)},{constant:a.constant&&d.constant})},statements:function(){for(var a=[];;)if(0<this.tokens.length&&!this.peek("}",")",";","]")&&a.push(this.filterChain()),!this.expect(";"))return 1===a.length?a[0]:function(c,d){for(var e,f=0;f<a.length;f++){var h=a[f];h&&(e=h(c,d))}return e}},filterChain:function(){for(var a=
this.expression(),c;;)if(c=this.expect("|"))a=this.binaryFn(a,c.fn,this.filter());else return a},filter:function(){for(var a=this.expect(),c=this.$filter(a.text),d=[];;)if(a=this.expect(":"))d.push(this.expression());else{var e=function(a,e,g){g=[g];for(var m=0;m<d.length;m++)g.push(d[m](a,e));return c.apply(a,g)};return function(){return e}}},expression:function(){return this.assignment()},assignment:function(){var a=this.ternary(),c,d;return(d=this.expect("="))?(a.assign||this.throwError("implies assignment but ["+
this.text.substring(0,d.index)+"] can not be assigned to",d),c=this.ternary(),function(d,f){return a.assign(d,c(d,f),f)}):a},ternary:function(){var a=this.logicalOR(),c,d;if(this.expect("?")){c=this.ternary();if(d=this.expect(":"))return this.ternaryFn(a,c,this.ternary());this.throwError("expected :",d)}else return a},logicalOR:function(){for(var a=this.logicalAND(),c;;)if(c=this.expect("||"))a=this.binaryFn(a,c.fn,this.logicalAND());else return a},logicalAND:function(){var a=this.equality(),c;if(c=
this.expect("&&"))a=this.binaryFn(a,c.fn,this.logicalAND());return a},equality:function(){var a=this.relational(),c;if(c=this.expect("==","!=","===","!=="))a=this.binaryFn(a,c.fn,this.equality());return a},relational:function(){var a=this.additive(),c;if(c=this.expect("<",">","<=",">="))a=this.binaryFn(a,c.fn,this.relational());return a},additive:function(){for(var a=this.multiplicative(),c;c=this.expect("+","-");)a=this.binaryFn(a,c.fn,this.multiplicative());return a},multiplicative:function(){for(var a=
this.unary(),c;c=this.expect("*","/","%");)a=this.binaryFn(a,c.fn,this.unary());return a},unary:function(){var a;return this.expect("+")?this.primary():(a=this.expect("-"))?this.binaryFn($a.ZERO,a.fn,this.unary()):(a=this.expect("!"))?this.unaryFn(a.fn,this.unary()):this.primary()},fieldAccess:function(a){var c=this,d=this.expect().text,e=Fc(d,this.options,this.text);return t(function(c,d,g){return e(g||a(c,d))},{assign:function(e,h,g){return rb(a(e,g),d,h,c.text,c.options)}})},objectIndex:function(a){var c=
this,d=this.expression();this.consume("]");return t(function(e,f){var h=a(e,f),g=d(e,f),m;if(!h)return s;(h=Za(h[g],c.text))&&(h.then&&c.options.unwrapPromises)&&(m=h,"$$v"in h||(m.$$v=s,m.then(function(a){m.$$v=a})),h=h.$$v);return h},{assign:function(e,f,h){var g=d(e,h);return Za(a(e,h),c.text)[g]=f}})},functionCall:function(a,c){var d=[];if(")"!==this.peekToken().text){do d.push(this.expression());while(this.expect(","))}this.consume(")");var e=this;return function(f,h){for(var g=[],m=c?c(f,h):
f,k=0;k<d.length;k++)g.push(d[k](f,h));k=a(f,h,m)||z;Za(m,e.text);Za(k,e.text);g=k.apply?k.apply(m,g):k(g[0],g[1],g[2],g[3],g[4]);return Za(g,e.text)}},arrayDeclaration:function(){var a=[],c=!0;if("]"!==this.peekToken().text){do{if(this.peek("]"))break;var d=this.expression();a.push(d);d.constant||(c=!1)}while(this.expect(","))}this.consume("]");return t(function(c,d){for(var h=[],g=0;g<a.length;g++)h.push(a[g](c,d));return h},{literal:!0,constant:c})},object:function(){var a=[],c=!0;if("}"!==this.peekToken().text){do{if(this.peek("}"))break;
var d=this.expect(),d=d.string||d.text;this.consume(":");var e=this.expression();a.push({key:d,value:e});e.constant||(c=!1)}while(this.expect(","))}this.consume("}");return t(function(c,d){for(var e={},m=0;m<a.length;m++){var k=a[m];e[k.key]=k.value(c,d)}return e},{literal:!0,constant:c})}};var Ob={},sa=C("$sce"),ea={HTML:"html",CSS:"css",URL:"url",RESOURCE_URL:"resourceUrl",JS:"js"},S=T.createElement("a"),Jc=qa(Q.location.href,!0);ic.$inject=["$provide"];Kc.$inject=["$locale"];Mc.$inject=["$locale"];
var Pc=".",Ne={yyyy:X("FullYear",4),yy:X("FullYear",2,0,!0),y:X("FullYear",1),MMMM:tb("Month"),MMM:tb("Month",!0),MM:X("Month",2,1),M:X("Month",1,1),dd:X("Date",2),d:X("Date",1),HH:X("Hours",2),H:X("Hours",1),hh:X("Hours",2,-12),h:X("Hours",1,-12),mm:X("Minutes",2),m:X("Minutes",1),ss:X("Seconds",2),s:X("Seconds",1),sss:X("Milliseconds",3),EEEE:tb("Day"),EEE:tb("Day",!0),a:function(a,c){return 12>a.getHours()?c.AMPMS[0]:c.AMPMS[1]},Z:function(a){a=-1*a.getTimezoneOffset();return a=(0<=a?"+":"")+(sb(Math[0<
a?"floor":"ceil"](a/60),2)+sb(Math.abs(a%60),2))},ww:Rc(2),w:Rc(1)},Me=/((?:[^yMdHhmsaZEw']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|w+))(.*)/,Le=/^\-?\d+$/;Lc.$inject=["$locale"];var Je=Y(O),Ke=Y(Ea);Nc.$inject=["$parse"];var jd=Y({restrict:"E",compile:function(a,c){8>=V&&(c.href||c.name||c.$set("href",""),a.append(T.createComment("IE fix")));if(!c.href&&!c.xlinkHref&&!c.name)return function(a,c){var f="[object SVGAnimatedString]"===ua.call(c.prop("href"))?"xlink:href":"href";c.on("click",
function(a){c.attr(f)||a.preventDefault()})}}}),Db={};r(mb,function(a,c){if("multiple"!=a){var d=ka("ng-"+c);Db[d]=function(){return{priority:100,link:function(a,f,h){a.$watch(h[d],function(a){h.$set(c,!!a)})}}}}});r(["src","srcset","href"],function(a){var c=ka("ng-"+a);Db[c]=function(){return{priority:99,link:function(d,e,f){var h=a,g=a;"href"===a&&"[object SVGAnimatedString]"===ua.call(e.prop("href"))&&(g="xlinkHref",f.$attr[g]="xlink:href",h=null);f.$observe(c,function(a){a&&(f.$set(g,a),V&&h&&
e.prop(h,f[g]))})}}}});var wb={$addControl:z,$removeControl:z,$setValidity:z,$setDirty:z,$setPristine:z};Sc.$inject=["$element","$attrs","$scope","$animate"];var Tc=function(a){return["$timeout",function(c){return{name:"form",restrict:a?"EAC":"E",controller:Sc,compile:function(){return{pre:function(a,e,f,h){if(!f.action){var g=function(a){a.preventDefault?a.preventDefault():a.returnValue=!1};pb(e[0],"submit",g);e.on("$destroy",function(){c(function(){Ta(e[0],"submit",g)},0,!1)})}var m=e.parent().controller("form"),
k=f.name||f.ngForm;k&&rb(a,k,h,k);if(m)e.on("$destroy",function(){m.$removeControl(h);k&&rb(a,k,s,k);t(h,wb)})}}}}}]},kd=Tc(),xd=Tc(!0),Te=/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/,Ue=/^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-z0-9-]+(\.[a-z0-9-]+)*$/i,Ve=/^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/,Uc=/^(\d{4})-(\d{2})-(\d{2})$/,Vc=/^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)$/,Rb=/^(\d{4})-W(\d\d)$/,Wc=/^(\d{4})-(\d\d)$/,Xc=/^(\d\d):(\d\d)$/,Yc={text:ab,date:bb("date",Uc,yb(Uc,
["yyyy","MM","dd"]),"yyyy-MM-dd"),"datetime-local":bb("datetimelocal",Vc,yb(Vc,["yyyy","MM","dd","HH","mm"]),"yyyy-MM-ddTHH:mm"),time:bb("time",Xc,yb(Xc,["HH","mm"]),"HH:mm"),week:bb("week",Rb,function(a){if(oa(a))return a;if(A(a)){Rb.lastIndex=0;var c=Rb.exec(a);if(c){a=+c[1];var d=+c[2],c=Qc(a),d=7*(d-1);return new Date(a,0,c.getDate()+d)}}return NaN},"yyyy-Www"),month:bb("month",Wc,yb(Wc,["yyyy","MM"]),"yyyy-MM"),number:function(a,c,d,e,f,h){ab(a,c,d,e,f,h);e.$parsers.push(function(a){var c=e.$isEmpty(a);
if(c||Ve.test(a))return e.$setValidity("number",!0),""===a?null:c?a:parseFloat(a);e.$setValidity("number",!1);return s});Oe(e,"number",c);e.$formatters.push(function(a){return e.$isEmpty(a)?"":""+a});d.min&&(a=function(a){var c=parseFloat(d.min);return na(e,"min",e.$isEmpty(a)||a>=c,a)},e.$parsers.push(a),e.$formatters.push(a));d.max&&(a=function(a){var c=parseFloat(d.max);return na(e,"max",e.$isEmpty(a)||a<=c,a)},e.$parsers.push(a),e.$formatters.push(a));e.$formatters.push(function(a){return na(e,
"number",e.$isEmpty(a)||zb(a),a)})},url:function(a,c,d,e,f,h){ab(a,c,d,e,f,h);a=function(a){return na(e,"url",e.$isEmpty(a)||Te.test(a),a)};e.$formatters.push(a);e.$parsers.push(a)},email:function(a,c,d,e,f,h){ab(a,c,d,e,f,h);a=function(a){return na(e,"email",e.$isEmpty(a)||Ue.test(a),a)};e.$formatters.push(a);e.$parsers.push(a)},radio:function(a,c,d,e){D(d.name)&&c.attr("name",db());c.on("click",function(){c[0].checked&&a.$apply(function(){e.$setViewValue(d.value)})});e.$render=function(){c[0].checked=
d.value==e.$viewValue};d.$observe("value",e.$render)},checkbox:function(a,c,d,e){var f=d.ngTrueValue,h=d.ngFalseValue;A(f)||(f=!0);A(h)||(h=!1);c.on("click",function(){a.$apply(function(){e.$setViewValue(c[0].checked)})});e.$render=function(){c[0].checked=e.$viewValue};e.$isEmpty=function(a){return a!==f};e.$formatters.push(function(a){return a===f});e.$parsers.push(function(a){return a?f:h})},hidden:z,button:z,submit:z,reset:z,file:z},fc=["$browser","$sniffer","$filter",function(a,c,d){return{restrict:"E",
require:"?ngModel",link:function(e,f,h,g){g&&(Yc[O(h.type)]||Yc.text)(e,f,h,g,c,a,d)}}}],vb="ng-valid",ub="ng-invalid",La="ng-pristine",xb="ng-dirty",We=["$scope","$exceptionHandler","$attrs","$element","$parse","$animate",function(a,c,d,e,f,h){function g(a,c){c=c?"-"+hb(c,"-"):"";h.removeClass(e,(a?ub:vb)+c);h.addClass(e,(a?vb:ub)+c)}this.$modelValue=this.$viewValue=Number.NaN;this.$parsers=[];this.$formatters=[];this.$viewChangeListeners=[];this.$pristine=!0;this.$dirty=!1;this.$valid=!0;this.$invalid=
!1;this.$name=d.name;var m=f(d.ngModel),k=m.assign;if(!k)throw C("ngModel")("nonassign",d.ngModel,fa(e));this.$render=z;this.$isEmpty=function(a){return D(a)||""===a||null===a||a!==a};var l=e.inheritedData("$formController")||wb,n=0,q=this.$error={};e.addClass(La);g(!0);this.$setValidity=function(a,c){q[a]!==!c&&(c?(q[a]&&n--,n||(g(!0),this.$valid=!0,this.$invalid=!1)):(g(!1),this.$invalid=!0,this.$valid=!1,n++),q[a]=!c,g(c,a),l.$setValidity(a,c,this))};this.$setPristine=function(){this.$dirty=!1;
this.$pristine=!0;h.removeClass(e,xb);h.addClass(e,La)};this.$setViewValue=function(d){this.$viewValue=d;this.$pristine&&(this.$dirty=!0,this.$pristine=!1,h.removeClass(e,La),h.addClass(e,xb),l.$setDirty());r(this.$parsers,function(a){d=a(d)});this.$modelValue!==d&&(this.$modelValue=d,k(a,d),r(this.$viewChangeListeners,function(a){try{a()}catch(d){c(d)}}))};var p=this;a.$watch(function(){var c=m(a);if(p.$modelValue!==c){var d=p.$formatters,e=d.length;for(p.$modelValue=c;e--;)c=d[e](c);p.$viewValue!==
c&&(p.$viewValue=c,p.$render())}return c})}],Md=function(){return{require:["ngModel","^?form"],controller:We,link:function(a,c,d,e){var f=e[0],h=e[1]||wb;h.$addControl(f);a.$on("$destroy",function(){h.$removeControl(f)})}}},Od=Y({require:"ngModel",link:function(a,c,d,e){e.$viewChangeListeners.push(function(){a.$eval(d.ngChange)})}}),gc=function(){return{require:"?ngModel",link:function(a,c,d,e){if(e){d.required=!0;var f=function(a){if(d.required&&e.$isEmpty(a))e.$setValidity("required",!1);else return e.$setValidity("required",
!0),a};e.$formatters.push(f);e.$parsers.unshift(f);d.$observe("required",function(){f(e.$viewValue)})}}}},Nd=function(){return{require:"ngModel",link:function(a,c,d,e){var f=(a=/\/(.*)\//.exec(d.ngList))&&RegExp(a[1])||d.ngList||",";e.$parsers.push(function(a){if(!D(a)){var c=[];a&&r(a.split(f),function(a){a&&c.push(aa(a))});return c}});e.$formatters.push(function(a){return J(a)?a.join(", "):s});e.$isEmpty=function(a){return!a||!a.length}}}},Xe=/^(true|false|\d+)$/,Pd=function(){return{priority:100,
compile:function(a,c){return Xe.test(c.ngValue)?function(a,c,f){f.$set("value",a.$eval(f.ngValue))}:function(a,c,f){a.$watch(f.ngValue,function(a){f.$set("value",a)})}}}},pd=ta(function(a,c,d){c.addClass("ng-binding").data("$binding",d.ngBind);a.$watch(d.ngBind,function(a){c.text(a==s?"":a)})}),rd=["$interpolate",function(a){return function(c,d,e){c=a(d.attr(e.$attr.ngBindTemplate));d.addClass("ng-binding").data("$binding",c);e.$observe("ngBindTemplate",function(a){d.text(a)})}}],qd=["$sce","$parse",
function(a,c){return function(d,e,f){e.addClass("ng-binding").data("$binding",f.ngBindHtml);var h=c(f.ngBindHtml);d.$watch(function(){return(h(d)||"").toString()},function(c){e.html(a.getTrustedHtml(h(d))||"")})}}],sd=Qb("",!0),ud=Qb("Odd",0),td=Qb("Even",1),vd=ta({compile:function(a,c){c.$set("ngCloak",s);a.removeClass("ng-cloak")}}),wd=[function(){return{scope:!0,controller:"@",priority:500}}],hc={};r("click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste".split(" "),
function(a){var c=ka("ng-"+a);hc[c]=["$parse",function(d){return{compile:function(e,f){var h=d(f[c]);return function(c,d,e){d.on(O(a),function(a){c.$apply(function(){h(c,{$event:a})})})}}}}]});var zd=["$animate",function(a){return{transclude:"element",priority:600,terminal:!0,restrict:"A",$$tlb:!0,link:function(c,d,e,f,h){var g,m,k;c.$watch(e.ngIf,function(f){Oa(f)?m||(m=c.$new(),h(m,function(c){c[c.length++]=T.createComment(" end ngIf: "+e.ngIf+" ");g={clone:c};a.enter(c,d.parent(),d)})):(k&&(k.remove(),
k=null),m&&(m.$destroy(),m=null),g&&(k=Cb(g.clone),a.leave(k,function(){k=null}),g=null))})}}}],Ad=["$http","$templateCache","$anchorScroll","$animate","$sce",function(a,c,d,e,f){return{restrict:"ECA",priority:400,terminal:!0,transclude:"element",controller:Pa.noop,compile:function(h,g){var m=g.ngInclude||g.src,k=g.onload||"",l=g.autoscroll;return function(g,h,p,r,s){var t=0,y,v,K,x=function(){v&&(v.remove(),v=null);y&&(y.$destroy(),y=null);K&&(e.leave(K,function(){v=null}),v=K,K=null)};g.$watch(f.parseAsResourceUrl(m),
function(f){var m=function(){!w(l)||l&&!g.$eval(l)||d()},p=++t;f?(a.get(f,{cache:c}).success(function(a){if(p===t){var c=g.$new();r.template=a;a=s(c,function(a){x();e.enter(a,null,h,m)});y=c;K=a;y.$emit("$includeContentLoaded");g.$eval(k)}}).error(function(){p===t&&x()}),g.$emit("$includeContentRequested")):(x(),r.template=null)})}}}}],Qd=["$compile",function(a){return{restrict:"ECA",priority:-400,require:"ngInclude",link:function(c,d,e,f){d.html(f.template);a(d.contents())(c)}}}],Bd=ta({priority:450,
compile:function(){return{pre:function(a,c,d){a.$eval(d.ngInit)}}}}),Cd=ta({terminal:!0,priority:1E3}),Dd=["$locale","$interpolate",function(a,c){var d=/{}/g;return{restrict:"EA",link:function(e,f,h){var g=h.count,m=h.$attr.when&&f.attr(h.$attr.when),k=h.offset||0,l=e.$eval(m)||{},n={},q=c.startSymbol(),p=c.endSymbol(),s=/^when(Minus)?(.+)$/;r(h,function(a,c){s.test(c)&&(l[O(c.replace("when","").replace("Minus","-"))]=f.attr(h.$attr[c]))});r(l,function(a,e){n[e]=c(a.replace(d,q+g+"-"+k+p))});e.$watch(function(){var c=
parseFloat(e.$eval(g));if(isNaN(c))return"";c in l||(c=a.pluralCat(c-k));return n[c](e,f,!0)},function(a){f.text(a)})}}}],Ed=["$parse","$animate",function(a,c){var d=C("ngRepeat");return{transclude:"element",priority:1E3,terminal:!0,$$tlb:!0,link:function(e,f,h,g,m){var k=h.ngRepeat,l=k.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/),n,q,p,s,t,w,y={$id:Ha};if(!l)throw d("iexp",k);h=l[1];g=l[2];(l=l[3])?(n=a(l),q=function(a,c,d){w&&(y[w]=a);y[t]=c;y.$index=d;return n(e,
y)}):(p=function(a,c){return Ha(c)},s=function(a){return a});l=h.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);if(!l)throw d("iidexp",h);t=l[3]||l[1];w=l[2];var H={};e.$watchCollection(g,function(a){var g,h,l=f[0],n,y={},A,B,z,D,C,L,J=[];if(cb(a))C=a,n=q||p;else{n=q||s;C=[];for(z in a)a.hasOwnProperty(z)&&"$"!=z.charAt(0)&&C.push(z);C.sort()}A=C.length;h=J.length=C.length;for(g=0;g<h;g++)if(z=a===C?g:C[g],D=a[z],D=n(z,D,g),ya(D,"`track by` id"),H.hasOwnProperty(D))L=H[D],delete H[D],y[D]=
L,J[g]=L;else{if(y.hasOwnProperty(D))throw r(J,function(a){a&&a.scope&&(H[a.id]=a)}),d("dupes",k,D);J[g]={id:D};y[D]=!1}for(z in H)H.hasOwnProperty(z)&&(L=H[z],g=Cb(L.clone),c.leave(g),r(g,function(a){a.$$NG_REMOVED=!0}),L.scope.$destroy());g=0;for(h=C.length;g<h;g++){z=a===C?g:C[g];D=a[z];L=J[g];J[g-1]&&(l=J[g-1].clone[J[g-1].clone.length-1]);if(L.scope){B=L.scope;n=l;do n=n.nextSibling;while(n&&n.$$NG_REMOVED);L.clone[0]!=n&&c.move(Cb(L.clone),null,v(l));l=L.clone[L.clone.length-1]}else B=e.$new();
B[t]=D;w&&(B[w]=z);B.$index=g;B.$first=0===g;B.$last=g===A-1;B.$middle=!(B.$first||B.$last);B.$odd=!(B.$even=0===(g&1));L.scope||m(B,function(a){a[a.length++]=T.createComment(" end ngRepeat: "+k+" ");c.enter(a,null,v(l));l=a;L.scope=B;L.clone=a;y[L.id]=L})}H=y})}}}],Fd=["$animate",function(a){return function(c,d,e){c.$watch(e.ngShow,function(c){a[Oa(c)?"removeClass":"addClass"](d,"ng-hide")})}}],yd=["$animate",function(a){return function(c,d,e){c.$watch(e.ngHide,function(c){a[Oa(c)?"addClass":"removeClass"](d,
"ng-hide")})}}],Gd=ta(function(a,c,d){a.$watch(d.ngStyle,function(a,d){d&&a!==d&&r(d,function(a,d){c.css(d,"")});a&&c.css(a)},!0)}),Hd=["$animate",function(a){return{restrict:"EA",require:"ngSwitch",controller:["$scope",function(){this.cases={}}],link:function(c,d,e,f){var h,g,m,k=[];c.$watch(e.ngSwitch||e.on,function(d){var n,q=k.length;if(0<q){if(m){for(n=0;n<q;n++)m[n].remove();m=null}m=[];for(n=0;n<q;n++){var p=g[n];k[n].$destroy();m[n]=p;a.leave(p,function(){m.splice(n,1);0===m.length&&(m=null)})}}g=
[];k=[];if(h=f.cases["!"+d]||f.cases["?"])c.$eval(e.change),r(h,function(d){var e=c.$new();k.push(e);d.transclude(e,function(c){var e=d.element;g.push(c);a.enter(c,e.parent(),e)})})})}}}],Id=ta({transclude:"element",priority:800,require:"^ngSwitch",link:function(a,c,d,e,f){e.cases["!"+d.ngSwitchWhen]=e.cases["!"+d.ngSwitchWhen]||[];e.cases["!"+d.ngSwitchWhen].push({transclude:f,element:c})}}),Jd=ta({transclude:"element",priority:800,require:"^ngSwitch",link:function(a,c,d,e,f){e.cases["?"]=e.cases["?"]||
[];e.cases["?"].push({transclude:f,element:c})}}),Ld=ta({link:function(a,c,d,e,f){if(!f)throw C("ngTransclude")("orphan",fa(c));f(function(a){c.empty();c.append(a)})}}),ld=["$templateCache",function(a){return{restrict:"E",terminal:!0,compile:function(c,d){"text/ng-template"==d.type&&a.put(d.id,c[0].text)}}}],Ye=C("ngOptions"),Kd=Y({terminal:!0}),md=["$compile","$parse",function(a,c){var d=/^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/,
e={$setViewValue:z};return{restrict:"E",require:["select","?ngModel"],controller:["$element","$scope","$attrs",function(a,c,d){var m=this,k={},l=e,n;m.databound=d.ngModel;m.init=function(a,c,d){l=a;n=d};m.addOption=function(c){ya(c,'"option value"');k[c]=!0;l.$viewValue==c&&(a.val(c),n.parent()&&n.remove())};m.removeOption=function(a){this.hasOption(a)&&(delete k[a],l.$viewValue==a&&this.renderUnknownOption(a))};m.renderUnknownOption=function(c){c="? "+Ha(c)+" ?";n.val(c);a.prepend(n);a.val(c);n.prop("selected",
!0)};m.hasOption=function(a){return k.hasOwnProperty(a)};c.$on("$destroy",function(){m.renderUnknownOption=z})}],link:function(e,h,g,m){function k(a,c,d,e){d.$render=function(){var a=d.$viewValue;e.hasOption(a)?(A.parent()&&A.remove(),c.val(a),""===a&&C.prop("selected",!0)):D(a)&&C?c.val(""):e.renderUnknownOption(a)};c.on("change",function(){a.$apply(function(){A.parent()&&A.remove();d.$setViewValue(c.val())})})}function l(a,c,d){var e;d.$render=function(){var a=new Va(d.$viewValue);r(c.find("option"),
function(c){c.selected=w(a.get(c.value))})};a.$watch(function(){va(e,d.$viewValue)||(e=$(d.$viewValue),d.$render())});c.on("change",function(){a.$apply(function(){var a=[];r(c.find("option"),function(c){c.selected&&a.push(c.value)});d.$setViewValue(a)})})}function n(e,f,g){function h(){var a={"":[]},c=[""],d,k,s,t,u;t=g.$modelValue;u=x(e)||[];var C=n?Sb(u):u,D,B,E;B={};s=!1;var F,K;if(p)if(v&&J(t))for(s=new Va([]),E=0;E<t.length;E++)B[m]=t[E],s.put(v(e,B),t[E]);else s=new Va(t);for(E=0;D=C.length,
E<D;E++){k=E;if(n){k=C[E];if("$"===k.charAt(0))continue;B[n]=k}B[m]=u[k];d=q(e,B)||"";(k=a[d])||(k=a[d]=[],c.push(d));p?d=w(s.remove(v?v(e,B):r(e,B))):(v?(d={},d[m]=t,d=v(e,d)===v(e,B)):d=t===r(e,B),s=s||d);F=l(e,B);F=w(F)?F:"";k.push({id:v?v(e,B):n?C[E]:E,label:F,selected:d})}p||(z||null===t?a[""].unshift({id:"",label:"",selected:!s}):s||a[""].unshift({id:"?",label:"",selected:!0}));B=0;for(C=c.length;B<C;B++){d=c[B];k=a[d];A.length<=B?(t={element:H.clone().attr("label",d),label:k.label},u=[t],A.push(u),
f.append(t.element)):(u=A[B],t=u[0],t.label!=d&&t.element.attr("label",t.label=d));F=null;E=0;for(D=k.length;E<D;E++)s=k[E],(d=u[E+1])?(F=d.element,d.label!==s.label&&F.text(d.label=s.label),d.id!==s.id&&F.val(d.id=s.id),d.selected!==s.selected&&F.prop("selected",d.selected=s.selected)):(""===s.id&&z?K=z:(K=y.clone()).val(s.id).attr("selected",s.selected).text(s.label),u.push({element:K,label:s.label,id:s.id,selected:s.selected}),F?F.after(K):t.element.append(K),F=K);for(E++;u.length>E;)u.pop().element.remove()}for(;A.length>
B;)A.pop()[0].element.remove()}var k;if(!(k=t.match(d)))throw Ye("iexp",t,fa(f));var l=c(k[2]||k[1]),m=k[4]||k[6],n=k[5],q=c(k[3]||""),r=c(k[2]?k[1]:m),x=c(k[7]),v=k[8]?c(k[8]):null,A=[[{element:f,label:""}]];z&&(a(z)(e),z.removeClass("ng-scope"),z.remove());f.empty();f.on("change",function(){e.$apply(function(){var a,c=x(e)||[],d={},h,k,l,q,t,w,u;if(p)for(k=[],q=0,w=A.length;q<w;q++)for(a=A[q],l=1,t=a.length;l<t;l++){if((h=a[l].element)[0].selected){h=h.val();n&&(d[n]=h);if(v)for(u=0;u<c.length&&
(d[m]=c[u],v(e,d)!=h);u++);else d[m]=c[h];k.push(r(e,d))}}else{h=f.val();if("?"==h)k=s;else if(""===h)k=null;else if(v)for(u=0;u<c.length;u++){if(d[m]=c[u],v(e,d)==h){k=r(e,d);break}}else d[m]=c[h],n&&(d[n]=h),k=r(e,d);1<A[0].length&&A[0][1].id!==h&&(A[0][1].selected=!1)}g.$setViewValue(k)})});g.$render=h;e.$watch(h)}if(m[1]){var q=m[0];m=m[1];var p=g.multiple,t=g.ngOptions,z=!1,C,y=v(T.createElement("option")),H=v(T.createElement("optgroup")),A=y.clone();g=0;for(var x=h.children(),F=x.length;g<F;g++)if(""===
x[g].value){C=z=x.eq(g);break}q.init(m,z,A);p&&(m.$isEmpty=function(a){return!a||0===a.length});t?n(e,h,m):p?l(e,h,m):k(e,h,m,q)}}}}],od=["$interpolate",function(a){var c={addOption:z,removeOption:z};return{restrict:"E",priority:100,compile:function(d,e){if(D(e.value)){var f=a(d.text(),!0);f||e.$set("value",d.text())}return function(a,d,e){var k=d.parent(),l=k.data("$selectController")||k.parent().data("$selectController");l&&l.databound?d.prop("selected",!1):l=c;f?a.$watch(f,function(a,c){e.$set("value",
a);a!==c&&l.removeOption(c);l.addOption(a)}):l.addOption(e.value);d.on("$destroy",function(){l.removeOption(e.value)})}}}}],nd=Y({restrict:"E",terminal:!1});Q.angular.bootstrap?console.log("WARNING: Tried to load angular more than once."):((Fa=Q.jQuery)?(v=Fa,t(Fa.fn,{scope:Ia.scope,isolateScope:Ia.isolateScope,controller:Ia.controller,injector:Ia.injector,inheritedData:Ia.inheritedData}),Eb("remove",!0,!0,!1),Eb("empty",!1,!1,!1),Eb("html",!1,!1,!0)):v=N,Pa.element=v,fd(Pa),v(T).ready(function(){cd(T,
bc)}))})(window,document);!angular.$$csp()&&angular.element(document).find("head").prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide{display:none !important;}ng\\:form{display:block;}.ng-animate-block-transitions{transition:0s all!important;-webkit-transition:0s all!important;}</style>');
//# sourceMappingURL=angular.min.js.map
| gpl-2.0 |
f1194361820/helper | commons/src/main/java/com/fjn/helper/common/jmx/client/JmxAuthBuilder.java | 1194 | /*
*
* Copyright 2018 FJN Corp.
*
* 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.
*
* Author Date Issue
* fs1194361820@163.com 2015-01-01 Initial Version
*
*/
package com.fjn.helper.common.jmx.client;
import java.util.HashMap;
import java.util.Map;
import javax.management.remote.JMXConnector;
public class JmxAuthBuilder {
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Map<String, ?> buildAuth(String user, String password) {
Map auth = new HashMap();
auth.put(JMXConnector.CREDENTIALS, new String[] { user, password });
return auth;
}
}
| gpl-2.0 |
GamerzHell9137/ppsspp | UI/MainScreen.cpp | 37855 | // Copyright (c) 2013- PPSSPP Project.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 2.0 or later versions.
// 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 2.0 for more details.
// A copy of the GPL 2.0 should have been included with the program.
// If not, see http://www.gnu.org/licenses/
// Official git repository and contact information can be found at
// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.
#include <cmath>
#include <algorithm>
#include "base/colorutil.h"
#include "base/display.h"
#include "base/timeutil.h"
#include "file/path.h"
#include "gfx_es2/draw_buffer.h"
#include "math/curves.h"
#include "base/stringutil.h"
#include "ui/ui_context.h"
#include "ui/view.h"
#include "ui/viewgroup.h"
#include "Common/FileUtil.h"
#include "Core/System.h"
#include "Core/Host.h"
#include "Core/Reporting.h"
#include "UI/BackgroundAudio.h"
#include "UI/EmuScreen.h"
#include "UI/MainScreen.h"
#include "UI/GameScreen.h"
#include "UI/GameInfoCache.h"
#include "UI/GameSettingsScreen.h"
#include "UI/MiscScreens.h"
#include "UI/ControlMappingScreen.h"
#include "UI/Store.h"
#include "UI/ui_atlas.h"
#include "Core/Config.h"
#include "GPU/GPUInterface.h"
#include "i18n/i18n.h"
#include "Core/HLE/sceDisplay.h"
#include "Core/HLE/sceUmd.h"
#ifdef _WIN32
#include "Windows/W32Util/ShellUtil.h"
#include "Windows/WndMainWindow.h"
#endif
#ifdef ANDROID_NDK_PROFILER
#include <stdlib.h>
#include "android/android-ndk-profiler/prof.h"
#endif
#ifdef USING_QT_UI
#include <QFileDialog>
#include <QFile>
#include <QDir>
#endif
#include <sstream>
bool MainScreen::showHomebrewTab = false;
class GameButton : public UI::Clickable {
public:
GameButton(const std::string &gamePath, bool gridStyle, UI::LayoutParams *layoutParams = 0)
: UI::Clickable(layoutParams), gridStyle_(gridStyle), gamePath_(gamePath), holdFrameCount_(0), holdEnabled_(true) {}
void Draw(UIContext &dc) override;
void GetContentDimensions(const UIContext &dc, float &w, float &h) const override {
if (gridStyle_) {
w = 144;
h = 80;
} else {
w = 500;
h = 50;
}
}
const std::string &GamePath() const { return gamePath_; }
void SetHoldEnabled(bool hold) {
holdEnabled_ = hold;
}
void Touch(const TouchInput &input) override {
UI::Clickable::Touch(input);
hovering_ = bounds_.Contains(input.x, input.y);
if (input.flags & TOUCH_UP) {
holdFrameCount_ = 0;
}
}
bool Key(const KeyInput &key) override {
std::vector<int> pspKeys;
bool showInfo = false;
if (KeyMap::KeyToPspButton(key.deviceId, key.keyCode, &pspKeys)) {
for (auto it = pspKeys.begin(), end = pspKeys.end(); it != end; ++it) {
// If the button mapped to triangle, then show the info.
if (HasFocus() && (key.flags & KEY_UP) && *it == CTRL_TRIANGLE) {
showInfo = true;
}
}
} else if (hovering_ && key.deviceId == DEVICE_ID_MOUSE && key.keyCode == NKCODE_EXT_MOUSEBUTTON_2) {
// If it's the right mouse button, and it's not otherwise mapped, show the info also.
if (key.flags & KEY_UP) {
showInfo = true;
}
}
if (showInfo) {
TriggerOnHoldClick();
return true;
}
return Clickable::Key(key);
}
void Update(const InputState &input_state) override {
if (down_ && holdEnabled_)
holdFrameCount_++;
else
holdFrameCount_ = 0;
// Hold button for 1.5 seconds to launch the game options
if (holdFrameCount_ > 90) {
TriggerOnHoldClick();
}
}
void FocusChanged(int focusFlags) override {
UI::Clickable::FocusChanged(focusFlags);
TriggerOnHighlight(focusFlags);
}
UI::Event OnHoldClick;
UI::Event OnHighlight;
private:
void TriggerOnHoldClick() {
holdFrameCount_ = 0;
UI::EventParams e;
e.v = this;
e.s = gamePath_;
down_ = false;
OnHoldClick.Trigger(e);
}
void TriggerOnHighlight(int focusFlags) {
UI::EventParams e;
e.v = this;
e.s = gamePath_;
e.a = focusFlags;
OnHighlight.Trigger(e);
}
bool gridStyle_;
std::string gamePath_;
std::string title_;
int holdFrameCount_;
bool holdEnabled_;
bool hovering_;
};
void GameButton::Draw(UIContext &dc) {
GameInfo *ginfo = g_gameInfoCache.GetInfo(dc.GetThin3DContext(), gamePath_, 0);
Thin3DTexture *texture = 0;
u32 color = 0, shadowColor = 0;
using namespace UI;
if (ginfo->iconTexture) {
texture = ginfo->iconTexture;
}
int x = bounds_.x;
int y = bounds_.y;
int w = 144;
int h = bounds_.h;
UI::Style style = dc.theme->itemStyle;
if (down_)
style = dc.theme->itemDownStyle;
if (!gridStyle_ || !texture) {
h = 50;
if (HasFocus())
style = down_ ? dc.theme->itemDownStyle : dc.theme->itemFocusedStyle;
Drawable bg = style.background;
dc.Draw()->Flush();
dc.RebindTexture();
dc.FillRect(bg, bounds_);
dc.Draw()->Flush();
}
if (texture) {
color = whiteAlpha(ease((time_now_d() - ginfo->timeIconWasLoaded) * 2));
shadowColor = blackAlpha(ease((time_now_d() - ginfo->timeIconWasLoaded) * 2));
float tw = texture->Width();
float th = texture->Height();
// Adjust position so we don't stretch the image vertically or horizontally.
// TODO: Add a param to specify fit? The below assumes it's never too wide.
float nw = h * tw / th;
x += (w - nw) / 2.0f;
w = nw;
}
int txOffset = down_ ? 4 : 0;
if (!gridStyle_) txOffset = 0;
Bounds overlayBounds = bounds_;
u32 overlayColor = 0;
if (holdEnabled_)
overlayColor = whiteAlpha((holdFrameCount_ - 15) * 0.01f);
// Render button
int dropsize = 10;
if (texture) {
if (txOffset) {
dropsize = 3;
y += txOffset * 2;
overlayBounds.y += txOffset * 2;
}
if (HasFocus()) {
dc.Draw()->Flush();
dc.RebindTexture();
float pulse = sinf(time_now() * 7.0f) * 0.25 + 0.8;
dc.Draw()->DrawImage4Grid(dc.theme->dropShadow4Grid, x - dropsize*1.5f, y - dropsize*1.5f, x + w + dropsize*1.5f, y + h + dropsize*1.5f, alphaMul(color, pulse), 1.0f);
dc.Draw()->Flush();
} else {
dc.Draw()->Flush();
dc.RebindTexture();
dc.Draw()->DrawImage4Grid(dc.theme->dropShadow4Grid, x - dropsize, y - dropsize*0.5f, x+w + dropsize, y+h+dropsize*1.5, alphaMul(shadowColor, 0.5f), 1.0f);
dc.Draw()->Flush();
}
}
if (texture) {
dc.Draw()->Flush();
dc.GetThin3DContext()->SetTexture(0, texture);
if (holdFrameCount_ > 60) {
// Blink before launching by holding
if (((holdFrameCount_ >> 3) & 1) == 0)
color = darkenColor(color);
}
dc.Draw()->DrawTexRect(x, y, x+w, y+h, 0, 0, 1, 1, color);
dc.Draw()->Flush();
}
char discNumInfo[8];
if (ginfo->disc_total > 1)
sprintf(discNumInfo, "-DISC%d", ginfo->disc_number);
else
strcpy(discNumInfo, "");
dc.Draw()->Flush();
dc.RebindTexture();
dc.SetFontStyle(dc.theme->uiFont);
if (!gridStyle_) {
float tw, th;
dc.Draw()->Flush();
dc.PushScissor(bounds_);
if (title_.empty() && !ginfo->title.empty()) {
title_ = ReplaceAll(ginfo->title + discNumInfo, "&", "&&");
title_ = ReplaceAll(title_, "\n", " ");
}
dc.MeasureText(dc.GetFontStyle(), title_.c_str(), &tw, &th, 0);
int availableWidth = bounds_.w - 150;
float sineWidth = std::max(0.0f, (tw - availableWidth)) / 2.0f;
float tx = 150;
if (availableWidth < tw) {
tx -= (1.0f + sin(time_now_d() * 1.5f)) * sineWidth;
Bounds tb = bounds_;
tb.x = bounds_.x + 150;
tb.w = bounds_.w - 150;
dc.PushScissor(tb);
}
dc.DrawText(title_.c_str(), bounds_.x + tx, bounds_.centerY(), style.fgColor, ALIGN_VCENTER);
if (availableWidth < tw) {
dc.PopScissor();
}
dc.Draw()->Flush();
dc.PopScissor();
} else if (!texture) {
dc.Draw()->Flush();
dc.PushScissor(bounds_);
dc.DrawText(title_.c_str(), bounds_.x + 4, bounds_.centerY(), style.fgColor, ALIGN_VCENTER);
dc.Draw()->Flush();
dc.PopScissor();
} else {
dc.Draw()->Flush();
}
if (!ginfo->id.empty() && g_Config.hasGameConfig(ginfo->id))
{
dc.Draw()->DrawImage(I_GEAR, x, y + h - ui_images[I_GEAR].h, 1.0f);
}
if (overlayColor) {
dc.FillRect(Drawable(overlayColor), overlayBounds);
}
dc.RebindTexture();
}
enum GameBrowserFlags {
FLAG_HOMEBREWSTOREBUTTON = 1
};
class DirButton : public UI::Button {
public:
DirButton(const std::string &path, UI::LayoutParams *layoutParams)
: UI::Button(path, layoutParams), path_(path), absolute_(false) {}
DirButton(const std::string &path, const std::string &text, UI::LayoutParams *layoutParams = 0)
: UI::Button(text, layoutParams), path_(path), absolute_(true) {}
virtual void Draw(UIContext &dc);
const std::string GetPath() const {
return path_;
}
bool PathAbsolute() const {
return absolute_;
}
private:
std::string path_;
bool absolute_;
};
void DirButton::Draw(UIContext &dc) {
using namespace UI;
Style style = dc.theme->buttonStyle;
if (HasFocus()) style = dc.theme->buttonFocusedStyle;
if (down_) style = dc.theme->buttonDownStyle;
if (!IsEnabled()) style = dc.theme->buttonDisabledStyle;
dc.FillRect(style.background, bounds_);
const std::string text = GetText();
int image = I_FOLDER;
if (text == "..") {
image = I_UP_DIRECTORY;
}
float tw, th;
dc.MeasureText(dc.GetFontStyle(), text.c_str(), &tw, &th, 0);
bool compact = bounds_.w < 180;
if (compact) {
// No icon, except "up"
dc.PushScissor(bounds_);
if (image == I_FOLDER) {
dc.DrawText(text.c_str(), bounds_.x + 5, bounds_.centerY(), style.fgColor, ALIGN_VCENTER);
} else {
dc.Draw()->DrawImage(image, bounds_.centerX(), bounds_.centerY(), 1.0f, 0xFFFFFFFF, ALIGN_CENTER);
}
dc.PopScissor();
} else {
bool scissor = false;
if (tw + 150 > bounds_.w) {
dc.PushScissor(bounds_);
scissor = true;
}
dc.Draw()->DrawImage(image, bounds_.x + 72, bounds_.centerY(), .88f, 0xFFFFFFFF, ALIGN_CENTER);
dc.DrawText(text.c_str(), bounds_.x + 150, bounds_.centerY(), style.fgColor, ALIGN_VCENTER);
if (scissor) {
dc.PopScissor();
}
}
}
class GameBrowser : public UI::LinearLayout {
public:
GameBrowser(std::string path, bool allowBrowsing, bool *gridStyle_, std::string lastText, std::string lastLink, int flags = 0, UI::LayoutParams *layoutParams = 0);
UI::Event OnChoice;
UI::Event OnHoldChoice;
UI::Event OnHighlight;
UI::Choice *HomebrewStoreButton() { return homebrewStoreButton_; }
private:
void Refresh();
bool IsCurrentPathPinned();
const std::vector<std::string> GetPinnedPaths();
const std::string GetBaseName(const std::string &path);
UI::EventReturn GameButtonClick(UI::EventParams &e);
UI::EventReturn GameButtonHoldClick(UI::EventParams &e);
UI::EventReturn GameButtonHighlight(UI::EventParams &e);
UI::EventReturn NavigateClick(UI::EventParams &e);
UI::EventReturn LayoutChange(UI::EventParams &e);
UI::EventReturn LastClick(UI::EventParams &e);
UI::EventReturn HomeClick(UI::EventParams &e);
UI::EventReturn PinToggleClick(UI::EventParams &e);
UI::ViewGroup *gameList_;
PathBrowser path_;
bool *gridStyle_;
bool allowBrowsing_;
std::string lastText_;
std::string lastLink_;
int flags_;
UI::Choice *homebrewStoreButton_;
};
GameBrowser::GameBrowser(std::string path, bool allowBrowsing, bool *gridStyle, std::string lastText, std::string lastLink, int flags, UI::LayoutParams *layoutParams)
: LinearLayout(UI::ORIENT_VERTICAL, layoutParams), gameList_(0), path_(path), gridStyle_(gridStyle), allowBrowsing_(allowBrowsing), lastText_(lastText), lastLink_(lastLink), flags_(flags) {
using namespace UI;
Refresh();
}
UI::EventReturn GameBrowser::LayoutChange(UI::EventParams &e) {
*gridStyle_ = e.a == 0 ? true : false;
Refresh();
return UI::EVENT_DONE;
}
UI::EventReturn GameBrowser::LastClick(UI::EventParams &e) {
LaunchBrowser(lastLink_.c_str());
return UI::EVENT_DONE;
}
UI::EventReturn GameBrowser::HomeClick(UI::EventParams &e) {
#ifdef ANDROID
path_.SetPath(g_Config.memStickDirectory);
#elif defined(USING_QT_UI)
I18NCategory *m = GetI18NCategory("MainMenu");
QString fileName = QFileDialog::getExistingDirectory(NULL, "Browse for Folder", g_Config.currentDirectory.c_str());
if (QDir(fileName).exists())
path_.SetPath(fileName.toStdString());
else
return UI::EVENT_DONE;
#elif defined(_WIN32)
I18NCategory *m = GetI18NCategory("MainMenu");
std::string folder = W32Util::BrowseForFolder(MainWindow::GetHWND(), m->T("Choose folder"));
if (!folder.size())
return UI::EVENT_DONE;
path_.SetPath(folder);
#elif defined(BLACKBERRY)
path_.SetPath(std::string(getenv("PERIMETER_HOME")) + "/shared/misc");
#else
path_.SetPath(getenv("HOME"));
#endif
g_Config.currentDirectory = path_.GetPath();
Refresh();
return UI::EVENT_DONE;
}
UI::EventReturn GameBrowser::PinToggleClick(UI::EventParams &e) {
auto &pinnedPaths = g_Config.vPinnedPaths;
if (IsCurrentPathPinned()) {
pinnedPaths.erase(std::remove(pinnedPaths.begin(), pinnedPaths.end(), path_.GetPath()), pinnedPaths.end());
} else {
pinnedPaths.push_back(path_.GetPath());
}
Refresh();
return UI::EVENT_DONE;
}
void GameBrowser::Refresh() {
using namespace UI;
homebrewStoreButton_ = 0;
// Kill all the contents
Clear();
Add(new Spacer(1.0f));
I18NCategory *m = GetI18NCategory("MainMenu");
// No topbar on recent screen
if (path_.GetPath() != "!RECENT") {
LinearLayout *topBar = new LinearLayout(ORIENT_HORIZONTAL, new LinearLayoutParams(FILL_PARENT, WRAP_CONTENT));
if (allowBrowsing_) {
topBar->Add(new Spacer(2.0f));
Margins pathMargins(5, 0);
topBar->Add(new TextView(path_.GetFriendlyPath().c_str(), ALIGN_VCENTER, true, new LinearLayoutParams(1.0f)));
#if defined(_WIN32) || defined(USING_QT_UI)
topBar->Add(new Choice(m->T("Browse", "Browse...")))->OnClick.Handle(this, &GameBrowser::HomeClick);
#else
topBar->Add(new Choice(m->T("Home")))->OnClick.Handle(this, &GameBrowser::HomeClick);
#endif
} else {
topBar->Add(new Spacer(new LinearLayoutParams(1.0f)));
}
ChoiceStrip *layoutChoice = topBar->Add(new ChoiceStrip(ORIENT_HORIZONTAL));
layoutChoice->AddChoice(I_GRID);
layoutChoice->AddChoice(I_LINES);
layoutChoice->SetSelection(*gridStyle_ ? 0 : 1);
layoutChoice->OnChoice.Handle(this, &GameBrowser::LayoutChange);
Add(topBar);
}
if (*gridStyle_) {
gameList_ = new UI::GridLayout(UI::GridLayoutSettings(150, 85), new LinearLayoutParams(FILL_PARENT, WRAP_CONTENT));
} else {
UI::LinearLayout *gl = new UI::LinearLayout(UI::ORIENT_VERTICAL, new LinearLayoutParams(FILL_PARENT, WRAP_CONTENT));
gl->SetSpacing(4.0f);
gameList_ = gl;
}
Add(gameList_);
// Find games in the current directory and create new ones.
std::vector<DirButton *> dirButtons;
std::vector<GameButton *> gameButtons;
if (path_.GetPath() == "!RECENT") {
for (size_t i = 0; i < g_Config.recentIsos.size(); i++) {
gameButtons.push_back(new GameButton(g_Config.recentIsos[i], *gridStyle_, new UI::LinearLayoutParams(*gridStyle_ == true ? UI::WRAP_CONTENT : UI::FILL_PARENT, UI::WRAP_CONTENT)));
}
} else {
std::vector<FileInfo> fileInfo;
path_.GetListing(fileInfo, "iso:cso:pbp:elf:prx:");
for (size_t i = 0; i < fileInfo.size(); i++) {
bool isGame = !fileInfo[i].isDirectory;
// Check if eboot directory
if (!isGame && path_.GetPath().size() >= 4 && File::Exists(path_.GetPath() + fileInfo[i].name + "/EBOOT.PBP"))
isGame = true;
else if (!isGame && File::Exists(path_.GetPath() + fileInfo[i].name + "/PSP_GAME/SYSDIR"))
isGame = true;
if (!isGame) {
if (allowBrowsing_) {
dirButtons.push_back(new DirButton(fileInfo[i].name, new UI::LinearLayoutParams(UI::FILL_PARENT, UI::FILL_PARENT)));
}
} else {
gameButtons.push_back(new GameButton(fileInfo[i].fullName, *gridStyle_, new UI::LinearLayoutParams(*gridStyle_ == true ? UI::WRAP_CONTENT : UI::FILL_PARENT, UI::WRAP_CONTENT)));
}
}
// Put RAR/ZIP files at the end to get them out of the way. They're only shown so that people
// can click them and get an explanation that they need to unpack them. This is necessary due
// to a flood of support email...
if (allowBrowsing_) {
fileInfo.clear();
path_.GetListing(fileInfo, "zip:rar:r01:7z:");
if (!fileInfo.empty()) {
UI::LinearLayout *zl = new UI::LinearLayout(UI::ORIENT_VERTICAL, new LinearLayoutParams(FILL_PARENT, WRAP_CONTENT));
zl->SetSpacing(4.0f);
Add(zl);
for (size_t i = 0; i < fileInfo.size(); i++) {
if (!fileInfo[i].isDirectory) {
GameButton *b = zl->Add(new GameButton(fileInfo[i].fullName, false, new UI::LinearLayoutParams(UI::FILL_PARENT, UI::WRAP_CONTENT)));
b->OnClick.Handle(this, &GameBrowser::GameButtonClick);
b->SetHoldEnabled(false);
}
}
}
}
}
if (allowBrowsing_) {
gameList_->Add(new DirButton("..", new UI::LinearLayoutParams(UI::FILL_PARENT, UI::FILL_PARENT)))->
OnClick.Handle(this, &GameBrowser::NavigateClick);
// Add any pinned paths before other directories.
auto pinnedPaths = GetPinnedPaths();
for (auto it = pinnedPaths.begin(), end = pinnedPaths.end(); it != end; ++it) {
gameList_->Add(new DirButton(*it, GetBaseName(*it), new UI::LinearLayoutParams(UI::FILL_PARENT, UI::FILL_PARENT)))->
OnClick.Handle(this, &GameBrowser::NavigateClick);
}
}
for (size_t i = 0; i < dirButtons.size(); i++) {
gameList_->Add(dirButtons[i])->OnClick.Handle(this, &GameBrowser::NavigateClick);
}
for (size_t i = 0; i < gameButtons.size(); i++) {
GameButton *b = gameList_->Add(gameButtons[i]);
b->OnClick.Handle(this, &GameBrowser::GameButtonClick);
b->OnHoldClick.Handle(this, &GameBrowser::GameButtonHoldClick);
b->OnHighlight.Handle(this, &GameBrowser::GameButtonHighlight);
}
// Show a button to toggle pinning at the very end.
if (allowBrowsing_) {
std::string caption = IsCurrentPathPinned() ? "-" : "+";
if (!*gridStyle_) {
caption = IsCurrentPathPinned() ? m->T("UnpinPath", "Unpin") : m->T("PinPath", "Pin");
}
gameList_->Add(new UI::Button(caption, new UI::LinearLayoutParams(UI::FILL_PARENT, UI::FILL_PARENT)))->
OnClick.Handle(this, &GameBrowser::PinToggleClick);
}
if (g_Config.bHomebrewStore && (flags_ & FLAG_HOMEBREWSTOREBUTTON)) {
Add(new Spacer());
homebrewStoreButton_ = Add(new Choice(m->T("DownloadFromStore", "Download from the PPSSPP Homebrew Store"), new UI::LinearLayoutParams(UI::WRAP_CONTENT, UI::WRAP_CONTENT)));
} else {
homebrewStoreButton_ = 0;
}
if (!lastText_.empty() && gameButtons.empty()) {
Add(new Spacer());
Add(new Choice(lastText_, new UI::LinearLayoutParams(UI::WRAP_CONTENT, UI::WRAP_CONTENT)))->OnClick.Handle(this, &GameBrowser::LastClick);
}
}
bool GameBrowser::IsCurrentPathPinned() {
const auto paths = g_Config.vPinnedPaths;
return std::find(paths.begin(), paths.end(), path_.GetPath()) != paths.end();
}
const std::vector<std::string> GameBrowser::GetPinnedPaths() {
#ifndef _WIN32
static const std::string sepChars = "/";
#else
static const std::string sepChars = "/\\";
#endif
const std::string currentPath = path_.GetPath();
const std::vector<std::string> paths = g_Config.vPinnedPaths;
std::vector<std::string> results;
for (size_t i = 0; i < paths.size(); ++i) {
// We want to exclude the current path, and its direct children.
if (paths[i] == currentPath) {
continue;
}
if (startsWith(paths[i], currentPath)) {
std::string descendant = paths[i].substr(currentPath.size());
// If there's only one separator (or none), its a direct child.
if (descendant.find_last_of(sepChars) == descendant.find_first_of(sepChars)) {
continue;
}
}
results.push_back(paths[i]);
}
return results;
}
const std::string GameBrowser::GetBaseName(const std::string &path) {
#ifndef _WIN32
static const std::string sepChars = "/";
#else
static const std::string sepChars = "/\\";
#endif
auto trailing = path.find_last_not_of(sepChars);
if (trailing != path.npos) {
size_t start = path.find_last_of(sepChars, trailing);
if (start != path.npos) {
return path.substr(start + 1, trailing - start);
}
return path.substr(0, trailing);
}
size_t start = path.find_last_of(sepChars);
if (start != path.npos) {
return path.substr(start + 1);
}
return path;
}
UI::EventReturn GameBrowser::GameButtonClick(UI::EventParams &e) {
GameButton *button = static_cast<GameButton *>(e.v);
UI::EventParams e2;
e2.s = button->GamePath();
// Insta-update - here we know we are already on the right thread.
OnChoice.Trigger(e2);
return UI::EVENT_DONE;
}
UI::EventReturn GameBrowser::GameButtonHoldClick(UI::EventParams &e) {
GameButton *button = static_cast<GameButton *>(e.v);
UI::EventParams e2;
e2.s = button->GamePath();
// Insta-update - here we know we are already on the right thread.
OnHoldChoice.Trigger(e2);
return UI::EVENT_DONE;
}
UI::EventReturn GameBrowser::GameButtonHighlight(UI::EventParams &e) {
// Insta-update - here we know we are already on the right thread.
OnHighlight.Trigger(e);
return UI::EVENT_DONE;
}
UI::EventReturn GameBrowser::NavigateClick(UI::EventParams &e) {
DirButton *button = static_cast<DirButton *>(e.v);
std::string text = button->GetPath();
if (button->PathAbsolute()) {
path_.SetPath(text);
} else {
path_.Navigate(text);
}
g_Config.currentDirectory = path_.GetPath();
Refresh();
return UI::EVENT_DONE;
}
MainScreen::MainScreen() : highlightProgress_(0.0f), prevHighlightProgress_(0.0f), backFromStore_(false), lockBackgroundAudio_(false) {
System_SendMessage("event", "mainscreen");
SetBackgroundAudioGame("");
lastVertical_ = UseVerticalLayout();
}
MainScreen::~MainScreen() {
SetBackgroundAudioGame("");
}
void MainScreen::CreateViews() {
// Information in the top left.
// Back button to the bottom left.
// Scrolling action menu to the right.
using namespace UI;
bool vertical = UseVerticalLayout();
I18NCategory *m = GetI18NCategory("MainMenu");
Margins actionMenuMargins(0, 10, 10, 0);
TabHolder *leftColumn = new TabHolder(ORIENT_HORIZONTAL, 64);
tabHolder_ = leftColumn;
leftColumn->SetClip(true);
if (g_Config.iMaxRecent > 0) {
ScrollView *scrollRecentGames = new ScrollView(ORIENT_VERTICAL, new LinearLayoutParams(FILL_PARENT, WRAP_CONTENT));
GameBrowser *tabRecentGames = new GameBrowser(
"!RECENT", false, &g_Config.bGridView1, "", "", 0,
new LinearLayoutParams(FILL_PARENT, FILL_PARENT));
scrollRecentGames->Add(tabRecentGames);
leftColumn->AddTab(m->T("Recent"), scrollRecentGames);
tabRecentGames->OnChoice.Handle(this, &MainScreen::OnGameSelectedInstant);
tabRecentGames->OnHoldChoice.Handle(this, &MainScreen::OnGameSelected);
tabRecentGames->OnHighlight.Handle(this, &MainScreen::OnGameHighlight);
}
ScrollView *scrollAllGames = new ScrollView(ORIENT_VERTICAL, new LinearLayoutParams(FILL_PARENT, WRAP_CONTENT));
ScrollView *scrollHomebrew = new ScrollView(ORIENT_VERTICAL, new LinearLayoutParams(FILL_PARENT, WRAP_CONTENT));
GameBrowser *tabAllGames = new GameBrowser(g_Config.currentDirectory, true, &g_Config.bGridView2,
m->T("How to get games"), "http://www.ppsspp.org/getgames.html", 0,
new LinearLayoutParams(FILL_PARENT, FILL_PARENT));
GameBrowser *tabHomebrew = new GameBrowser(GetSysDirectory(DIRECTORY_GAME), false, &g_Config.bGridView3,
m->T("How to get homebrew & demos", "How to get homebrew && demos"), "http://www.ppsspp.org/gethomebrew.html",
FLAG_HOMEBREWSTOREBUTTON,
new LinearLayoutParams(FILL_PARENT, FILL_PARENT));
Choice *hbStore = tabHomebrew->HomebrewStoreButton();
if (hbStore) {
hbStore->OnClick.Handle(this, &MainScreen::OnHomebrewStore);
}
scrollAllGames->Add(tabAllGames);
scrollHomebrew->Add(tabHomebrew);
leftColumn->AddTab(m->T("Games"), scrollAllGames);
leftColumn->AddTab(m->T("Homebrew & Demos"), scrollHomebrew);
tabAllGames->OnChoice.Handle(this, &MainScreen::OnGameSelectedInstant);
tabHomebrew->OnChoice.Handle(this, &MainScreen::OnGameSelectedInstant);
tabAllGames->OnHoldChoice.Handle(this, &MainScreen::OnGameSelected);
tabHomebrew->OnHoldChoice.Handle(this, &MainScreen::OnGameSelected);
tabAllGames->OnHighlight.Handle(this, &MainScreen::OnGameHighlight);
tabHomebrew->OnHighlight.Handle(this, &MainScreen::OnGameHighlight);
if (g_Config.recentIsos.size() > 0) {
leftColumn->SetCurrentTab(0);
} else if (g_Config.iMaxRecent > 0) {
leftColumn->SetCurrentTab(1);
}
if (backFromStore_ || showHomebrewTab) {
leftColumn->SetCurrentTab(2);
backFromStore_ = false;
showHomebrewTab = false;
}
/* if (info) {
texvGameIcon_ = leftColumn->Add(new TextureView(0, IS_DEFAULT, new AnchorLayoutParams(144 * 2, 80 * 2, 10, 10, NONE, NONE)));
tvTitle_ = leftColumn->Add(new TextView(0, info->title, ALIGN_LEFT, 1.0f, new AnchorLayoutParams(10, 200, NONE, NONE)));
tvGameSize_ = leftColumn->Add(new TextView(0, "...", ALIGN_LEFT, 1.0f, new AnchorLayoutParams(10, 250, NONE, NONE)));
tvSaveDataSize_ = leftColumn->Add(new TextView(0, "...", ALIGN_LEFT, 1.0f, new AnchorLayoutParams(10, 290, NONE, NONE)));
} */
ViewGroup *rightColumn = new ScrollView(ORIENT_VERTICAL);
LinearLayout *rightColumnItems = new LinearLayout(ORIENT_VERTICAL, new LinearLayoutParams(FILL_PARENT, WRAP_CONTENT));
rightColumnItems->SetSpacing(0.0f);
rightColumn->Add(rightColumnItems);
char versionString[256];
sprintf(versionString, "%s", PPSSPP_GIT_VERSION);
rightColumnItems->SetSpacing(0.0f);
LinearLayout *logos = new LinearLayout(ORIENT_HORIZONTAL);
#ifdef GOLD
logos->Add(new ImageView(I_ICONGOLD, IS_DEFAULT, new AnchorLayoutParams(64, 64, 10, 10, NONE, NONE, false)));
#else
logos->Add(new ImageView(I_ICON, IS_DEFAULT, new AnchorLayoutParams(64, 64, 10, 10, NONE, NONE, false)));
#endif
logos->Add(new ImageView(I_LOGO, IS_DEFAULT, new LinearLayoutParams(Margins(-12, 0, 0, 0))));
rightColumnItems->Add(logos);
rightColumnItems->Add(new TextView(versionString, new LinearLayoutParams(Margins(70, -6, 0, 0))))->SetSmall(true);
#if defined(_WIN32) || defined(USING_QT_UI)
rightColumnItems->Add(new Choice(m->T("Load","Load...")))->OnClick.Handle(this, &MainScreen::OnLoadFile);
#endif
rightColumnItems->Add(new Choice(m->T("Game Settings", "Settings")))->OnClick.Handle(this, &MainScreen::OnGameSettings);
rightColumnItems->Add(new Choice(m->T("Credits")))->OnClick.Handle(this, &MainScreen::OnCredits);
rightColumnItems->Add(new Choice(m->T("www.ppsspp.org")))->OnClick.Handle(this, &MainScreen::OnPPSSPPOrg);
#ifndef GOLD
Choice *gold = rightColumnItems->Add(new Choice(m->T("Support PPSSPP")));
gold->OnClick.Handle(this, &MainScreen::OnSupport);
gold->SetIcon(I_ICONGOLD);
#endif
rightColumnItems->Add(new Spacer(25.0));
rightColumnItems->Add(new Choice(m->T("Exit")))->OnClick.Handle(this, &MainScreen::OnExit);
if (vertical) {
root_ = new LinearLayout(ORIENT_VERTICAL);
rightColumn->ReplaceLayoutParams(new LinearLayoutParams(FILL_PARENT, WRAP_CONTENT));
leftColumn->ReplaceLayoutParams(new LinearLayoutParams(1.0));
root_->Add(rightColumn);
root_->Add(leftColumn);
} else {
root_ = new LinearLayout(ORIENT_HORIZONTAL);
leftColumn->ReplaceLayoutParams(new LinearLayoutParams(1.0));
rightColumn->ReplaceLayoutParams(new LinearLayoutParams(300, FILL_PARENT, actionMenuMargins));
root_->Add(leftColumn);
root_->Add(rightColumn);
}
root_->SetDefaultFocusView(tabHolder_);
I18NCategory *u = GetI18NCategory("Upgrade");
upgradeBar_ = 0;
if (!g_Config.upgradeMessage.empty()) {
upgradeBar_ = new LinearLayout(ORIENT_HORIZONTAL, new LinearLayoutParams(FILL_PARENT, WRAP_CONTENT));
UI::Margins textMargins(10, 5);
UI::Margins buttonMargins(0, 0);
UI::Drawable solid(0xFFbd9939);
upgradeBar_->SetBG(solid);
upgradeBar_->Add(new TextView(u->T("New version of PPSSPP available") + std::string(": ") + g_Config.upgradeVersion, new LinearLayoutParams(1.0f, textMargins)));
upgradeBar_->Add(new Button(u->T("Download"), new LinearLayoutParams(buttonMargins)))->OnClick.Handle(this, &MainScreen::OnDownloadUpgrade);
upgradeBar_->Add(new Button(u->T("Dismiss"), new LinearLayoutParams(buttonMargins)))->OnClick.Handle(this, &MainScreen::OnDismissUpgrade);
// Slip in under root_
LinearLayout *newRoot = new LinearLayout(ORIENT_VERTICAL);
newRoot->Add(root_);
newRoot->Add(upgradeBar_);
root_->ReplaceLayoutParams(new LinearLayoutParams(1.0));
root_ = newRoot;
}
}
UI::EventReturn MainScreen::OnDownloadUpgrade(UI::EventParams &e) {
#ifdef ANDROID
// Go to app store
#ifdef GOLD
LaunchBrowser("market://details?id=org.ppsspp.ppssppgold");
#else
LaunchBrowser("market://details?id=org.ppsspp.ppsspp");
#endif
#else
// Go directly to ppsspp.org and let the user sort it out
LaunchBrowser("http://www.ppsspp.org/downloads.html");
#endif
return UI::EVENT_DONE;
}
UI::EventReturn MainScreen::OnDismissUpgrade(UI::EventParams &e) {
g_Config.DismissUpgrade();
upgradeBar_->SetVisibility(UI::V_GONE);
return UI::EVENT_DONE;
}
void MainScreen::sendMessage(const char *message, const char *value) {
// Always call the base class method first to handle the most common messages.
UIScreenWithBackground::sendMessage(message, value);
if (!strcmp(message, "boot")) {
screenManager()->switchScreen(new EmuScreen(value));
SetBackgroundAudioGame(value);
}
if (!strcmp(message, "control mapping")) {
UpdateUIState(UISTATE_MENU);
screenManager()->push(new ControlMappingScreen());
}
if (!strcmp(message, "settings")) {
UpdateUIState(UISTATE_MENU);
screenManager()->push(new GameSettingsScreen(""));
}
}
void MainScreen::update(InputState &input) {
UIScreen::update(input);
UpdateUIState(UISTATE_MENU);
bool vertical = UseVerticalLayout();
if (vertical != lastVertical_) {
RecreateViews();
lastVertical_ = vertical;
}
}
bool MainScreen::UseVerticalLayout() const {
return dp_yres > dp_xres * 1.1f;
}
UI::EventReturn MainScreen::OnLoadFile(UI::EventParams &e) {
#if defined(USING_QT_UI)
QString fileName = QFileDialog::getOpenFileName(NULL, "Load ROM", g_Config.currentDirectory.c_str(), "PSP ROMs (*.iso *.cso *.pbp *.elf *.zip)");
if (QFile::exists(fileName)) {
QDir newPath;
g_Config.currentDirectory = newPath.filePath(fileName).toStdString();
g_Config.Save();
screenManager()->switchScreen(new EmuScreen(fileName.toStdString()));
}
#elif defined(USING_WIN_UI)
MainWindow::BrowseAndBoot("");
#endif
return UI::EVENT_DONE;
}
extern void DrawBackground(UIContext &dc, float alpha);
void MainScreen::DrawBackground(UIContext &dc) {
UIScreenWithBackground::DrawBackground(dc);
if (highlightedGamePath_.empty() && prevHighlightedGamePath_.empty()) {
return;
}
if (DrawBackgroundFor(dc, prevHighlightedGamePath_, 1.0f - prevHighlightProgress_)) {
if (prevHighlightProgress_ < 1.0f) {
prevHighlightProgress_ += 1.0f / 20.0f;
}
}
if (!highlightedGamePath_.empty()) {
if (DrawBackgroundFor(dc, highlightedGamePath_, highlightProgress_)) {
if (highlightProgress_ < 1.0f) {
highlightProgress_ += 1.0f / 20.0f;
}
}
}
}
bool MainScreen::DrawBackgroundFor(UIContext &dc, const std::string &gamePath, float progress) {
dc.Flush();
GameInfo *ginfo = 0;
if (!gamePath.empty()) {
ginfo = g_gameInfoCache.GetInfo(dc.GetThin3DContext(), gamePath, GAMEINFO_WANTBG);
// Loading texture data may bind a texture.
dc.RebindTexture();
// Let's not bother if there's no picture.
if (!ginfo || (!ginfo->pic1Texture && !ginfo->pic0Texture)) {
return false;
}
} else {
return false;
}
if (ginfo->pic1Texture) {
dc.GetThin3DContext()->SetTexture(0, ginfo->pic1Texture);
} else if (ginfo->pic0Texture) {
dc.GetThin3DContext()->SetTexture(0, ginfo->pic0Texture);
}
uint32_t color = whiteAlpha(ease(progress)) & 0xFFc0c0c0;
dc.Draw()->DrawTexRect(dc.GetBounds(), 0,0,1,1, color);
dc.Flush();
dc.RebindTexture();
return true;
}
UI::EventReturn MainScreen::OnGameSelected(UI::EventParams &e) {
#ifdef _WIN32
std::string path = ReplaceAll(e.s, "\\", "/");
#else
std::string path = e.s;
#endif
SetBackgroundAudioGame(path);
lockBackgroundAudio_ = true;
screenManager()->push(new GameScreen(path));
return UI::EVENT_DONE;
}
UI::EventReturn MainScreen::OnGameHighlight(UI::EventParams &e) {
using namespace UI;
#ifdef _WIN32
std::string path = ReplaceAll(e.s, "\\", "/");
#else
std::string path = e.s;
#endif
if (!highlightedGamePath_.empty() || (e.a == FF_LOSTFOCUS && highlightedGamePath_ == path)) {
if (prevHighlightedGamePath_.empty() || prevHighlightProgress_ >= 0.75f) {
prevHighlightedGamePath_ = highlightedGamePath_;
prevHighlightProgress_ = 1.0 - highlightProgress_;
}
highlightedGamePath_.clear();
}
if (e.a == FF_GOTFOCUS) {
highlightedGamePath_ = path;
highlightProgress_ = 0.0f;
}
if ((!highlightedGamePath_.empty() || e.a == FF_LOSTFOCUS) && !lockBackgroundAudio_)
SetBackgroundAudioGame(highlightedGamePath_);
lockBackgroundAudio_ = false;
return UI::EVENT_DONE;
}
UI::EventReturn MainScreen::OnGameSelectedInstant(UI::EventParams &e) {
#ifdef _WIN32
std::string path = ReplaceAll(e.s, "\\", "/");
#else
std::string path = e.s;
#endif
// Go directly into the game.
screenManager()->switchScreen(new EmuScreen(path));
return UI::EVENT_DONE;
}
UI::EventReturn MainScreen::OnGameSettings(UI::EventParams &e) {
// screenManager()->push(new SettingsScreen());
auto gameSettings = new GameSettingsScreen("", "");
gameSettings->OnRecentChanged.Handle(this, &MainScreen::OnRecentChange);
screenManager()->push(gameSettings);
return UI::EVENT_DONE;
}
UI::EventReturn MainScreen::OnRecentChange(UI::EventParams &e) {
RecreateViews();
if (host) {
host->UpdateUI();
}
return UI::EVENT_DONE;
}
UI::EventReturn MainScreen::OnCredits(UI::EventParams &e) {
screenManager()->push(new CreditsScreen());
return UI::EVENT_DONE;
}
UI::EventReturn MainScreen::OnHomebrewStore(UI::EventParams &e) {
screenManager()->push(new StoreScreen());
return UI::EVENT_DONE;
}
UI::EventReturn MainScreen::OnSupport(UI::EventParams &e) {
#ifdef ANDROID
LaunchBrowser("market://details?id=org.ppsspp.ppssppgold");
#else
LaunchBrowser("http://central.ppsspp.org/buygold");
#endif
return UI::EVENT_DONE;
}
UI::EventReturn MainScreen::OnPPSSPPOrg(UI::EventParams &e) {
LaunchBrowser("http://www.ppsspp.org");
return UI::EVENT_DONE;
}
UI::EventReturn MainScreen::OnForums(UI::EventParams &e) {
LaunchBrowser("http://forums.ppsspp.org");
return UI::EVENT_DONE;
}
UI::EventReturn MainScreen::OnExit(UI::EventParams &e) {
System_SendMessage("event", "exitprogram");
// Request the framework to exit cleanly.
System_SendMessage("finish", "");
// We shouldn't call NativeShutdown here at all, it should be done by the framework.
#ifdef ANDROID
#ifdef ANDROID_NDK_PROFILER
moncleanup();
#endif
exit(0);
#endif
UpdateUIState(UISTATE_EXIT);
return UI::EVENT_DONE;
}
void MainScreen::dialogFinished(const Screen *dialog, DialogResult result) {
if (dialog->tag() == "store") {
backFromStore_ = true;
RecreateViews();
}
}
void UmdReplaceScreen::CreateViews() {
using namespace UI;
Margins actionMenuMargins(0, 100, 15, 0);
I18NCategory *m = GetI18NCategory("MainMenu");
I18NCategory *d = GetI18NCategory("Dialog");
TabHolder *leftColumn = new TabHolder(ORIENT_HORIZONTAL, 64, new LinearLayoutParams(1.0));
leftColumn->SetClip(true);
ViewGroup *rightColumn = new ScrollView(ORIENT_VERTICAL, new LinearLayoutParams(270, FILL_PARENT, actionMenuMargins));
LinearLayout *rightColumnItems = new LinearLayout(ORIENT_VERTICAL, new LinearLayoutParams(FILL_PARENT, WRAP_CONTENT));
rightColumnItems->SetSpacing(0.0f);
rightColumn->Add(rightColumnItems);
if (g_Config.iMaxRecent > 0) {
ScrollView *scrollRecentGames = new ScrollView(ORIENT_VERTICAL, new LinearLayoutParams(FILL_PARENT, WRAP_CONTENT));
GameBrowser *tabRecentGames = new GameBrowser(
"!RECENT", false, &g_Config.bGridView1, "", "", 0,
new LinearLayoutParams(FILL_PARENT, FILL_PARENT));
scrollRecentGames->Add(tabRecentGames);
leftColumn->AddTab(m->T("Recent"), scrollRecentGames);
tabRecentGames->OnChoice.Handle(this, &UmdReplaceScreen::OnGameSelectedInstant);
tabRecentGames->OnHoldChoice.Handle(this, &UmdReplaceScreen::OnGameSelected);
}
ScrollView *scrollAllGames = new ScrollView(ORIENT_VERTICAL, new LinearLayoutParams(FILL_PARENT, WRAP_CONTENT));
GameBrowser *tabAllGames = new GameBrowser(g_Config.currentDirectory, true, &g_Config.bGridView2,
m->T("How to get games"), "http://www.ppsspp.org/getgames.html", 0,
new LinearLayoutParams(FILL_PARENT, FILL_PARENT));
scrollAllGames->Add(tabAllGames);
leftColumn->AddTab(m->T("Games"), scrollAllGames);
tabAllGames->OnChoice.Handle(this, &UmdReplaceScreen::OnGameSelectedInstant);
tabAllGames->OnHoldChoice.Handle(this, &UmdReplaceScreen::OnGameSelected);
rightColumnItems->Add(new Choice(d->T("Cancel")))->OnClick.Handle(this, &UmdReplaceScreen::OnCancel);
rightColumnItems->Add(new Choice(m->T("Game Settings")))->OnClick.Handle(this, &UmdReplaceScreen::OnGameSettings);
if (g_Config.recentIsos.size() > 0) {
leftColumn->SetCurrentTab(0);
} else if (g_Config.iMaxRecent > 0) {
leftColumn->SetCurrentTab(1);
}
root_ = new LinearLayout(ORIENT_HORIZONTAL);
root_->Add(leftColumn);
root_->Add(rightColumn);
}
void UmdReplaceScreen::update(InputState &input) {
UpdateUIState(UISTATE_PAUSEMENU);
UIScreen::update(input);
}
UI::EventReturn UmdReplaceScreen::OnGameSelected(UI::EventParams &e) {
__UmdReplace(e.s);
screenManager()->finishDialog(this, DR_OK);
return UI::EVENT_DONE;
}
UI::EventReturn UmdReplaceScreen::OnCancel(UI::EventParams &e) {
screenManager()->finishDialog(this, DR_CANCEL);
return UI::EVENT_DONE;
}
UI::EventReturn UmdReplaceScreen::OnGameSettings(UI::EventParams &e) {
screenManager()->push(new GameSettingsScreen(""));
return UI::EVENT_DONE;
}
UI::EventReturn UmdReplaceScreen::OnGameSelectedInstant(UI::EventParams &e) {
__UmdReplace(e.s);
screenManager()->finishDialog(this, DR_OK);
return UI::EVENT_DONE;
}
| gpl-2.0 |
mrcpj1998/BulletJumpers | src/options.lua | 1443 | function loadOptions()
--Declare the options var and clear it
options = {}
options.playerName = "lolrus"
options.fullscreen = false
options.jumpKey = "up"
options.leftKey = "left"
options.rightKey = "right"
local words = {}
local s = love.filesystem.read("options.pref")
--splits the string from filesystem
for w in (s .. ";"):gmatch("([^;]*);") do
table.insert(words, w)
end
--Sets keys
for i,v in ipairs(words) do
if v == "jumpKey" then options.jumpKey = words[i+1] end
if v == "rightKey" then options.rightKey = words[i+1]end
if v == "leftKey" then options.leftKey = words[i+1]end
if v == "fullscreen" then if words[i+1] == "true" then options.fullscreen = "true" fullscreen = true love.window.setMode(1360,768, {fullscreen = true}) else options.fullscreen = "false" end end
if v == "playerName" then options.playerName = words[i+1] end
end
end
function saveOptions()
local optionString = "jumpKey;"..options.jumpKey..";rightKey;"..options.rightKey..";leftKey;"..options.leftKey..";fullscreen;"..options.fullscreen..";playerName;"..options.playerName
love.filesystem.write("options.pref",optionString)
end
function changeFullScreen()
if fullscreen then
love.window.setMode(1360,768, {fullscreen = false})
options.fullscreen = "false"
else
love.window.setMode(1360,768, {fullscreen = true})
fullscreen = true
options.fullscreen = "true"
end
end | gpl-2.0 |
mailoplatform/ServerTools | src/de/maltesermailo/OpMessage/PlayerListener.java | 4859 | package de.maltesermailo.OpMessage;
import java.io.File;
import org.bukkit.Bukkit;
import org.bukkit.Effect;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.World;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
public class PlayerListener implements Listener {
Location center;
final int max = 30;
@EventHandler
public void onInteract(final PlayerInteractEvent e) {
final Player p = e.getPlayer();
if (e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK) {
if (e.getPlayer().hasPermission("gb.fly")) {
if (p.getItemInHand().getType() == Material.FEATHER) {
if (p.getAllowFlight()) {
p.setAllowFlight(false);
p.setFlying(false);
p.sendMessage("Du kannst nun nicht mehr fliegen!");
} else {
p.setAllowFlight(true);
p.setFlying(true);
p.sendMessage("Du kannst nun fliegen!");
p.setFoodLevel(p.getFoodLevel() - 5);
}
}
}
}
if (p.hasPermission("gb.klasse2")) {
if (p.getItemInHand().getType() == Material.ENDER_PEARL && p.getItemInHand().getAmount() < 64) {
p.getItemInHand().setAmount(64);
}
}
if (p.hasPermission("gb.klasse3")) {
if (p.getItemInHand().getType() == Material.WORKBENCH) {
if (e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK) {
p.openWorkbench(p.getLocation(), true);
e.setCancelled(true);
}
}
}
if (p.hasPermission("gb.klasse4")) {
}
if (e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK) {
if (p.getItemInHand().getType() == Material.EYE_OF_ENDER) {
if(!p.hasPermission("cn.spawn")) {
p.sendMessage("§cInsufficent Permissions!");
return;
}
File file = new File("plugins//OpMessage//spawn.yml");
if(!file.exists()) {
p.sendMessage("§cEs wurde noch kein Spawn gesetzt!");
return;
}
YamlConfiguration cfg = YamlConfiguration.loadConfiguration(file);
Location loc = p.getLocation();
double x = cfg.getDouble("X");
double y = cfg.getDouble("Y");
double z = cfg.getDouble("Z");
double yaw = cfg.getDouble("Yaw");
double pitch = cfg.getDouble("Pitch");
String worldname = cfg.getString("Worldname");
World welt = Bukkit.getWorld(worldname);
loc.setX(x);
loc.setY(y);
loc.setZ(z);
loc.setYaw((float) yaw);
loc.setPitch((float) pitch);
loc.setWorld(welt);
p.teleport(loc);
p.sendMessage("§7Du wurdest zum §6Spawn §7teleportiert.");
e.setCancelled(true);
}
}
if (e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK) {
if (p.getItemInHand().getType() == Material.ENDER_PEARL) {
p.setVelocity(p.getLocation().getDirection().multiply(1.5));
e.setCancelled(true);
}
}
}
public long onFly() {
return 0;
}
@EventHandler
public void onTree(BlockBreakEvent e) {
Player p = e.getPlayer();
if (e.getBlock().getType() == Material.LEAVES) {
p.getInventory().addItem(new ItemStack(Material.APPLE, 2));
}
}
@EventHandler
public void onFall(EntityDamageEvent e) {
if (e.getEntityType() == EntityType.PLAYER) {
e.getEntity().setFallDistance(0.0F);
if (e.getCause().equals(DamageCause.FALL)) {
Player p = (Player) e.getEntity();
p.playSound(p.getLocation(), Sound.ENDERMAN_TELEPORT, (float) 1, (float) 1);
e.setCancelled(true);
p.playEffect(p.getLocation(), Effect.ENDER_SIGNAL, null);
}
}
}
@EventHandler
public void onCommand(PlayerCommandPreprocessEvent e) {
if (!e.getPlayer().hasPermission("cn.usecommands")) {
if (e.getMessage().equalsIgnoreCase("/craft help") | e.getMessage().equalsIgnoreCase("/craft") | e.getMessage().equalsIgnoreCase("/craft support") | e.getMessage().equalsIgnoreCase("/donotuse") | e.getMessage().equalsIgnoreCase("/bw leave") | e.getMessage().equalsIgnoreCase("/spawn")) {
e.setMessage(e.getMessage());
} else {
Player cs = e.getPlayer();
cs.sendMessage(e.getMessage());
e.setMessage("/donotuse");
}
}
}
}
| gpl-2.0 |
ia-toki/judgels | judgels-backends/uriel/uriel-app/src/main/java/judgels/uriel/file/FileFs.java | 220 | package judgels.uriel.file;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import javax.inject.Qualifier;
@Qualifier
@Retention(RUNTIME)
public @interface FileFs {}
| gpl-2.0 |
sk19871216/Yilife | app/src/main/java/com/jiuan/android/app/yilife/imageloader/MyAdapter.java | 4179 | package com.jiuan.android.app.yilife.imageloader;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import com.jiuan.android.app.yilife.R;
import com.jiuan.android.app.yilife.utils.CommonAdapter;
import com.jiuan.android.app.yilife.utils.ToastOnly;
import com.jiuan.android.app.yilife.utils.ViewHolder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class MyAdapter extends CommonAdapter<String>
{
/**
* 用户选择的图片,存储为图片的完整路径
*/
public static List<String> mSelectedImage = new LinkedList<String>();
public static List<String> mSelectedImage_count = new LinkedList<String>();
public static ArrayList<String> linshilist = new ArrayList<String>();
/**
* 文件夹路径
*/
private String mDirPath;
private TextView tv_select;
public static ArrayList<Drawable> mDrawlist = new ArrayList<Drawable>();
public MyAdapter(Context context, List<String> mDatas, int itemLayoutId,
String dirPath,TextView tv)
{
super(context, mDatas, itemLayoutId);
this.mDirPath = dirPath;
this.tv_select = tv;
tv_select.setText("已选择"+mSelectedImage_count.size()+"/5张");
}
@Override
public void convert(final ViewHolder helper, final String item)
{
//设置no_pic
helper.setImageResource(R.id.id_item_image, R.drawable.pictures_no);
//设置no_selected
helper.setImageResource(R.id.id_item_select,
R.drawable.picture_unselected);
//设置图片
helper.setImageByUrl(R.id.id_item_image, mDirPath + "/" + item);
if (item.equals("")){
helper.getConvertView().setFocusable(false);
}
final ImageView mImageView = helper.getView(R.id.id_item_image);
final ImageView mSelect = helper.getView(R.id.id_item_select);
mImageView.setColorFilter(null);
//设置ImageView的点击事件
mImageView.setOnClickListener(new OnClickListener()
{
//选择,则将图片变暗,反之则反之
@Override
public void onClick(View v)
{
// 已经选择过该图片
if (mSelectedImage.contains(mDirPath + "/" + item)) {
mDrawlist.remove(mImageView.getDrawable());
mSelectedImage.remove(mDirPath + "/" + item);
mSelectedImage_count.remove(mDirPath + "/" + item);
linshilist.remove(mDirPath + "/" + item);
mSelect.setImageResource(R.drawable.picture_unselected);
mImageView.setColorFilter(null);
} else
// 未选择该图片
{
if (mSelectedImage_count.size() < 5) {
mDrawlist.add(mImageView.getDrawable());
mSelectedImage.add(mDirPath + "/" + item);
mSelectedImage_count.add(mDirPath + "/" + item);
linshilist.add(mDirPath + "/" + item);
mSelect.setImageResource(R.drawable.pictures_selected);
mImageView.setColorFilter(Color.parseColor("#77000000"));
} else {
// if (mSelectedImage_count.size()==5){
ToastOnly toastOnly = new ToastOnly(mContext);
toastOnly.toastShowShort("最多选择5张");
// Toast.makeText(mContext,"最多选择5张",Toast.LENGTH_SHORT).show();
}
}
// tv_select = helper.getView(R.id.tv_showimage_select);
tv_select.setText("已选择" + mSelectedImage_count.size() + "/5张");
}
});
/**
* 已经选择过的图片,显示出选择过的效果
*/
if (mSelectedImage.contains(mDirPath + "/" + item))
{
mSelect.setImageResource(R.drawable.pictures_selected);
mImageView.setColorFilter(Color.parseColor("#77000000"));
}
}
}
| gpl-2.0 |
FishFilletsNG/fillets-data | script/propulsion/demo_dialogs_sv.lua | 998 |
dialogId("dlg-x-poster1", "font_poster", "Squirrel - this is a notion that will be effective today widely talked about in the next few years in connection with interspace propulsion. This is also possible reason of UFO visits of the Earth.")
dialogStr("Ekorrar - det här är ett meddelande som kommer att bli mycket omtalat de närmaste åren i samband med intergalaktisk drivkraft. Det är också den troligaste orsaken till att UFO besöker jorden.")
dialogId("dlg-x-poster2", "font_poster", "Yes, a few cases of squirrel kidnaps were reported in past 5 years, especially from Arizona, Utah and Southern Moravia, but no one really took them seriously. Now we know the whole appalling truth. Technical description is included.")
dialogStr("Ja, några få fall av ekorrkidnappning har rapporterats under de senaste fem åren, speciellt från Arizona, Utha och södra Moravien, men ingen tog dem på allvar. Vi vet nu den hela intressanta sanningen. Tekniska specifikationer är inkluderade.")
| gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest10174.java | 2308 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark 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.
*
* The Benchmark 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
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest10174")
public class BenchmarkTest10174 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = request.getParameter("foo");
String bar = new Test().doSomething(param);
try {
float rand = java.security.SecureRandom.getInstance("SHA1PRNG").nextFloat();
} catch (java.security.NoSuchAlgorithmException e) {
System.out.println("Problem executing SecureRandom.nextFloat() - TestCase");
throw new ServletException(e);
}
response.getWriter().println("Weak Randomness Test java.security.SecureRandom.nextFloat() executed");
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
String bar = param;
if (param.length() > 1) {
bar = param.substring(0,param.length()-1);
}
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| gpl-2.0 |
shaun2029/Wifi-Reset | src/uk/co/immutablefix/wifireset/WifiResetActivity.java | 2457 | // Copyright 2013 Shaun Simpson shauns2029@gmail.com
package uk.co.immutablefix.wifireset;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* This class provides a basic demonstration of how to write an Android
* activity. Inside of its window, it places a single view: an EditText that
* displays and edits some internal text.
*/
public class WifiResetActivity extends Activity {
static final private int BACK_ID = Menu.FIRST;
public WifiResetActivity() {
}
/** Called with the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate our UI from its XML layout description.
setContentView(R.layout.wifireset_activity);
// Hook up button presses to the appropriate event handler.
((Button) findViewById(R.id.back)).setOnClickListener(mBackListener);
}
/**
* Called when the activity is about to start interacting with the user.
*/
@Override
protected void onResume() {
super.onResume();
}
/**
* Called when your activity's options menu needs to be created.
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// We are going to create two menus. Note that we assign them
// unique integer IDs, labels from our string resources, and
// given them shortcuts.
menu.add(0, BACK_ID, 0, R.string.back).setShortcut('0', 'b');
return true;
}
/**
* Called right before your activity's option menu is displayed.
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
return true;
}
/**
* Called when a menu item is selected.
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case BACK_ID:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A call-back for when the user presses the back button.
*/
OnClickListener mBackListener = new OnClickListener() {
public void onClick(View v) {
finish();
}
};
}
| gpl-2.0 |
terrychao2013/Aemon | Translation/src/StringItem.java | 3470 | import java.util.ArrayList;
public class StringItem {
private String mStringId;
private String mLocale;
private ArrayList<String> values = new ArrayList<String>();
public StringItem(String id, String locale) {
mStringId = id;
mLocale = locale;
}
public void addValue(String value) {
values.add(value);
}
public String getStringId() {
return mStringId;
}
public String[] getValues() {
String[] ret = new String[values.size()];
ret = values.toArray(ret);
return ret;
}
public String getLocale() {
return mLocale;
}
public boolean hasValueContent() {
boolean ret = false;
for (String s : values) {
if (s != null && s.length() > 0) {
ret = true;
break;
}
}
return ret;
}
public String getXMLString() {
StringBuilder sb = new StringBuilder();
if (values.size() > 1) {
sb.append(" <string-array name=\"");
sb.append(mStringId);
sb.append("\">\n");
for (String value : values) {
sb.append(" <item>");
sb.append(value);
sb.append("</item>\n");
}
sb.append("<string-array>");
} else if (values.size() == 1){
sb.append(" <string name=\"");
sb.append(mStringId);
sb.append("\">");
sb.append(getXmlValueString(values.get(0)));
sb.append("</string>");
}
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof StringItem)) {
return false;
}
StringItem item = (StringItem)obj;
if (mLocale.equals(item.getLocale())) {
if (values.size() == item.getValues().length) {
boolean equal = false;
for (String value : values) {
for (String s : item.getValues()) {
if (value.equals(s)) {
equal = true;
}
}
}
return equal;
}
}
return false;
}
private String getXmlValueString(String originalString) {
String ret = originalString;
ret = correctSymbol(ret);
ret = addQuoteInSpecialString(ret);
return ret;
}
private String addQuoteInSpecialString(String originalString) {
String ret = originalString;
if (originalString != null && originalString.contains("'")) {
if (!originalString.contains("\\'")) {
ret = ret.replace("'", "\\'");
}
if (!originalString.startsWith("\"")) {
ret = "\"" + ret + "\"";
}
}
return ret;
}
public static String correctSymbol(String original) {
String ret = correctAnd(original);
ret = correctPercentage(ret);
return ret;
}
private static String correctAnd(String original) {
String ret = original;
if (original != null
&& original.contains("&")
&& !original.contains("&")
&& !original.contains("<")
&& !original.contains(">")
&& !original.contains("&#")/*for color string*/) {
ret = original.replace("&", "&");
}
return ret;
}
private static String[][] PERCENT_CORRECTION_LIST = {
{"%1$ s", "%1$s"},
{"%2$ s", "%2$s"},
{"%1$ d", "%1$d"},
{"%2$ d", "%2$d"},
{"% s", "%s"},
{"% S", "%S"},
{"%S", "%s"},
{"%1$ ", "%1$s "},
{"%1$!", "%1$s!"},
{"\"curve_uninstall_msg_inte\">% ", "\"curve_uninstall_msg_inte\">%s "},
};
private static String correctPercentage(String original) {
String ret = original;
if (ret.contains("%")) {
for (String[] corrections : PERCENT_CORRECTION_LIST) {
String error = corrections[0];
if (ret.contains(error)) {
ret = ret.replace(error, corrections[1]);
}
}
}
return ret;
}
} | gpl-2.0 |
sergeev/hgroundcore | src/scripts/scripts/zone/zulaman/boss_janalai.cpp | 21315 | /* Copyright (C) 2006 - 2008 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
*(at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* ScriptData
SDName: Boss_Janalai
SD%Complete: 100
SDComment:
SDCategory: Zul'Aman
EndScriptData */
#include "precompiled.h"
#include "def_zulaman.h"
#include "GridNotifiers.h"
#define SAY_AGGRO -1568000
#define SAY_FIRE_BOMBS -1568001
#define SAY_SUMMON_HATCHER -1568002
#define SAY_ALL_EGGS -1568003
#define SAY_BERSERK -1568004
#define SAY_SLAY_1 -1568005
#define SAY_SLAY_2 -1568006
#define SAY_DEATH -1568007
#define SAY_EVENT_STRANGERS -1568008 // aka INTRO1
#define SAY_EVENT_FRIENDS -1568009 // aka INTRO2
// Jan'alai
// --Spell
#define SPELL_FLAME_BREATH 43140
#define SPELL_FIRE_WALL 43113
#define SPELL_ENRAGE 44779
#define SPELL_SUMMON_PLAYERS 43097
#define SPELL_TELE_TO_CENTER 43098 // coord
#define SPELL_HATCH_ALL 43144
#define SPELL_BERSERK 45078
// -- Fire Bob Spells
#define SPELL_FIRE_BOMB_CHANNEL 42621 // last forever
#define SPELL_FIRE_BOMB_THROW 42628 // throw visual
#define SPELL_FIRE_BOMB_DUMMY 42629 // bomb visual
#define SPELL_FIRE_BOMB_DAMAGE 42630
// --Summons
#define MOB_AMANI_HATCHER 23818
#define MOB_HATCHLING 23598 // 42493
#define MOB_EGG 23817
#define MOB_FIRE_BOMB 23920
// -- Hatcher Spells
#define SPELL_HATCH_EGG 43734 // 42471
// -- Hatchling Spells
#define SPELL_FLAMEBUFFET 43299
const int area_dx = 44;
const int area_dy = 51;
float JanalainPos[1][3] =
{
{-33.93, 1149.27, 19}
};
float FireWallCoords[4][4] =
{
{-10.13, 1149.27, 19, 3.1415},
{-33.93, 1123.90, 19, 0.5*3.1415},
{-54.80, 1150.08, 19, 0},
{-33.93, 1175.68, 19, 1.5*3.1415}
};
float hatcherway[2][5][3] =
{
{
{-87.46,1170.09,6},
{-74.41,1154.75,6},
{-52.74,1153.32,19},
{-33.37,1172.46,19},
{-33.09,1203.87,19}
},
{
{-86.57,1132.85,6},
{-73.94,1146.00,6},
{-52.29,1146.51,19},
{-33.57,1125.72,19},
{-34.29,1095.22,19}
}
};
struct boss_janalaiAI : public ScriptedAI
{
boss_janalaiAI(Creature *c) : ScriptedAI(c)
{
pInstance =(c->GetInstanceData());
SpellEntry *TempSpell = (SpellEntry*)GetSpellStore()->LookupEntry(SPELL_HATCH_EGG);
if(TempSpell && TempSpell->EffectImplicitTargetA[0] != 1)
{
TempSpell->EffectImplicitTargetA[0] = 1;
TempSpell->EffectImplicitTargetB[0] = 0;
}
wLoc.coord_x = -33.93;
wLoc.coord_y = 1149.27;
wLoc.coord_z = 19;
wLoc.mapid = c->GetMapId();
}
ScriptedInstance *pInstance;
WorldLocation wLoc;
uint32 FireBreathTimer;
uint32 BombTimer;
uint32 BombSequenceTimer;
uint32 BombCount;
uint32 HatcherTimer;
uint32 EnrageTimer;
uint32 ResetTimer;
bool noeggs;
bool enraged;
bool isBombing;
bool isFlameBreathing;
uint64 FireBombGUIDs[40];
uint32 checkTimer;
bool Intro;
void Reset()
{
if(pInstance && pInstance->GetData(DATA_JANALAIEVENT) != DONE)
pInstance->SetData(DATA_JANALAIEVENT, NOT_STARTED);
FireBreathTimer = 8000;
BombTimer = 30000;
BombSequenceTimer = 1000;
BombCount = 0;
HatcherTimer = 10000;
EnrageTimer = 300000;
ResetTimer = 5000;
noeggs = false;
isBombing =false;
enraged = false;
isFlameBreathing = false;
for(uint8 i = 0; i < 40; i++)
FireBombGUIDs[i] = 0;
HatchAllEggs(1);
checkTimer = 3000;
Intro = false;
}
void MoveInLineOfSight(Unit *who)
{
if(!Intro && me->IsHostileTo(who) && who->IsWithinDist(me, 20, false))
{
Intro = true;
DoScriptText(RAND(SAY_EVENT_FRIENDS, SAY_EVENT_STRANGERS), m_creature);
}
CreatureAI::MoveInLineOfSight(who);
}
void JustDied(Unit* Killer)
{
DoScriptText(SAY_DEATH, m_creature);
if(pInstance)
pInstance->SetData(DATA_JANALAIEVENT, DONE);
}
void KilledUnit(Unit* victim)
{
DoScriptText(RAND(SAY_SLAY_1, SAY_SLAY_2), m_creature);
}
void EnterCombat(Unit *who)
{
if(pInstance)
pInstance->SetData(DATA_JANALAIEVENT, IN_PROGRESS);
DoScriptText(SAY_AGGRO, m_creature);
// DoZoneInCombat();
}
void DamageDeal(Unit* target, uint32 &damage)
{
if(isFlameBreathing)
{
if(!m_creature->HasInArc(M_PI/6, target))
damage = 0;
}
}
void FireWall()
{
uint8 WallNum;
Creature* wall = NULL;
for(uint8 i = 0; i < 4; i++)
{
if(i == 0 || i == 2)
WallNum = 3;
else
WallNum = 2;
for(uint8 j = 0; j < WallNum; j++)
{
if(WallNum == 3)
wall = m_creature->SummonCreature(MOB_FIRE_BOMB, FireWallCoords[i][0],FireWallCoords[i][1]+5*(j-1),FireWallCoords[i][2],FireWallCoords[i][3],TEMPSUMMON_TIMED_DESPAWN,15000);
else
wall = m_creature->SummonCreature(MOB_FIRE_BOMB, FireWallCoords[i][0]-2+4*j,FireWallCoords[i][1],FireWallCoords[i][2],FireWallCoords[i][3],TEMPSUMMON_TIMED_DESPAWN,15000);
if(wall) wall->CastSpell(wall, SPELL_FIRE_WALL, true);
}
}
}
void SpawnBombs()
{
float dx, dy;
for( int i(0); i < 40; i++)
{
dx =(rand()%(area_dx))-(area_dx/2);
dy =(rand()%(area_dy))-(area_dy/2);
Creature* bomb = DoSpawnCreature(MOB_FIRE_BOMB, dx, dy, 0, 0, TEMPSUMMON_TIMED_DESPAWN, 15000);
if(bomb) FireBombGUIDs[i] = bomb->GetGUID();
}
BombCount = 0;
}
bool HatchAllEggs(uint32 action) //1: reset, 2: isHatching all
{
std::list<Creature*> templist;
float x, y, z;
m_creature->GetPosition(x, y, z);
{
Hellground::AllCreaturesOfEntryInRange check(m_creature, MOB_EGG, 100);
Hellground::ObjectListSearcher<Creature, Hellground::AllCreaturesOfEntryInRange> searcher(templist, check);
Cell::VisitGridObjects(me, searcher, 100);
}
//error_log("Eggs %d at middle", templist.size());
if(!templist.size())
return false;
for(std::list<Creature*>::iterator i = templist.begin(); i != templist.end(); ++i)
{
if(action == 1)
(*i)->SetDisplayId(10056);
else if(action == 2 &&(*i)->GetDisplayId() != 11686)
(*i)->CastSpell(*i, SPELL_HATCH_EGG, false);
}
return true;
}
void Boom()
{
std::list<Creature*> templist;
float x, y, z;
m_creature->GetPosition(x, y, z);
{
Hellground::AllCreaturesOfEntryInRange check(m_creature, MOB_FIRE_BOMB, 100);
Hellground::ObjectListSearcher<Creature, Hellground::AllCreaturesOfEntryInRange> searcher(templist, check);
Cell::VisitGridObjects(me, searcher, me->GetMap()->GetVisibilityDistance());
}
for(std::list<Creature*>::iterator i = templist.begin(); i != templist.end(); ++i)
{
(*i)->CastSpell(*i, SPELL_FIRE_BOMB_DAMAGE, true);
(*i)->RemoveAllAuras();
}
}
void HandleBombSequence()
{
if(BombCount < 40)
{
if(Unit *FireBomb = Unit::GetUnit((*m_creature), FireBombGUIDs[BombCount]))
{
FireBomb->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
DoCast(FireBomb, SPELL_FIRE_BOMB_THROW, true);
FireBomb->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
}
BombCount++;
if(BombCount == 40)
{
BombSequenceTimer = 5000;
}else BombSequenceTimer = 100;
}
else
{
Boom();
isBombing = false;
BombTimer = 20000+rand()%20000;
m_creature->RemoveAurasDueToSpell(SPELL_FIRE_BOMB_CHANNEL);
}
}
void UpdateAI(const uint32 diff)
{
if(isFlameBreathing)
{
if(!m_creature->IsNonMeleeSpellCasted(false))
{
isFlameBreathing = false;
}else
{
if(EnrageTimer > diff)
EnrageTimer -= diff;
else
EnrageTimer = 0;
if(HatcherTimer > diff)
HatcherTimer -= diff;
else
HatcherTimer = 0;
return;
}
}
if(isBombing)
{
if(BombSequenceTimer < diff)
{
HandleBombSequence();
}else
BombSequenceTimer -= diff;
if(EnrageTimer > diff)
EnrageTimer -= diff;
else
EnrageTimer = 0;
if(HatcherTimer > diff)
HatcherTimer -= diff;
else
HatcherTimer = 0;
return;
}
if(!UpdateVictim())
return;
if (checkTimer < diff)
{
if (!m_creature->IsWithinDistInMap(&wLoc, 23))
EnterEvadeMode();
else
DoZoneInCombat();
checkTimer = 3000;
}
else
checkTimer -= diff;
//enrage if under 25% hp before 5 min.
if(!enraged && m_creature->GetHealth() * 4 < m_creature->GetMaxHealth())
EnrageTimer = 0;
if(EnrageTimer < diff)
{
if(!enraged)
{
m_creature->CastSpell(m_creature, SPELL_ENRAGE, true);
enraged = true;
EnrageTimer = 300000;
}
else
{
DoScriptText(SAY_BERSERK, m_creature);
m_creature->CastSpell(m_creature, SPELL_BERSERK, true);
EnrageTimer = 300000;
}
}else EnrageTimer -= diff;
if(BombTimer < diff)
{
DoScriptText(SAY_FIRE_BOMBS, m_creature);
m_creature->AttackStop();
m_creature->GetMotionMaster()->Clear();
DoTeleportTo(JanalainPos[0][0],JanalainPos[0][1],JanalainPos[0][2]);
m_creature->StopMoving();
m_creature->CastSpell(m_creature, SPELL_FIRE_BOMB_CHANNEL, false);
//DoTeleportPlayer(m_creature, JanalainPos[0][0], JanalainPos[0][1],JanalainPos[0][2], 0);
//m_creature->CastSpell(m_creature, SPELL_TELE_TO_CENTER, true);
FireWall();
SpawnBombs();
isBombing = true;
BombSequenceTimer = 100;
//Teleport every Player into the middle
Map *map = m_creature->GetMap();
if(!map->IsDungeon()) return;
Map::PlayerList const &PlayerList = map->GetPlayers();
for(Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i)
{
if (Player* i_pl = i->getSource())
if(i_pl->isAlive())
DoTeleportPlayer(i_pl, JanalainPos[0][0]-5+rand()%10, JanalainPos[0][1]-5+rand()%10, JanalainPos[0][2], 0);
}
//m_creature->CastSpell(Temp, SPELL_SUMMON_PLAYERS, true); // core bug, spell does not work if too far
return;
}else BombTimer -= diff;
if(!noeggs)
{
if(100 * m_creature->GetHealth() < 35 * m_creature->GetMaxHealth())
{
DoScriptText(SAY_ALL_EGGS, m_creature);
m_creature->AttackStop();
m_creature->GetMotionMaster()->Clear();
DoTeleportTo(JanalainPos[0][0],JanalainPos[0][1],JanalainPos[0][2]);
m_creature->StopMoving();
m_creature->CastSpell(m_creature, SPELL_HATCH_ALL, false);
HatchAllEggs(2);
noeggs = true;
}
else if(HatcherTimer < diff)
{
if(HatchAllEggs(0))
{
DoScriptText(SAY_SUMMON_HATCHER, m_creature);
m_creature->SummonCreature(MOB_AMANI_HATCHER,hatcherway[0][0][0],hatcherway[0][0][1],hatcherway[0][0][2],0,TEMPSUMMON_CORPSE_TIMED_DESPAWN,10000);
m_creature->SummonCreature(MOB_AMANI_HATCHER,hatcherway[1][0][0],hatcherway[1][0][1],hatcherway[1][0][2],0,TEMPSUMMON_CORPSE_TIMED_DESPAWN,10000);
HatcherTimer = 90000;
}
else
noeggs = true;
}else HatcherTimer -= diff;
}
if(ResetTimer < diff)
{
float x, y, z, o;
m_creature->GetHomePosition(x, y, z, o);
if(m_creature->GetPositionZ() <= z-7)
{
EnterEvadeMode();
return;
}
ResetTimer = 5000;
}else ResetTimer -= diff;
DoMeleeAttackIfReady();
if(FireBreathTimer < diff)
{
if(Unit* target = SelectUnit(SELECT_TARGET_RANDOM,0, GetSpellMaxRange(SPELL_FLAME_BREATH), true))
{
m_creature->AttackStop();
m_creature->GetMotionMaster()->Clear();
m_creature->CastSpell(target, SPELL_FLAME_BREATH, false);
m_creature->StopMoving();
isFlameBreathing = true;
}
FireBreathTimer = 8000;
}else FireBreathTimer -= diff;
}
};
CreatureAI* GetAI_boss_janalaiAI(Creature *_Creature)
{
return new boss_janalaiAI(_Creature);
}
struct mob_janalai_firebombAI : public ScriptedAI
{
mob_janalai_firebombAI(Creature *c) : ScriptedAI(c){}
void Reset() {}
void SpellHit(Unit *caster, const SpellEntry *spell)
{
if(spell->Id == SPELL_FIRE_BOMB_THROW)
m_creature->CastSpell(m_creature, SPELL_FIRE_BOMB_DUMMY, true);
}
void EnterCombat(Unit* who) {}
void AttackStart(Unit* who) {}
void MoveInLineOfSight(Unit* who) {}
void UpdateAI(const uint32 diff) {}
};
CreatureAI* GetAI_mob_janalai_firebombAI(Creature *_Creature)
{
return new mob_janalai_firebombAI(_Creature);
}
struct mob_amanishi_hatcherAI : public ScriptedAI
{
mob_amanishi_hatcherAI(Creature *c) : ScriptedAI(c)
{
pInstance =(c->GetInstanceData());
}
ScriptedInstance *pInstance;
uint32 waypoint;
uint32 HatchNum;
uint32 WaitTimer;
bool side;
bool hasChangedSide;
bool isHatching;
void Reset()
{
side =(m_creature->GetPositionY() < 1150);
waypoint = 0;
isHatching = false;
hasChangedSide = false;
WaitTimer = 1;
HatchNum = 0;
}
bool HatchEggs(uint32 num)
{
std::list<Creature*> templist;
float x, y, z;
m_creature->GetPosition(x, y, z);
{
Hellground::AllCreaturesOfEntryInRange check(m_creature, 23817, 50);
Hellground::ObjectListSearcher<Creature, Hellground::AllCreaturesOfEntryInRange> searcher(templist, check);
Cell::VisitGridObjects(me, searcher, 50);
}
//error_log("Eggs %d at %d", templist.size(), side);
for(std::list<Creature*>::iterator i = templist.begin(); i != templist.end() && num > 0; ++i)
{
if((*i)->GetDisplayId() != 11686)
{
(*i)->CastSpell(*i, SPELL_HATCH_EGG, false);
num--;
}
}
if(num)
return false; // no more templist
else
return true;
}
void EnterCombat(Unit* who) {}
void AttackStart(Unit*) {}
void MoveInLineOfSight(Unit*) {}
void MovementInform(uint32, uint32)
{
if(waypoint == 5)
{
isHatching = true;
HatchNum = 1;
WaitTimer = 5000;
}
else
WaitTimer = 1;
}
void UpdateAI(const uint32 diff)
{
if(!pInstance || !(pInstance->GetData(DATA_JANALAIEVENT) == IN_PROGRESS))
{
m_creature->SetVisibility(VISIBILITY_OFF);
m_creature->setDeathState(JUST_DIED);
return;
}
if(!isHatching)
{
if(WaitTimer)
{
m_creature->GetMotionMaster()->Clear();
m_creature->GetMotionMaster()->MovePoint(0,hatcherway[side][waypoint][0],hatcherway[side][waypoint][1],hatcherway[side][waypoint][2]);
waypoint++;
WaitTimer = 0;
}
}
else
{
if(WaitTimer < diff)
{
if(HatchEggs(HatchNum))
{
HatchNum++;
WaitTimer = 10000;
}
else if(!hasChangedSide)
{
side = side ? 0 : 1;
isHatching = false;
waypoint = 3;
WaitTimer = 1;
hasChangedSide = true;
}
else
{
m_creature->SetVisibility(VISIBILITY_OFF);
m_creature->setDeathState(JUST_DIED);
}
}else WaitTimer -= diff;
}
}
};
CreatureAI* GetAI_mob_amanishi_hatcherAI(Creature *_Creature)
{
return new mob_amanishi_hatcherAI(_Creature);
}
struct mob_hatchlingAI : public ScriptedAI
{
mob_hatchlingAI(Creature *c) : ScriptedAI(c)
{
pInstance =(c->GetInstanceData());
}
ScriptedInstance *pInstance;
uint32 BuffetTimer;
void Reset()
{
BuffetTimer = 7000;
if(m_creature->GetPositionY() > 1150)
m_creature->GetMotionMaster()->MovePoint(0, hatcherway[0][3][0]+rand()%4-2,1150+rand()%4-2,hatcherway[0][3][2]);
else
m_creature->GetMotionMaster()->MovePoint(0,hatcherway[1][3][0]+rand()%4-2,1150+rand()%4-2,hatcherway[1][3][2]);
m_creature->SetLevitate(true);
}
void EnterCombat(Unit *who) {/*DoZoneInCombat();*/}
void UpdateAI(const uint32 diff)
{
if(!pInstance || !(pInstance->GetData(DATA_JANALAIEVENT) == IN_PROGRESS))
{
m_creature->SetVisibility(VISIBILITY_OFF);
m_creature->setDeathState(JUST_DIED);
return;
}
if(!UpdateVictim())
return;
if(BuffetTimer < diff)
{
m_creature->CastSpell(m_creature->getVictim(), SPELL_FLAMEBUFFET, false);
BuffetTimer = 10000;
}else BuffetTimer -= diff;
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI_mob_hatchlingAI(Creature *_Creature)
{
return new mob_hatchlingAI(_Creature);
}
struct mob_eggAI : public ScriptedAI
{
mob_eggAI(Creature *c) : ScriptedAI(c){}
void Reset() {}
void EnterCombat(Unit* who) {}
void AttackStart(Unit* who) {}
void MoveInLineOfSight(Unit* who) {}
void UpdateAI(const uint32 diff) {}
void SpellHit(Unit *caster, const SpellEntry *spell)
{
if(spell->Id == SPELL_HATCH_EGG)
{
DoSpawnCreature(MOB_HATCHLING, 0, 0, 0, 0, TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 60000);
m_creature->SetDisplayId(11686);
}
}
};
CreatureAI* GetAI_mob_eggAI(Creature *_Creature)
{
return new mob_eggAI(_Creature);
}
void AddSC_boss_janalai()
{
Script *newscript;
newscript = new Script;
newscript->Name="boss_janalai";
newscript->GetAI = &GetAI_boss_janalaiAI;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name="mob_janalai_firebomb";
newscript->GetAI = &GetAI_mob_janalai_firebombAI;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name="mob_janalai_hatcher";
newscript->GetAI = &GetAI_mob_amanishi_hatcherAI;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name="mob_janalai_hatchling";
newscript->GetAI = &GetAI_mob_hatchlingAI;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name="mob_janalai_egg";
newscript->GetAI = &GetAI_mob_eggAI;
newscript->RegisterSelf();
}
| gpl-2.0 |
minhduc150496/ftunews.com | wp-content/themes/FTUNEWSv3/header.php | 6523 | <?php
/**
* @package WordPress
* @subpackage HTML5_Boilerplate
* @file header.php
*/
?>
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame
Remove this if you use the .htaccess -->
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title><?php wp_title('«', true, 'right'); ?> <?php bloginfo('name'); ?></title>
<meta name="viewport" content="width=device-width">
<!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
<?php versioned_stylesheet($GLOBALS["TEMPLATE_RELATIVE_URL"]."html5-boilerplate/css/normalize.css") ?>
<?php versioned_stylesheet($GLOBALS["TEMPLATE_RELATIVE_URL"]."html5-boilerplate/css/main.css") ?>
<!-- Wordpress Templates require a style.css in theme root directory -->
<?php versioned_stylesheet($GLOBALS["TEMPLATE_RELATIVE_URL"]."style.css") ?>
<!-- All JavaScript at the bottom, except for Modernizr which enables HTML5 elements & feature detects -->
<?php versioned_javascript($GLOBALS["TEMPLATE_RELATIVE_URL"]."html5-boilerplate/js/vendor/modernizr-2.6.1.min.js") ?>
<!-- Wordpress Head Items -->
<link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />
<?php wp_head(); ?>
<link href="<?php echo get_template_directory_uri(); ?>/images/Logo ftunews tron.png" rel="shortcut icon" type="image/x-icon" />
<link href="<?php echo get_template_directory_uri(); ?>/html5-boilerplate/css/bootstrap.min.css" rel="stylesheet">
<link href="<?php echo get_template_directory_uri(); ?>/html5-boilerplate/css/font-awesome.min.css" rel="stylesheet">
<link href='https://fonts.googleapis.com/css?family=Roboto&subset=latin,vietnamese' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Noto+Serif&subset=latin,vietnamese' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro&subset=latin,vietnamese' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Kanit:400,300,300italic,400italic,500,500italic,600,600italic,700,700italic,800,800italic&subset=latin,vietnamese' rel='stylesheet' type='text/css'>
<link href="<?php echo get_template_directory_uri(); ?>/html5-boilerplate/slick/slick.css" rel="stylesheet">
<link href="<?php echo get_template_directory_uri(); ?>/ftunews.css" rel="stylesheet"/>
</head>
<body <?php body_class(); ?>>
<!--[if lt IE 7]>
<p class="chromeframe">You are using an outdated browser. <a href="http://browsehappy.com/">Upgrade your browser today</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to better experience this site.</p>
<![endif]-->
<!-- header -->
<header>
<div class="container">
<div class="float-left display-none-xs" style="margin-top:30px;">
<div class="header-ftunews">
<a href="<?php echo get_site_url(); ?>">FTUNEWS</a>
</div>
<div class="vertical-line"></div>
<div class="trending-container">
<div class="float-left" style="height:20px">
<div class="label-trending">
TRENDING
</div><div class="trending-prev fa fa-angle-left"></div><div class="trending-next fa fa-angle-right"></div>
</div>
<div class="trending-slick">
<?php
// Most view
$args = array(
'posts_per_page' => 5,
'order' => 'DESC',
'orderyby' => 'date'
);
query_posts($args);
while (have_posts()):
the_post();
?>
<div>
<a href="<?php the_permalink() ?>"><?php the_title() ?></a>
</div>
<?php
endwhile;
wp_reset_query();
?>
</div>
</div>
<div class="header-social-box" style="float: right">
<div class="header-follow-us">FOLLOW US ON</div>
<a href="https://www.facebook.com/iloveftunews" class="fa fa-facebook header-social" style="margin-right:15px"></a>
<a href="https://www.youtube.com/user/ftunews" class="fa fa-youtube header-social" ></a>
</div>
<div class="vertical-line" style="float:right"></div>
</div>
<nav class="navbar navbar-default">
<div class="navbar-header" style="position: relative">
<div class="header-ftunews-collapsed">
<a href="<?php echo get_site_url() ?>">FTUNEWS</a>
</div>
<button type="button" class="navbar-toggle collapsed btn-hamburger" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="fa fa-bars"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<?php
$args = array(
'hide_empty' => 0,
'parent' => 0,
'exclude' => '1',
);
$cats = get_categories($args);
foreach ($cats as $cat) {
?>
<li><a href="<?php echo get_site_url(),'/category/',$cat->slug ?>"><?php echo $cat->cat_name ?></a></li>
<?php
}
?>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="javascript:jQuery('#header-search-bar').slideToggle();">search</a></li>
</ul>
</div>
</nav>
</div>
</header>
<div id="header-search-bar" class="header-search-bar">
<form role="search" method="get" action="<?php echo get_site_url(),'/'; ?>">
<input type="text" class="header-search-bar-input" placeholder="Search for article & more" name="s">
</form>
</div>
| gpl-2.0 |
iucn-whp/world-heritage-outlook | portlets/iucn-dbservice-portlet/docroot/WEB-INF/src/com/iucn/whp/dbservice/model/impl/state_lkpBaseImpl.java | 1799 | /**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.iucn.whp.dbservice.model.impl;
import com.iucn.whp.dbservice.model.state_lkp;
import com.iucn.whp.dbservice.service.state_lkpLocalServiceUtil;
import com.liferay.portal.kernel.exception.SystemException;
/**
* The extended model base implementation for the state_lkp service. Represents a row in the "whp_state_lkp" database table, with each column mapped to a property of this class.
*
* <p>
* This class exists only as a container for the default extended model level methods generated by ServiceBuilder. Helper methods and all application logic should be put in {@link state_lkpImpl}.
* </p>
*
* @author alok.sen
* @see state_lkpImpl
* @see com.iucn.whp.dbservice.model.state_lkp
* @generated
*/
public abstract class state_lkpBaseImpl extends state_lkpModelImpl
implements state_lkp {
/*
* NOTE FOR DEVELOPERS:
*
* Never modify or reference this class directly. All methods that expect a state_lkp model instance should use the {@link state_lkp} interface instead.
*/
public void persist() throws SystemException {
if (this.isNew()) {
state_lkpLocalServiceUtil.addstate_lkp(this);
}
else {
state_lkpLocalServiceUtil.updatestate_lkp(this);
}
}
} | gpl-2.0 |
cblichmann/idajava | javasrc/src/de/blichmann/idajava/natives/SWIGTYPE_p_qvectorT__qstringT_char_t_t.java | 808 | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.0
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package de.blichmann.idajava.natives;
public class SWIGTYPE_p_qvectorT__qstringT_char_t_t {
private long swigCPtr;
protected SWIGTYPE_p_qvectorT__qstringT_char_t_t(long cPtr, boolean futureUse) {
swigCPtr = cPtr;
}
protected SWIGTYPE_p_qvectorT__qstringT_char_t_t() {
swigCPtr = 0;
}
protected static long getCPtr(SWIGTYPE_p_qvectorT__qstringT_char_t_t obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
}
| gpl-2.0 |
ewout/moodle-atpusp | mod/attforblock/lib.php | 13009 | <?PHP // $Id: lib.php,v 1.4.2.5 2009/03/11 18:21:08 dlnsk Exp $
/// Library of functions and constants for module attforblock
$attforblock_CONSTANT = 7; /// for example
function attforblock_install() {
$result = true;
$arr = array('P' => 2, 'A' => 0, 'L' => 1, 'E' => 1);
foreach ($arr as $k => $v) {
unset($rec);
$rec->courseid = 0;
$rec->acronym = get_string($k.'acronym', 'attforblock');
$rec->description = get_string($k.'full', 'attforblock');
$rec->grade = $v;
$rec->visible = 1;
$rec->deleted = 0;
$result = $result && insert_record('attendance_statuses', $rec);
}
return $result;
}
function attforblock_add_instance($attforblock) {
/// Given an object containing all the necessary data,
/// (defined by the form in mod.html) this function
/// will create a new instance and return the id number
/// of the new instance.
$attforblock->timemodified = time();
if ($att = get_record('attforblock', 'course', $attforblock->course)) {
$modnum = get_field('modules', 'id', 'name', 'attforblock');
if (!get_record('course_modules', 'course', $attforblock->course, 'module', $modnum)) {
delete_records('attforblock', 'course', $attforblock->course);
$attforblock->id = insert_record('attforblock', $attforblock);
} else {
return false;
}
} else {
$attforblock->id = insert_record('attforblock', $attforblock);
}
//Copy statuses for new instance from defaults
if (!get_records('attendance_statuses', 'courseid', $attforblock->course)) {
$statuses = get_records('attendance_statuses', 'courseid', 0, 'id');
foreach($statuses as $stat) {
$rec = $stat;
$rec->courseid = $attforblock->course;
insert_record('attendance_statuses', $rec);
}
}
// attforblock_grade_item_update($attforblock);
// attforblock_update_grades($attforblock);
return $attforblock->id;
}
function attforblock_update_instance($attforblock) {
/// Given an object containing all the necessary data,
/// (defined by the form in mod.html) this function
/// will update an existing instance with new data.
$attforblock->timemodified = time();
$attforblock->id = $attforblock->instance;
if (! update_record('attforblock', $attforblock)) {
return false;
}
attforblock_grade_item_update($attforblock);
return true;
}
function attforblock_delete_instance($id) {
/// Given an ID of an instance of this module,
/// this function will permanently delete the instance
/// and any data that depends on it.
if (! $attforblock = get_record('attforblock', 'id', $id)) {
return false;
}
$result = delete_records('attforblock', 'id', $id);
attforblock_grade_item_delete($attforblock);
return $result;
}
function attforblock_delete_course($course, $feedback=true){
if ($sess = get_records('attendance_sessions', 'courseid', $course->id, '', 'id')) {
$slist = implode(',', array_keys($sess));
delete_records_select('attendance_log', "sessionid IN ($slist)");
delete_records('attendance_sessions', 'courseid', $course->id);
}
delete_records('attendance_statuses', 'courseid', $course->id);
//Inform about changes performed if feedback is enabled
// if ($feedback) {
// notify(get_string('deletedefaults', 'lesson', $count));
// }
return true;
}
/**
* Called by course/reset.php
* @param $mform form passed by reference
*/
function attforblock_reset_course_form_definition(&$mform) {
$mform->addElement('header', 'attendanceheader', get_string('modulename', 'attforblock'));
$mform->addElement('static', 'description', get_string('description', 'attforblock'),
get_string('resetdescription', 'attforblock'));
$mform->addElement('checkbox', 'reset_attendance_log', get_string('deletelogs','attforblock'));
$mform->addElement('checkbox', 'reset_attendance_sessions', get_string('deletesessions','attforblock'));
$mform->disabledIf('reset_attendance_sessions', 'reset_attendance_log', 'notchecked');
$mform->addElement('checkbox', 'reset_attendance_statuses', get_string('resetstatuses','attforblock'));
$mform->setAdvanced('reset_attendance_statuses');
$mform->disabledIf('reset_attendance_statuses', 'reset_attendance_log', 'notchecked');
}
/**
* Course reset form defaults.
*/
function attforblock_reset_course_form_defaults($course) {
return array('reset_attendance_log'=>0, 'reset_attendance_statuses'=>0, 'reset_attendance_sessions'=>0);
}
function attforblock_reset_userdata($data) {
if (!empty($data->reset_attendance_log)) {
$sess = get_records('attendance_sessions', 'courseid', $data->courseid, '', 'id');
$slist = implode(',', array_keys($sess));
delete_records_select('attendance_log', "sessionid IN ($slist)");
set_field('attendance_sessions', 'lasttaken', 0, 'courseid', $data->courseid);
}
if (!empty($data->reset_attendance_statuses)) {
delete_records('attendance_statuses', 'courseid', $data->courseid);
$statuses = get_records('attendance_statuses', 'courseid', 0, 'id');
foreach($statuses as $stat) {
$rec = $stat;
$rec->courseid = $data->courseid;
insert_record('attendance_statuses', $rec);
}
}
if (!empty($data->reset_attendance_sessions)) {
delete_records('attendance_sessions', 'courseid', $data->courseid);
}
}
function attforblock_user_outline($course, $user, $mod, $attforblock) {
/// Return a small object with summary information about what a
/// user has done with a given particular instance of this module
/// Used for user activity reports.
/// $return->time = the time they did it
/// $return->info = a short text description
require_once('locallib.php');
if (isstudent($course->id, $user->id)) {
if ($sescount = get_attendance($user->id,$course)) {
$strgrade = get_string('grade');
$maxgrade = get_maxgrade($user->id, $course);
$usergrade = get_grade($user->id, $course);
$percent = get_percent($user->id,$course);
$result->info = "$strgrade: $usergrade / $maxgrade ($percent%)";
}
}
return $result;
}
function attforblock_user_complete($course, $user, $mod, $attforblock) {
/// Print a detailed representation of what a user has done with
/// a given particular instance of this module, for user activity reports.
require_once('locallib.php');
if (isstudent($course->id, $user->id)) {
// if (! $cm = get_coursemodule_from_instance("attforblock", $attforblock->id, $course->id)) {
// error("Course Module ID was incorrect");
// }
print_user_attendaces($user, $mod, $course);
}
//return true;
}
function attforblock_print_recent_activity($course, $isteacher, $timestart) {
/// Given a course and a time, this module should find recent activity
/// that has occurred in attforblock activities and print it out.
/// Return true if there was output, or false is there was none.
return false; // True if anything was printed, otherwise false
}
function attforblock_cron () {
/// Function to be run periodically according to the moodle cron
/// This function searches for things that need to be done, such
/// as sending out mail, toggling flags etc ...
return true;
}
/**
* Return grade for given user or all users.
*
* @param int $attforblockid id of attforblock
* @param int $userid optional user id, 0 means all users
* @return array array of grades, false if none
*/
function attforblock_get_user_grades($attforblock, $userid=0) {
global $CFG;
require_once('locallib.php');
if (! $course = get_record('course', 'id', $attforblock->course)) {
error("Course is misconfigured");
}
$result = false;
if ($userid) {
$result = array();
$result[$userid]->userid = $userid;
$result[$userid]->rawgrade = $attforblock->grade * get_percent($userid, $course) / 100;
} else {
if ($students = get_course_students($course->id)) {
$result = array();
foreach ($students as $student) {
$result[$student->id]->userid = $student->id;
$result[$student->id]->rawgrade = $attforblock->grade * get_percent($student->id, $course) / 100;
}
}
}
return $result;
}
/**
* Update grades by firing grade_updated event
*
* @param object $attforblock null means all attforblocks
* @param int $userid specific user only, 0 mean all
*/
function attforblock_update_grades($attforblock=null, $userid=0, $nullifnone=true) {
global $CFG;
if (!function_exists('grade_update')) { //workaround for buggy PHP versions
require_once($CFG->libdir.'/gradelib.php');
}
if ($attforblock != null) {
if ($grades = attforblock_get_user_grades($attforblock, $userid)) {
foreach($grades as $k=>$v) {
if ($v->rawgrade == -1) {
$grades[$k]->rawgrade = null;
}
}
attforblock_grade_item_update($attforblock, $grades);
} else {
attforblock_grade_item_update($attforblock);
}
} else {
$sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
FROM {$CFG->prefix}attforblock a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
WHERE m.name='attforblock' AND m.id=cm.module AND cm.instance=a.id";
if ($rs = get_recordset_sql($sql)) {
while ($attforblock = rs_fetch_next_record($rs)) {
// if ($attforblock->grade != 0) {
attforblock_update_grades($attforblock);
// } else {
// attforblock_grade_item_update($attforblock);
// }
}
rs_close($rs);
}
}
}
/**
* Create grade item for given attforblock
*
* @param object $attforblock object with extra cmidnumber
* @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
* @return int 0 if ok, error code otherwise
*/
function attforblock_grade_item_update($attforblock, $grades=NULL) {
global $CFG;
require_once('locallib.php');
if (!function_exists('grade_update')) { //workaround for buggy PHP versions
require_once($CFG->libdir.'/gradelib.php');
}
if (!isset($attforblock->courseid)) {
$attforblock->courseid = $attforblock->course;
}
if (! $course = get_record('course', 'id', $attforblock->course)) {
error("Course is misconfigured");
}
//$attforblock->grade = get_maxgrade($course);
if(!empty($attforblock->cmidnumber)){
$params = array('itemname'=>$attforblock->name, 'idnumber'=>$attforblock->cmidnumber);
}else{
// MDL-14303
$cm = get_coursemodule_from_instance('attforblock', $attforblock->id);
$params = array('itemname'=>$attforblock->name, 'idnumber'=>$cm->id);
}
if ($attforblock->grade > 0) {
$params['gradetype'] = GRADE_TYPE_VALUE;
$params['grademax'] = $attforblock->grade;
$params['grademin'] = 0;
}
else if ($attforblock->grade < 0) {
$params['gradetype'] = GRADE_TYPE_SCALE;
$params['scaleid'] = -$attforblock->grade;
} else {
$params['gradetype'] = GRADE_TYPE_NONE;
}
if ($grades === 'reset') {
$params['reset'] = true;
$grades = NULL;
}
return grade_update('mod/attforblock', $attforblock->courseid, 'mod', 'attforblock', $attforblock->id, 0, $grades, $params);
}
/**
* Delete grade item for given attforblock
*
* @param object $attforblock object
* @return object attforblock
*/
function attforblock_grade_item_delete($attforblock) {
global $CFG;
require_once($CFG->libdir.'/gradelib.php');
if (!isset($attforblock->courseid)) {
$attforblock->courseid = $attforblock->course;
}
return grade_update('mod/attforblock', $attforblock->courseid, 'mod', 'attforblock', $attforblock->id, 0, NULL, array('deleted'=>1));
}
function attforblock_get_participants($attforblockid) {
//Must return an array of user records (all data) who are participants
//for a given instance of attforblock. Must include every user involved
//in the instance, independient of his role (student, teacher, admin...)
//See other modules as example.
return false;
}
function attforblock_scale_used ($attforblockid, $scaleid) {
//This function returns if a scale is being used by one attforblock
//it it has support for grading and scales. Commented code should be
//modified if necessary. See forum, glossary or journal modules
//as reference.
$return = false;
//$rec = get_record("attforblock","id","$attforblockid","scale","-$scaleid");
//
//if (!empty($rec) && !empty($scaleid)) {
// $return = true;
//}
return $return;
}
//////////////////////////////////////////////////////////////////////////////////////
/// Any other attforblock functions go here. Each of them must have a name that
/// starts with attforblock_
?>
| gpl-2.0 |
SvichkarevAnatoly/stepic-java-web-service | task3/src/main/java/datasets/UserDataSet.java | 1299 | package datasets;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "users")
public class UserDataSet implements Serializable {
private static final long serialVersionUID = -8706689714326132798L;
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "login", unique = true, updatable = false)
private String login;
@Column(name = "pass", unique = false, updatable = false)
private String pass;
//Important to Hibernate!
@SuppressWarnings("UnusedDeclaration")
public UserDataSet() {
}
public UserDataSet(String login, String pass) {
setId(-1);
setLogin(login);
setPass(pass);
}
public long getId() {
return id;
}
public String getPass() {
return pass;
}
public void setId(long id) {
this.id = id;
}
public void setLogin(String login) {
this.login = login;
}
public void setPass(String pass) {
this.pass = pass;
}
@Override
public String toString() {
return "UserDataSet{" +
"id=" + id + ", " +
"login='" + login + "', " +
"pass='" + pass + "'" +
'}';
}
}
| gpl-2.0 |
athiasjerome/XORCISM | SOURCES/XORCISMModel/STAGEDESCRIPTION.cs | 1730 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace XORCISMModel
{
using System;
using System.Collections.Generic;
public partial class STAGEDESCRIPTION
{
public int StageDescriptionID { get; set; }
public int StageID { get; set; }
public int DescriptionID { get; set; }
public Nullable<int> VocabularyID { get; set; }
public Nullable<System.DateTimeOffset> CreatedDate { get; set; }
public Nullable<int> CreationObjectID { get; set; }
public Nullable<System.DateTimeOffset> timestamp { get; set; }
public Nullable<System.DateTimeOffset> ValidFromDate { get; set; }
public Nullable<System.DateTimeOffset> ValidUntilDate { get; set; }
public Nullable<int> ValidityID { get; set; }
public Nullable<int> ConfidenceLevelID { get; set; }
public Nullable<int> ConfidenceReasonID { get; set; }
public virtual CONFIDENCELEVEL CONFIDENCELEVEL { get; set; }
public virtual CONFIDENCEREASON CONFIDENCEREASON { get; set; }
public virtual CREATIONOBJECT CREATIONOBJECT { get; set; }
public virtual DESCRIPTION DESCRIPTION { get; set; }
public virtual STAGE STAGE { get; set; }
public virtual VALIDITY VALIDITY { get; set; }
public virtual VOCABULARY VOCABULARY { get; set; }
}
}
| gpl-2.0 |
huojiecs/game1 | game-server/app/tools/openSdks/tencent/msdkWxPayment.js | 5414 | /**
* Created by kazi on 2014/6/10.
*/
var logger = require('pomelo/node_modules/pomelo-logger').getLogger('tencent-payment', __filename);
var apiWrapper = require('./../common/apiWrapper');
var config = require('./../../config');
var urlencode = require('urlencode');
var request = require('request');
var Q = require('q');
var _ = require('underscore');
var Handler = module.exports;
var makeCookie = function (path) {
return {
session_id: 'hy_gameid',
session_type: 'wc_actoken',
org_loc: urlencode(path),
appip: '127.0.0.1'
};
};
var getAppId = function () {
if (config.vendors.tencent.platId === 0) {
return config.vendors.msdkPayment.offerId
}
return config.vendors.msdkPayment.appid
};
Handler.get_balance_m = function (params) {
var path = '/mpay/get_balance_m';
var requires = {
openid: 'string',
openkey: 'string',
pay_token: 'string',
pf: 'string',
pfkey: 'string',
zoneid: 'number',
appip: 'string'
};
return apiWrapper.request(requires, params, makeCookie(path), function () {
return apiWrapper.makeURL(config.vendors.msdkPayment.hostUrl, path, params,
getAppId(),
config.vendors.msdkPayment.appKey + '&');
});
};
Handler.pre_transfer = function (params) {
var path = '/mpay/pre_transfer';
var requires = {
openid: 'string',
openkey: 'string',
pay_token: 'string',
pf: 'string',
pfkey: 'string',
userip: 'string',
zoneid: 'number',
dstzoneid: 'number',
amt: 'number',
receiver: 'number',
exchange_fee: 'number',
accounttype: 'string',
appremark: 'string'
};
return apiWrapper.request(requires, params, makeCookie(path), function () {
return apiWrapper.makeURL(config.vendors.msdkPayment.hostUrl, path, params,
getAppId(),
config.vendors.msdkPayment.appKey + '&');
});
};
Handler.confirm_transfer = function (params) {
var path = '/mpay/confirm_transfer';
var requires = {
openid: 'string',
openkey: 'string',
pay_token: 'string',
pf: 'string',
pfkey: 'string',
userip: 'string',
zoneid: 'number',
token_id: 'string',
accounttype: 'string',
appremark: 'string'
};
return apiWrapper.request(requires, params, makeCookie(path), function () {
return apiWrapper.makeURL(config.vendors.msdkPayment.hostUrl, path, params,
getAppId(),
config.vendors.msdkPayment.appKey + '&');
});
};
Handler.cancel_transfer = function (params) {
var path = '/mpay/cancel_transfer';
var requires = {
openid: 'string',
openkey: 'string',
pay_token: 'string',
pf: 'string',
pfkey: 'string',
userip: 'string',
zoneid: 'number',
token_id: 'string',
accounttype: 'string',
appremark: 'string'
};
return apiWrapper.request(requires, params, makeCookie(path), function () {
return apiWrapper.makeURL(config.vendors.msdkPayment.hostUrl, path, params,
getAppId(),
config.vendors.msdkPayment.appKey + '&');
});
};
Handler.pay_m = function (params) {
var path = '/mpay/pay_m';
var requires = {
openid: 'string',
openkey: 'string',
pay_token: 'string',
pf: 'string',
pfkey: 'string',
userip: 'string',
zoneid: 'number',
amt: 'number',
accounttype: 'string'
};
return apiWrapper.request(requires, params, makeCookie(path), function () {
return apiWrapper.makeURL(config.vendors.msdkPayment.hostUrl, path, params,
getAppId(),
config.vendors.msdkPayment.appKey + '&');
});
};
Handler.cancel_pay_m = function (params) {
var path = '/mpay/cancel_pay_m';
var requires = {
openid: 'string',
openkey: 'string',
pay_token: 'string',
pf: 'string',
pfkey: 'string',
userip: 'string',
zoneid: 'number',
amt: 'number',
billno: 'string'
};
return apiWrapper.request(requires, params, makeCookie(path), function () {
return apiWrapper.makeURL(config.vendors.msdkPayment.hostUrl, path, params,
getAppId(),
config.vendors.msdkPayment.appKey + '&');
});
};
Handler.present_m = function (params) {
var path = '/mpay/present_m';
var requires = {
openid: 'string',
openkey: 'string',
pay_token: 'string',
pf: 'string',
pfkey: 'string',
userip: 'string',
zoneid: 'number',
discountid: 'number',
giftid: 'number',
presenttimes: 'number'
};
return apiWrapper.request(requires, params, makeCookie(path), function () {
return apiWrapper.makeURL(config.vendors.msdkPayment.hostUrl, path, params,
getAppId(),
config.vendors.msdkPayment.appKey + '&');
});
};
| gpl-2.0 |
jmc-88/tint3 | src/util/pipe_test.cc | 5286 | #include "catch.hpp"
#include <cstring>
#include <string>
#include <utility>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "behavior_control.hh"
#include "unix_features.hh"
#include "util/log.hh"
#include "util/pipe.hh"
TEST_CASE("move constructor") {
util::Pipe p1;
int read_fd = p1.ReadEnd();
int write_fd = p1.WriteEnd();
REQUIRE(p1.IsAlive());
REQUIRE(read_fd != -1);
REQUIRE(write_fd != -1);
FORCE_STD_MOVE(util::Pipe p2{std::move(p1)});
REQUIRE(p2.IsAlive());
REQUIRE(p2.ReadEnd() == read_fd);
REQUIRE(p2.WriteEnd() == write_fd);
REQUIRE_FALSE(p1.IsAlive());
REQUIRE(p1.ReadEnd() == -1);
REQUIRE(p1.WriteEnd() == -1);
}
TEST_CASE("non blocking") {
auto assert_nonblocking = [](int fd) {
int flags = fcntl(fd, F_GETFL);
if (flags == -1) {
FAIL("fcntl(" << fd << ", F_GETFL): " << strerror(errno));
}
if ((flags & O_NONBLOCK) == 0) {
FAIL("file descriptor " << fd << " is blocking");
}
};
util::Pipe p{util::Pipe::Options::kNonBlocking};
INFO("ReadEnd: file descriptor " << p.ReadEnd());
assert_nonblocking(p.ReadEnd());
INFO("WriteEnd: file descriptor " << p.WriteEnd());
assert_nonblocking(p.WriteEnd());
}
constexpr unsigned int kBufferSize = 1024;
constexpr char kPipeName[] = "/tint3_pipe_test_shm";
constexpr char kTempTemplate[] = "/tmp/tint3_pipe_test.XXXXXX";
class SharedMemory {
public:
SharedMemory(const char* shm_name, unsigned int shm_size)
: shm_name_(shm_name), shm_size_(shm_size), shm_fd_(-1), mem_(nullptr) {
#ifdef TINT3_HAVE_SHM_OPEN
shm_unlink(shm_name_.c_str());
shm_fd_ = shm_open(shm_name_.c_str(), O_RDWR | O_CREAT | O_EXCL,
S_IWUSR | S_IRUSR);
if (shm_fd_ == -1) {
FAIL("shm_open(" << shm_name_ << "): " << strerror(errno));
}
#else // TINT3_HAVE_SHM_OPEN
char temp_name[sizeof(kTempTemplate) + 1] = {'\0'};
std::strcpy(temp_name, kTempTemplate);
shm_fd_ = mkstemp(temp_name);
if (shm_fd_ == -1) {
FAIL("mkstemp(): " << strerror(errno));
}
shm_name_.assign(temp_name);
#endif // TINT3_HAVE_SHM_OPEN
if (ftruncate(shm_fd_, shm_size) == -1) {
close(shm_fd_);
#ifdef TINT3_HAVE_SHM_OPEN
shm_unlink(shm_name_.c_str());
#endif // TINT3_HAVE_SHM_OPEN
FAIL("ftruncate(" << shm_fd_ << "): " << strerror(errno));
}
mem_ = mmap(nullptr, shm_size_, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd_,
0);
if (mem_ == MAP_FAILED) {
close(shm_fd_);
#ifdef TINT3_HAVE_SHM_OPEN
shm_unlink(shm_name_.c_str());
#endif // TINT3_HAVE_SHM_OPEN
FAIL("mmap(): " << strerror(errno));
}
std::memset(mem_, 0, shm_size_);
}
~SharedMemory() {
if (mem_ != MAP_FAILED) {
if (munmap(mem_, shm_size_) != 0) {
WARN("munmap(" << mem_ << "): " << strerror(errno));
}
}
if (shm_fd_ != -1) {
if (close(shm_fd_) != 0) {
WARN("close(" << shm_fd_ << "): " << strerror(errno));
}
#ifdef TINT3_HAVE_SHM_OPEN
if (shm_unlink(shm_name_.c_str()) != 0) {
WARN("shm_unlink(" << shm_name_ << "): " << strerror(errno));
}
#else // TINT3_HAVE_SHM_OPEN
if (unlink(shm_name_.c_str()) != 0) {
WARN("unlink(" << shm_name_ << "): " << strerror(errno));
}
#endif // TINT3_HAVE_SHM_OPEN
}
}
int fd() const { return shm_fd_; }
void* addr() const { return mem_; }
private:
std::string shm_name_;
unsigned int shm_size_;
int shm_fd_;
void* mem_;
};
class PipeTestFixture {
public:
PipeTestFixture() : shm_(kPipeName, kBufferSize) {}
int GetFileDescriptor() const { return shm_.fd(); }
unsigned int CountNonZeroBytes() const {
const char* ptr = static_cast<char*>(shm_.addr());
unsigned int written_bytes = 0;
for (; *ptr != '\0'; ++ptr) {
++written_bytes;
}
return written_bytes;
}
protected:
const SharedMemory shm_;
};
namespace test {
class MockSelfPipe : public util::SelfPipe {
public:
explicit MockSelfPipe(int shm_fd) {
pipe_fd_[0] = dup(shm_fd);
if (pipe_fd_[0] == -1) {
FAIL("dup(" << shm_fd << "): " << strerror(errno));
}
pipe_fd_[1] = dup(shm_fd);
if (pipe_fd_[1] == -1) {
close(pipe_fd_[0]);
FAIL("dup(" << shm_fd << "): " << strerror(errno));
}
alive_ = true;
}
~MockSelfPipe() {
// util::~Pipe() closes the file descriptors.
}
};
} // namespace test
TEST_CASE_METHOD(PipeTestFixture, "WriteOneByte", "Writing works.") {
test::MockSelfPipe mock_self_pipe{GetFileDescriptor()};
mock_self_pipe.WriteOneByte();
REQUIRE(CountNonZeroBytes() == 1);
mock_self_pipe.WriteOneByte();
mock_self_pipe.WriteOneByte();
REQUIRE(CountNonZeroBytes() == 3);
}
TEST_CASE_METHOD(PipeTestFixture, "ReadPendingBytes", "Reading works.") {
test::MockSelfPipe mock_self_pipe{GetFileDescriptor()};
// This will read as long as there's something to read -- in our case, it's
// until the end of file, which is determined by the above ftruncate()
// (i.e., kBufferSize bytes).
mock_self_pipe.ReadPendingBytes();
off_t position = lseek(GetFileDescriptor(), 0, SEEK_CUR);
REQUIRE(static_cast<unsigned int>(position) == kBufferSize);
}
| gpl-2.0 |
schlos/GreenAlert | app/Http/Controllers/api/ApiSubscriptionController.php | 9994 | <?php namespace Greenalert\Http\Controllers\api;
use Greenalert\Http\Controllers\Controller;
use Greenalert\Project;
use Greenalert\Subscription;
use Greenalert\User;
use Illuminate\Http\Request;
class ApiSubscriptionController extends Controller {
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
$subscriptions = Subscription::paginate(10);
return response()->json(array(
'error' => false,
'subscriptions' => $subscriptions->toArray(),
'status' => 'OK'),
200
);
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store()
{
// VALIDATORS
// Validate type
$rules = array(
'type' => array('required', 'in:project,map')
);
$messages = array(
'type.required' => 'NO_TYPE'
);
$validator = \Validator::make(\Input::all(), $rules, $messages);
if ($validator->fails()) {
return response()->json(
array(
'error' => true,
'validator' => $validator->messages()
),
500
);
}
// TODO: Validate project_id + email
// Validate email + duplicate
if (\Input::get('type') == 'project') {
$confirm_token = md5(\Input::get('project_id') . \Input::get('email'));
} else {
$confirm_token = md5(\Input::get('bounds') . \Input::get('email'));
}
$data = \Input::all();
$data = array_add($data, 'confirm_token', $confirm_token);
$rules = array(
'email' => array('required', 'email'),
'confirm_token' => 'unique:subscriptions'
);
$messages = array(
'email.required' => 'NO_EMAIL',
'email.email' => 'NOT_EMAIL',
'confirm_token.unique' => 'DUPLICATE'
);
$validator = \Validator::make($data, $rules, $messages);
if ($validator->fails()) {
return response()->json(
array(
'error' => true,
'validator' => $validator->messages()
),
500
);
}
// Validate bounds
if (\Input::get('type') == 'map') {
$bounds = explode(",", \Input::get('bounds'));
if (count($bounds) != 4 || !\Input::has('bounds')) {
return response()->json(array(
'error' => true,
'validator' => 'BOUNDS_ERROR'),
500
);
}
}
// SUBSCRIBE
User::firstOrCreate(array('email' => \Input::get('email')));
$user = User::where('email', \Input::get('email'))->first();
$subscription = new Subscription;
$subscription->user_id = $user->id;
$subscription->confirm_token = $confirm_token;
$subscription->geojson = \Input::get('geojson');
if (\Input::get('type') == 'project') {
$subscription->project_id = \Input::get('project_id');
} elseif (\Input::get('type') == 'map') {
$subscription->sw_lat = $bounds[0];
$subscription->sw_lng = $bounds[1];
$subscription->ne_lat = $bounds[2];
$subscription->ne_lng = $bounds[3];
$subscription->bounds = \Input::get('bounds');
$subscription->center = \Input::get('center');
$subscription->zoom = \Input::get('zoom');
}
$subscription->save();
$user->increment('subscriptions');
return response()->json(array(
'error' => false,
'subscription' => $subscription->toArray(),
'status' => 'OK'
),
200
);
}
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
*/
public function update($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy($id)
{
$subscription = Subscription::withTrashed()->find($id);
if ($subscription->confirm_token != \Input::get('confirm_token')) {
return response()->json(array(
'error' => true,
'message' => 'Sorry, we were not able to unsubscribe you.',
'status' => 'UNSUBSCRIBE_FAILED'
),
405
);
}
if (\Input::get('restore') == 1) {
$subscription->status = 1;
$subscription->save();
$subscription->restore();
} else {
$subscription->status = 2;
$subscription->save();
$subscription->delete();
}
return response()->json(array(
'error' => false,
'subscription' => $subscription->toArray(),
'status' => 'DELETED'
),
200
);
}
/**
* Confirm Subscription
*
* @param string $confirm_token
* @return View
*/
public function confirm($confirm_token)
{
//
$subscription = Subscription::withTrashed()->where('confirm_token', $confirm_token)->firstOrFail();
if ($subscription->status == 0) {
$subscription->status = 1;
$subscription->save();
$msg_confirm = 'Confirmed';
}
$user = User::find($subscription->user_id);
if (\Input::has('fullname')) {
$user->fullname = \Input::get('fullname');
$user->save();
$msg_details = 'Updated';
}
if ($subscription->project_id == 0) {
$map_image_link = 'https://api.tiles.mapbox.com/v4/codeforafrica.ji193j10' .
'/geojson(' . urlencode($subscription->geojson) . ')' .
'/auto/600x250.png?' .
'access_token=pk.eyJ1IjoiY29kZWZvcmFmcmljYSIsImEiOiJVLXZVVUtnIn0.JjVvqHKBGQTNpuDMJtZ8Qg';
$map_link = secure_asset('map/#!/bounds=' . $subscription->bounds);
} else {
$map_image_link = 'https://api.tiles.mapbox.com/v4/codeforafrica.ji193j10/' .
$subscription->geojson . '/600x250.png256?' .
'access_token=pk.eyJ1IjoiY29kZWZvcmFmcmljYSIsImEiOiJVLXZVVUtnIn0.JjVvqHKBGQTNpuDMJtZ8Qg';
$map_link = secure_asset('map/#!/center=' .
$subscription->project->geo_lat . ',' . $subscription->project->geo_lng .
'&zoom=11');
}
$user_email = substr(explode("@", $user->email)[0], 0, 1);
for ($i = 0; $i < strlen(substr(explode("@", $user->email)[0], 1)); $i++) {
$user_email .= 'x';
}
$user_email .= '@' . explode("@", $user->email)[1];
$data = compact(
'msg_confirm', 'msg_details',
'subscription', 'user', 'user_email',
'map_image_link', 'map_link'
);
return view('subscriptions.confirm', $data);
}
public function email()
{
// Get fisrt subscription
$subscription = Subscription::first();
$user = User::find($subscription->user_id);
// Get first project
$project = Project::first();
$project_geo = $project->geo();
if (strlen($project->title) > 80) {
$project->title = substr($project->title, 0, 80) . '...';
}
if (strlen($project->description) > 200) {
$project->description = substr($project->description, 0, 200) . '...';
}
// Check email type
if (preg_match('/alert*/', \Input::get('type'))) {
$view_name = 'emails.alerts.default';
$map_image_link = 'https://api.tiles.mapbox.com/v4/codeforafrica.ji193j10' .
'/pin-l-star+27AE60(' . $project_geo->lng . ',' . $project_geo->lat . ')' .
'/' . $project_geo->lng . ',' . $project_geo->lat . ',11' .
'/600x250.png?' .
'access_token=pk.eyJ1IjoiY29kZWZvcmFmcmljYSIsImEiOiJVLXZVVUtnIn0.JjVvqHKBGQTNpuDMJtZ8Qg';
if (\Input::get('type') == 'alert_status') {
$view_name = 'emails.alerts.status';
}
$project_title = $project->title;
$project_id = $project->id;
} else {
$view_name = 'emails.subscription.new';
$map_image_link = 'https://api.tiles.mapbox.com/v4/codeforafrica.ji193j10' .
'/geojson(' . urlencode($subscription->geojson) . ')' .
'/auto/600x250.png?' .
'access_token=pk.eyJ1IjoiY29kZWZvcmFmcmljYSIsImEiOiJVLXZVVUtnIn0.JjVvqHKBGQTNpuDMJtZ8Qg';
$project_id = $subscription->project_id;
}
// New Subscription
$confirm_url = secure_asset('subscriptions/' . $subscription->confirm_token);
$data = compact(
'subscription', 'user', 'map_image_link',
'confirm_url', 'project_title', 'project_id'
);
$view = view($view_name, $data);
if (\Input::get('inline', 0) == 1) {
// TODO: Make inline view
// return Inliner::inline($view);
}
return $view;
}
}
| gpl-2.0 |
kaplun/invenio | modules/bibedit/lib/bibeditmulti_webinterface.py | 12829 | ## This file is part of Invenio.
## Copyright (C) 2009, 2010, 2011 CERN.
##
## Invenio 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.
##
## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Invenio Multiple Record Editor web interface."""
__revision__ = "$Id"
__lastupdated__ = """$Date: 2008/08/12 09:26:46 $"""
from invenio.jsonutils import json, json_unicode_to_utf8
from invenio.webinterface_handler import WebInterfaceDirectory, \
wash_urlargd
from invenio.webpage import page
from invenio.messages import gettext_set_language
from invenio import bibeditmulti_engine as multi_edit_engine
from invenio.webuser import page_not_authorized
from invenio.access_control_engine import acc_authorize_action
class _ActionTypes:
"""Define the available action types"""
test_search = "testSearch"
display_detailed_record = "displayDetailedRecord"
preview_results = "previewResults"
display_detailed_result = "displayDetailedResult"
submit_changes = "submitChanges"
def __init__(self):
"""Nothing to init"""
pass
class _FieldActionTypes:
"""Define the available action types"""
add = "0"
delete = "1"
update = "2"
def __init__(self):
"""Nothing to init"""
pass
class _SubfieldActionTypes:
"""Define the available action types"""
add = "0"
delete = "1"
replace_content = "2"
replace_text = "3"
def __init__(self):
"""Nothing to init"""
pass
class WebInterfaceMultiEditPages(WebInterfaceDirectory):
"""Defines the set of /multiedit pages."""
_exports = [""]
_action_types = _ActionTypes()
_field_action_types = _FieldActionTypes()
_subfield_action_types = _SubfieldActionTypes()
_JSON_DATA_KEY = "jsondata"
def index(self, req, form):
""" The function called by default"""
argd = wash_urlargd(form, {
self._JSON_DATA_KEY: (str, ""),
})
# load the right message language
language = argd["ln"]
_ = gettext_set_language(language)
# check user credentials
(auth_code, auth_msg) = acc_authorize_action(req, "runbibeditmulti")
if 0 != auth_code:
return page_not_authorized(req = req,
ln = language,
text = auth_msg)
if argd[self._JSON_DATA_KEY]:
return self._process_json_request(form, req)
body = multi_edit_engine.perform_request_index(language)
title = _("Multi-Record Editor")
metaheaderadd = multi_edit_engine.get_scripts()
metaheaderadd = metaheaderadd + multi_edit_engine.get_css()
return page(title = title,
metaheaderadd = metaheaderadd,
body = body,
req = req,
language = language)
__call__ = index
def _process_json_request(self, form, req):
"""Takes care about the json requests."""
argd = wash_urlargd(form, {
self._JSON_DATA_KEY: (str, ""),
})
# load json data
json_data_string = argd[self._JSON_DATA_KEY]
json_data_unicode = json.loads(json_data_string)
json_data = json_unicode_to_utf8(json_data_unicode)
language = json_data["language"]
search_criteria = json_data["searchCriteria"]
output_tags = json_data["outputTags"]
output_tags = output_tags.split(',')
output_tags = [tag.strip() for tag in output_tags]
action_type = json_data["actionType"]
current_record_id = json_data["currentRecordID"]
commands = json_data["commands"]
output_format = json_data["outputFormat"]
page_to_display = json_data["pageToDisplay"]
collection = json_data["collection"]
compute_modifications = json_data["compute_modifications"]
checked_records = json_data["checked_records"]
json_response = {}
if action_type == self._action_types.test_search:
json_response.update(multi_edit_engine.perform_request_test_search(
search_criteria,
[],
output_format,
page_to_display,
language,
output_tags,
collection,
req=req,
checked_records=checked_records))
json_response['display_info_box'] = 1
json_response['info_html'] = ""
return json.dumps(json_response)
elif action_type == self._action_types.display_detailed_record:
json_response.update(multi_edit_engine.perform_request_detailed_record(
current_record_id,
[],
output_format,
language))
return json.dumps(json_response)
elif action_type == self._action_types.preview_results:
commands_list, upload_mode, tag_list = self._create_commands_list(commands)
json_response = {}
json_response.update(multi_edit_engine.perform_request_test_search(
search_criteria,
commands_list,
output_format,
page_to_display,
language,
output_tags,
collection,
compute_modifications,
upload_mode,
req,
checked_records))
return json.dumps(json_response)
elif action_type == self._action_types.display_detailed_result:
commands_list, upload_mode, tag_list = self._create_commands_list(commands)
json_response.update(multi_edit_engine.perform_request_detailed_record(
current_record_id,
commands_list,
output_format,
language))
return json.dumps(json_response)
elif action_type == self._action_types.submit_changes:
commands_list, upload_mode, tag_list = self._create_commands_list(commands)
json_response.update(multi_edit_engine.perform_request_submit_changes(search_criteria, commands_list, language, upload_mode, tag_list, collection, req, checked_records))
return json.dumps(json_response)
# In case we obtain wrong action type we return empty page.
return " "
def _create_subfield_commands_list(self, subfields):
"""Creates the list of commands for the given subfields.
@param subfields: json structure containing information about
the subfileds. This data is used for creating the commands.
@return: list of subfield commands.
"""
commands_list = []
upload_mode_replace = False
for current_subfield in subfields:
action = current_subfield["action"]
subfield_code = current_subfield["subfieldCode"]
value = current_subfield["value"]
if "additionalValues" in current_subfield:
additional_values = current_subfield["additionalValues"]
else:
additional_values = []
new_value = current_subfield["newValue"]
condition = current_subfield["condition"]
condition_exact_match = False
condition_does_not_exist = False
if int(current_subfield["conditionSubfieldExactMatch"]) == 0:
condition_exact_match = True
if int(current_subfield["conditionSubfieldExactMatch"]) == 2:
condition_does_not_exist = True
condition_subfield = current_subfield["conditionSubfield"]
if action == self._subfield_action_types.add:
subfield_command = multi_edit_engine.AddSubfieldCommand(subfield_code, value, condition=condition, condition_exact_match=condition_exact_match, condition_does_not_exist=condition_does_not_exist, condition_subfield=condition_subfield)
elif action == self._subfield_action_types.delete:
subfield_command = multi_edit_engine.DeleteSubfieldCommand(subfield_code, condition=condition, condition_exact_match=condition_exact_match, condition_does_not_exist=condition_does_not_exist, condition_subfield=condition_subfield)
upload_mode_replace = True
elif action == self._subfield_action_types.replace_content:
subfield_command = multi_edit_engine.ReplaceSubfieldContentCommand(subfield_code, value, condition=condition, condition_exact_match=condition_exact_match, condition_does_not_exist=condition_does_not_exist, condition_subfield=condition_subfield)
elif action == self._subfield_action_types.replace_text:
subfield_command = multi_edit_engine.ReplaceTextInSubfieldCommand(subfield_code, value, new_value, condition=condition, condition_exact_match=condition_exact_match, condition_does_not_exist=condition_does_not_exist, condition_subfield=condition_subfield, additional_values=additional_values)
else:
raise ValueError("Invalid action: %s" % action)
commands_list.append(subfield_command)
return commands_list, upload_mode_replace
def _create_commands_list(self, commands_json_structure):
"""Creates a list of commands recognized by multiedit engine"""
commands_list = []
upload_mode = '-c'
tag_list = ["001"]
for current_field in commands_json_structure:
tag = current_field["tag"]
tag_list.append(tag)
ind1 = current_field["ind1"]
ind2 = current_field["ind2"]
action = current_field["action"]
conditionSubfield = current_field["conditionSubfield"]
condition = current_field["condition"]
condition_exact_match = False
condition_does_not_exist = False
if int(current_field["conditionSubfieldExactMatch"]) == 0:
condition_exact_match = True
if int(current_field["conditionSubfieldExactMatch"]) == 2:
condition_does_not_exist = True
subfields = current_field["subfields"]
subfield_commands, upload_mode_replace = self._create_subfield_commands_list(subfields)
if upload_mode_replace:
upload_mode = '-r'
# create appropriate command depending on the type
if action == self._field_action_types.add:
command = multi_edit_engine.AddFieldCommand(tag, ind1, ind2, subfield_commands)
elif action == self._field_action_types.delete:
command = multi_edit_engine.DeleteFieldCommand(tag, ind1, ind2, subfield_commands, conditionSubfield, condition, condition_exact_match, condition_does_not_exist)
upload_mode = '-r'
elif action == self._field_action_types.update:
command = multi_edit_engine.UpdateFieldCommand(tag, ind1, ind2, subfield_commands)
else:
raise ValueError("Invalid action: %s" % action)
commands_list.append(command)
return commands_list, upload_mode, tag_list
| gpl-2.0 |
holzgeist/Piwigo | language/el_GR/install.lang.php | 8592 | <?php
// +-----------------------------------------------------------------------+
// | Piwigo - a PHP based photo gallery |
// +-----------------------------------------------------------------------+
// | Copyright(C) 2008-2014 Piwigo Team http://piwigo.org |
// | Copyright(C) 2003-2008 PhpWebGallery Team http://phpwebgallery.net |
// | Copyright(C) 2002-2003 Pierrick LE GALL http://le-gall.net/pierrick |
// +-----------------------------------------------------------------------+
// | 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 |
// | |
// | 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. |
// +-----------------------------------------------------------------------+
$lang['database tables names will be prefixed with it (enables you to manage better your tables)'] = "τα ονόματα των πινάκων της βάσης δεδομένων θα πάρουν αυτό το πρόθεμα (σας επιτρέπει να διαχειρίζεστε τους πίνακες σας καλύτερα)";
$lang['enter a login for webmaster'] = "Εισάγετε ένα όνομα χρήστη για τον webmaster";
$lang['webmaster login can\'t contain characters \' or "'] = "Το όνομα χρήστη δεν μπορεί να περιέχει τους χαρακτήρες ' ή \"";
$lang['please enter your password again'] = "Παρακαλώ εισάγετε τον κωδικό πάλι";
$lang['Keep it confidential, it enables you to access administration panel'] = "Κρατήστε το εμπιστευτικό, επιτρέπει να έχετε πρόσβαση σε πίνακα διαχείρισης";
$lang['Password [confirm]'] = "Κωδικός [επιβεβαίωση]";
$lang['verification'] = "Επιβεβαίωση";
$lang['Need help ? Ask your question on <a href="%s">Piwigo message board</a>.'] = "Χρειάζεστε βοήθεια; Ρωτήστε στο <a href=\"%s\">Πίνακα μηνυμάτων του Piwigo</a>.";
$lang['Visitors will be able to contact site administrator with this mail'] = "Οι επισκέπτες θα μπορούν να χρησιμοποιήσουν αυτό το email για να επικοινωνήσουν με τον διαχειριστή του site";
$lang['PHP 5 is required'] = 'Aπαιτείτε PHP 5.2';
$lang['It appears your webhost is currently running PHP %s.'] = "Φαίνετται ότι ο webhost τώρα τρέχει PHP %s.";
$lang['Piwigo may try to switch your configuration to PHP 5 by creating or modifying a .htaccess file.'] = 'Το Piwigo θα προσπαθήσει να αλλάξει την διαμόρφωση της PHP 5.2 δημιουργώντας ή τροποποιώντας ένα .htaccess αρχείο.';
$lang['Note you can change your configuration by yourself and restart Piwigo after that.'] = "Λάβε υπ' όψη ότι μπορείς να αλλάξεις την διαμόρφωση και να επανεκκινήσεις το Piwigo μετά από αυτό.";
$lang['Try to configure PHP 5'] = 'Προσπάθησε να διαμορφώσεις την PHP 5.2';
$lang['Sorry!'] = "Συγγνώμη!";
$lang['Piwigo was not able to configure PHP 5.'] = 'Το Piwigo δεν είναι σε θέση να διαμορφώσει την PHP 5.2';
$lang['You may referer to your hosting provider\'s support and see how you could switch to PHP 5 by yourself.'] = 'Πρέπει να αναφέρετε στην υποστήριξη του παροχέα ςσας για να διαπιστώσετε πως μπορείτε να αλλάξετε σε PHP 5.2 μόνοι σας.';
$lang['Hope to see you back soon.'] = "Ελπίζουμε να σας δούμε πάλι σύντομα.";
$lang['Congratulations, Piwigo installation is completed'] = 'Συγχαρητήρια, η εγκατάσταση του Piwigo ολοκληρώθηκε';
$lang['An alternate solution is to copy the text in the box above and paste it into the file "local/config/database.inc.php" (Warning : database.inc.php must only contain what is in the textarea, no line return or space character)'] = 'Μια εναλλακτική λύση είναι να αντιγράψετε το κείμενο σε στο πλαίσιο παρακάτω και να το επικολλήστε στο αρχείο "local/config/database.inc.php" (Προειδοποίηση : το database.inc.php πρέπει να περιέχει ότι είναι στην περιοχή κειμένου, χωρίς enter ή κενό)';
$lang['Creation of config file local/config/database.inc.php failed.'] = 'Η δημιουργία του αρχείου local/config/database.inc.php απέτυχε.';
$lang['Download the config file'] = 'Κατέβασμα του αρχείου διαμόρωσης';
$lang['You can download the config file and upload it to local/config directory of your installation.'] = 'Μπορείς να κατεβάσεις το αρχείο διαμόρφωσης και να το ανεβάσεις στο local/config κατάλογο της εγκατάστασης σου.';
$lang['Just another Piwigo gallery'] = 'Ακόμα μια γκαλερί Piwigo';
$lang['Welcome to my photo gallery'] = 'Καλώς ήλθατε στη φωτογραφική μου γκαλερί';
$lang['Admin configuration'] = 'Ρυθμίσεις Διαχειριστή της ιστοσελίδας';
$lang['Basic configuration'] = 'Βασικές διαμόρφωση';
$lang['Can\'t connect to server'] = 'Δεν είναι δυνατή η σύνδεση με τον διακομιστή';
$lang['Connection to server succeed, but it was impossible to connect to database'] = 'Σύνδεση με διακομιστή επιτυχής, αλλά η σύνδεση με τη βάση δεδομένων είναι αδύνατη';
$lang['Database configuration'] = 'Διαμόρφωση Βάσης Δεδομένων';
$lang['Database name'] = 'Όνομα Βάσης Δεδομένων';
$lang['Database table prefix'] = 'πρόθεμα πίνακα της βάσης δεδομένων ';
$lang['Default gallery language'] = 'Γλώσσας προεπιλεγμένης γκαλερί';
$lang['Don\'t hesitate to consult our forums for any help : %s'] = 'Μην διστάσετε να συμβουλευτείτε το φόρουμ μας για οποιαδήποτε βοήθεια:%s';
$lang['Host'] = 'διακομιστήw υποδοχής';
$lang['Installation'] = 'Εγκατάσταση';
$lang['It will be shown to the visitors. It is necessary for website administration'] = 'Έτσι Θα δείχνει στους επισκέπτες. Είναι απαραίτητο για την διαχείριση της ιστοσελίδας';
$lang['Start Install'] = 'Ξεκινήστε την εγκατάσταση';
$lang['User'] = 'Χρήστης';
$lang['Welcome to your new installation of Piwigo!'] = 'Καλώς ήρθατε στην νέα σας εγκατάσταση του Piwigo!';
$lang['also given by your host provider'] = 'Επίσης, δίνεται από την εταιρία φιλοξενίας σας';
$lang['user login given by your host provider'] = 'Όνομα χρήστη που έχει λάβει από το φορέα υποδοχής σας';
$lang['user password given by your host provider'] = 'Κωδικός προσβασης χρήστη που έχει λάβει από το φορέα υποδοχής σας';
$lang['localhost or other, supplied by your host provider'] = 'localhost ή άλλο, που σας παρέχεται από τον πάροχο φιλοξενίας σας'; | gpl-2.0 |
kbcmdba/pjs2 | Libs/Models/ApplicationStatusModel.php | 4652 | <?php
/**
* phpjobseeker
*
* Copyright (C) 2009, 2015, 2017 Kevin Benton - kbenton at bentonfam dot org
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
namespace com\kbcmdba\pjs2;
/**
* ApplicationStatus Model
*/
class ApplicationStatusModel extends ModelBase
{
private $_id;
private $_statusValue;
private $_isActive;
private $_sortKey;
private $_style;
private $_summaryCount;
private $_created;
private $_updated;
/**
* class constructor
*/
public function __construct()
{
parent::__construct();
}
/**
* Validate model for insert
*
* @return boolean
*/
public function validateForAdd()
{
return ((Tools::isNullOrEmptyString(Tools::param('id'))) && (! Tools::isNullOrEmptyString(Tools::param('statusValue'))) && (! Tools::isNullOrEmptyString(Tools::param('sortKey'))) && (Tools::isNullOrEmptyString(Tools::param('summaryCount'))));
}
/**
* Validate model for update
*
* @return boolean
*/
public function validateForUpdate()
{
return ((! Tools::isNullOrEmptyString(Tools::param('id'))) && (! Tools::isNullOrEmptyString(Tools::param('statusValue'))) && (! Tools::isNullOrEmptyString(Tools::param('sortKey'))) && (Tools::isNullOrEmptyString(Tools::param('summaryCount'))));
}
public function populateFromForm()
{
$this->setId(Tools::param('id'));
$this->setStatusValue(Tools::param('statusValue'));
$this->setIsActive(Tools::param('isActive'));
$this->setSortKey(Tools::param('sortKey'));
$this->setStyle(Tools::param('style'));
$this->setSummaryCount(Tools::param('summaryCount'));
$this->setCreated(Tools::param('created'));
$this->setUpdated(Tools::param('updated'));
}
/**
*
* @return integer
*/
public function getId()
{
return $this->_id;
}
/**
*
* @param integer $id
*/
public function setId($id)
{
$this->_id = $id;
}
/**
*
* @return string
*/
public function getStatusValue()
{
return $this->_statusValue;
}
/**
*
* @param string $statusValue
*/
public function setStatusValue($statusValue)
{
$this->_statusValue = $statusValue;
}
/**
*
* @return boolean
*/
public function getIsActive()
{
return $this->_isActive;
}
/**
*
* @param boolean $isActive
*/
public function setIsActive($isActive)
{
$this->_isActive = $isActive;
}
/**
*
* @return integer
*/
public function getSortKey()
{
return $this->_sortKey;
}
/**
*
* @param integer $sortKey
*/
public function setSortKey($sortKey)
{
$this->_sortKey = $sortKey;
}
/**
*
* @return string
*/
public function getStyle()
{
return $this->_style;
}
/**
*
* @param string $style
*/
public function setStyle($style)
{
$this->_style = $style;
}
/**
*
* @return int
*/
public function getSummaryCount()
{
return $this->_summaryCount;
}
/**
*
* @param int $summaryCount
*/
public function setSummaryCount($summaryCount)
{
$this->_summaryCount = $summaryCount;
}
/**
*
* @return string
*/
public function getCreated()
{
return $this->_created;
}
/**
*
* @param string $created
*/
public function setCreated($created)
{
$this->_created = $created;
}
/**
*
* @return string
*/
public function getUpdated()
{
return $this->_updated;
}
/**
*
* @param string $updated
*/
public function setUpdated($updated)
{
$this->_updated = $updated;
}
}
| gpl-2.0 |