repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
ShVerni/RoboRuckus
|
src/RoboRuckus/wwwroot/Scripts/monitor.js
|
15980
|
$(function () {
// Set up arrays for card faces and details
var faces = new Array();
faces["right"] = "R";
faces["left"] = "L";
faces["uturn"] = "U";
faces["backup"] = "B";
var detail = new Array();
detail["right"] = "Right";
detail["left"] = "Left";
detail["backup"] = "Backup";
detail["uturn"] = "U-Turn";
detail["forward"] = "Move";
var flags = $("#board").data("flag");
// Loads board background image
$("#board").css("background-image", 'url("/images/boards/' + $("#board").data("board") + '.png")');
// Check if game is started
if ($("#startButton").data("started") === "True") {
$("#startButton").hide();
$("#controlButtons").show();
} else {
$("#startButton").show();
$("#controlButtons").hide();
}
// Start a timer to check the game status every second
var fetcher = new Interval(function () { $.get("/Setup/Status", function (data) { processData(data); }); }, 1000);
fetcher.start();
// Create connection to player hub
const connection = new signalR.HubConnectionBuilder()
.withUrl("/playerHub")
.configureLogging(signalR.LogLevel.Information)
.build();
// Makes sure the monitor is ready for a round if multiple monitors are being used
connection.on("requestdeal", () => {
if (!fetcher.isRunning()) {
$(".ui-droppable").droppable("destroy");
$("#cardsContainer").empty();
// Restart the update interval
fetcher.start();
}
});
// Shows a preview of the upcoming register
connection.on("showRegister", (cards, robots) => {
$("#cardsContainer").empty();
var _cards = $.parseJSON(cards);
var _robots = $.parseJSON(robots);
var i = 1;
$.each(_cards, function () {
var face;
var details;
if (this.direction === "forward") {
face = this.magnitude;
details = detail[this.direction] + " " + this.magnitude;
}
else {
face = faces[this.direction];
details = detail[this.direction];
}
// Append card to card container
$("#cardsContainer").append("<li id='card" + i + "' class='ui-widget-content dealtCard'>\
<div class='cardBody'>\
<p class='order'>" + this.priority + "</p>\
<p class='face'>" + face + "</p>\
<p class='details'>" + details + "</p>\
<img src='/images/cards/bg.png'alt='card'>\
<p class='robot-names'>" + _robots[i - 1] + "</p>\
</div>\
</li>"
);
$("#card" + i).data("cardinfo", this);
i++;
});
// Minimum width of window is 7 slots worth
boxes = $(".dealtCard").length;
// Set the width of the cards to fill the screen in one row
resize();
});
// Shows the current move being executed
connection.on("showMove", (card, robot, register) => {
$("#cardsContainer").empty();
var _card = $.parseJSON(card);
var face;
var details;
if (_card.direction === "forward") {
face = _card.magnitude;
details = detail[_card.direction] + " " + _card.magnitude;
}
else {
face = faces[_card.direction];
details = detail[_card.direction];
}
$("#cardsContainer").append("<li class='ui-widget-content dealtCard'>\
<div class='cardBody'>\
<p class='order'>" + _card.priority + "</p>\
<p class='face'>" + face + "</p>\
<p class='details'>" + details + "</p>\
<img src='/images/cards/bg.png'alt='card'>\
</div>\
</li>\
<li style=\"display: block\" id='player'>Robot moving: " + robot + "<\li>"
);
//Set the width of the cards to fill the screen in one row
var imageWidth = (($(window).width() - 80) / 8);
if (imageWidth < 350) {
var percent = (imageWidth / 350);
var imageHeight = percent * 520;
$(".order").css("font-size", percent * 4 + "em");
$(".face").css("font-size", percent * 11.8 + "em");
$(".details").css("font-size", percent * 2.5 + "em");
$("#cardsContainer img, .slot img").width(imageWidth);
$("#cardsContainer img,.slot img").height(imageHeight);
$("#cardsContainer li, .slot li").css({
"height": "",
"width": ""
});
$("#player").css("font-size", percent * 3 + "em");
$(".slot, #sendcards").width(imageWidth + 2);
$(".slot, #sendcards").height(imageHeight + 28);
$("#cardsContainer").css("min-height", imageHeight + 5);
}
});
// Processes the current game status
function processData(data) {
$("#botStatus").empty();
$(".boardSquare").empty().css("background", "").removeClass("managePlayer").off("click");
var i = 1;
if (flags !== null) {
flags.forEach(function (entry) {
$("#" + entry[0] + "_" + entry[1]).html('<div class="flags"><p>' + i + " ⚐</p></div>").addClass("hasFlag").data("flag", i);
i++;
});
}
// Check if robots need to re-enter game
if (data.entering) {
// Pause the update interval
fetcher.stop();
// Get all the bots that need re-entering
var content = '<div id="botContainer" class="ui-helper-reset">';
$.each(data.players, function () {
if (this.reenter !== 0) {
content += '<div class="bots" data-number="' + this.number.toString() + '" data-orientation="1"><p>' + (this.number + 1).toString() + '↑</p></div>';
content += '<p>Checkpoint: [' + this.last_x + ', ' + this.last_y + ']</p>';
}
});
content += '</div><button id="sendBots">Re-enter Bots</button>';
// Add content to the cardContainer
$("#cardsContainer").html(content);
// Make bots dragable
$(".bots").draggable({
revert: "invalid", // When not dropped, the item will revert back to its initial position
containment: "document",
cursor: "move"
}).attr('unselectable', 'on').on('selectstart', false).click(function () {
orient(this);
});
// Make the bot container dropppable
$("#botContainer").droppable({
accept: ".boardSquare div",
hoverClass: "ui-state-hover",
drop: function (event, ui) {
var parent = $(ui.draggable).parent();
parent.droppable("enable");
if (parent.hasClass("hasFlag"))
{
parent.append('<div class="flags"><p>' + parent.data("flag") + " ⚐</p></div>");
}
$(ui.draggable).detach().css({ top: "auto", left: "auto", margin: "0 0 1em 0" }).appendTo(this);
}
});
// Make board squares droppable for player re-entry
$(".boardSquare").droppable({
accept: "#botContainer div, .boardSquare div",
hoverClass: "ui-state-hover",
drop: function (event, ui) {
$(this).droppable("disable").empty();
var parent = $(ui.draggable).parent();
if (parent.hasClass("boardSquare")) {
parent.droppable("enable");
if (parent.hasClass("hasFlag")) {
parent.append('<div class="flags"><p>' + parent.data("flag") + " ⚐</p></div>");
}
}
$(ui.draggable).detach().css({ top: "", left: "", margin: "0 auto", position: "" }).appendTo(this);
}
});
// Bind function to re-enter bots
$("#sendBots").button().click(sendBots);
} else {
// Display updated bot statuses
$.each(data.players, function () {
$("#botStatus").append("<p>Player number " + (this.number + 1).toString() + " Damage: " + this.damage + " Flags: " + this.flags + " Lives: " + this.lives + "</p>");
var orientation;
switch (this.direction) {
case 0:
orientation = "→";
break;
case 1:
orientation = "↑";
break;
case 2:
orientation = "←";
break;
case 3:
orientation = "↓";
break;
}
$("#" + this.x.toString() + "_" + this.y.toString()).html('<p data-player="' + (this.number + 1).toString() + '">' + (this.number + 1).toString() + orientation + "</p>").css("background", "yellow").addClass("managePlayer");
});
$(".managePlayer").click(function (event) {
event.stopImmediatePropagation();
$('<div id="dialog"></div>').html('<iframe style="border: 0px; " src="/Setup/Manage/' + $(this).find("p").data("player") + '" width="100%" height="100%"></iframe>').dialog({
autoOpen: true,
height: 650,
width: 450,
title: "Manage Player" + $(this).find("p").data("player")
});
});
}
}
// Display a message from the server
connection.on("displayMessage", (message, sound) => {
$("#cardsContainer").html("<h2>" + message + "</h2>");
});
// Start the connection to the player hub
connection.start().catch(err => console.error(err.toString()));
// Sends bot info to server for re-entry
function sendBots() {
if ($('#botContainer > .bots').length === 0) {
var result = "[";
var first = true;
$(".bots").each(function (index) {
if (!first)
{
result += ",";
}
first = false;
var coord = $(this).parent().attr("id");
result += "[" + $(this).data("number") + ", " + coord.substring(0, coord.indexOf("_")) + ", " + coord.substring(coord.indexOf("_") + 1) + ", " + $(this).data("orientation") + "]";
});
result += "]";
$(".ui-droppable").droppable("destroy");
$.post("/Setup/enterPlayers", { players: result });
$("#cardsContainer").empty();
// Restart the update interval
fetcher.start();
}
}
// Re-orients a bot when clicked
function orient(bot) {
if ($(bot).parents('.boardSquare').length > 0) {
var direction = $(bot).data("orientation");
switch (direction) {
case 0:
direction = 3;
break;
case 1:
direction = 0;
break;
case 2:
direction = 1;
break;
case 3:
direction = 2;
break;
}
$(bot).data("orientation", direction);
var orientation;
switch (direction) {
case 0:
orientation = "→";
break;
case 1:
orientation = "↑";
break;
case 2:
orientation = "←";
break;
case 3:
orientation = "↓";
break;
}
$(bot).html("<p>" + ($(bot).data("number") + 1).toString() + orientation + "</p>");
}
}
// Starts the game
$("#startGame").button().click(function (event) {
$.get("/Setup/startGame?status=0", function (data) {
// alert(data);
$("#startButton").hide();
$("#controlButtons").show();
});
});
// Resets the current game
$("#reset").button().click(function (event) {
$.get("/Setup/Reset?resetAll=0", function (data) { alert(data); });
$("#startButton").show();
$("#controlButtons").hide();
});
// Resets the game the very start power on state
$("#resetAll").button().click(function (event) {
$.get("/Setup/Reset?resetAll=1", function (data) {
alert(data);
setTimeout(function () {
window.location.assign("/Setup");
}, 1);
});
});
// Timer button toggle effects
$("#timer").button().click(function () {
if ($('#timer').prop("checked")) {
$.get("/Setup/Timer?timerEnable=true", function (data) {
if (data === "OK") {
$("#timerText").html("Timer Enabled");
} else {
$('#timer').prop("checked", false);
$('#timer').button("refresh");
}
});
} else {
$.get("/Setup/Timer?timerEnable=false", function (data) {
if (data === "OK") {
$("#timerText").html("Timer Disabled");
} else {
$('#timer').prop("checked", true);
$('#timer').button("refresh");
}
});
}
});
$("#timerLabel").hover(function () {
$(this).removeClass("ui-state-hover");
});
if ($('#timer').prop("checked")) {
$("#timerText").html("Timer Enabled");
}
else {
$("#timerText").html("Timer Disabled");
}
function resize() {
var imageWidth = (($(window).width() - 80) / boxes) / 3;
if (imageWidth < 350) {
var percent = imageWidth / 350;
var imageHeight = percent * 520;
$(".order").css("font-size", percent * 4 + "em");
$(".face").css("font-size", percent * 11.8 + "em");
$(".details").css("font-size", percent * 2.5 + "em");
$(".robot-names").css("font-size", percent * 2.5 + "em");
$("#cardsContainer img, .slot img").width(imageWidth);
$("#cardsContainer img, .slot img").height(imageHeight);
$("#cardsContainer li, .slot li").css({
"height": "",
"width": ""
});
$("#cardsContainer").css("min-height", imageHeight + 5);
}
else {
$(".order").css("font-size", "2.15em");
$("#cardsContainer img, .slot img").width(350);
$("#cardsContainer img, .slot img").height(520);
$("#cardsContainer li, .slot li").css({
"height": "",
"width": ""
});
$("#cardsContainer").css("min-height", 525);
}
$("#labelText").css("font-size", 1.35 + (0.3 * (9 - boxes)) + "vw");
}
});
// Creates an interval with an associated running status
function Interval(fn, time) {
var timer = false;
this.start = function () {
if (!this.isRunning())
timer = setInterval(fn, time);
};
this.stop = function () {
clearInterval(timer);
timer = false;
};
this.isRunning = function () {
return timer !== false;
};
}
|
agpl-3.0
|
stephaneperry/Silverpeas-Components
|
kmelia/kmelia-ejb/src/main/java/com/stratelia/webactiv/kmelia/KmeliaException.java
|
2145
|
/**
* Copyright (C) 2000 - 2011 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://repository.silverpeas.com/legal/licensing"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.stratelia.webactiv.kmelia;
import com.stratelia.webactiv.util.exception.SilverpeasException;
public class KmeliaException extends SilverpeasException {
private static final long serialVersionUID = 9074259824141013543L;
/**
* constructors
*/
public KmeliaException(String callingClass, int errorLevel, String message) {
super(callingClass, errorLevel, message);
}
public KmeliaException(String callingClass, int errorLevel, String message,
String extraParams) {
super(callingClass, errorLevel, message, extraParams);
}
public KmeliaException(String callingClass, int errorLevel, String message,
Exception nested) {
super(callingClass, errorLevel, message, nested);
}
public KmeliaException(String callingClass, int errorLevel, String message,
String extraParams, Exception nested) {
super(callingClass, errorLevel, message, extraParams, nested);
}
/**
* getModule
*/
public String getModule() {
return "kmelia";
}
}
|
agpl-3.0
|
peer-node/flex
|
src/base/util_time.cpp
|
2867
|
#include <boost/foreach.hpp>
#include <src/net/netbase.h>
#include "base/util.h"
#include "sync.h"
#include "util_compare.h"
#include "util_log.h"
#include "util_format.h"
#include "ui_interface.h"
using namespace std;
//
// "Never go to sea with two chronometers; take one or three."
// Our three time sources are:
// - System clock
// - Median of other nodes clocks
// - The user (asking the user to fix the system clock if the first two disagree)
//
static int64_t nMockTime = 0; // For unit testing
int64_t nMockTimeMicros = 0;
int64_t GetTime()
{
if (nMockTime) return nMockTime;
return (int64_t) time(NULL);
}
void SetMockTime(int64_t nMockTimeIn)
{
nMockTime = nMockTimeIn;
}
static CCriticalSection cs_nTimeOffset;
static int64_t nTimeOffset = 0;
void SetTimeOffset(int64_t offset)
{
LOCK(cs_nTimeOffset);
nTimeOffset = offset;
}
int64_t GetTimeOffset()
{
LOCK(cs_nTimeOffset);
return nTimeOffset;
}
int64_t GetAdjustedTime()
{
return GetTime() + GetTimeOffset();
}
void AddTimeData(const CNetAddr& ip, int64_t nTime)
{
int64_t nOffsetSample = nTime - GetTime();
LOCK(cs_nTimeOffset);
// Ignore duplicates
static set<CNetAddr> setKnown;
if (!setKnown.insert(ip).second)
return;
// Add data
static CMedianFilter<int64_t> vTimeOffsets(200,0);
vTimeOffsets.input(nOffsetSample);
LogPrintf("Added time data, samples %d, offset %+d (%+d minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
if (vTimeOffsets.size() >= 2)
{
int64_t nMedian = vTimeOffsets.median();
std::vector<int64_t> vSorted = vTimeOffsets.sorted();
// Only let other nodes change our time by so much
if (abs64(nMedian) < 70 * 60)
{
nTimeOffset = nMedian;
}
else
{
nTimeOffset = 0;
static bool fDone;
if (!fDone)
{
// If nobody has a time different than ours but within 5 minutes of ours, give a warning
bool fMatch = false;
BOOST_FOREACH(int64_t nOffset, vSorted)
if (nOffset != 0 && abs64(nOffset) < 5 * 60)
fMatch = true;
if (!fMatch)
{
fDone = true;
string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong Teleport will not work properly.");
strMiscWarning = strMessage;
LogPrintf("*** %s\n", strMessage);
}
}
}
if (fDebug)
{
BOOST_FOREACH(int64_t n, vSorted)
LogPrintf("%+d ", n);
LogPrintf("| ");
}
LogPrintf("nTimeOffset = %+d (%+d minutes)\n", nTimeOffset, nTimeOffset/60);
}
}
|
agpl-3.0
|
tvtsoft/odoo8
|
addons/stock_dropshipping/tests/test_invoicing.py
|
2559
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Author: Leonardo Pistone
# Copyright 2015 Camptocamp SA
from openerp.tests.common import TransactionCase
class TestCreateInvoice(TransactionCase):
def setUp(self):
super(TestCreateInvoice, self).setUp()
self.Wizard = self.env['stock.invoice.onshipping']
self.customer = self.env.ref('base.res_partner_3')
product = self.env.ref('product.product_product_36')
dropship_route = self.env.ref('stock_dropshipping.route_drop_shipping')
# Create Sale Journal
self.env['account.journal'].create({'name': 'Purchase Journal - Test', 'code': 'DSTPJ', 'type': 'purchase', 'company_id': self.env.ref('base.main_company').id})
user_type_id = self.env.ref('account.data_account_type_payable')
account_pay_id = self.env['account.account'].create({'code': 'X1012', 'name': 'Purchase - Test Payable Account', 'user_type_id': user_type_id.id, 'reconcile': True})
user_type_id = self.env.ref('account.data_account_type_expenses')
account_exp_id = self.env['account.account'].create({'code': 'X1013', 'name': 'Purchase - Test Expense Account', 'user_type_id': user_type_id.id, 'reconcile': True})
self.customer.write({'property_account_payable_id': account_pay_id.id})
product.product_tmpl_id.write({'property_account_expense_id': account_exp_id.id})
self.so = self.env['sale.order'].create({
'partner_id': self.customer.id,
})
self.sol = self.env['sale.order.line'].create({
'name': '/',
'order_id': self.so.id,
'product_id': product.id,
'route_id': dropship_route.id,
})
def test_po_on_delivery_creates_correct_invoice(self):
self.so.action_button_confirm()
po = self.so.procurement_group_id.procurement_ids.purchase_id
self.assertTrue(po)
po.invoice_method = 'picking'
po.signal_workflow('purchase_confirm')
picking = po.picking_ids
self.assertEqual(1, len(picking))
picking.action_done()
wizard = self.Wizard.with_context({
'active_id': picking.id,
'active_ids': [picking.id],
}).create({})
invoice_ids = wizard.create_invoice()
invoices = self.env['account.invoice'].browse(invoice_ids)
self.assertEqual(1, len(invoices))
self.assertEqual(invoices.type, 'in_invoice')
self.assertEqual(invoices, po.invoice_ids)
|
agpl-3.0
|
judo520/windcrm
|
custom/application/Ext/Language/es_es.lang.ext.php
|
67152
|
<?php
//WARNING: The contents of this file are auto-generated
/**
* Extensions to SugarCRM
* @package Reschedule for SugarCRM
* @subpackage Products
* @copyright SalesAgility Ltd http://www.salesagility.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
* along with this program; if not, see http://www.gnu.org/licenses
* or write to the Free Software Foundation,Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA
*
* @author Salesagility Ltd <support@salesagility.com>
*/
$app_list_strings['call_reschedule_dom'][''] = '';
$app_list_strings['call_reschedule_dom']['Out of Office'] = 'Fuera de la Oficina';
$app_list_strings['call_reschedule_dom']['In a Meeting'] = 'En una reunion';
$app_strings['LBL_RESCHEDULE_LABEL'] = 'Replanificar';
$app_strings['LBL_RESCHEDULE_TITLE'] = 'Por favor ingrese los datos de la Replanificación';
$app_strings['LBL_RESCHEDULE_DATE'] = 'Fecha:';
$app_strings['LBL_RESCHEDULE_REASON'] = 'Razón:';
$app_strings['LBL_RESCHEDULE_ERROR1'] = 'Por favor seleccione una fecha válida';
$app_strings['LBL_RESCHEDULE_ERROR2'] = 'Por favor seleccione una razón';
$app_strings['LBL_RESCHEDULE_PANEL'] = 'Replanificar';
$app_strings['LBL_RESCHEDULE_HISTORY'] = 'Historial de Intentos de Llamada';
$app_strings['LBL_RESCHEDULE_COUNT'] = 'Intentos de Llamada';
/**
*
* @package Advanced OpenPortal
* @copyright SalesAgility Ltd http://www.salesagility.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
* along with this program; if not, see http://www.gnu.org/licenses
* or write to the Free Software Foundation,Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA
*
* @author Salesagility Ltd <support@salesagility.com>
*/
$app_list_strings['moduleList']['AOP_AOP_Case_Events'] = 'Eventos de Casos';
$app_list_strings['moduleList']['AOP_AOP_Case_Updates'] = 'Actualizaciones de Casos';
$app_list_strings['moduleList']['AOP_Case_Events'] = 'Eventos de Casos';
$app_list_strings['moduleList']['AOP_Case_Updates'] = 'Actualizaciones de Casos';
$app_strings['LBL_AOP_EMAIL_REPLY_DELIMITER'] = '========== Por favor responda por encima de esta linea ==========';
$app_list_strings['case_state_dom'] =
array (
'Open' => 'Abierto',
'Closed' => 'Cerrado',
);
$app_list_strings['case_state_default_key'] = 'Open';
$app_list_strings['case_status_default_key'] = 'Open_New';
$app_list_strings['case_status_dom'] =
array (
'Open_New' => 'Nuevo',
'Open_Assigned' => 'Asignado',
'Closed_Closed' => 'Cerrado',
'Open_Pending Input' => 'Pendiente de Información',
'Closed_Rejected' => 'Rechazado',
'Closed_Duplicate' => 'Duplicado',
);
$app_strings['LBL_MAP'] = 'Mapa';
$app_strings['LBL_MAPS'] = 'Mapas';
$app_strings['LBL_JJWG_MAPS_LNG'] = 'Longitud';
$app_strings['LBL_JJWG_MAPS_LAT'] = 'Latitud';
$app_strings['LBL_JJWG_MAPS_GEOCODE_STATUS'] = 'Geocode Estado';
$app_strings['LBL_JJWG_MAPS_ADDRESS'] = 'Dirección';
$app_strings['LBL_BUG_FIX'] = 'Bug Fix';
$app_list_strings['moduleList']['jjwg_Maps'] = 'Mapas';
$app_list_strings['moduleList']['jjwg_Markers'] = 'Marcadores de Mapa';
$app_list_strings['moduleList']['jjwg_Areas'] = 'Map Ãreas';
$app_list_strings['moduleList']['jjwg_Address_Cache'] = 'Mapa de Caché';
$app_list_strings['map_unit_type_list']['mi'] = 'Miles';
$app_list_strings['map_unit_type_list']['km'] = 'Kilómetros';
// Plural
$app_list_strings['map_module_type_list']['Cases'] = 'Casos';
$app_list_strings['map_module_type_list']['Leads'] = 'Cliente Potencial';
$app_list_strings['map_module_type_list']['Contacts'] = 'Contactos';
$app_list_strings['map_module_type_list']['Accounts'] = 'Cuentas';
$app_list_strings['map_module_type_list']['Opportunities'] = 'Oportunidades';
$app_list_strings['map_module_type_list']['Meetings'] = 'Reuniones';
$app_list_strings['map_module_type_list']['Project'] = 'Proyectos';
$app_list_strings['map_module_type_list']['Prospects'] = 'Público Objetivo';
// Signular
$app_list_strings['map_relate_type_list']['Cases'] = 'Caso';
$app_list_strings['map_relate_type_list']['Leads'] = 'Cliente Potencial';
$app_list_strings['map_relate_type_list']['Contacts'] = 'Contacto';
$app_list_strings['map_relate_type_list']['Accounts'] = 'Cuenta';
$app_list_strings['map_relate_type_list']['Opportunities'] = 'Oportunidad';
$app_list_strings['map_relate_type_list']['Meetings'] = 'Reunión';
$app_list_strings['map_relate_type_list']['Project'] = 'Proyecto';
$app_list_strings['map_relate_type_list']['Prospects'] = 'Público Objetivo';
$app_list_strings['marker_image_list']['accident'] = 'Accidente';
$app_list_strings['marker_image_list']['administration'] = 'Administración';
$app_list_strings['marker_image_list']['agriculture'] = 'Agricultura';
$app_list_strings['marker_image_list']['aircraft_small'] = 'Aviación pequeña';
$app_list_strings['marker_image_list']['airplane_tourism'] = 'Avion Turismo';
$app_list_strings['marker_image_list']['airport'] = 'Aeropueerto';
$app_list_strings['marker_image_list']['amphitheater'] = 'Anfiteatro';
$app_list_strings['marker_image_list']['apartment'] = 'Departamento';
$app_list_strings['marker_image_list']['aquarium'] = 'Acuario';
$app_list_strings['marker_image_list']['arch'] = 'Arch';
$app_list_strings['marker_image_list']['atm'] = 'Atm';
$app_list_strings['marker_image_list']['audio'] = 'Audio';
$app_list_strings['marker_image_list']['bank'] = 'Banco';
$app_list_strings['marker_image_list']['bank_euro'] = 'Banco Euro';
$app_list_strings['marker_image_list']['bank_pound'] = 'Banco Libra';
$app_list_strings['marker_image_list']['bar'] = 'Bar';
$app_list_strings['marker_image_list']['beach'] = 'Playa';
$app_list_strings['marker_image_list']['beautiful'] = 'Belleza';
$app_list_strings['marker_image_list']['bicycle_parking'] = 'Estacionamiento de Bicicletas';
$app_list_strings['marker_image_list']['big_city'] = 'Ciudad Grande';
$app_list_strings['marker_image_list']['bridge'] = 'Puente';
$app_list_strings['marker_image_list']['bridge_modern'] = 'Puente Moderno';
$app_list_strings['marker_image_list']['bus'] = 'Bus';
$app_list_strings['marker_image_list']['cable_car'] = 'Cable carril';
$app_list_strings['marker_image_list']['car'] = 'Automóvil';
$app_list_strings['marker_image_list']['car_rental'] = 'Alquiler de Automóviles';
$app_list_strings['marker_image_list']['carrepair'] = 'Reparación de Automóviles';
$app_list_strings['marker_image_list']['castle'] = 'Castillo';
$app_list_strings['marker_image_list']['cathedral'] = 'Catedral';
$app_list_strings['marker_image_list']['chapel'] = 'Capilla';
$app_list_strings['marker_image_list']['church'] = 'Iglesia';
$app_list_strings['marker_image_list']['city_square'] = 'Area Central';
$app_list_strings['marker_image_list']['cluster'] = 'Clúster';
$app_list_strings['marker_image_list']['cluster_2'] = 'Clúster 2';
$app_list_strings['marker_image_list']['cluster_3'] = 'Clúster 3';
$app_list_strings['marker_image_list']['cluster_4'] = 'Clúster 4';
$app_list_strings['marker_image_list']['cluster_5'] = 'Clúster 5';
$app_list_strings['marker_image_list']['coffee'] = 'Café';
$app_list_strings['marker_image_list']['community_centre'] = 'Centro Comunitario';
$app_list_strings['marker_image_list']['company'] = 'Empresa';
$app_list_strings['marker_image_list']['conference'] = 'Conferencia';
$app_list_strings['marker_image_list']['construction'] = 'Construcción';
$app_list_strings['marker_image_list']['convenience'] = 'Conveniencia';
$app_list_strings['marker_image_list']['court'] = 'Juzgado';
$app_list_strings['marker_image_list']['cruise'] = 'Crucero';
$app_list_strings['marker_image_list']['currency_exchange'] = 'Cambio de Moneda';
$app_list_strings['marker_image_list']['customs'] = 'Aduana';
$app_list_strings['marker_image_list']['cycling'] = 'Ciclismo';
$app_list_strings['marker_image_list']['dam'] = 'Represa';
$app_list_strings['marker_image_list']['days_dim'] = 'DÃas Dim';
$app_list_strings['marker_image_list']['days_dom'] = 'DÃas Dom';
$app_list_strings['marker_image_list']['days_jeu'] = 'DÃas Jeu';
$app_list_strings['marker_image_list']['days_jue'] = 'DÃas Jue';
$app_list_strings['marker_image_list']['days_lun'] = 'DÃas Lun';
$app_list_strings['marker_image_list']['days_mar'] = 'DÃas Mar';
$app_list_strings['marker_image_list']['days_mer'] = 'DÃas Mer';
$app_list_strings['marker_image_list']['days_mie'] = 'DÃas Mie';
$app_list_strings['marker_image_list']['days_qua'] = 'DÃas Qua';
$app_list_strings['marker_image_list']['days_qui'] = 'DÃas Qui';
$app_list_strings['marker_image_list']['days_sab'] = 'DÃas Sab';
$app_list_strings['marker_image_list']['days_sam'] = 'DÃas Sam';
$app_list_strings['marker_image_list']['days_seg'] = 'DÃas Seg';
$app_list_strings['marker_image_list']['days_sex'] = 'DÃas Sex';
$app_list_strings['marker_image_list']['days_ter'] = 'DÃas Ter';
$app_list_strings['marker_image_list']['days_ven'] = 'DÃas Ven';
$app_list_strings['marker_image_list']['days_vie'] = 'DÃas Vie';
$app_list_strings['marker_image_list']['dentist'] = 'Dentista';
$app_list_strings['marker_image_list']['deptartment_store'] = 'Tienda por Departamentos';
$app_list_strings['marker_image_list']['disability'] = 'Discapacidad';
$app_list_strings['marker_image_list']['disabled_parking'] = 'Estacionamiento p/Discapacitados';
$app_list_strings['marker_image_list']['doctor'] = 'Doctor';
$app_list_strings['marker_image_list']['dog_leash'] = 'Correa p/Perros';
$app_list_strings['marker_image_list']['down'] = 'Abajo';
$app_list_strings['marker_image_list']['down_left'] = 'Abajo Izquierda';
$app_list_strings['marker_image_list']['down_right'] = 'Abajo Derecha';
$app_list_strings['marker_image_list']['down_then_left'] = 'Abajo luego a la izquierda';
$app_list_strings['marker_image_list']['down_then_right'] = 'Abajo luego a la derecha';
$app_list_strings['marker_image_list']['drugs'] = 'Drogas';
$app_list_strings['marker_image_list']['elevator'] = 'Elevador';
$app_list_strings['marker_image_list']['embassy'] = 'Embajada';
$app_list_strings['marker_image_list']['expert'] = 'Experto';
$app_list_strings['marker_image_list']['factory'] = 'Fábrica';
$app_list_strings['marker_image_list']['falling_rocks'] = 'Zona de Derrumbes';
$app_list_strings['marker_image_list']['fast_food'] = 'Comida Rápida';
$app_list_strings['marker_image_list']['festival'] = 'Festival';
$app_list_strings['marker_image_list']['fjord'] = 'Fiordo';
$app_list_strings['marker_image_list']['forest'] = 'Bosque';
$app_list_strings['marker_image_list']['fountain'] = 'Fuente';
$app_list_strings['marker_image_list']['friday'] = 'Viernes';
$app_list_strings['marker_image_list']['garden'] = 'JardÃn';
$app_list_strings['marker_image_list']['gas_station'] = 'Bomba de Combustible';
$app_list_strings['marker_image_list']['geyser'] = 'Geyser';
$app_list_strings['marker_image_list']['gifts'] = 'Regalos';
$app_list_strings['marker_image_list']['gourmet'] = 'Gourmet';
$app_list_strings['marker_image_list']['grocery'] = 'Almacén';
$app_list_strings['marker_image_list']['hairsalon'] = 'Estilista';
$app_list_strings['marker_image_list']['helicopter'] = 'Helicóptero';
$app_list_strings['marker_image_list']['highway'] = 'Autopista';
$app_list_strings['marker_image_list']['historical_quarter'] = 'Casco Histórico';
$app_list_strings['marker_image_list']['home'] = 'Hogar';
$app_list_strings['marker_image_list']['hospital'] = 'Hospital';
$app_list_strings['marker_image_list']['hostel'] = 'Hostel';
$app_list_strings['marker_image_list']['hotel'] = 'Hotel';
$app_list_strings['marker_image_list']['hotel_1_star'] = 'Hotel 1 Estrella';
$app_list_strings['marker_image_list']['hotel_2_stars'] = 'Hotel 2 Estrellas';
$app_list_strings['marker_image_list']['hotel_3_stars'] = 'Hotel 3 Estrellas';
$app_list_strings['marker_image_list']['hotel_4_stars'] = 'Hotel 4 Estrellas';
$app_list_strings['marker_image_list']['hotel_5_stars'] = 'Hotel 5 Estrellas';
$app_list_strings['marker_image_list']['info'] = 'Info';
$app_list_strings['marker_image_list']['justice'] = 'Juzgado';
$app_list_strings['marker_image_list']['lake'] = 'Lago';
$app_list_strings['marker_image_list']['laundromat'] = 'LavanderÃa';
$app_list_strings['marker_image_list']['left'] = 'Izquierda';
$app_list_strings['marker_image_list']['left_then_down'] = 'Izquierda Luego Abajo';
$app_list_strings['marker_image_list']['left_then_up'] = 'Izquierda Luego Arriba';
$app_list_strings['marker_image_list']['library'] = 'Biblioteca';
$app_list_strings['marker_image_list']['lighthouse'] = 'Iluminación';
$app_list_strings['marker_image_list']['liquor'] = 'Expendio de Bebidas Alcoholicas';
$app_list_strings['marker_image_list']['lock'] = 'Candado';
$app_list_strings['marker_image_list']['main_road'] = 'Camino Principal';
$app_list_strings['marker_image_list']['massage'] = 'Masajes';
$app_list_strings['marker_image_list']['mobile_phone_tower'] = 'Antena de TelefonÃa Móvil';
$app_list_strings['marker_image_list']['modern_tower'] = 'Torre Moderna';
$app_list_strings['marker_image_list']['monastery'] = 'Monasterio';
$app_list_strings['marker_image_list']['monday'] = 'Lunes';
$app_list_strings['marker_image_list']['monument'] = 'Monumento';
$app_list_strings['marker_image_list']['mosque'] = 'Mezquita';
$app_list_strings['marker_image_list']['motorcycle'] = 'Motocicleta';
$app_list_strings['marker_image_list']['museum'] = 'Museo';
$app_list_strings['marker_image_list']['music_live'] = 'Música en Vivo';
$app_list_strings['marker_image_list']['oil_pump_jack'] = 'Oil Pump Jack';
$app_list_strings['marker_image_list']['pagoda'] = 'Pagoda';
$app_list_strings['marker_image_list']['palace'] = 'Palacio';
$app_list_strings['marker_image_list']['panoramic'] = 'Vista Panorámica';
$app_list_strings['marker_image_list']['park'] = 'Parque';
$app_list_strings['marker_image_list']['park_and_ride'] = 'Parque y Camiata';
$app_list_strings['marker_image_list']['parking'] = 'Estacionamiento';
$app_list_strings['marker_image_list']['photo'] = 'Foto';
$app_list_strings['marker_image_list']['picnic'] = 'Picnic';
$app_list_strings['marker_image_list']['places_unvisited'] = 'Lugares no Visitados';
$app_list_strings['marker_image_list']['places_visited'] = 'Lugares Visitados';
$app_list_strings['marker_image_list']['playground'] = 'Plaza';
$app_list_strings['marker_image_list']['police'] = 'PolicÃa';
$app_list_strings['marker_image_list']['port'] = 'Puerto';
$app_list_strings['marker_image_list']['postal'] = 'Postal';
$app_list_strings['marker_image_list']['power_line_pole'] = 'Poste de LÃnea Eléctrica';
$app_list_strings['marker_image_list']['power_plant'] = 'Planta de EnergÃa';
$app_list_strings['marker_image_list']['power_substation'] = 'Subestación de EnergÃa';
$app_list_strings['marker_image_list']['public_art'] = 'Arte Público';
$app_list_strings['marker_image_list']['rain'] = 'Lluvia';
$app_list_strings['marker_image_list']['real_estate'] = 'Inmobiliaria';
$app_list_strings['marker_image_list']['regroup'] = 'Reagrupamiento';
$app_list_strings['marker_image_list']['resort'] = 'Resort';
$app_list_strings['marker_image_list']['restaurant'] = 'Restaurant';
$app_list_strings['marker_image_list']['restaurant_african'] = 'Restaurant Africana';
$app_list_strings['marker_image_list']['restaurant_barbecue'] = 'Restaurant Barbacoa';
$app_list_strings['marker_image_list']['restaurant_buffet'] = 'Restaurant Buffet';
$app_list_strings['marker_image_list']['restaurant_chinese'] = 'Restaurant Chino';
$app_list_strings['marker_image_list']['restaurant_fish'] = 'Restaurant Pescado';
$app_list_strings['marker_image_list']['restaurant_fish_chips'] = 'Restaurant Chips de Pescado';
$app_list_strings['marker_image_list']['restaurant_gourmet'] = 'Restaurant Gourmet';
$app_list_strings['marker_image_list']['restaurant_greek'] = 'Restaurant Griego';
$app_list_strings['marker_image_list']['restaurant_indian'] = 'Restaurant Hindú';
$app_list_strings['marker_image_list']['restaurant_italian'] = 'Restaurant Italiano';
$app_list_strings['marker_image_list']['restaurant_japanese'] = 'Restaurant Japonés';
$app_list_strings['marker_image_list']['restaurant_kebab'] = 'Restaurant Brochette';
$app_list_strings['marker_image_list']['restaurant_korean'] = 'Restaurant Coreano';
$app_list_strings['marker_image_list']['restaurant_mediterranean'] = 'Restaurant Mediterráneo';
$app_list_strings['marker_image_list']['restaurant_mexican'] = 'Restaurant Mexicano';
$app_list_strings['marker_image_list']['restaurant_romantic'] = 'Restaurant Romántico';
$app_list_strings['marker_image_list']['restaurant_thai'] = 'Restaurant Thai';
$app_list_strings['marker_image_list']['restaurant_turkish'] = 'Restaurant Turco';
$app_list_strings['marker_image_list']['right'] = 'Derecha';
$app_list_strings['marker_image_list']['right_then_down'] = 'Derecha Luego Abajo';
$app_list_strings['marker_image_list']['right_then_up'] = 'Derecha Luego Arriba';
$app_list_strings['marker_image_list']['satursday'] = 'Sábado';
$app_list_strings['marker_image_list']['school'] = 'Escuela';
$app_list_strings['marker_image_list']['shopping_mall'] = 'Mall';
$app_list_strings['marker_image_list']['shore'] = 'Apuntalamiento';
$app_list_strings['marker_image_list']['sight'] = 'Vista';
$app_list_strings['marker_image_list']['small_city'] = 'Pequeña Ciudad';
$app_list_strings['marker_image_list']['snow'] = 'Nieve';
$app_list_strings['marker_image_list']['spaceport'] = 'Puerto Espacial';
$app_list_strings['marker_image_list']['speed_100'] = 'Velocidad 100';
$app_list_strings['marker_image_list']['speed_110'] = 'Velocidad 110';
$app_list_strings['marker_image_list']['speed_120'] = 'Velocidad 120';
$app_list_strings['marker_image_list']['speed_130'] = 'Velocidad 130';
$app_list_strings['marker_image_list']['speed_20'] = 'Velocidad 20';
$app_list_strings['marker_image_list']['speed_30'] = 'Velocidad 30';
$app_list_strings['marker_image_list']['speed_40'] = 'Velocidad 40';
$app_list_strings['marker_image_list']['speed_50'] = 'Velocidad 50';
$app_list_strings['marker_image_list']['speed_60'] = 'Velocidad 60';
$app_list_strings['marker_image_list']['speed_hump'] = 'Velocidad Hump';
$app_list_strings['marker_image_list']['stadium'] = 'Estadio';
$app_list_strings['marker_image_list']['statue'] = 'Estatua';
$app_list_strings['marker_image_list']['steam_train'] = 'Tren a Vapor';
$app_list_strings['marker_image_list']['stop'] = 'Stop';
$app_list_strings['marker_image_list']['stoplight'] = 'Semáforo';
$app_list_strings['marker_image_list']['subway'] = 'Subterráneo';
$app_list_strings['marker_image_list']['sun'] = 'Sol';
$app_list_strings['marker_image_list']['sunday'] = 'Domingo';
$app_list_strings['marker_image_list']['supermarket'] = 'Super Mercado';
$app_list_strings['marker_image_list']['synagogue'] = 'Sinagoga';
$app_list_strings['marker_image_list']['tapas'] = 'Tapas';
$app_list_strings['marker_image_list']['taxi'] = 'Taxi';
$app_list_strings['marker_image_list']['taxiway'] = 'VÃa p/Taxis';
$app_list_strings['marker_image_list']['teahouse'] = 'Casa de Té';
$app_list_strings['marker_image_list']['telephone'] = 'Teléfono';
$app_list_strings['marker_image_list']['temple_hindu'] = 'Templo Hindú';
$app_list_strings['marker_image_list']['terrace'] = 'Terraza';
$app_list_strings['marker_image_list']['text'] = 'Texto';
$app_list_strings['marker_image_list']['theater'] = 'Teatro';
$app_list_strings['marker_image_list']['theme_park'] = 'Parque Temático';
$app_list_strings['marker_image_list']['thursday'] = 'Jueves';
$app_list_strings['marker_image_list']['toilets'] = 'Toilets';
$app_list_strings['marker_image_list']['toll_station'] = 'Peaje';
$app_list_strings['marker_image_list']['tower'] = 'Torre';
$app_list_strings['marker_image_list']['traffic_enforcement_camera'] = 'Control de Velocidad';
$app_list_strings['marker_image_list']['train'] = 'Tren';
$app_list_strings['marker_image_list']['tram'] = 'TranvÃa';
$app_list_strings['marker_image_list']['truck'] = 'Camión';
$app_list_strings['marker_image_list']['tuesday'] = 'Martes';
$app_list_strings['marker_image_list']['tunnel'] = 'Tunel';
$app_list_strings['marker_image_list']['turn_left'] = 'Giro a la Izquierda';
$app_list_strings['marker_image_list']['turn_right'] = 'Giro a la Derecha';
$app_list_strings['marker_image_list']['university'] = 'Universidad';
$app_list_strings['marker_image_list']['up'] = 'Arriba';
$app_list_strings['marker_image_list']['vespa'] = 'Vespa';
$app_list_strings['marker_image_list']['video'] = 'Video';
$app_list_strings['marker_image_list']['villa'] = 'Villa';
$app_list_strings['marker_image_list']['water'] = 'Water';
$app_list_strings['marker_image_list']['waterfall'] = 'Waterfall';
$app_list_strings['marker_image_list']['watermill'] = 'Watermill';
$app_list_strings['marker_image_list']['waterpark'] = 'Waterpark';
$app_list_strings['marker_image_list']['watertower'] = 'Watertower';
$app_list_strings['marker_image_list']['wednesday'] = 'Wednesday';
$app_list_strings['marker_image_list']['wifi'] = 'Wifi';
$app_list_strings['marker_image_list']['wind_turbine'] = 'Wind Turbine';
$app_list_strings['marker_image_list']['windmill'] = 'Windmill';
$app_list_strings['marker_image_list']['winery'] = 'Winery';
$app_list_strings['marker_image_list']['work_office'] = 'Work Office';
$app_list_strings['marker_image_list']['world_heritage_site'] = 'World Heritage Site';
$app_list_strings['marker_image_list']['zoo'] = 'Zoo';
$app_list_strings['marker_image_list']['speed_70'] = 'Velocidad 70';
$app_list_strings['marker_image_list']['speed_80'] = 'Velocidad 80';
$app_list_strings['marker_image_list']['speed_90'] = 'Velocidad 90';
$app_list_strings['marker_image_list']['speed_hump'] = 'Velocidad Hump';
$app_list_strings['marker_image_list']['stadium'] = 'Stadium';
$app_list_strings['marker_image_list']['statue'] = 'Statue';
$app_list_strings['marker_image_list']['steam_train'] = 'Steam Train';
$app_list_strings['marker_image_list']['stop'] = 'Stop';
$app_list_strings['marker_image_list']['stoplight'] = 'Stoplight';
$app_list_strings['marker_image_list']['subway'] = 'Subway';
$app_list_strings['marker_image_list']['sun'] = 'Sun';
$app_list_strings['marker_image_list']['sunday'] = 'Sunday';
$app_list_strings['marker_image_list']['supermarket'] = 'Supermarket';
$app_list_strings['marker_image_list']['synagogue'] = 'Synagogue';
$app_list_strings['marker_image_list']['tapas'] = 'Tapas';
$app_list_strings['marker_image_list']['taxi'] = 'Taxi';
$app_list_strings['marker_image_list']['taxiway'] = 'Taxiway';
$app_list_strings['marker_image_list']['teahouse'] = 'Teahouse';
$app_list_strings['marker_image_list']['telephone'] = 'Telephone';
$app_list_strings['marker_image_list']['temple_hindu'] = 'Temple Hindu';
$app_list_strings['marker_image_list']['terrace'] = 'Terrace';
$app_list_strings['marker_image_list']['text'] = 'Text';
$app_list_strings['marker_image_list']['theater'] = 'Theater';
$app_list_strings['marker_image_list']['theme_park'] = 'Theme Park';
$app_list_strings['marker_image_list']['thursday'] = 'Thursday';
$app_list_strings['marker_image_list']['toilets'] = 'Toilets';
$app_list_strings['marker_image_list']['toll_station'] = 'Toll Station';
$app_list_strings['marker_image_list']['tower'] = 'Tower';
$app_list_strings['marker_image_list']['traffic_enforcement_camera'] = 'Traffic Enforcement Camera';
$app_list_strings['marker_image_list']['train'] = 'Train';
$app_list_strings['marker_image_list']['tram'] = 'Tram';
$app_list_strings['marker_image_list']['truck'] = 'Truck';
$app_list_strings['marker_image_list']['tuesday'] = 'Tuesday';
$app_list_strings['marker_image_list']['tunnel'] = 'Tunnel';
$app_list_strings['marker_image_list']['turn_left'] = 'Turn Left';
$app_list_strings['marker_image_list']['turn_right'] = 'Turn Right';
$app_list_strings['marker_image_list']['university'] = 'University';
$app_list_strings['marker_image_list']['up'] = 'Up';
$app_list_strings['marker_image_list']['up_left'] = 'Arriba Izquierda';
$app_list_strings['marker_image_list']['up_right'] = 'Arriba Derecha';
$app_list_strings['marker_image_list']['up_then_left'] = 'Arriba Luego Izquierda';
$app_list_strings['marker_image_list']['up_then_right'] = 'Arriba Luego Derecha';
$app_list_strings['marker_image_list']['vespa'] = 'Vespa';
$app_list_strings['marker_image_list']['video'] = 'Video';
$app_list_strings['marker_image_list']['villa'] = 'Villa';
$app_list_strings['marker_image_list']['water'] = 'Agua';
$app_list_strings['marker_image_list']['waterfall'] = 'Cascada';
$app_list_strings['marker_image_list']['watermill'] = 'Molino de Agua';
$app_list_strings['marker_image_list']['waterpark'] = 'Parque Acuático';
$app_list_strings['marker_image_list']['watertower'] = 'Torre de Agua';
$app_list_strings['marker_image_list']['wednesday'] = 'Miércoles';
$app_list_strings['marker_image_list']['wifi'] = 'WiFi';
$app_list_strings['marker_image_list']['wind_turbine'] = 'Turbina de Viento';
$app_list_strings['marker_image_list']['windmill'] = 'Molino de Viento';
$app_list_strings['marker_image_list']['winery'] = 'Lagar';
$app_list_strings['marker_image_list']['work_office'] = 'Oficina';
$app_list_strings['marker_image_list']['world_heritage_site'] = 'Patrimonio de la Humanidad';
$app_list_strings['marker_image_list']['zoo'] = 'Zoo';
/**
* Advanced OpenReports, SugarCRM Reporting.
* @package Advanced OpenReports for SugarCRM
* @copyright SalesAgility Ltd http://www.salesagility.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
* along with this program; if not, see http://www.gnu.org/licenses
* or write to the Free Software Foundation,Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA
*
* @author SalesAgility <info@salesagility.com>
*/
$app_list_strings['moduleList']['AOR_Reports'] = 'Reportes';
$app_list_strings['moduleList']['AOR_Conditions'] = 'Condiciones de Reportes';
$app_list_strings['moduleList']['AOR_Charts'] = 'Gráficos de Reportes';
$app_list_strings['moduleList']['AOR_Fields'] = 'Campos de Reportes';
$app_list_strings['aor_operator_list']['Equal_To'] = 'Igual a';
$app_list_strings['aor_operator_list']['Not_Equal_To'] = 'No igual a';
$app_list_strings['aor_operator_list']['Greater_Than'] = 'Mayor que';
$app_list_strings['aor_operator_list']['Less_Than'] = 'Menor que';
$app_list_strings['aor_operator_list']['Greater_Than_or_Equal_To'] = 'Mayor o igual a';
$app_list_strings['aor_operator_list']['Less_Than_or_Equal_To'] = 'Menor o igual a';
$app_list_strings['aor_sql_operator_list']['Equal_To'] = '=';
$app_list_strings['aor_sql_operator_list']['Not_Equal_To'] = '!=';
$app_list_strings['aor_sql_operator_list']['Greater_Than'] = '>';
$app_list_strings['aor_sql_operator_list']['Less_Than'] = '<';
$app_list_strings['aor_sql_operator_list']['Greater_Than_or_Equal_To'] = '>=';
$app_list_strings['aor_sql_operator_list']['Less_Than_or_Equal_To'] = '<=';
$app_list_strings['aor_condition_operator_list']['And'] = 'Y';
$app_list_strings['aor_condition_operator_list']['OR'] = 'O';
$app_list_strings['aor_condition_type_list']['Value'] = 'Valor';
$app_list_strings['aor_condition_type_list']['Field'] = 'Campo';
$app_list_strings['aor_condition_type_list']['Date'] = 'Fecha';
$app_list_strings['aor_condition_type_list']['Multi'] = 'Multiple';
$app_list_strings['aor_date_type_list'][''] = '';
$app_list_strings['aor_date_type_list']['minute'] = 'Minutos';
$app_list_strings['aor_date_type_list']['hour'] = 'Horas';
$app_list_strings['aor_date_type_list']['day'] = 'Dias';
$app_list_strings['aor_date_type_list']['week'] = 'Semanas';
$app_list_strings['aor_date_type_list']['month'] = 'Meses';
$app_list_strings['aor_date_type_list']['business_hours'] = 'Horas Laborales';
$app_list_strings['aor_date_options']['now'] = 'Ahora';
$app_list_strings['aor_date_options']['field'] = 'Este Campo';
$app_list_strings['aor_date_operator']['now'] = '';
$app_list_strings['aor_date_operator']['plus'] = '+';
$app_list_strings['aor_date_operator']['minus'] = '-';
$app_list_strings['aor_sort_operator'][''] = '';
$app_list_strings['aor_sort_operator']['ASC'] = 'Ascendente';
$app_list_strings['aor_sort_operator']['DESC'] = 'Descendente';
$app_list_strings['aor_function_list'][''] = '';
$app_list_strings['aor_function_list']['COUNT'] = 'Cantidad';
$app_list_strings['aor_function_list']['MIN'] = 'Minimo';
$app_list_strings['aor_function_list']['MAX'] = 'Maximo';
$app_list_strings['aor_function_list']['SUM'] = 'Suma';
$app_list_strings['aor_function_list']['AVG'] = 'Promedio';
/**
* Advanced OpenWorkflow, Automating SugarCRM.
* @package Advanced OpenWorkflow for SugarCRM
* @copyright SalesAgility Ltd http://www.salesagility.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
* along with this program; if not, see http://www.gnu.org/licenses
* or write to the Free Software Foundation,Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA
*
* @author SalesAgility <info@salesagility.com>
*/
$app_list_strings['moduleList']['AOW_WorkFlow'] = 'WorkFlow';
$app_list_strings['moduleList']['AOW_Conditions'] = 'Condiciones de WorkFlow';
$app_list_strings['moduleList']['AOW_Processed'] = 'AuditorÃa del Proceso';
$app_list_strings['moduleList']['AOW_Actions'] = 'Acciones del WorkFlow';
$app_list_strings['aow_status_list']['Active'] = 'Activo';
$app_list_strings['aow_status_list']['Inactive'] = 'Inactivo';
$app_list_strings['aow_operator_list']['Equal_To'] = 'Igual a';
$app_list_strings['aow_operator_list']['Not_Equal_To'] = 'No igual a';
$app_list_strings['aow_operator_list']['Greater_Than'] = 'Mayor que';
$app_list_strings['aow_operator_list']['Less_Than'] = 'Menor que';
$app_list_strings['aow_operator_list']['Greater_Than_or_Equal_To'] = 'Mayor que o igual a';
$app_list_strings['aow_operator_list']['Less_Than_or_Equal_To'] = 'Menor que o igual a';
$app_list_strings['aow_sql_operator_list']['Equal_To'] = '=';
$app_list_strings['aow_sql_operator_list']['Not_Equal_To'] = '!=';
$app_list_strings['aow_sql_operator_list']['Greater_Than'] = '>';
$app_list_strings['aow_sql_operator_list']['Less_Than'] = '<';
$app_list_strings['aow_sql_operator_list']['Greater_Than_or_Equal_To'] = '>=';
$app_list_strings['aow_sql_operator_list']['Less_Than_or_Equal_To'] = '<=';
$app_list_strings['aow_process_status_list']['Complete'] = 'Completado';
$app_list_strings['aow_process_status_list']['Running'] = 'Ejecutando';
$app_list_strings['aow_process_status_list']['Pending'] = 'Pendiente';
$app_list_strings['aow_process_status_list']['Failed'] = 'Fallido';
$app_list_strings['aow_condition_operator_list']['And'] = 'Y';
$app_list_strings['aow_condition_operator_list']['OR'] = 'O';
$app_list_strings['aow_condition_operator_list']['OR'] = 'O';
$app_list_strings['aow_condition_type_list']['Value'] = 'Valor';
$app_list_strings['aow_condition_type_list']['Field'] = 'Campo';
$app_list_strings['aow_condition_type_list']['Date'] = 'Fecha';
$app_list_strings['aow_condition_type_list']['Multi'] = 'Multiple';
$app_list_strings['aow_action_type_list']['Value'] = 'Valor';
$app_list_strings['aow_action_type_list']['Field'] = 'Campo';
$app_list_strings['aow_action_type_list']['Date'] = 'Fecha';
$app_list_strings['aow_action_type_list']['Round_Robin'] = 'Round Robin';
$app_list_strings['aow_action_type_list']['Least_Busy'] = 'Menos Ocupado';
$app_list_strings['aow_action_type_list']['Random'] = 'Al azar';
$app_list_strings['aow_rel_action_type_list']['Value'] = 'Valor';
$app_list_strings['aow_rel_action_type_list']['Field'] = 'Campo';
$app_list_strings['aow_date_type_list'][''] = '';
$app_list_strings['aow_date_type_list']['minute'] = 'Minutos';
$app_list_strings['aow_date_type_list']['hour'] = 'Horas';
$app_list_strings['aow_date_type_list']['day'] = 'Dias';
$app_list_strings['aow_date_type_list']['week'] = 'Semanas';
$app_list_strings['aow_date_type_list']['month'] = 'Meses';
$app_list_strings['aow_date_type_list']['business_hours'] = 'Horas Laborales';
$app_list_strings['aow_date_options']['now'] = 'Ahora';
$app_list_strings['aow_date_options']['field'] = 'Este Campo';
$app_list_strings['aow_date_operator']['now'] = '';
$app_list_strings['aow_date_operator']['plus'] = '+';
$app_list_strings['aow_date_operator']['minus'] = '-';
$app_list_strings['aow_assign_options']['all'] = 'TODOS los Usuarios';
$app_list_strings['aow_assign_options']['role'] = 'TODOS los Usuarios de un Rol';
$app_list_strings['aow_assign_options']['security_group'] = 'TODOS los Usuarios de un Equipo';
$app_list_strings['aow_email_type_list']['Email Address'] = 'Email';
$app_list_strings['aow_email_type_list']['Record Email'] = 'Email del Registro';
$app_list_strings['aow_email_type_list']['Specify User'] = 'Usuario';
$app_list_strings['aow_email_type_list']['Related Field'] = 'Campo Relacionado';
/**
* Products, Quotations & Invoices modules.
* Extensions to SugarCRM
* @package Advanced OpenSales for SugarCRM
* @subpackage Products
* @copyright SalesAgility Ltd http://www.salesagility.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
* along with this program; if not, see http://www.gnu.org/licenses
* or write to the Free Software Foundation,Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA
*
* @author Salesagility Ltd <support@salesagility.com>
*/
$app_list_strings['moduleList']['AOS_Contracts'] = 'Contratos';
$app_list_strings['moduleList']['AOS_Invoices'] = 'Facturas';
$app_list_strings['moduleList']['AOS_PDF_Templates'] = 'Formatos PDF';
$app_list_strings['moduleList']['AOS_Product_Categories'] = 'CategorÃas de Productos';
$app_list_strings['moduleList']['AOS_Products'] = 'Productos';
$app_list_strings['moduleList']['AOS_Products_Quotes'] = 'Cotizaciones de Productos';
$app_list_strings['moduleList']['AOS_Line_Item_Groups'] = 'Grupos de Lineas de Items';
$app_list_strings['moduleList']['AOS_Quotes'] = 'Cotizaciones';
$app_list_strings['aos_quotes_type_dom'][''] = '';
$app_list_strings['aos_quotes_type_dom']['Analyst'] = 'Analista';
$app_list_strings['aos_quotes_type_dom']['Competitor'] = 'Competidor';
$app_list_strings['aos_quotes_type_dom']['Customer'] = 'Cliente';
$app_list_strings['aos_quotes_type_dom']['Integrator'] = 'Integrador';
$app_list_strings['aos_quotes_type_dom']['Investor'] = 'Inversionista';
$app_list_strings['aos_quotes_type_dom']['Partner'] = 'Socio';
$app_list_strings['aos_quotes_type_dom']['Press'] = 'Prensa';
$app_list_strings['aos_quotes_type_dom']['Prospect'] = 'Prospecto';
$app_list_strings['aos_quotes_type_dom']['Reseller'] = 'Revendedor';
$app_list_strings['aos_quotes_type_dom']['Other'] = 'Otro';
$app_list_strings['template_ddown_c_list'][''] = '';
$app_list_strings['quote_stage_dom']['Draft'] = 'Borrador';
$app_list_strings['quote_stage_dom']['Negotiation'] = 'Negociación';
$app_list_strings['quote_stage_dom']['Delivered'] = 'Entregado';
$app_list_strings['quote_stage_dom']['On Hold'] = 'En Espera';
$app_list_strings['quote_stage_dom']['Confirmed'] = 'Confirmado';
$app_list_strings['quote_stage_dom']['Closed Accepted'] = 'Cerrado Aceptado';
$app_list_strings['quote_stage_dom']['Closed Lost'] = 'Cerrado Pérdido';
$app_list_strings['quote_stage_dom']['Closed Dead'] = 'Cerrado Muerto';
$app_list_strings['quote_term_dom']['Net 15'] = 'Red 15';
$app_list_strings['quote_term_dom']['Net 30'] = 'Red 30';
$app_list_strings['quote_term_dom'][''] = '';
$app_list_strings['approval_status_dom']['Approved'] = 'Approvado';
$app_list_strings['approval_status_dom']['Not Approved'] = 'No Approvado';
$app_list_strings['approval_status_dom'][''] = '';
$app_list_strings['vat_list']['16.0'] = '16.0';
$app_list_strings['vat_list']['11.0'] = '11.0';
$app_list_strings['vat_list']['18.0'] = '18.0';
$app_list_strings['discount_list']['Percentage'] = 'Porcentaje';
$app_list_strings['discount_list']['Amount'] = 'Cantidad';
$app_list_strings['aos_invoices_type_dom'][''] = '';
$app_list_strings['aos_invoices_type_dom']['Analyst'] = 'Analista';
$app_list_strings['aos_invoices_type_dom']['Competitor'] = 'Competidor';
$app_list_strings['aos_invoices_type_dom']['Customer'] = 'Cliente';
$app_list_strings['aos_invoices_type_dom']['Integrator'] = 'Integrador';
$app_list_strings['aos_invoices_type_dom']['Investor'] = 'Inversionista';
$app_list_strings['aos_invoices_type_dom']['Partner'] = 'Socio';
$app_list_strings['aos_invoices_type_dom']['Press'] = 'Prensa';
$app_list_strings['aos_invoices_type_dom']['Prospect'] = 'Prospecto';
$app_list_strings['aos_invoices_type_dom']['Reseller'] = 'Revendedor';
$app_list_strings['aos_invoices_type_dom']['Other'] = 'Otro';
$app_list_strings['invoice_status_dom']['Paid'] = 'Pagado';
$app_list_strings['invoice_status_dom']['Unpaid'] = 'No Pagado';
$app_list_strings['invoice_status_dom']['Cancelled'] = 'Cancelado';
$app_list_strings['invoice_status_dom'][''] = '';
$app_list_strings['quote_invoice_status_dom']['Not Invoiced'] = 'No Facturado';
$app_list_strings['quote_invoice_status_dom']['Invoiced'] = 'Facturado';
$app_list_strings['product_code_dom']['XXXX'] = 'XXXX';
$app_list_strings['product_code_dom']['YYYY'] = 'YYYY';
$app_list_strings['product_category_dom']['Laptops'] = 'Laptops';
$app_list_strings['product_category_dom']['Desktops'] = 'Desktops';
$app_list_strings['product_category_dom'][''] = '';
$app_list_strings['product_type_dom']['Good'] = 'Bien';
$app_list_strings['product_type_dom']['Service'] = 'Servicio';
$app_list_strings['product_quote_parent_type_dom']['AOS_Quotes'] = 'Cotizaciones';
$app_list_strings['product_quote_parent_type_dom']['AOS_Invoices'] = 'Facturas';
$app_list_strings['pdf_template_type_dom']['AOS_Quotes'] = 'Cotizaciones';
$app_list_strings['pdf_template_type_dom']['AOS_Invoices'] = 'Facturas';
$app_list_strings['pdf_template_type_dom']['Accounts'] = 'Cuentas';
$app_list_strings['pdf_template_type_dom']['Contacts'] = 'Contactos';
$app_list_strings['pdf_template_type_dom']['Leads'] = 'Oportunidades';
$app_list_strings['contract_status_list']['Not Started'] = 'No Iniciado';
$app_list_strings['contract_status_list']['In Progress'] = 'En Desarrollo';
$app_list_strings['contract_status_list']['Signed'] = 'Firmado';
$app_list_strings['contract_type_list']['Type'] = 'Tipo';
$app_strings['LBL_GENERATE_LETTER'] = 'Generar Carta';
$app_strings['LBL_SELECT_TEMPLATE'] = 'Por favor seleccione un formato';
$app_strings['LBL_NO_TEMPLATE'] = 'ERROR\nNo se encontraron formatos.\nPor favor vaya al módulo de Formatos PDF y cree uno';
$app_list_strings['vat_list']['0.0'] = '0%';
$app_list_strings['vat_list']['5.0'] = '5%';
$app_list_strings['vat_list']['7.5'] = '7.5%';
$app_list_strings['vat_list']['17.5'] = '17.5%';
$app_list_strings['vat_list']['20.0'] = '20%';
$app_list_strings['pdf_template_sample_dom'][''] = '';
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
* SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd.
* Copyright (C) 2011 - 2014 Salesagility Ltd.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
* reasonably feasible for technical reasons, the Appropriate Legal Notices must
* display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM".
********************************************************************************/
$app_list_strings['moduleList']['FP_events'] = 'Eventos';
$app_list_strings['moduleList']['FP_Event_Locations'] = 'Ubicaciones';
$app_list_strings['invite_template_list'][''] = '';
$app_list_strings['fp_event_invite_status_dom']['Invited'] = 'Invitado';
$app_list_strings['fp_event_invite_status_dom']['Not Invited'] = 'No Invitado';
$app_list_strings['fp_event_invite_status_dom']['Attended'] = 'Asistió';
$app_list_strings['fp_event_invite_status_dom']['Not Attended'] = 'No Asistió';
$app_list_strings['fp_event_status_dom']['Accepted'] = 'Aceptado';
$app_list_strings['fp_event_status_dom']['Declined'] = 'Rechazado';
$app_list_strings['fp_event_status_dom']['No Response'] = 'Sin Respuesta';
$app_strings['LBL_STATUS_EVENT'] = 'Estado de Invitación';
$app_strings['LBL_ACCEPT_STATUS'] = 'Estado de Aceptación';
$app_list_strings["moduleList"]["SecurityGroups"] = 'Administración de Grupos de Seguridad';
$app_strings['LBL_LOGIN_AS'] = "Conexión como ";
$app_strings['LBL_LOGOUT_AS'] = "Cerrar sesión como ";
$app_strings['LBL_SECURITYGROUP'] = 'Administración de Grupo';
$app_strings['LBL_MAP'] = 'Mapa';
$app_strings['LBL_MAPS'] = 'Mapas';
$app_strings['LBL_JJWG_MAPS_LNG'] = 'Longitud';
$app_strings['LBL_JJWG_MAPS_LAT'] = 'Latitud';
$app_strings['LBL_JJWG_MAPS_GEOCODE_STATUS'] = 'Geocode Estado';
$app_strings['LBL_JJWG_MAPS_ADDRESS'] = 'Dirección';
$app_strings['LBL_BUG_FIX'] = 'Bug Fix';
$app_list_strings['moduleList']['jjwg_Maps'] = 'Mapas';
$app_list_strings['moduleList']['jjwg_Markers'] = 'Marcadores de Mapa';
$app_list_strings['moduleList']['jjwg_Areas'] = 'Map Ãreas';
$app_list_strings['moduleList']['jjwg_Address_Cache'] = 'Mapa de Caché';
$app_list_strings['map_unit_type_list']['mi'] = 'Miles';
$app_list_strings['map_unit_type_list']['km'] = 'Kilómetros';
// Plural
$app_list_strings['map_module_type_list']['Cases'] = 'Casos';
$app_list_strings['map_module_type_list']['Leads'] = 'Cliente Potencial';
$app_list_strings['map_module_type_list']['Contacts'] = 'Contactos';
$app_list_strings['map_module_type_list']['Accounts'] = 'Cuentas';
$app_list_strings['map_module_type_list']['Opportunities'] = 'Oportunidades';
$app_list_strings['map_module_type_list']['Meetings'] = 'Reuniones';
$app_list_strings['map_module_type_list']['Project'] = 'Proyectos';
$app_list_strings['map_module_type_list']['Prospects'] = 'Público Objetivo';
// Signular
$app_list_strings['map_relate_type_list']['Cases'] = 'Caso';
$app_list_strings['map_relate_type_list']['Leads'] = 'Cliente Potencial';
$app_list_strings['map_relate_type_list']['Contacts'] = 'Contacto';
$app_list_strings['map_relate_type_list']['Accounts'] = 'Cuenta';
$app_list_strings['map_relate_type_list']['Opportunities'] = 'Oportunidad';
$app_list_strings['map_relate_type_list']['Meetings'] = 'Reunión';
$app_list_strings['map_relate_type_list']['Project'] = 'Proyecto';
$app_list_strings['map_relate_type_list']['Prospects'] = 'Público Objetivo';
$app_list_strings['marker_image_list']['accident'] = 'Accidente';
$app_list_strings['marker_image_list']['administration'] = 'Administración';
$app_list_strings['marker_image_list']['agriculture'] = 'Agricultura';
$app_list_strings['marker_image_list']['aircraft_small'] = 'Aviación pequeña';
$app_list_strings['marker_image_list']['airplane_tourism'] = 'Avion Turismo';
$app_list_strings['marker_image_list']['airport'] = 'Aeropueerto';
$app_list_strings['marker_image_list']['amphitheater'] = 'Anfiteatro';
$app_list_strings['marker_image_list']['apartment'] = 'Departamento';
$app_list_strings['marker_image_list']['aquarium'] = 'Acuario';
$app_list_strings['marker_image_list']['arch'] = 'Arch';
$app_list_strings['marker_image_list']['atm'] = 'Atm';
$app_list_strings['marker_image_list']['audio'] = 'Audio';
$app_list_strings['marker_image_list']['bank'] = 'Banco';
$app_list_strings['marker_image_list']['bank_euro'] = 'Banco Euro';
$app_list_strings['marker_image_list']['bank_pound'] = 'Banco Libra';
$app_list_strings['marker_image_list']['bar'] = 'Bar';
$app_list_strings['marker_image_list']['beach'] = 'Playa';
$app_list_strings['marker_image_list']['beautiful'] = 'Belleza';
$app_list_strings['marker_image_list']['bicycle_parking'] = 'Estacionamiento de Bicicletas';
$app_list_strings['marker_image_list']['big_city'] = 'Ciudad Grande';
$app_list_strings['marker_image_list']['bridge'] = 'Puente';
$app_list_strings['marker_image_list']['bridge_modern'] = 'Puente Moderno';
$app_list_strings['marker_image_list']['bus'] = 'Bus';
$app_list_strings['marker_image_list']['cable_car'] = 'Cable carril';
$app_list_strings['marker_image_list']['car'] = 'Automóvil';
$app_list_strings['marker_image_list']['car_rental'] = 'Alquiler de Automóviles';
$app_list_strings['marker_image_list']['carrepair'] = 'Reparación de Automóviles';
$app_list_strings['marker_image_list']['castle'] = 'Castillo';
$app_list_strings['marker_image_list']['cathedral'] = 'Catedral';
$app_list_strings['marker_image_list']['chapel'] = 'Capilla';
$app_list_strings['marker_image_list']['church'] = 'Iglesia';
$app_list_strings['marker_image_list']['city_square'] = 'Area Central';
$app_list_strings['marker_image_list']['cluster'] = 'Clúster';
$app_list_strings['marker_image_list']['cluster_2'] = 'Clúster 2';
$app_list_strings['marker_image_list']['cluster_3'] = 'Clúster 3';
$app_list_strings['marker_image_list']['cluster_4'] = 'Clúster 4';
$app_list_strings['marker_image_list']['cluster_5'] = 'Clúster 5';
$app_list_strings['marker_image_list']['coffee'] = 'Café';
$app_list_strings['marker_image_list']['community_centre'] = 'Centro Comunitario';
$app_list_strings['marker_image_list']['company'] = 'Empresa';
$app_list_strings['marker_image_list']['conference'] = 'Conferencia';
$app_list_strings['marker_image_list']['construction'] = 'Construcción';
$app_list_strings['marker_image_list']['convenience'] = 'Conveniencia';
$app_list_strings['marker_image_list']['court'] = 'Juzgado';
$app_list_strings['marker_image_list']['cruise'] = 'Crucero';
$app_list_strings['marker_image_list']['currency_exchange'] = 'Cambio de Moneda';
$app_list_strings['marker_image_list']['customs'] = 'Aduana';
$app_list_strings['marker_image_list']['cycling'] = 'Ciclismo';
$app_list_strings['marker_image_list']['dam'] = 'Represa';
$app_list_strings['marker_image_list']['days_dim'] = 'DÃas Dim';
$app_list_strings['marker_image_list']['days_dom'] = 'DÃas Dom';
$app_list_strings['marker_image_list']['days_jeu'] = 'DÃas Jeu';
$app_list_strings['marker_image_list']['days_jue'] = 'DÃas Jue';
$app_list_strings['marker_image_list']['days_lun'] = 'DÃas Lun';
$app_list_strings['marker_image_list']['days_mar'] = 'DÃas Mar';
$app_list_strings['marker_image_list']['days_mer'] = 'DÃas Mer';
$app_list_strings['marker_image_list']['days_mie'] = 'DÃas Mie';
$app_list_strings['marker_image_list']['days_qua'] = 'DÃas Qua';
$app_list_strings['marker_image_list']['days_qui'] = 'DÃas Qui';
$app_list_strings['marker_image_list']['days_sab'] = 'DÃas Sab';
$app_list_strings['marker_image_list']['days_sam'] = 'DÃas Sam';
$app_list_strings['marker_image_list']['days_seg'] = 'DÃas Seg';
$app_list_strings['marker_image_list']['days_sex'] = 'DÃas Sex';
$app_list_strings['marker_image_list']['days_ter'] = 'DÃas Ter';
$app_list_strings['marker_image_list']['days_ven'] = 'DÃas Ven';
$app_list_strings['marker_image_list']['days_vie'] = 'DÃas Vie';
$app_list_strings['marker_image_list']['dentist'] = 'Dentista';
$app_list_strings['marker_image_list']['deptartment_store'] = 'Tienda por Departamentos';
$app_list_strings['marker_image_list']['disability'] = 'Discapacidad';
$app_list_strings['marker_image_list']['disabled_parking'] = 'Estacionamiento p/Discapacitados';
$app_list_strings['marker_image_list']['doctor'] = 'Doctor';
$app_list_strings['marker_image_list']['dog_leash'] = 'Correa p/Perros';
$app_list_strings['marker_image_list']['down'] = 'Abajo';
$app_list_strings['marker_image_list']['down_left'] = 'Abajo Izquierda';
$app_list_strings['marker_image_list']['down_right'] = 'Abajo Derecha';
$app_list_strings['marker_image_list']['down_then_left'] = 'Abajo luego a la izquierda';
$app_list_strings['marker_image_list']['down_then_right'] = 'Abajo luego a la derecha';
$app_list_strings['marker_image_list']['drugs'] = 'Drogas';
$app_list_strings['marker_image_list']['elevator'] = 'Elevador';
$app_list_strings['marker_image_list']['embassy'] = 'Embajada';
$app_list_strings['marker_image_list']['expert'] = 'Experto';
$app_list_strings['marker_image_list']['factory'] = 'Fábrica';
$app_list_strings['marker_image_list']['falling_rocks'] = 'Zona de Derrumbes';
$app_list_strings['marker_image_list']['fast_food'] = 'Comida Rápida';
$app_list_strings['marker_image_list']['festival'] = 'Festival';
$app_list_strings['marker_image_list']['fjord'] = 'Fiordo';
$app_list_strings['marker_image_list']['forest'] = 'Bosque';
$app_list_strings['marker_image_list']['fountain'] = 'Fuente';
$app_list_strings['marker_image_list']['friday'] = 'Viernes';
$app_list_strings['marker_image_list']['garden'] = 'JardÃn';
$app_list_strings['marker_image_list']['gas_station'] = 'Bomba de Combustible';
$app_list_strings['marker_image_list']['geyser'] = 'Geyser';
$app_list_strings['marker_image_list']['gifts'] = 'Regalos';
$app_list_strings['marker_image_list']['gourmet'] = 'Gourmet';
$app_list_strings['marker_image_list']['grocery'] = 'Almacén';
$app_list_strings['marker_image_list']['hairsalon'] = 'Estilista';
$app_list_strings['marker_image_list']['helicopter'] = 'Helicóptero';
$app_list_strings['marker_image_list']['highway'] = 'Autopista';
$app_list_strings['marker_image_list']['historical_quarter'] = 'Casco Histórico';
$app_list_strings['marker_image_list']['home'] = 'Hogar';
$app_list_strings['marker_image_list']['hospital'] = 'Hospital';
$app_list_strings['marker_image_list']['hostel'] = 'Hostel';
$app_list_strings['marker_image_list']['hotel'] = 'Hotel';
$app_list_strings['marker_image_list']['hotel_1_star'] = 'Hotel 1 Estrella';
$app_list_strings['marker_image_list']['hotel_2_stars'] = 'Hotel 2 Estrellas';
$app_list_strings['marker_image_list']['hotel_3_stars'] = 'Hotel 3 Estrellas';
$app_list_strings['marker_image_list']['hotel_4_stars'] = 'Hotel 4 Estrellas';
$app_list_strings['marker_image_list']['hotel_5_stars'] = 'Hotel 5 Estrellas';
$app_list_strings['marker_image_list']['info'] = 'Info';
$app_list_strings['marker_image_list']['justice'] = 'Juzgado';
$app_list_strings['marker_image_list']['lake'] = 'Lago';
$app_list_strings['marker_image_list']['laundromat'] = 'LavanderÃa';
$app_list_strings['marker_image_list']['left'] = 'Izquierda';
$app_list_strings['marker_image_list']['left_then_down'] = 'Izquierda Luego Abajo';
$app_list_strings['marker_image_list']['left_then_up'] = 'Izquierda Luego Arriba';
$app_list_strings['marker_image_list']['library'] = 'Biblioteca';
$app_list_strings['marker_image_list']['lighthouse'] = 'Iluminación';
$app_list_strings['marker_image_list']['liquor'] = 'Expendio de Bebidas Alcoholicas';
$app_list_strings['marker_image_list']['lock'] = 'Candado';
$app_list_strings['marker_image_list']['main_road'] = 'Camino Principal';
$app_list_strings['marker_image_list']['massage'] = 'Masajes';
$app_list_strings['marker_image_list']['mobile_phone_tower'] = 'Antena de TelefonÃa Móvil';
$app_list_strings['marker_image_list']['modern_tower'] = 'Torre Moderna';
$app_list_strings['marker_image_list']['monastery'] = 'Monasterio';
$app_list_strings['marker_image_list']['monday'] = 'Lunes';
$app_list_strings['marker_image_list']['monument'] = 'Monumento';
$app_list_strings['marker_image_list']['mosque'] = 'Mezquita';
$app_list_strings['marker_image_list']['motorcycle'] = 'Motocicleta';
$app_list_strings['marker_image_list']['museum'] = 'Museo';
$app_list_strings['marker_image_list']['music_live'] = 'Música en Vivo';
$app_list_strings['marker_image_list']['oil_pump_jack'] = 'Oil Pump Jack';
$app_list_strings['marker_image_list']['pagoda'] = 'Pagoda';
$app_list_strings['marker_image_list']['palace'] = 'Palacio';
$app_list_strings['marker_image_list']['panoramic'] = 'Vista Panorámica';
$app_list_strings['marker_image_list']['park'] = 'Parque';
$app_list_strings['marker_image_list']['park_and_ride'] = 'Parque y Camiata';
$app_list_strings['marker_image_list']['parking'] = 'Estacionamiento';
$app_list_strings['marker_image_list']['photo'] = 'Foto';
$app_list_strings['marker_image_list']['picnic'] = 'Picnic';
$app_list_strings['marker_image_list']['places_unvisited'] = 'Lugares no Visitados';
$app_list_strings['marker_image_list']['places_visited'] = 'Lugares Visitados';
$app_list_strings['marker_image_list']['playground'] = 'Plaza';
$app_list_strings['marker_image_list']['police'] = 'PolicÃa';
$app_list_strings['marker_image_list']['port'] = 'Puerto';
$app_list_strings['marker_image_list']['postal'] = 'Postal';
$app_list_strings['marker_image_list']['power_line_pole'] = 'Poste de LÃnea Eléctrica';
$app_list_strings['marker_image_list']['power_plant'] = 'Planta de EnergÃa';
$app_list_strings['marker_image_list']['power_substation'] = 'Subestación de EnergÃa';
$app_list_strings['marker_image_list']['public_art'] = 'Arte Público';
$app_list_strings['marker_image_list']['rain'] = 'Lluvia';
$app_list_strings['marker_image_list']['real_estate'] = 'Inmobiliaria';
$app_list_strings['marker_image_list']['regroup'] = 'Reagrupamiento';
$app_list_strings['marker_image_list']['resort'] = 'Resort';
$app_list_strings['marker_image_list']['restaurant'] = 'Restaurant';
$app_list_strings['marker_image_list']['restaurant_african'] = 'Restaurant Africana';
$app_list_strings['marker_image_list']['restaurant_barbecue'] = 'Restaurant Barbacoa';
$app_list_strings['marker_image_list']['restaurant_buffet'] = 'Restaurant Buffet';
$app_list_strings['marker_image_list']['restaurant_chinese'] = 'Restaurant Chino';
$app_list_strings['marker_image_list']['restaurant_fish'] = 'Restaurant Pescado';
$app_list_strings['marker_image_list']['restaurant_fish_chips'] = 'Restaurant Chips de Pescado';
$app_list_strings['marker_image_list']['restaurant_gourmet'] = 'Restaurant Gourmet';
$app_list_strings['marker_image_list']['restaurant_greek'] = 'Restaurant Griego';
$app_list_strings['marker_image_list']['restaurant_indian'] = 'Restaurant Hindú';
$app_list_strings['marker_image_list']['restaurant_italian'] = 'Restaurant Italiano';
$app_list_strings['marker_image_list']['restaurant_japanese'] = 'Restaurant Japonés';
$app_list_strings['marker_image_list']['restaurant_kebab'] = 'Restaurant Brochette';
$app_list_strings['marker_image_list']['restaurant_korean'] = 'Restaurant Coreano';
$app_list_strings['marker_image_list']['restaurant_mediterranean'] = 'Restaurant Mediterráneo';
$app_list_strings['marker_image_list']['restaurant_mexican'] = 'Restaurant Mexicano';
$app_list_strings['marker_image_list']['restaurant_romantic'] = 'Restaurant Romántico';
$app_list_strings['marker_image_list']['restaurant_thai'] = 'Restaurant Thai';
$app_list_strings['marker_image_list']['restaurant_turkish'] = 'Restaurant Turco';
$app_list_strings['marker_image_list']['right'] = 'Derecha';
$app_list_strings['marker_image_list']['right_then_down'] = 'Derecha Luego Abajo';
$app_list_strings['marker_image_list']['right_then_up'] = 'Derecha Luego Arriba';
$app_list_strings['marker_image_list']['satursday'] = 'Sábado';
$app_list_strings['marker_image_list']['school'] = 'Escuela';
$app_list_strings['marker_image_list']['shopping_mall'] = 'Mall';
$app_list_strings['marker_image_list']['shore'] = 'Apuntalamiento';
$app_list_strings['marker_image_list']['sight'] = 'Vista';
$app_list_strings['marker_image_list']['small_city'] = 'Pequeña Ciudad';
$app_list_strings['marker_image_list']['snow'] = 'Nieve';
$app_list_strings['marker_image_list']['spaceport'] = 'Puerto Espacial';
$app_list_strings['marker_image_list']['speed_100'] = 'Velocidad 100';
$app_list_strings['marker_image_list']['speed_110'] = 'Velocidad 110';
$app_list_strings['marker_image_list']['speed_120'] = 'Velocidad 120';
$app_list_strings['marker_image_list']['speed_130'] = 'Velocidad 130';
$app_list_strings['marker_image_list']['speed_20'] = 'Velocidad 20';
$app_list_strings['marker_image_list']['speed_30'] = 'Velocidad 30';
$app_list_strings['marker_image_list']['speed_40'] = 'Velocidad 40';
$app_list_strings['marker_image_list']['speed_50'] = 'Velocidad 50';
$app_list_strings['marker_image_list']['speed_60'] = 'Velocidad 60';
$app_list_strings['marker_image_list']['speed_hump'] = 'Velocidad Hump';
$app_list_strings['marker_image_list']['stadium'] = 'Estadio';
$app_list_strings['marker_image_list']['statue'] = 'Estatua';
$app_list_strings['marker_image_list']['steam_train'] = 'Tren a Vapor';
$app_list_strings['marker_image_list']['stop'] = 'Stop';
$app_list_strings['marker_image_list']['stoplight'] = 'Semáforo';
$app_list_strings['marker_image_list']['subway'] = 'Subterráneo';
$app_list_strings['marker_image_list']['sun'] = 'Sol';
$app_list_strings['marker_image_list']['sunday'] = 'Domingo';
$app_list_strings['marker_image_list']['supermarket'] = 'Super Mercado';
$app_list_strings['marker_image_list']['synagogue'] = 'Sinagoga';
$app_list_strings['marker_image_list']['tapas'] = 'Tapas';
$app_list_strings['marker_image_list']['taxi'] = 'Taxi';
$app_list_strings['marker_image_list']['taxiway'] = 'VÃa p/Taxis';
$app_list_strings['marker_image_list']['teahouse'] = 'Casa de Té';
$app_list_strings['marker_image_list']['telephone'] = 'Teléfono';
$app_list_strings['marker_image_list']['temple_hindu'] = 'Templo Hindú';
$app_list_strings['marker_image_list']['terrace'] = 'Terraza';
$app_list_strings['marker_image_list']['text'] = 'Texto';
$app_list_strings['marker_image_list']['theater'] = 'Teatro';
$app_list_strings['marker_image_list']['theme_park'] = 'Parque Temático';
$app_list_strings['marker_image_list']['thursday'] = 'Jueves';
$app_list_strings['marker_image_list']['toilets'] = 'Toilets';
$app_list_strings['marker_image_list']['toll_station'] = 'Peaje';
$app_list_strings['marker_image_list']['tower'] = 'Torre';
$app_list_strings['marker_image_list']['traffic_enforcement_camera'] = 'Control de Velocidad';
$app_list_strings['marker_image_list']['train'] = 'Tren';
$app_list_strings['marker_image_list']['tram'] = 'TranvÃa';
$app_list_strings['marker_image_list']['truck'] = 'Camión';
$app_list_strings['marker_image_list']['tuesday'] = 'Martes';
$app_list_strings['marker_image_list']['tunnel'] = 'Tunel';
$app_list_strings['marker_image_list']['turn_left'] = 'Giro a la Izquierda';
$app_list_strings['marker_image_list']['turn_right'] = 'Giro a la Derecha';
$app_list_strings['marker_image_list']['university'] = 'Universidad';
$app_list_strings['marker_image_list']['up'] = 'Arriba';
$app_list_strings['marker_image_list']['vespa'] = 'Vespa';
$app_list_strings['marker_image_list']['video'] = 'Video';
$app_list_strings['marker_image_list']['villa'] = 'Villa';
$app_list_strings['marker_image_list']['water'] = 'Water';
$app_list_strings['marker_image_list']['waterfall'] = 'Waterfall';
$app_list_strings['marker_image_list']['watermill'] = 'Watermill';
$app_list_strings['marker_image_list']['waterpark'] = 'Waterpark';
$app_list_strings['marker_image_list']['watertower'] = 'Watertower';
$app_list_strings['marker_image_list']['wednesday'] = 'Wednesday';
$app_list_strings['marker_image_list']['wifi'] = 'Wifi';
$app_list_strings['marker_image_list']['wind_turbine'] = 'Wind Turbine';
$app_list_strings['marker_image_list']['windmill'] = 'Windmill';
$app_list_strings['marker_image_list']['winery'] = 'Winery';
$app_list_strings['marker_image_list']['work_office'] = 'Work Office';
$app_list_strings['marker_image_list']['world_heritage_site'] = 'World Heritage Site';
$app_list_strings['marker_image_list']['zoo'] = 'Zoo';
$app_list_strings['marker_image_list']['speed_70'] = 'Velocidad 70';
$app_list_strings['marker_image_list']['speed_80'] = 'Velocidad 80';
$app_list_strings['marker_image_list']['speed_90'] = 'Velocidad 90';
$app_list_strings['marker_image_list']['speed_hump'] = 'Velocidad Hump';
$app_list_strings['marker_image_list']['stadium'] = 'Stadium';
$app_list_strings['marker_image_list']['statue'] = 'Statue';
$app_list_strings['marker_image_list']['steam_train'] = 'Steam Train';
$app_list_strings['marker_image_list']['stop'] = 'Stop';
$app_list_strings['marker_image_list']['stoplight'] = 'Stoplight';
$app_list_strings['marker_image_list']['subway'] = 'Subway';
$app_list_strings['marker_image_list']['sun'] = 'Sun';
$app_list_strings['marker_image_list']['sunday'] = 'Sunday';
$app_list_strings['marker_image_list']['supermarket'] = 'Supermarket';
$app_list_strings['marker_image_list']['synagogue'] = 'Synagogue';
$app_list_strings['marker_image_list']['tapas'] = 'Tapas';
$app_list_strings['marker_image_list']['taxi'] = 'Taxi';
$app_list_strings['marker_image_list']['taxiway'] = 'Taxiway';
$app_list_strings['marker_image_list']['teahouse'] = 'Teahouse';
$app_list_strings['marker_image_list']['telephone'] = 'Telephone';
$app_list_strings['marker_image_list']['temple_hindu'] = 'Temple Hindu';
$app_list_strings['marker_image_list']['terrace'] = 'Terrace';
$app_list_strings['marker_image_list']['text'] = 'Text';
$app_list_strings['marker_image_list']['theater'] = 'Theater';
$app_list_strings['marker_image_list']['theme_park'] = 'Theme Park';
$app_list_strings['marker_image_list']['thursday'] = 'Thursday';
$app_list_strings['marker_image_list']['toilets'] = 'Toilets';
$app_list_strings['marker_image_list']['toll_station'] = 'Toll Station';
$app_list_strings['marker_image_list']['tower'] = 'Tower';
$app_list_strings['marker_image_list']['traffic_enforcement_camera'] = 'Traffic Enforcement Camera';
$app_list_strings['marker_image_list']['train'] = 'Train';
$app_list_strings['marker_image_list']['tram'] = 'Tram';
$app_list_strings['marker_image_list']['truck'] = 'Truck';
$app_list_strings['marker_image_list']['tuesday'] = 'Tuesday';
$app_list_strings['marker_image_list']['tunnel'] = 'Tunnel';
$app_list_strings['marker_image_list']['turn_left'] = 'Turn Left';
$app_list_strings['marker_image_list']['turn_right'] = 'Turn Right';
$app_list_strings['marker_image_list']['university'] = 'University';
$app_list_strings['marker_image_list']['up'] = 'Up';
$app_list_strings['marker_image_list']['up_left'] = 'Arriba Izquierda';
$app_list_strings['marker_image_list']['up_right'] = 'Arriba Derecha';
$app_list_strings['marker_image_list']['up_then_left'] = 'Arriba Luego Izquierda';
$app_list_strings['marker_image_list']['up_then_right'] = 'Arriba Luego Derecha';
$app_list_strings['marker_image_list']['vespa'] = 'Vespa';
$app_list_strings['marker_image_list']['video'] = 'Video';
$app_list_strings['marker_image_list']['villa'] = 'Villa';
$app_list_strings['marker_image_list']['water'] = 'Agua';
$app_list_strings['marker_image_list']['waterfall'] = 'Cascada';
$app_list_strings['marker_image_list']['watermill'] = 'Molino de Agua';
$app_list_strings['marker_image_list']['waterpark'] = 'Parque Acuático';
$app_list_strings['marker_image_list']['watertower'] = 'Torre de Agua';
$app_list_strings['marker_image_list']['wednesday'] = 'Miércoles';
$app_list_strings['marker_image_list']['wifi'] = 'WiFi';
$app_list_strings['marker_image_list']['wind_turbine'] = 'Turbina de Viento';
$app_list_strings['marker_image_list']['windmill'] = 'Molino de Viento';
$app_list_strings['marker_image_list']['winery'] = 'Lagar';
$app_list_strings['marker_image_list']['work_office'] = 'Oficina';
$app_list_strings['marker_image_list']['world_heritage_site'] = 'Patrimonio de la Humanidad';
$app_list_strings['marker_image_list']['zoo'] = 'Zoo';
?>
|
agpl-3.0
|
Twitchtastic/Gitorious
|
public/javascripts/gitorious/diff_browser.js
|
27599
|
/*
#--
# Copyright (C) 2007-2009 Johan Sørensen <johan@johansorensen.com>
# Copyright (C) 2009 Marius Mathiesen <marius.mathiesen@gmail.com>
# Copyright (C) 2010 Christian Johansen <christian@shortcut.no>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#--
*/
/*jslint nomen: false, eqeqeq: false, plusplus: false, onevar: false,
regexp: false*/
/*global gitorious, Gitorious, diffBrowserCompactCommitSelectable, $, document, window, console*/
if (!this.Gitorious) {
this.Gitorious = {};
}
Gitorious.Sha = function (sha) {
this.fullSha = sha;
this.shortSha = function () {
return this.fullSha.substring(0, 7);
};
this.sha = function () {
return this.fullSha;
};
};
Gitorious.ShaSpec = function () {
this.allShas = [];
this.addSha = function (s) {
this.allShas.push(new Gitorious.Sha(s));
};
// Add shas from a string, eg ff0-bba
this.parseShas = function (shaString) {
var pair = shaString.split("-");
this.addSha(pair[0]);
if (pair.length > 1) {
this.addSha(pair[1]);
}
};
this.firstSha = function () {
return this.allShas[0];
};
this.lastSha = function () {
return this.allShas[this.allShas.length - 1];
};
this.shaSpecs = function (callback) {
if (this.allShas.length < 2) {
return [this.firstSha()];
} else {
return [this.firstSha(), this.lastSha()];
}
};
this.shaSpec = function () {
var _specs = this.shaSpecs();
return $.map(_specs, function (s) {
return s.sha();
}).join("-");
};
this.shaSpecWithVersion = function () {
var result = this.shaSpec();
if (this.hasVersion()) {
result = result + "@" + this.getVersion();
}
return result;
};
this.shortShaSpec = function () {
var _specs = this.shaSpecs();
return $.map(_specs, function (s) {
return s.shortSha();
}).join("-");
};
this.singleCommit = function () {
return this.firstSha().sha() == this.lastSha().sha();
};
this.setVersion = function (v) {
this._version = v;
};
this.getVersion = function () {
return this._version;
};
this.hasVersion = function () {
return typeof(this._version) != "undefined";
};
this.summarizeHtml = function () {
$("#current_shas").attr("data-merge-request-current-shas", this.shaSpec());
if (this.singleCommit()) {
$("#current_shas .several_shas").hide();
$("#current_shas .single_sha").show();
$("#current_shas .single_sha .merge_base").html(this.firstSha().shortSha());
} else {
$("#current_shas .several_shas").show();
$("#current_shas .single_sha").hide();
$("#current_shas .several_shas .first").html(this.firstSha().shortSha());
$("#current_shas .several_shas .last").html(this.lastSha().shortSha());
}
};
};
Gitorious.ShaSpec.parseLocationHash = function (hash) {
if (hash == "" || typeof(hash) == "undefined") {
return null;
}
var result = new Gitorious.ShaSpec();
var _hash = hash.replace(/#/, "");
var specAndVersion = _hash.split("@");
result.parseShas(specAndVersion[0]);
result.setVersion(specAndVersion[1]);
return result;
};
// Return an instance from a String
Gitorious.ShaSpec.parseShas = function (shaString) {
var result = new Gitorious.ShaSpec();
result.parseShas(shaString);
return result;
};
Gitorious.setDiffBrowserHunkStateFromCookie = function () {
if ($.cookie("merge-requests-diff-hunks-state") === "expanded") {
$('#merge_request_diff .file-diff .header').removeClass("closed").addClass("open");
$('#merge_request_diff .diff-hunks:hidden').show();
} else if ($.cookie("commits-diff-hunks-state")) {
if ($.cookie("commits-diff-hunks-state") === "expanded") {
$('#commit-diff-container .file-diff .header').removeClass("closed").addClass("open");
$('#commit-diff-container .diff-hunks:hidden').show();
} else {
$('#commit-diff-container .file-diff .header').removeClass("open").addClass("closed");
$('#commit-diff-container .diff-hunks:hidden').hide();
}
}
};
gitorious.app.observe("DiffBrowserDidReloadDiffs",
Gitorious.setDiffBrowserHunkStateFromCookie);
Gitorious.DiffBrowser = function (shas) {
gitorious.app.notify("DiffBrowserWillReloadDiffs", this);
var c = Gitorious.MergeRequestController.getInstance();
var version = c.determineCurrentVersion();
c.update({ version: version, sha: shas });
};
Gitorious.DiffBrowser.CommentHighlighter = {
_lastHighlightedComment: null,
removePrevious: function () {
if (!this._lastHighlightedComment) {
return;
}
this.remove(this._lastHighlightedComment);
},
add: function (commentElement) {
this.removePrevious();
commentElement.addClass("highlighted");
this.toggle(commentElement, 'highlighted', 'add');
this._lastHighlightedComment = commentElement;
},
remove: function (commentElement) {
commentElement.removeClass("highlighted");
this.toggle(commentElement, 'highlighted', 'remove');
},
toggle: function (commentElement, cssClass, action) {
var lineData = commentElement.attr("gts:lines").split(/[^\d\-]/);
var rows = commentElement.parents("table").find("tr.changes:not(.hunk-sep,.unmod)");
var startRow = rows.filter("[data-line-num-tuple=" + lineData[0] + "]");
var sliceStart = rows.indexOf(startRow[0]);
var sliceEnd = sliceStart + parseInt(lineData[2], 10) + 1;
rows.slice(sliceStart, sliceEnd)[action + "Class"]("highlighted");
}
};
Gitorious.DiffBrowser.KeyNavigationController = function () {
this._lastElement = null;
this._enabled = false;
this._callback = function (event) {
if (event.keyCode === 74) { // j
this.scrollToNext();
} else if (event.keyCode === 75) { // k
this.scrollToPrevious();
} else if (event.keyCode === 88) { // x
this.expandCommentsAtCurrentIndex();
}
};
this.expandCommentsAtCurrentIndex = function () {
if (!this._lastElement) {
return;
}
var comments = $(this._lastElement).find("table tr td .diff-comments");
if (comments.is(":hidden")) {
comments.show();
} else {
comments.hide();
}
};
this.scrollToNext = function () {
var elements = $("#merge_request_diff .file-diff");
if (!this._lastElement) {
this._lastElement = elements[0];
this.scrollToElement(elements[0]);
return;
}
var idx = elements.indexOf(this._lastElement);
idx++;
if (elements[idx]) {
this.scrollToElement(elements[idx]);
} else {
this.scrollToElement(elements[elements.length - 1]);
}
};
this.scrollToPrevious = function () {
var elements = $("#merge_request_diff .file-diff");
if (this._lastElement === elements[0]) {
return;
}
var idx = elements.indexOf(this._lastElement);
idx--;
if (idx >= 0 && elements[idx]) {
this.scrollToElement(elements[idx]);
}
};
this.scrollToElement = function (el) {
var element = $(el);
element.find(".header").removeClass("closed").addClass("open");
element.find(".diff-hunks:hidden").slideDown();
$.scrollTo(element, { axis: "y", offset: -10 });
this._lastElement = element[0];
};
this.enable = function () {
if (this._enabled) {
return;
}
this.disable();
$(window).bind("keydown", this._callback.bind(this));
// unbind whenever we're in an input field
$(":input").focus(this.disable.bind(this));
var self = this;
$(":input").blur(function () {
$(window).bind("keydown", self._callback.bind(self));
});
this._enabled = true;
};
this.disable = function () {
if (!this._enabled) {
return;
}
$(window).unbind("keydown", this._callback.bind(this));
this._enabled = false;
};
};
Gitorious.DiffBrowser.KeyNavigation = new Gitorious.DiffBrowser.KeyNavigationController();
gitorious.app.observe("DiffBrowserDidReloadDiffs",
Gitorious.DiffBrowser.KeyNavigation.enable.bind(Gitorious.DiffBrowser.KeyNavigation));
gitorious.app.observe("DiffBrowserWillPresentCommentForm",
Gitorious.DiffBrowser.KeyNavigation.disable.bind(Gitorious.DiffBrowser.KeyNavigation));
Gitorious.MergeRequestController = function () {
this._currentShaRange = null; // The sha range currently displayed
this._currentVersion = null; // The version currently displayed
this._requestedShaRange = null; // The requested sha range
this._requestedVersion = null; // The requested version
this._setCurrentShaRange = function (shas) {
this._currentShaRange = shas;
};
this._setCurrentVersion = function (version) {
this._currentVersion = version;
};
this.shaSelected = function (sha) {
this._requestedShaRange = sha;
};
this.versionSelected = function (version) {
this._requestedVersion = version;
};
this._setTransport = function (transport) {
this._transport = transport;
};
// The correct diff url given the current version and sha selection
this.getDiffUrl = function () {
if (this._requestedVersion) {
return $("li[data-mr-version-number=" + this._requestedVersion + "]").
attr("data-mr-version-url") + "?commit_shas=" + this.getCurrentShaRange();
} else {
return $("#merge_request_commit_selector").
attr("data-merge-request-version-url");
}
};
//Callback when new diffs are received from the server
this.diffsReceived = function (data, message) {
this._setCurrentVersion(this._requestedVersion);
this._setCurrentShaRange(this._requestedShaRange);
};
this.getTransport = function () {
return this._transport || $;
};
this.update = function (o) {
if (o.version) {
this.versionSelected(o.version);
}
if (o.sha) {
this.shaSelected(o.sha);
}
if (this.needsUpdate()) {
$("#merge_request_diff").html(Gitorious.MergeRequestDiffSpinner);
this.replaceDiffContents(this._requestedShaRange);
}
};
// Loads diffs for the given sha range. +callback+ is a an function
// that will be called on +caller+ when changed successfully
this.replaceDiffContents = function (shaRange, callback, caller) {
var options = {};
if (shaRange) {
this.shaSelected(shaRange);
options.data = { "commit_shas": shaRange };
}
options.url = this.getDiffUrl();
var self = this;
options.success = function (data, text) {
self.diffsReceivedSuccessfully(data, text, callback, caller);
};
options.error = function (xhr, statusText, errorThrown) {
self.diffsReceivedWithError(xhr, statusText, errorThrown);
};
this.getTransport().ajax(options);
};
this.diffsReceivedSuccessfully = function (data, responseText, callback, caller) {
this._currentShaRange = this._requestedShaRange;
this._currentVersion = this._requestedVersion;
$("#merge_request_diff").html(data);
var spec = new Gitorious.ShaSpec();
spec.parseShas(this._currentShaRange);
spec.summarizeHtml();
gitorious.app.notify("DiffBrowserDidReloadDiffs", this);
if (callback) {
callback.apply(caller);
}
};
this.diffsReceivedWithError = function (xhr, statusText, errorThrown) {
$("#merge_request_diff").html(
'<div class="merge_request_diff_loading_indicator">' +
"An error has occured. Please try again later.</div>"
);
};
this.needsUpdate = function () {
return (this._currentShaRange != this._requestedShaRange) ||
(this._currentVersion != this._requestedVersion);
};
this.willSelectShas = function () {
$("#current_shas .label").html("Selecting");
};
this.didReceiveVersion = function (spec) {
spec.setVersion(this.determineCurrentVersion());
document.location.hash = spec.shaSpecWithVersion();
};
this.determineCurrentVersion = function () {
return $("#merge_request_version").text().replace(/[^0-9]+/g, "");
};
this.isSelectingShas = function (spec) {
spec.setVersion(this.determineCurrentVersion());
document.location.hash = spec.shaSpecWithVersion();
spec.summarizeHtml();
};
this.findCurrentlySelectedShas = function (spec) {
var allShas = $("li.single_commit a").map(function () {
return $(this).attr("data-commit-sha");
});
var currentShas = [];
for (var i = allShas.indexOf(spec.firstSha().sha());
i <= allShas.indexOf(spec.lastSha().sha());
i++) {
currentShas.push(allShas[i]);
}
return currentShas;
};
// De-selects any selected sha links, replace with
// commits included in +spec+ (ShaSpec object or String)
this.simulateShaSelection = function (shaSpec) {
$("li.ui-selected").removeClass("ui-selected");
var currentShas = this.findCurrentlySelectedShas(shaSpec);
$.each(currentShas, function (ind, sha) {
$("[data-commit-sha='" + sha + "']").parent().addClass("ui-selected");
});
};
// Loads the requested (from path part of uri) shas and version
this.loadFromBookmark = function (spec) {
this.simulateShaSelection(spec);
};
this.didSelectShas = function (spec) {
$("#current_shas .label").html("Showing");
// In case a range has been selected, also display what's in between as selected
var currentShas = this.findCurrentlySelectedShas(spec);
$.each(currentShas, function (idx, sha) {
var l = $("[data-commit-sha='" + sha + "']").parent();
if (!l.hasClass("ui-selected")) {
l.addClass("ui-selected");
}
});
var attr = "data-merge-request-version-url";
var mr_diff_url = $("#merge_request_commit_selector").attr(attr);
var diff_browser = new Gitorious.DiffBrowser(spec.shaSpec());
};
// Another version was selected, update sha listing if necessary
this.versionChanged = function (v) {
this.versionSelected(v);
if (this.needsUpdate()) {
var url = $("#merge_request_version").attr("gts:url") +
"?version=" + v;
this.getTransport().ajax({
url: url,
success: function (data, text) {
gitorious.app.notify("MergeRequestShaListingReceived",
true, data, text, v);
},
error: function (xhr, statusText, errorThrown) {
gitorious.app.notify("MergeRequestShaListingReceived", false);
}
});
} else {
gitorious.app.notify("MergeRequestShaListingUpdated", "Same version");
}
};
// User has selected another version to be displayed
this.loadVersion = function (v) {
var self = this;
this._requestedVersion = v;
var url = $("#merge_request_version").attr("gts:url") +
"?version=" + v;
this.getTransport().ajax({
url: url,
success: function (data, text) {
self.shaListingReceived(true, data, text, v, function () {
this.replaceDiffContents();
}, self);
},
error: function (xhr, statusText, errorThrown) {
if (typeof console != "undefined" && console.error) {
console.error("Got an error selecting a different version");
}
}
});
};
this.shaListingReceived = function (successful, data, text, version, callback, caller) {
if (successful) {
$("#merge_request_version").html("Version " + version);
this.replaceShaListing(data);
gitorious.app.notify("MergeRequestShaListingUpdated", "new");
if (callback && caller) {
callback.apply(caller);
}
} else {
// console.error("Got an error when fetching shas");
}
};
this.getCurrentShaRange = function () {
return $("#current_shas").attr("data-merge-request-current-shas");
};
this.isDisplayingShaRange = function (r) {
return this.getCurrentShaRange() == r;
};
this.replaceShaListing = function (markup) {
$("#diff_browser_for_current_version").html(markup);
Gitorious.currentMRCompactSelectable.selectable("destroy");
Gitorious.currentMRCompactSelectable = diffBrowserCompactCommitSelectable();
};
};
Gitorious.MergeRequestController.getInstance = function () {
if (Gitorious.MergeRequestController._instance) {
return Gitorious.MergeRequestController._instance;
} else {
var result = new Gitorious.MergeRequestController();
gitorious.app.observe("MergeRequestDiffReceived",
result.diffsReceived.bind(result));
gitorious.app.observe("MergeRequestShaListingReceived",
result.shaListingReceived.bind(result));
Gitorious.MergeRequestController._instance = result;
return result;
}
};
// To preserve memory and avoid errors, we remove the selectables
Gitorious.disableCommenting = function () {
$("table.codediff").selectable("destroy");
};
// Makes line numbers selectable for commenting
Gitorious.enableCommenting = function () {
this.MAX_COMMENTABLES = 1500;
// Don't add if we're dealing with a large diff
if ($("table.codediff td.commentable").length > this.MAX_COMMENTABLES) {
$("table.codediff td.commentable").removeClass("commentable");
return false;
}
$("table.codediff").selectable({
filter: "td.commentable, td.line-num-cut",
start: function (e, ui) {
Gitorious.CommentForm.destroyAll();
},
cancel: ".inline_comments, td.code, td.line-num-cut",
stop: function (e, ui) {
var diffTable = e.target;
var allLineNumbers = [];
$(diffTable).find("td.ui-selected").each(function () {
if ($(this).hasClass("line-num-cut")) {
return false; // break on hunk seperators
}
$(this).parent().addClass("selected-for-commenting");
allLineNumbers.push($(this).parents("tr").attr("data-line-num-tuple"));
});
var path = $(diffTable).parent().prev(".header").children(".title").text();
var commentForm = new Gitorious.CommentForm(path);
commentForm.setLineNumbers(allLineNumbers.unique());
if (commentForm.hasLines()) {
commentForm.display($(this).parents(".file-diff"));
}
}
});
// Comment highlighting of associated lines
$("table tr td.code .diff-comment").each(function () {
var lines = $(this).attr("gts:lines").split(",");
var commentBody = $(this).find(".body").text();
var replyCallback = function () {
Gitorious.CommentForm.destroyAll();
var lines = $(this).parents("div.diff-comment").attr("gts:lines").split(",");
var path = $(this).parents("table").parent().prev(".header"
).children(".title").text();
var commentForm = new Gitorious.CommentForm(path);
commentForm.setLineNumbers(lines);
commentForm.setInitialCommentBody(commentBody);
if (commentForm.hasLines()) {
commentForm.display($(this).parents(".file-diff"));
}
return false;
};
$(this).hover(function () {
Gitorious.DiffBrowser.CommentHighlighter.add($(this));
$(this).find(".reply").show().click(replyCallback);
}, function () {
Gitorious.DiffBrowser.CommentHighlighter.remove($(this));
$(this).find(".reply").hide().unbind("click", replyCallback);
});
});
};
gitorious.app.observe("DiffBrowserDidReloadDiffs",
Gitorious.enableCommenting.bind(Gitorious));
gitorious.app.observe("DiffBrowserWillReloadDiffs",
Gitorious.disableCommenting.bind(Gitorious));
Gitorious.CommentForm = function (path) {
this.path = path;
this.numbers = [];
this.initialCommentBody = null;
this.container = $("#inline_comment_form");
this.setLineNumbers = function (n) {
var result = [];
n.each(function (i, number) {
if (number != "") {
result.push(number);
}
});
this.numbers = result;
};
this.setInitialCommentBody = function (body) {
var text = $.trim(body);
this.initialCommentBody = $.map(text.split(/\r?\n/), function (str) {
return "> " + str;
}).join("\n") + "\n\n";
return this.initialCommentBody;
};
// returns the lines as our internal representation
// The fomat is
// $first_line-number-tuple:$last-line-number-tuple+$extra-lines
// where $first-line-number-tuple is the first element in the
// data-line-num-tuple from the <tr> off the selected row and
// $last-line-number-tuple being the last. $extra-lines is the
// number of rows the selection span (without the initial row)
this.linesAsInternalFormat = function () {
var first = this.numbers[0];
var last = this.numbers[this.numbers.length - 1];
var span = this.numbers.length - 1;
return first + ':' + last + '+' + span;
};
this.lastLineNumber = function () {
return this.numbers[this.numbers.length - 1];
};
this.hasLines = function () {
return this.numbers.length > 0;
};
this.getSummary = function () {
return "Commenting on " + this.path;
};
this.reset = function () {
this.container.find(".progress").hide();
this.container.find(":input").show();
this.container.find("#comment_body").val("");
};
this.updateData = function () {
this.container.find("#description").text(this.getSummary());
var shas = $("#current_shas").attr("data-merge-request-current-shas");
this.container.find("#comment_sha1").val(shas);
this.container.find("#comment_path").val(this.path);
this.container.find("#comment_context").val(this._getRawDiffContext());
this.container.find(".cancel").click(Gitorious.CommentForm.destroyAll);
this.container.find("#comment_lines").val(this.linesAsInternalFormat());
};
this.display = function (diffContainer) {
this.reset();
gitorious.app.notify("DiffBrowserWillPresentCommentForm", this);
this.updateData();
this.container.fadeIn();
if (this.initialCommentBody && this.container.find("#comment_body").val() == "") {
this.container.find("#comment_body").val(this.initialCommentBody);
}
this.container.find("#comment_body").focus();
var zeForm = this.container.find("form");
var lastLine = this.lastLineNumber();
zeForm.submit(function () {
zeForm.find(".progress").show("fast");
zeForm.find(":input").hide("fast");
$.ajax({
url: $(this).attr("action"),
data: $(this).serialize(),
type: "POST",
dataType: "json",
success: function (data, text) {
gitorious.app.notify("DiffBrowserWillReloadDiffs", this);
diffContainer.replaceWith(data["file-diff"]);
$(".commentable.comments").append(data.comment);
gitorious.app.notify("DiffBrowserDidReloadDiffs", this);
$("#diff-inline-comments-for-" + lastLine).slideDown();
Gitorious.CommentForm.destroyAll();
},
error: function (xhr, statusText, errorThrown) {
var errorDisplay = $(zeForm).find(".error");
zeForm.find(".progress").hide("fast");
zeForm.find(":input").show("fast");
errorDisplay.text("Please make sure your comment is valid");
errorDisplay.show("fast");
}
});
return false;
});
this.container.keydown(function (e) {
if (e.which == 27) { // Escape
Gitorious.CommentForm.destroyAll();
}
});
};
this._getRawDiffContext = function () {
// Extract the affected diffs (as raw quoted diffs) and return them
var idiffRegexp = /(<span class="idiff">|<\/span>)/gmi;
var comments = $("#merge_request_comments .comment.inline .inline_comment_link a");
var plainDiff = [];
var selectors = $.map(this.numbers, function (e) {
return "table.codediff.inline tr[data-line-num-tuple=" + e + "]";
});
// extract the raw diff data from each row
$(selectors.join(",")).each(function () {
var cell = $(this).find("td.code");
var op = (cell.hasClass("ins") ? "+ " : "- ");
plainDiff.push(op + cell.find(".diff-content").html().replace(idiffRegexp, ''));
});
return (plainDiff.length > 0 ? plainDiff.join("\n") : "");
};
};
Gitorious.CommentForm.destroyAll = function () {
$("#inline_comment_form").fadeOut("fast").unbind("keydown");
$("#inline_comment_form").find(".cancel_button").unbind("click");
$("#inline_comment_form form").unbind("submit");
$(".selected-for-commenting").removeClass("selected-for-commenting");
$(".ui-selected").removeClass("ui-selected");
Gitorious.DiffBrowser.KeyNavigation.enable();
};
|
agpl-3.0
|
Bemujo/https-github.com-numenta-nupic
|
src/test/unit/algorithms/ConnectionsTest.cpp
|
15893
|
/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2014, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 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 Affero Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
/** @file
* Implementation of unit tests for Connections
*/
#include <fstream>
#include <iostream>
#include <nupic/algorithms/Connections.hpp>
#include "gtest/gtest.h"
using namespace std;
using namespace nupic;
using namespace nupic::algorithms::connections;
#define EPSILON 0.0000001
namespace {
void setupSampleConnections(Connections &connections)
{
Segment segment;
Synapse synapse;
Cell cell, presynapticCell;
cell.idx = 10;
segment = connections.createSegment(cell);
presynapticCell.idx = 150;
synapse = connections.createSynapse(segment, presynapticCell, 0.85);
presynapticCell.idx = 151;
synapse = connections.createSynapse(segment, presynapticCell, 0.15);
cell.idx = 20;
segment = connections.createSegment(cell);
presynapticCell.idx = 80;
synapse = connections.createSynapse(segment, presynapticCell, 0.85);
presynapticCell.idx = 81;
synapse = connections.createSynapse(segment, presynapticCell, 0.85);
presynapticCell.idx = 82;
synapse = connections.createSynapse(segment, presynapticCell, 0.85);
connections.updateSynapsePermanence(synapse, 0.15);
segment = connections.createSegment(cell);
presynapticCell.idx = 50;
synapse = connections.createSynapse(segment, presynapticCell, 0.85);
presynapticCell.idx = 51;
synapse = connections.createSynapse(segment, presynapticCell, 0.85);
presynapticCell.idx = 52;
synapse = connections.createSynapse(segment, presynapticCell, 0.15);
}
Activity computeSampleActivity(Connections &connections)
{
Cell cell;
vector<Cell> input;
cell.idx = 150; input.push_back(cell);
cell.idx = 151; input.push_back(cell);
cell.idx = 50; input.push_back(cell);
cell.idx = 52; input.push_back(cell);
cell.idx = 80; input.push_back(cell);
cell.idx = 81; input.push_back(cell);
cell.idx = 82; input.push_back(cell);
Activity activity = connections.computeActivity(input, 0.50, 2);
return activity;
}
/**
* Creates a segment, and makes sure that it got created on the correct cell.
*/
TEST(ConnectionsTest, testCreateSegment)
{
Connections connections(1024);
Segment segment;
Cell cell(10);
segment = connections.createSegment(cell);
ASSERT_EQ(segment.idx, 0);
ASSERT_EQ(segment.cell.idx, cell.idx);
segment = connections.createSegment(cell);
ASSERT_EQ(segment.idx, 1);
ASSERT_EQ(segment.cell.idx, cell.idx);
vector<Segment> segments = connections.segmentsForCell(cell);
ASSERT_EQ(segments.size(), 2);
for (SegmentIdx i = 0; i < (SegmentIdx)segments.size(); i++) {
ASSERT_EQ(segments[i].idx, i);
ASSERT_EQ(segments[i].cell.idx, cell.idx);
}
}
/**
* Creates many segments on a cell, until hits segment limit. Then creates
* another segment, and checks that it destroyed the least recently used
* segment and created a new one in its place.
*/
TEST(ConnectionsTest, testCreateSegmentReuse)
{
Connections connections(1024, 2);
Cell cell;
Segment segment;
vector<Segment> segments;
setupSampleConnections(connections);
auto numSegments = connections.numSegments();
Activity activity = computeSampleActivity(connections);
cell.idx = 20;
segment = connections.createSegment(cell);
// Should have reused segment with index 1
ASSERT_EQ(segment.idx, 1);
segments = connections.segmentsForCell(cell);
ASSERT_EQ(segments.size(), 2);
ASSERT_EQ(numSegments, connections.numSegments());
segment = connections.createSegment(cell);
// Should have reused segment with index 0
ASSERT_EQ(segment.idx, 0);
segments = connections.segmentsForCell(cell);
ASSERT_EQ(segments.size(), 2);
ASSERT_EQ(numSegments, connections.numSegments());
}
/**
* Creates a synapse, and makes sure that it got created on the correct
* segment, and that its data was correctly stored.
*/
TEST(ConnectionsTest, testCreateSynapse)
{
Connections connections(1024);
Cell cell(10), presynapticCell;
Segment segment = connections.createSegment(cell);
Synapse synapse;
presynapticCell.idx = 50;
synapse = connections.createSynapse(segment, presynapticCell, 0.34);
ASSERT_EQ(synapse.idx, 0);
ASSERT_EQ(synapse.segment.idx, segment.idx);
presynapticCell.idx = 150;
synapse = connections.createSynapse(segment, presynapticCell, 0.48);
ASSERT_EQ(synapse.idx, 1);
ASSERT_EQ(synapse.segment.idx, segment.idx);
vector<Synapse> synapses = connections.synapsesForSegment(segment);
ASSERT_EQ(synapses.size(), 2);
for (SynapseIdx i = 0; i < synapses.size(); i++) {
ASSERT_EQ(synapses[i].idx, i);
ASSERT_EQ(synapses[i].segment.idx, segment.idx);
ASSERT_EQ(synapses[i].segment.cell.idx, cell.idx);
}
SynapseData synapseData;
synapseData = connections.dataForSynapse(synapses[0]);
ASSERT_EQ(synapseData.presynapticCell.idx, 50);
ASSERT_NEAR(synapseData.permanence, (Permanence)0.34, EPSILON);
synapseData = connections.dataForSynapse(synapses[1]);
ASSERT_EQ(synapseData.presynapticCell.idx, 150);
ASSERT_NEAR(synapseData.permanence, (Permanence)0.48, EPSILON);
}
/**
* Creates a segment, destroys it, and makes sure it got destroyed along with
* all of its synapses.
*/
TEST(ConnectionsTest, testDestroySegment)
{
Connections connections(1024);
Cell cell;
Segment segment;
setupSampleConnections(connections);
auto numSegments = connections.numSegments();
cell.idx = 20;
segment.cell = cell;
segment.idx = 0;
connections.destroySegment(segment);
ASSERT_EQ(connections.numSegments(), numSegments-1);
ASSERT_THROW(connections.synapsesForSegment(segment);, runtime_error);
Activity activity = computeSampleActivity(connections);
ASSERT_EQ(activity.activeSegmentsForCell.size(), 0);
ASSERT_EQ(activity.numActiveSynapsesForSegment.size(), 2);
}
/**
* Creates a segment, creates a number of synapses on it, destroys a synapse,
* and makes sure it got destroyed.
*/
TEST(ConnectionsTest, testDestroySynapse)
{
Connections connections(1024);
Cell cell;
Segment segment;
Synapse synapse;
setupSampleConnections(connections);
auto numSynapses = connections.numSynapses();
cell.idx = 20;
segment.cell = cell;
segment.idx = 0;
synapse.segment = segment;
synapse.idx = 0;
connections.destroySynapse(synapse);
ASSERT_EQ(connections.numSynapses(), numSynapses-1);
vector<Synapse> synapses = connections.synapsesForSegment(segment);
ASSERT_EQ(synapses.size(), 2);
Activity activity = computeSampleActivity(connections);
ASSERT_EQ(activity.activeSegmentsForCell.size(), 0);
segment.cell.idx = 20; segment.idx = 0;
ASSERT_EQ(activity.numActiveSynapsesForSegment[segment], 1);
}
/**
* Creates a synapse and updates its permanence, and makes sure that its
* data was correctly updated.
*/
TEST(ConnectionsTest, testUpdateSynapsePermanence)
{
Connections connections(1024);
Cell cell(10), presynapticCell(50);
Segment segment = connections.createSegment(cell);
Synapse synapse = connections.createSynapse(segment, presynapticCell, 0.34);
connections.updateSynapsePermanence(synapse, 0.21);
SynapseData synapseData = connections.dataForSynapse(synapse);
ASSERT_NEAR(synapseData.permanence, (Real)0.21, EPSILON);
}
/**
* Creates a sample set of connections, and makes sure that getting the most
* active segment for a collection of cells returns the right segment.
*/
TEST(ConnectionsTest, testMostActiveSegmentForCells)
{
Connections connections(1024);
Segment segment;
Synapse synapse;
Cell cell, presynapticCell;
vector<Cell> cells;
vector<Cell> input;
cell.idx = 10; presynapticCell.idx = 150;
segment = connections.createSegment(cell);
synapse = connections.createSynapse(segment, presynapticCell, 0.34);
cell.idx = 20; presynapticCell.idx = 50;
segment = connections.createSegment(cell);
synapse = connections.createSynapse(segment, presynapticCell, 0.85);
Cell cell1(10), cell2(20);
cells.push_back(cell1);
cells.push_back(cell2);
Cell input1(50);
input.push_back(input1);
bool result = connections.mostActiveSegmentForCells(
cells, input, 0, segment);
ASSERT_EQ(result, true);
ASSERT_EQ(segment.cell.idx, 20);
ASSERT_EQ(segment.idx, 0);
}
/**
* Creates a sample set of connections, and makes sure that getting the most
* active segment for a collection of cells with no activity returns
* no segment.
*/
TEST(ConnectionsTest, testMostActiveSegmentForCellsNone)
{
Connections connections(1024);
Segment segment;
Synapse synapse;
Cell cell, presynapticCell;
vector<Cell> cells;
vector<Cell> input;
cell.idx = 10; presynapticCell.idx = 150;
segment = connections.createSegment(cell);
synapse = connections.createSynapse(segment, presynapticCell, 0.34);
cell.idx = 20; presynapticCell.idx = 50;
segment = connections.createSegment(cell);
synapse = connections.createSynapse(segment, presynapticCell, 0.85);
Cell cell1(10), cell2(20);
cells.push_back(cell1);
cells.push_back(cell2);
Cell input1(150);
input.push_back(input1);
bool result = connections.mostActiveSegmentForCells(
cells, input, 2, segment);
ASSERT_EQ(result, false);
}
/**
* Creates a sample set of connections, computes some activity for it,
* and checks that we can get the correct least recently used segment
* for a number of cells.
*
* Then, destroys the least recently used segment, computes more activity,
* creates another segment, and checks that the least recently used segment
* is not the newly created one.
*/
TEST(ConnectionsTest, testLeastRecentlyUsedSegment)
{
Connections connections(1024);
Cell cell;
Segment segment;
setupSampleConnections(connections);
cell.idx = 5;
ASSERT_EQ(connections.leastRecentlyUsedSegment(cell, segment), false);
cell.idx = 20;
ASSERT_EQ(connections.leastRecentlyUsedSegment(cell, segment), true);
ASSERT_EQ(segment.idx, 0);
computeSampleActivity(connections);
ASSERT_EQ(connections.leastRecentlyUsedSegment(cell, segment), true);
ASSERT_EQ(segment.idx, 1);
connections.destroySegment(segment);
ASSERT_EQ(connections.leastRecentlyUsedSegment(cell, segment), true);
ASSERT_EQ(segment.idx, 0);
computeSampleActivity(connections);
segment = connections.createSegment(cell);
ASSERT_EQ(connections.leastRecentlyUsedSegment(cell, segment), true);
ASSERT_EQ(segment.idx, 0);
}
/**
* Creates a sample set of connections, and makes sure that computing the
* activity for a collection of cells with no activity returns the right
* activity data.
*/
TEST(ConnectionsTest, testComputeActivity)
{
Connections connections(1024);
Cell cell;
Segment segment;
setupSampleConnections(connections);
Activity activity = computeSampleActivity(connections);
ASSERT_EQ(activity.activeSegmentsForCell.size(), 1);
cell.idx = 20;
ASSERT_EQ(activity.activeSegmentsForCell[cell].size(), 1);
segment = activity.activeSegmentsForCell[cell][0];
ASSERT_EQ(segment.idx, 0);
ASSERT_EQ(segment.cell.idx, 20);
ASSERT_EQ(activity.numActiveSynapsesForSegment.size(), 3);
segment.cell.idx = 10; segment.idx = 0;
ASSERT_EQ(activity.numActiveSynapsesForSegment[segment], 1);
segment.cell.idx = 20; segment.idx = 0;
ASSERT_EQ(activity.numActiveSynapsesForSegment[segment], 2);
segment.cell.idx = 20; segment.idx = 1;
ASSERT_EQ(activity.numActiveSynapsesForSegment[segment], 1);
}
/**
* Creates a sample set of connections, and makes sure that we can get the
* active segments from the computed activity.
*/
TEST(ConnectionsTest, testActiveSegments)
{
Connections connections(1024);
Cell cell;
Segment segment;
setupSampleConnections(connections);
Activity activity = computeSampleActivity(connections);
vector<Segment> activeSegments = connections.activeSegments(activity);
ASSERT_EQ(activeSegments.size(), 1);
segment = activeSegments[0];
ASSERT_EQ(segment.idx, 0);
ASSERT_EQ(segment.cell.idx, 20);
}
/**
* Creates a sample set of connections, and makes sure that we can get the
* active cells from the computed activity.
*/
TEST(ConnectionsTest, testActiveCells)
{
Connections connections(1024);
Cell cell;
Segment segment;
setupSampleConnections(connections);
Activity activity = computeSampleActivity(connections);
vector<Cell> activeCells = connections.activeCells(activity);
ASSERT_EQ(activeCells.size(), 1);
ASSERT_EQ(activeCells[0].idx, 20);
}
/**
* Creates a sample set of connections, and makes sure that we can get the
* correct number of segments.
*/
TEST(ConnectionsTest, testNumSegments)
{
Connections connections(1024);
setupSampleConnections(connections);
ASSERT_EQ(connections.numSegments(), 3);
}
/**
* Creates a sample set of connections, and makes sure that we can get the
* correct number of synapses.
*/
TEST(ConnectionsTest, testNumSynapses)
{
Connections connections(1024);
setupSampleConnections(connections);
ASSERT_EQ(connections.numSynapses(), 8);
}
/**
* Creates a sample set of connections with destroyed segments/synapses,
* computes sample activity, and makes sure that we can write to a
* filestream and read it back correctly.
*/
TEST(ConnectionsTest, testWriteRead)
{
const char* filename = "ConnectionsSerialization.tmp";
Connections c1(1024, 1024, 1024), c2;
setupSampleConnections(c1);
Segment segment;
Cell cell, presynapticCell;
cell.idx = 10;
presynapticCell.idx = 400;
segment = c1.createSegment(cell);
c1.createSynapse(segment, presynapticCell, 0.5);
c1.destroySegment(segment);
computeSampleActivity(c1);
ofstream os(filename, ios::binary);
c1.write(os);
os.close();
ifstream is(filename, ios::binary);
c2.read(is);
is.close();
ASSERT_EQ(c1, c2);
int ret = ::remove(filename);
NTA_CHECK(ret == 0) << "Failed to delete " << filename;
}
TEST(ConnectionsTest, testSaveLoad)
{
Connections c1(1024, 1024, 1024), c2;
setupSampleConnections(c1);
Cell cell(10), presynapticCell(400);
auto segment = c1.createSegment(cell);
c1.createSynapse(segment, presynapticCell, 0.5);
c1.destroySegment(segment);
computeSampleActivity(c1);
{
stringstream ss;
c1.save(ss);
c2.load(ss);
}
ASSERT_EQ(c1, c2);
}
} // end namespace nupic
|
agpl-3.0
|
auroreallibe/Silverpeas-Core
|
core-library/src/test/java/org/silverpeas/core/mail/SmtpMailTestSuite.java
|
1640
|
/*
* Copyright (C) 2000 - 2015 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.silverpeas.core.mail;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
/**
* Test suite to sequence the unit tests on the file processing API.
* As each unit tests works on the same file structure, it is required to sequence them so
* that they work on the filesystem each of their turn.
* @author mmoquillon
*/
@RunWith(Suite.class)
@Suite.SuiteClasses({
TestSmtpMailSendingMassive.class,
TestSmtpMailSending.class
})
public class SmtpMailTestSuite {
}
|
agpl-3.0
|
kobolabs/qt-everywhere-4.8.0
|
doc/src/snippets/splitterhandle/splitter.cpp
|
3038
|
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
** the names of its contributors may be used to endorse or promote
** products derived from this software without specific prior written
** permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtGui>
#include "splitter.h"
SplitterHandle::SplitterHandle(Qt::Orientation orientation, QSplitter *parent)
: QSplitterHandle(orientation, parent)
{
gradient.setColorAt(0.0, Qt::darkGreen);
gradient.setColorAt(0.25, Qt::white);
gradient.setColorAt(1.0, Qt::darkGreen);
}
//! [0]
void SplitterHandle::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
if (orientation() == Qt::Horizontal) {
gradient.setStart(rect().left(), rect().height()/2);
gradient.setFinalStop(rect().right(), rect().height()/2);
} else {
gradient.setStart(rect().width()/2, rect().top());
gradient.setFinalStop(rect().width()/2, rect().bottom());
}
painter.fillRect(event->rect(), QBrush(gradient));
}
//! [0]
Splitter::Splitter(Qt::Orientation orientation, QWidget *parent)
: QSplitter(orientation, parent)
{
}
//! [1]
QSplitterHandle *Splitter::createHandle()
{
return new SplitterHandle(orientation(), this);
}
//! [1]
|
lgpl-2.1
|
xwiki/xwiki-platform
|
xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/filter/XWikiAttachmentFilter.java
|
1120
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This 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 software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.xpn.xwiki.internal.filter;
import org.xwiki.filter.event.xwiki.XWikiWikiAttachmentFilter;
/**
*
* @version $Id$
* @since 6.2M1
*/
public interface XWikiAttachmentFilter extends XWikiWikiAttachmentFilter
{
}
|
lgpl-2.1
|
gallardo/opencms-core
|
src/org/opencms/flex/CmsFlexRequestKey.java
|
7689
|
/*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
*
* 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.
*
* For further information about Alkacon Software GmbH & Co. KG, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.flex;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsRequestContext;
import org.opencms.jsp.util.CmsJspStandardContextBean;
import org.opencms.jsp.util.CmsJspStandardContextBean.TemplateBean;
import org.opencms.loader.CmsTemplateContextManager;
import org.opencms.loader.I_CmsResourceLoader;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.util.CmsCollectionsGenericWrapper;
import org.opencms.util.CmsRequestUtil;
import org.opencms.util.CmsUUID;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
/**
* Describes the caching behaviour (or caching options) for a Flex request.<p>
*
* @since 6.0.0
*/
public class CmsFlexRequestKey {
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsFlexRequestKey.class);
/** The current container element. */
private String m_containerElement;
/** The request context this request was made in. */
private CmsRequestContext m_context;
/** The current detail view id. */
private CmsUUID m_detailViewId;
/** Stores the device this request was made with. */
private String m_device;
/** The (Flex) Http request this key was constructed for. */
private HttpServletRequest m_request;
/** The OpenCms resource that this key is used for. */
private String m_resource;
/**
* This constructor is used when building a cache key from a request.<p>
*
* The request contains several data items that are neccessary to construct
* the output. These items are e.g. the Query-String, the requested resource,
* the current time etc. etc.
* All required items are saved in the constructed cache - key.<p>
*
* @param req the request to construct the key for
* @param target the requested resource in the OpenCms VFS
* @param online must be true for an online resource, false for offline resources
*/
public CmsFlexRequestKey(HttpServletRequest req, String target, boolean online) {
// store the request
m_request = req;
// fetch the cms from the request
CmsObject cms = CmsFlexController.getCmsObject(req);
// store the request context
m_context = cms.getRequestContext();
// calculate the resource name
m_resource = CmsFlexCacheKey.getKeyName(m_context.addSiteRoot(target), online);
// calculate the device
m_device = OpenCms.getSystemInfo().getDeviceSelector().getDeviceType(req);
CmsJspStandardContextBean standardContext = CmsJspStandardContextBean.getInstance(req);
// get the current container element
String templateContextKey = "";
TemplateBean templateBean = (TemplateBean)(req.getAttribute(CmsTemplateContextManager.ATTR_TEMPLATE_BEAN));
if (templateBean != null) {
templateContextKey = templateBean.getName();
}
m_containerElement = standardContext.elementCachingHash() + "_tc_" + templateContextKey;
// get the current detail view id
m_detailViewId = standardContext.getDetailContentId();
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_FLEXREQUESTKEY_CREATED_NEW_KEY_1, m_resource));
}
}
/**
* Returns the request attributes.<p>
*
* @return the request attributes
*/
public Map<String, Object> getAttributes() {
Map<String, Object> attrs = CmsRequestUtil.getAtrributeMap(m_request);
if (attrs.size() == 0) {
return null;
}
return attrs;
}
/**
* Returns the current container element.<p>
*
* @return the current container element
*/
public String getContainerElement() {
return m_containerElement;
}
/**
* Returns the device.<p>
*
* @return the device
*/
public String getDevice() {
return m_device;
}
/**
* Returns the element.<p>
*
* @return the element
*/
public String getElement() {
return m_request.getParameter(I_CmsResourceLoader.PARAMETER_ELEMENT);
}
/**
* Returns the encoding.<p>
*
* @return the encoding
*/
public String getEncoding() {
return m_context.getEncoding();
}
/**
* Returns the ip.<p>
*
* @return the ip
*/
public String getIp() {
return m_context.getRemoteAddress();
}
/**
* Returns the locale.<p>
*
* @return the locale
*/
public String getLocale() {
return m_context.getLocale().toString();
}
/**
* Returns the parameters.<p>
*
* @return the parameters
*/
public Map<String, String[]> getParams() {
// get the params
Map<String, String[]> params = CmsCollectionsGenericWrapper.map(m_request.getParameterMap());
if (params.size() == 0) {
return null;
}
return params;
}
/**
* Returns the port.<p>
*
* @return the port
*/
public Integer getPort() {
return new Integer(m_request.getServerPort());
}
/**
* Returns the resource.<p>
*
* @return the resource
*/
public String getResource() {
return m_resource;
}
/**
* Returns the schemes.<p>
*
* @return the schemes
*/
public String getScheme() {
return m_request.getScheme().toLowerCase();
}
/**
* Returns the the current users session, or <code>null</code> if the current user
* has no session.<p>
*
* @return the current users session, or <code>null</code> if the current user has no session
*/
public HttpSession getSession() {
return m_request.getSession(false);
}
/**
* Returns the site root.<p>
*
* @return the site root
*/
public String getSite() {
return m_context.getSiteRoot();
}
/**
* Returns the uri.<p>
*
* @return the uri
*/
public String getUri() {
String uri = m_context.addSiteRoot(m_context.getUri());
if (m_detailViewId != null) {
uri += m_detailViewId.toString() + "/";
}
return uri;
}
/**
* Returns the user.<p>
*
* @return the user
*/
public String getUser() {
return m_context.getCurrentUser().getName();
}
}
|
lgpl-2.1
|
lnu/nhibernate-core
|
src/NHibernate/Transform/DistinctRootEntityResultTransformer.cs
|
2401
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace NHibernate.Transform
{
[Serializable]
public class DistinctRootEntityResultTransformer : IResultTransformer, ITupleSubsetResultTransformer
{
private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(DistinctRootEntityResultTransformer));
private static readonly object Hasher = new object();
internal sealed class Identity
{
internal readonly object entity;
internal Identity(object entity)
{
this.entity = entity;
}
public override bool Equals(object other)
{
Identity that = (Identity) other;
return ReferenceEquals(entity, that.entity);
}
public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(entity);
}
}
public object TransformTuple(object[] tuple, string[] aliases)
{
return tuple[tuple.Length - 1];
}
public IList TransformList(IList list)
{
IList result = (IList)Activator.CreateInstance(list.GetType());
var distinct = new HashSet<Identity>();
for (int i = 0; i < list.Count; i++)
{
object entity = list[i];
if (distinct.Add(new Identity(entity)))
{
result.Add(entity);
}
}
if (log.IsDebugEnabled())
{
log.Debug("transformed: {0} rows to: {1} distinct results", list.Count, result.Count);
}
return result;
}
public bool[] IncludeInTransform(String[] aliases, int tupleLength)
{
//return RootEntityResultTransformer.INSTANCE.includeInTransform(aliases, tupleLength);
var transformer = new RootEntityResultTransformer();
return transformer.IncludeInTransform(aliases, tupleLength);
}
public bool IsTransformedValueATupleElement(String[] aliases, int tupleLength)
{
//return RootEntityResultTransformer.INSTANCE.isTransformedValueATupleElement(null, tupleLength);
var transformer = new RootEntityResultTransformer();
return transformer.IsTransformedValueATupleElement(null, tupleLength);
}
public override bool Equals(object obj)
{
if (obj == null || obj.GetHashCode() != Hasher.GetHashCode())
{
return false;
}
// NH-3957: do not rely on hashcode alone.
// Must be the exact same type
return obj.GetType() == typeof(DistinctRootEntityResultTransformer);
}
public override int GetHashCode()
{
return Hasher.GetHashCode();
}
}
}
|
lgpl-2.1
|
EGP-CIG-REU/dealii
|
tests/physics/elasticity-standard_tensors_01.cc
|
5795
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2016 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, 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.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
// test standard tensor definitions
#include "../tests.h"
#include <deal.II/base/symmetric_tensor.h>
#include <deal.II/base/tensor.h>
#include <deal.II/base/logstream.h>
#include <deal.II/physics/elasticity/standard_tensors.h>
#include <fstream>
#include <iomanip>
using namespace dealii::Physics::Elasticity;
const double c10 = 10.0;
const double c01 = 20.0;
// Consider a Mooney-Rivlin material:
// psi = c10.(I1 - dim) + c01.(I2 - dim)
// where I1 = I1(C), I2 = I2(C)
// Then dI1/dC = I and dI2/dC = I1.I - C
// and S = 2 dpsi/dC
template<int dim>
SymmetricTensor<2,dim>
get_S (const Tensor<2,dim> &F)
{
const SymmetricTensor<2,dim> C = symmetrize(transpose(F)*F);
const double I1 = first_invariant(C);
return 2.0*c10*StandardTensors<dim>::I
+ 2.0*c01*(I1*StandardTensors<dim>::I - C);
}
// For isotropic media, tau = 2.b.dpsi/db == 2.dpsi/db . b
// where b = F.F^{T}, I1(b) == I1(C) and
// I2(b) == I2(C)
template<int dim>
SymmetricTensor<2,dim>
get_tau (const Tensor<2,dim> &F)
{
const SymmetricTensor<2,dim> b = symmetrize(F*transpose(F));
const double I1 = first_invariant(b);
const SymmetricTensor<2,dim>
tmp = 2.0*c10*StandardTensors<dim>::I
+ 2.0*c01*(I1*StandardTensors<dim>::I - b);
return symmetrize(static_cast< Tensor<2,dim> >(tmp)*static_cast< Tensor<2,dim> >(b));
}
template<int dim>
void
test_standard_tensors ()
{
SymmetricTensor<2,dim> t;
for (unsigned int i=0; i<dim; ++i)
for (unsigned int j=i; j<dim; ++j)
t[i][j] = dim*i+j+1.0;
// Check second-order identity tensor I:
AssertThrow (std::fabs (StandardTensors<dim>::I*t - trace(t)) < 1e-14,
ExcInternalError());
AssertThrow (std::fabs (t*StandardTensors<dim>::I - trace(t)) < 1e-14,
ExcInternalError());
// Check fourth-order identity tensor II:
AssertThrow (std::fabs ((StandardTensors<dim>::S*t - t).norm()) < 1e-14,
ExcInternalError());
AssertThrow (std::fabs ((t*StandardTensors<dim>::S - t).norm()) < 1e-14,
ExcInternalError());
// Check fourth-order tensor IxI:
AssertThrow (std::fabs ((StandardTensors<dim>::IxI*t - trace(t)*unit_symmetric_tensor<dim>()).norm()) < 1e-14,
ExcInternalError());
AssertThrow (std::fabs ((t*StandardTensors<dim>::IxI - trace(t)*unit_symmetric_tensor<dim>()).norm()) < 1e-14,
ExcInternalError());
// Check spatial deviatoric tensor dev_P:
AssertThrow (std::fabs ((StandardTensors<dim>::dev_P*t - (t - (trace(t)/dim)*unit_symmetric_tensor<dim>())).norm()) < 1e-14,
ExcInternalError());
AssertThrow (std::fabs ((t*StandardTensors<dim>::dev_P - (t - (trace(t)/dim)*unit_symmetric_tensor<dim>())).norm()) < 1e-14,
ExcInternalError());
// Check referential deviatoric tensor Dev_P:
Tensor<2,dim> F (unit_symmetric_tensor<dim>());
F[0][1] = 0.5;
F[1][0] = 0.25;
const Tensor<2,dim> F_inv = invert(F);
// Pull-back a fictitious stress tensor, project it onto a deviatoric space, and
// then push it forward again
// tau = F.S.F^{T} --> S = F^{-1}*tau*F^{-T}
const SymmetricTensor<2,dim> s = symmetrize(F_inv*static_cast< Tensor<2,dim> >(t)*transpose(F_inv));
const SymmetricTensor<2,dim> Dev_P_T_x_s = StandardTensors<dim>::Dev_P_T(F)*s;
const SymmetricTensor<2,dim> s_x_Dev_P = s*StandardTensors<dim>::Dev_P(F);
// Note: The extra factor J^{2/dim} arises due to the definition of Dev_P
// including the factor J^{-2/dim}. Ultimately the stress definitions
// for s,t do not align with those required to have the direct relationship
// s*Dev_P == dev_P*t. For this we would need S = 2.dW/dC|_{C=\bar{C}} and
// t = F.S.F^{T} and \bar{C} = det(F)^{-2/dim} F^{T}.F .
AssertThrow (std::fabs ((symmetrize(std::pow(determinant(F), 2.0/dim)*F*static_cast< Tensor<2,dim> >(s_x_Dev_P)*transpose(F)) - StandardTensors<dim>::dev_P*t).norm()) < 1e-14,
ExcInternalError());
AssertThrow (std::fabs ((symmetrize(std::pow(determinant(F), 2.0/dim)*F*static_cast< Tensor<2,dim> >(Dev_P_T_x_s)*transpose(F)) - StandardTensors<dim>::dev_P*t).norm()) < 1e-14,
ExcInternalError());
// Repeat the above exercise for a "real" material response
const Tensor<2,dim> F_bar = std::pow(determinant(F), -1.0/dim)*F;
const SymmetricTensor<2,dim> S_bar = get_S(F_bar);
const SymmetricTensor<2,dim> tau_bar = symmetrize(F_bar*static_cast< Tensor<2,dim> >(S_bar)*transpose(F_bar)); // Note: tau_bar = tau(F) |_{F = F_bar}
AssertThrow (std::fabs ((tau_bar - get_tau(F_bar)).norm()) < 1e-9,
ExcInternalError());
const SymmetricTensor<2,dim> S_iso = S_bar*StandardTensors<dim>::Dev_P(F);
const SymmetricTensor<2,dim> tau_iso = StandardTensors<dim>::dev_P*tau_bar;
AssertThrow (std::fabs ((symmetrize(F*static_cast< Tensor<2,dim> >(S_iso)*transpose(F)) - tau_iso).norm()) < 1e-9,
ExcInternalError());
}
int main ()
{
std::ofstream logfile("output");
deallog << std::setprecision(3);
deallog.attach(logfile);
deallog.threshold_double(1.e-10);
test_standard_tensors<2> ();
test_standard_tensors<3> ();
deallog << "OK" << std::endl;
}
|
lgpl-2.1
|
rlane/ncursesw-ruby
|
extconf.rb
|
3566
|
#!/usr/bin/env ruby
# ncurses-ruby is a ruby module for accessing the FSF's ncurses library
# (C) 2002, 2004 Tobias Peters <t-peters@users.berlios.de>
# (C) 2005, 2009 Tobias Herzke
#
# This module 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 of the License, or (at your option) any later version.
#
# This module is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this module; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# $Id: extconf.rb,v 1.14 2009/05/03 14:13:27 t-peters Exp $
require "mkmf"
$CFLAGS += " -g"
$CXXFLAGS = $CFLAGS
have_header("unistd.h")
have_header("locale.h")
if have_header("ncurses.h")
curses_header = "ncurses.h"
elsif have_header("ncurses/curses.h")
curses_header = "ncurses/curses.h"
elsif have_header("curses.h")
curses_header = "curses.h"
else
raise "ncurses header file not found"
end
if have_library("ncursesw", "wmove")
curses_lib = "ncursesw"
elsif have_library("pdcurses", "wmove")
curses_lib = "pdcurses"
else
raise "ncurses library not found"
end
have_func("newscr")
have_func("TABSIZE")
have_func("ESCDELAY")
have_func("keybound")
have_func("curses_version")
have_func("tigetstr")
have_func("getwin")
have_func("putwin")
have_func("ungetmouse")
have_func("mousemask")
have_func("wenclose")
have_func("mouseinterval")
have_func("wmouse_trafo")
have_func("mcprint")
have_func("has_key")
have_func("delscreen")
have_func("define_key")
have_func("keyok")
have_func("resizeterm")
have_func("use_default_colors")
have_func("use_extended_names")
have_func("wresize")
have_func("attr_on")
have_func("attr_off")
have_func("attr_set")
have_func("chgat")
have_func("color_set")
have_func("filter")
have_func("intrflush")
have_func("mvchgat")
have_func("mvhline")
have_func("mvvline")
have_func("mvwchgat")
have_func("mvwhline")
have_func("mvwvline")
have_func("noqiflush")
have_func("putp")
have_func("qiflush")
have_func("scr_dump")
have_func("scr_init")
have_func("scr_restore")
have_func("scr_set")
have_func("slk_attr_off")
have_func("slk_attr_on")
have_func("slk_attr")
have_func("slk_attr_set")
have_func("slk_color")
have_func("tigetflag")
have_func("tigetnum")
have_func("use_env")
have_func("vidattr")
have_func("vid_attr")
have_func("wattr_on")
have_func("wattr_off")
have_func("wattr_set")
have_func("wchgat")
have_func("wcolor_set")
have_func("getattrs")
puts "checking which debugging functions to wrap..."
have_func("_tracef")
have_func("_tracedump")
have_func("_nc_tracebits")
have_func("_traceattr")
have_func("_traceattr2")
have_func("_tracechar")
have_func("_tracechtype")
have_func("_tracechtype2")
have_func("_tracemouse")
puts "checking for other functions that appeared after ncurses version 5.0..."
have_func("assume_default_colors")
have_func("attr_get")
puts "checking for the panel library..."
if have_header("panel.h")
have_library("panelw", "panel_hidden")
end
puts "checking for the form library..."
if have_header("form.h")
have_library("formw", "new_form")
end
puts "checking for the menu library..."
if have_header("menu.h")
have_library("menu", "new_menu")
end
create_makefile('ncursesw_bin')
|
lgpl-2.1
|
EGP-CIG-REU/dealii
|
tests/sparsity/sparsity_tools_02.cc
|
1787
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2008 - 2016 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, 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.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
// apply SparsityTools::reorder_hierarchical to a graph that consists
// of two non-connected parts.
#include "../tests.h"
#include <deal.II/lac/sparsity_tools.h>
#include <deal.II/lac/dynamic_sparsity_pattern.h>
#include <iomanip>
#include <fstream>
int main ()
{
std::ofstream logfile("output");
logfile.setf(std::ios::fixed);
deallog << std::setprecision(3);
deallog.attach(logfile);
deallog.threshold_double(1.e-10);
DynamicSparsityPattern dsp (8,8);
for (unsigned int i=0; i<8; ++i)
dsp.add (i,i);
// create a graph with components 0,2 and 1,3 that are disconnected
dsp.add (0,2);
dsp.add (2,0);
dsp.add (1,3);
dsp.add (3,1);
// couple all indices between 3 and 7 except 4
for (unsigned int i=3; i<7; ++i)
for (unsigned int j=3; j<7; ++j)
if (i != 4 && j != 4)
dsp.add(i,j);
// indices 4,7 couple
dsp.add (4,7);
dsp.add (7,4);
// now find permutation
std::vector<types::global_dof_index> permutation(8);
SparsityTools::reorder_hierarchical (dsp, permutation);
for (unsigned int i=0; i<permutation.size(); ++i)
deallog << permutation[i] << std::endl;
}
|
lgpl-2.1
|
gallardo/opencms-core
|
src/org/opencms/jsp/CmsJspTagInclude.java
|
24854
|
/*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
*
* 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.
*
* For further information about Alkacon Software GmbH & Co. KG, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.jsp;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsPropertyDefinition;
import org.opencms.flex.CmsFlexController;
import org.opencms.flex.CmsFlexResponse;
import org.opencms.loader.CmsJspLoader;
import org.opencms.loader.CmsLoaderException;
import org.opencms.loader.I_CmsResourceLoader;
import org.opencms.loader.I_CmsResourceStringDumpLoader;
import org.opencms.main.CmsException;
import org.opencms.main.OpenCms;
import org.opencms.staticexport.CmsLinkManager;
import org.opencms.util.CmsCollectionsGenericWrapper;
import org.opencms.util.CmsRequestUtil;
import org.opencms.util.CmsStringUtil;
import org.opencms.workplace.editors.directedit.CmsDirectEditParams;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTagSupport;
/**
* Implementation of the <code><cms:include/></code> tag,
* used to include another OpenCms managed resource in a JSP.<p>
*
* @since 6.0.0
*/
public class CmsJspTagInclude extends BodyTagSupport implements I_CmsJspTagParamParent {
/** Serial version UID required for safe serialization. */
private static final long serialVersionUID = 705978510743164951L;
/** The value of the "attribute" attribute. */
private String m_attribute;
/** The value of the "cacheable" attribute. */
private boolean m_cacheable;
/** The value of the "editable" attribute. */
private boolean m_editable;
/** The value of the "element" attribute. */
private String m_element;
/** Map to save parameters to the include in. */
private Map<String, String[]> m_parameterMap;
/** The value of the "property" attribute. */
private String m_property;
/** The value of the "suffix" attribute. */
private String m_suffix;
/** The value of the "page" attribute. */
private String m_target;
/**
* Empty constructor, required for attribute value initialization.<p>
*/
public CmsJspTagInclude() {
super();
m_cacheable = true;
}
/**
* Adds parameters to a parameter Map that can be used for a http request.<p>
*
* @param parameters the Map to add the parameters to
* @param name the name to add
* @param value the value to add
* @param overwrite if <code>true</code>, a parameter in the map will be overwritten by
* a parameter with the same name, otherwise the request will have multiple parameters
* with the same name (which is possible in http requests)
*/
public static void addParameter(Map<String, String[]> parameters, String name, String value, boolean overwrite) {
// No null values allowed in parameters
if ((parameters == null) || (name == null) || (value == null)) {
return;
}
// Check if the parameter name (key) exists
if (parameters.containsKey(name) && (!overwrite)) {
// Yes: Check name values if value exists, if so do nothing, else add new value
String[] values = parameters.get(name);
String[] newValues = new String[values.length + 1];
System.arraycopy(values, 0, newValues, 0, values.length);
newValues[values.length] = value;
parameters.put(name, newValues);
} else {
// No: Add new parameter name / value pair
String[] values = new String[] {value};
parameters.put(name, values);
}
}
/**
* Includes the selected target.<p>
*
* @param context the current JSP page context
* @param target the target for the include, might be <code>null</code>
* @param element the element to select form the target might be <code>null</code>
* @param editable flag to indicate if the target is editable
* @param paramMap a map of parameters for the include, will be merged with the request
* parameters, might be <code>null</code>
* @param attrMap a map of attributes for the include, will be merged with the request
* attributes, might be <code>null</code>
* @param req the current request
* @param res the current response
*
* @throws JspException in case something goes wrong
*/
public static void includeTagAction(
PageContext context,
String target,
String element,
boolean editable,
Map<String, String[]> paramMap,
Map<String, Object> attrMap,
ServletRequest req,
ServletResponse res)
throws JspException {
// no locale and no cachable parameter are used by default
includeTagAction(context, target, element, null, editable, true, paramMap, attrMap, req, res);
}
/**
* Includes the selected target.<p>
*
* @param context the current JSP page context
* @param target the target for the include, might be <code>null</code>
* @param element the element to select form the target, might be <code>null</code>
* @param locale the locale to use for the selected element, might be <code>null</code>
* @param editable flag to indicate if the target is editable
* @param cacheable flag to indicate if the target should be cacheable in the Flex cache
* @param paramMap a map of parameters for the include, will be merged with the request
* parameters, might be <code>null</code>
* @param attrMap a map of attributes for the include, will be merged with the request
* attributes, might be <code>null</code>
* @param req the current request
* @param res the current response
*
* @throws JspException in case something goes wrong
*/
public static void includeTagAction(
PageContext context,
String target,
String element,
Locale locale,
boolean editable,
boolean cacheable,
Map<String, String[]> paramMap,
Map<String, Object> attrMap,
ServletRequest req,
ServletResponse res)
throws JspException {
// the Flex controller provides access to the internal OpenCms structures
CmsFlexController controller = CmsFlexController.getController(req);
if (target == null) {
// set target to default
target = controller.getCmsObject().getRequestContext().getUri();
}
// resolve possible relative URI
target = CmsLinkManager.getAbsoluteUri(target, controller.getCurrentRequest().getElementUri());
try {
// check if the target actually exists in the OpenCms VFS
controller.getCmsObject().readResource(target);
} catch (CmsException e) {
// store exception in controller and discontinue
controller.setThrowable(e, target);
throw new JspException(e);
}
// include direct edit "start" element (if enabled)
boolean directEditOpen = editable
&& CmsJspTagEditable.startDirectEdit(context, new CmsDirectEditParams(target, element));
// save old parameters from request
Map<String, String[]> oldParameterMap = CmsCollectionsGenericWrapper.map(req.getParameterMap());
try {
// each include will have it's unique map of parameters
Map<String, String[]> parameterMap = (paramMap == null)
? new HashMap<String, String[]>()
: new HashMap<String, String[]>(paramMap);
if (cacheable && (element != null)) {
// add template element selector for JSP templates (only required if cacheable)
addParameter(parameterMap, I_CmsResourceLoader.PARAMETER_ELEMENT, element, true);
}
// add parameters to set the correct element
controller.getCurrentRequest().addParameterMap(parameterMap);
// each include will have it's unique map of attributes
Map<String, Object> attributeMap = (attrMap == null)
? new HashMap<String, Object>()
: new HashMap<String, Object>(attrMap);
// add attributes to set the correct element
controller.getCurrentRequest().addAttributeMap(attributeMap);
if (cacheable) {
// use include with cache
includeActionWithCache(controller, context, target, parameterMap, attributeMap, req, res);
} else {
// no cache required
includeActionNoCache(controller, context, target, element, locale, req, res);
}
} finally {
// restore old parameter map (if required)
if (oldParameterMap != null) {
controller.getCurrentRequest().setParameterMap(oldParameterMap);
}
}
// include direct edit "end" element (if required)
if (directEditOpen) {
CmsJspTagEditable.endDirectEdit(context);
}
}
/**
* Includes the selected target without caching.<p>
*
* @param controller the current JSP controller
* @param context the current JSP page context
* @param target the target for the include
* @param element the element to select form the target
* @param locale the locale to select from the target
* @param req the current request
* @param res the current response
*
* @throws JspException in case something goes wrong
*/
private static void includeActionNoCache(
CmsFlexController controller,
PageContext context,
String target,
String element,
Locale locale,
ServletRequest req,
ServletResponse res)
throws JspException {
try {
// include is not cachable
CmsFile file = controller.getCmsObject().readFile(target);
CmsObject cms = controller.getCmsObject();
if (locale == null) {
locale = cms.getRequestContext().getLocale();
}
// get the loader for the requested file
I_CmsResourceLoader loader = OpenCms.getResourceManager().getLoader(file);
String content;
if (loader instanceof I_CmsResourceStringDumpLoader) {
// loader can provide content as a String
I_CmsResourceStringDumpLoader strLoader = (I_CmsResourceStringDumpLoader)loader;
content = strLoader.dumpAsString(cms, file, element, locale, req, res);
} else {
if (!(req instanceof HttpServletRequest) || !(res instanceof HttpServletResponse)) {
// http type is required for loader (no refactoring to avoid changes to interface)
CmsLoaderException e = new CmsLoaderException(
Messages.get().container(Messages.ERR_BAD_REQUEST_RESPONSE_0));
throw new JspException(e);
}
// get the bytes from the loader and convert them to a String
byte[] result = loader.dump(
cms,
file,
element,
locale,
(HttpServletRequest)req,
(HttpServletResponse)res);
String encoding;
if (loader instanceof CmsJspLoader) {
// in case of JSPs use the response encoding
encoding = res.getCharacterEncoding();
} else {
// use the encoding from the property or the system default if not available
encoding = cms.readPropertyObject(
file,
CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING,
true).getValue(OpenCms.getSystemInfo().getDefaultEncoding());
}
// If the included target issued a redirect null will be returned from loader
if (result == null) {
result = new byte[0];
}
content = new String(result, encoding);
}
// write the content String to the JSP output writer
context.getOut().print(content);
} catch (ServletException e) {
// store original Exception in controller in order to display it later
Throwable t = (e.getRootCause() != null) ? e.getRootCause() : e;
t = controller.setThrowable(t, target);
throw new JspException(t);
} catch (IOException e) {
// store original Exception in controller in order to display it later
Throwable t = controller.setThrowable(e, target);
throw new JspException(t);
} catch (CmsException e) {
// store original Exception in controller in order to display it later
Throwable t = controller.setThrowable(e, target);
throw new JspException(t);
}
}
/**
* Includes the selected target using the Flex cache.<p>
*
* @param controller the current JSP controller
* @param context the current JSP page context
* @param target the target for the include, might be <code>null</code>
* @param parameterMap a map of parameters for the include
* @param attributeMap a map of request attributes for the include
* @param req the current request
* @param res the current response
*
* @throws JspException in case something goes wrong
*/
private static void includeActionWithCache(
CmsFlexController controller,
PageContext context,
String target,
Map<String, String[]> parameterMap,
Map<String, Object> attributeMap,
ServletRequest req,
ServletResponse res)
throws JspException {
try {
// add the target to the include list (the list will be initialized if it is currently empty)
controller.getCurrentResponse().addToIncludeList(target, parameterMap, attributeMap);
// now use the Flex dispatcher to include the target (this will also work for targets in the OpenCms VFS)
controller.getCurrentRequest().getRequestDispatcher(target).include(req, res);
// write out a FLEX_CACHE_DELIMITER char on the page, this is used as a parsing delimiter later
context.getOut().print(CmsFlexResponse.FLEX_CACHE_DELIMITER);
} catch (ServletException e) {
// store original Exception in controller in order to display it later
Throwable t = (e.getRootCause() != null) ? e.getRootCause() : e;
t = controller.setThrowable(t, target);
throw new JspException(t);
} catch (IOException e) {
// store original Exception in controller in order to display it later
Throwable t = controller.setThrowable(e, target);
throw new JspException(t);
}
}
/**
* This methods adds parameters to the current request.<p>
*
* Parameters added here will be treated like parameters from the
* HttpRequest on included pages.<p>
*
* Remember that the value for a parameter in a HttpRequest is a
* String array, not just a simple String. If a parameter added here does
* not already exist in the HttpRequest, it will be added. If a parameter
* exists, another value will be added to the array of values. If the
* value already exists for the parameter, nothing will be added, since a
* value can appear only once per parameter.<p>
*
* @param name the name to add
* @param value the value to add
* @see org.opencms.jsp.I_CmsJspTagParamParent#addParameter(String, String)
*/
public void addParameter(String name, String value) {
// No null values allowed in parameters
if ((name == null) || (value == null)) {
return;
}
// Check if internal map exists, create new one if not
if (m_parameterMap == null) {
m_parameterMap = new HashMap<String, String[]>();
}
addParameter(m_parameterMap, name, value, false);
}
/**
* @return <code>EVAL_PAGE</code>
*
* @see javax.servlet.jsp.tagext.Tag#doEndTag()
*
* @throws JspException by interface default
*/
@Override
public int doEndTag() throws JspException {
ServletRequest req = pageContext.getRequest();
ServletResponse res = pageContext.getResponse();
if (CmsFlexController.isCmsRequest(req)) {
// this will always be true if the page is called through OpenCms
CmsObject cms = CmsFlexController.getCmsObject(req);
String target = null;
// try to find out what to do
if (m_target != null) {
// option 1: target is set with "page" or "file" parameter
target = m_target + getSuffix();
} else if (m_property != null) {
// option 2: target is set with "property" parameter
try {
String prop = cms.readPropertyObject(cms.getRequestContext().getUri(), m_property, true).getValue();
if (prop != null) {
target = prop + getSuffix();
}
} catch (RuntimeException e) {
// target must be null
target = null;
} catch (Exception e) {
// target will be null
e = null;
}
} else if (m_attribute != null) {
// option 3: target is set in "attribute" parameter
try {
String attr = (String)req.getAttribute(m_attribute);
if (attr != null) {
target = attr + getSuffix();
}
} catch (RuntimeException e) {
// target must be null
target = null;
} catch (Exception e) {
// target will be null
e = null;
}
} else {
// option 4: target might be set in body
String body = null;
if (getBodyContent() != null) {
body = getBodyContent().getString();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(body)) {
// target IS set in body
target = body + getSuffix();
}
// else target is not set at all, default will be used
}
}
// now perform the include action
includeTagAction(
pageContext,
target,
m_element,
null,
m_editable,
m_cacheable,
m_parameterMap,
CmsRequestUtil.getAtrributeMap(req),
req,
res);
release();
}
return EVAL_PAGE;
}
/**
* Returns <code>{@link #EVAL_BODY_BUFFERED}</code>.<p>
*
* @return <code>{@link #EVAL_BODY_BUFFERED}</code>
*
* @see javax.servlet.jsp.tagext.Tag#doStartTag()
*/
@Override
public int doStartTag() {
return EVAL_BODY_BUFFERED;
}
/**
* Returns the attribute.<p>
*
* @return the attribute
*/
public String getAttribute() {
return m_attribute != null ? m_attribute : "";
}
/**
* Returns the cacheable flag.<p>
*
* @return the cacheable flag
*/
public String getCacheable() {
return String.valueOf(m_cacheable);
}
/**
* Returns the editable flag.<p>
*
* @return the editable flag
*/
public String getEditable() {
return String.valueOf(m_editable);
}
/**
* Returns the element.<p>
*
* @return the element
*/
public String getElement() {
return m_element;
}
/**
* Returns the value of <code>{@link #getPage()}</code>.<p>
*
* @return the value of <code>{@link #getPage()}</code>
* @see #getPage()
*/
public String getFile() {
return getPage();
}
/**
* Returns the include page target.<p>
*
* @return the include page target
*/
public String getPage() {
return m_target != null ? m_target : "";
}
/**
* Returns the property.<p>
*
* @return the property
*/
public String getProperty() {
return m_property != null ? m_property : "";
}
/**
* Returns the suffix.<p>
*
* @return the suffix
*/
public String getSuffix() {
return m_suffix != null ? m_suffix : "";
}
/**
* @see javax.servlet.jsp.tagext.Tag#release()
*/
@Override
public void release() {
super.release();
m_target = null;
m_suffix = null;
m_property = null;
m_element = null;
m_parameterMap = null;
m_editable = false;
m_cacheable = true;
}
/**
* Sets the attribute.<p>
*
* @param attribute the attribute to set
*/
public void setAttribute(String attribute) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(attribute)) {
m_attribute = attribute;
}
}
/**
* Sets the cacheable flag.<p>
*
* Cachable is <code>true</code> by default.<p>
*
* @param cacheable the flag to set
*/
public void setCacheable(String cacheable) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(cacheable)) {
m_cacheable = Boolean.valueOf(cacheable).booleanValue();
}
}
/**
* Sets the editable flag.<p>
*
* Editable is <code>false</code> by default.<p>
*
* @param editable the flag to set
*/
public void setEditable(String editable) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(editable)) {
m_editable = Boolean.valueOf(editable).booleanValue();
}
}
/**
* Sets the element.<p>
*
* @param element the element to set
*/
public void setElement(String element) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(element)) {
m_element = element;
}
}
/**
* Sets the file, same as using <code>setPage()</code>.<p>
*
* @param file the file to set
* @see #setPage(String)
*/
public void setFile(String file) {
setPage(file);
}
/**
* Sets the include page target.<p>
*
* @param target the target to set
*/
public void setPage(String target) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(target)) {
m_target = target;
}
}
/**
* Sets the property.<p>
*
* @param property the property to set
*/
public void setProperty(String property) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(property)) {
m_property = property;
}
}
/**
* Sets the suffix.<p>
*
* @param suffix the suffix to set
*/
public void setSuffix(String suffix) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(suffix)) {
m_suffix = suffix.toLowerCase();
}
}
}
|
lgpl-2.1
|
openwayne/chaos_theory
|
mods/mobf_core/mobf/mgen_probab/direction_control.lua
|
18782
|
-------------------------------------------------------------------------------
-- Mob Framework Mod by Sapier
--
-- You may copy, use, modify or do nearly anything except removing this
-- copyright notice.
-- And of course you are NOT allow to pretend you have written it.
--
--! @file direction_control.lua
--! @brief functions for direction control in probabilistic movement gen
--! @copyright Sapier
--! @author Sapier
--! @date 2012-08-09
--
--! @ingroup mgen_probab
--! @{
-- Contact sapier a t gmx net
-------------------------------------------------------------------------------
--! @class direction_control
--! @brief functions for direction control in probabilistic movement gen
direction_control = {}
--!@}
-------------------------------------------------------------------------------
-- name: changeaccel(pos,entity,velocity)
--
--! @brief find a suitable new acceleration for mob
--! @memberof direction_control
--! @private
--
--! @param pos current position
--! @param entity mob to get acceleration for
--! @param current_velocity current velocity
--! @return {{ x/y/z accel} + jump flag really?
-------------------------------------------------------------------------------
function direction_control.changeaccel(pos,entity,current_velocity)
local maxtries = 5
local old_quality = environment.pos_quality(pos,entity)
local new_accel =
direction_control.get_random_acceleration(
entity.data.movement.min_accel,
entity.data.movement.max_accel,graphics.getyaw(entity),0)
local pos_predicted =
movement_generic.predict_next_block(pos,current_velocity,new_accel)
local new_quality = environment.pos_quality(pos_predicted,entity)
local prefered_state =
environment.evaluate_state( new_quality,
old_quality,
MQ_IN_MEDIA,
nil,
GQ_FULL,
SQ_POSSIBLE,
SQ_OK)
while not prefered_state do
dbg_mobf.pmovement_lvl1("MOBF: predicted pos " .. printpos(pos_predicted)
.. " isn't perfect " .. maxtries .. " tries left, state: "
.. new_quality.tostring(new_quality))
--don't loop forever get to save mode and try next time
if maxtries <= 0 then
dbg_mobf.pmovement_lvl1(
"MOBF: Aborting acceleration finding for this cycle due to max retries")
if state == "collision_jumpable" then
dbg_mobf.movement_lvl1("Returning "
..printpos(new_accel).." as new accel as mob may jump")
return new_accel
end
dbg_mobf.pmovement_lvl1(
"MOBF: Didn't find a suitable acceleration stopping movement: "
.. entity.data.name .. printpos(pos))
entity.object:setvelocity({x=0,y=0,z=0})
entity.dynamic_data.movement.started = false
--don't slow down mob
return { x=0,
y=0,
z=0 }
end
local probab = math.random()
--accept possible surface in rare cases
if probab < 0.3 then
local acceptable_state =
environment.evaluate_state(new_quality,
nil,
MQ_IN_MEDIA,
GQ_PARTIAL,
nil,
SQ_WRONG,
SQ_POSSIBLE)
if acceptable_state then
return new_accel
end
end
--accept possible surface in rare cases
if probab < 0.2 then
local acceptable_state =
environment.evaluate_state(new_quality,
nil,
MQ_IN_MEDIA,
nil,
GQ_FULL,
SQ_WRONG,
SQ_POSSIBLE)
if acceptable_state then
return new_accel
end
end
--try another acceleration
new_accel =
direction_control.get_random_acceleration(
entity.data.movement.min_accel,
entity.data.movement.max_accel,
graphics.getyaw(entity),1.57)
pos_predicted =
movement_generic.predict_next_block(pos,current_velocity,new_accel)
local prefered_state =
environment.evaluate_state( new_quality,
old_quality,
MQ_IN_MEDIA,
nil,
GQ_FULL,
SQ_POSSIBLE,
SQ_OK)
maxtries = maxtries -1
end
return new_accel
end
-------------------------------------------------------------------------------
-- name: get_random_acceleration(minaccel,maxaccel,current_yaw, minrotation)
--
--! @brief get a random x/z acceleration within a specified acceleration range
--! @memberof direction_control
--! @private
--
--! @param minaccel minimum acceleration to use
--! @param maxaccel maximum acceleration
--! @param current_yaw current orientation of mob
--! @param minrotation minimum rotation to perform
--! @return x/y/z acceleration
-------------------------------------------------------------------------------
function direction_control.get_random_acceleration(
minaccel,maxaccel,current_yaw, minrotation)
local direction = 1
if math.random() < 0.5 then
direction = -1
end
--calc random absolute value
local rand_accel = (math.random() * (maxaccel - minaccel)) + minaccel
local orientation_delta = mobf_gauss(math.pi/6,1/2)
--calculate new acceleration
local new_direction =
current_yaw + ((minrotation + orientation_delta) * direction)
local new_accel = mobf_calc_vector_components(new_direction,rand_accel)
dbg_mobf.pmovement_lvl3(" new direction: " .. new_direction ..
" old direction: " .. current_yaw ..
" new accel: " .. printpos(new_accel) ..
" orientation_delta: " .. orientation_delta)
return new_accel
end
-------------------------------------------------------------------------------
-- name: precheck_movement(entity,movement_state,pos_predicted,pos_predicted_quality)
--
--! @brief check if x/z movement results in invalid position and change
-- movement if required
--! @memberof direction_control
--
--! @param entity mob to generate movement
--! @param movement_state current state of movement
--! @param pos_predicted position mob will be next
--! @param pos_predicted_quality quality of predicted position
--! @return movement_state is changed!
-------------------------------------------------------------------------------
function direction_control.precheck_movement(
entity,movement_state,pos_predicted,pos_predicted_quality)
if movement_state.changed then
--someone already changed something
return
end
local prefered_quality =
environment.evaluate_state(pos_predicted_quality, LT_GOOD_POS)
-- ok predicted pos isn't as good as we'd wanted it to be let's find out why
if not prefered_quality then
local mob_is_safe =
environment.evaluate_state(pos_predicted_quality, LT_SAFE_POS)
if movement_state.current_quality == nil then
movement_state.current_quality = environment.pos_quality(
movement_state.basepos,
entity
)
end
if environment.compare_state(
movement_state.current_quality,
pos_predicted_quality) > 0
and
pos_predicted_quality.media_quality == MQ_IN_MEDIA then
--movement state is better than old one so we're fine
return
end
local walking_at_edge =
environment.evaluate_state(pos_predicted_quality, LT_SAFE_EDGE_POS)
if walking_at_edge then
--mob center still on ground but at worst walking at edge, do nothing
return
end
if (pos_predicted_quality.geometry_quality == GQ_NONE) then
dbg_mobf.pmovement_lvl2("MOBF: mob " .. entity.data.name .. " is dropping")
return
end
local drop_pending =
(pos_predicted_quality.geometry_quality <= GQ_PARTIAL and
pos_predicted_quality.center_geometry_quality <= GQ_NONE) or
pos_predicted_quality.surface_quality_min <= SQ_WATER
if drop_pending then
dbg_mobf.pmovement_lvl2(
"MOBF: mob " .. entity.data.name
.. " is going to walk on water or drop")
local new_pos =
environment.get_pos_same_level(movement_state.basepos,1,entity,
function(quality)
return environment.evaluate_state(quality,LT_SAFE_EDGE_POS)
end
)
if new_pos == nil then
dbg_mobf.pmovement_lvl2(
"MOBF: mob " .. entity.data.name .. " trying edge pos")
new_pos = environment.get_pos_same_level(movement_state.basepos,1,entity,
function(quality)
return environment.evaluate_state(quality,LT_EDGE_POS)
end
)
end
if new_pos == nil then
dbg_mobf.pmovement_lvl2(
"MOBF: mob " .. entity.data.name .. " trying relaxed surface")
new_pos = environment.get_pos_same_level(movement_state.basepos,1,entity,
function(quality)
return environment.evaluate_state(quality,
LT_EDGE_POS_GOOD_CENTER)
end
)
end
if new_pos == nil then
dbg_mobf.pmovement_lvl2(
"MOBF: mob " .. entity.data.name
.. " trying even more relaxed surface")
new_pos = environment.get_pos_same_level(movement_state.basepos,1,entity,
function(quality)
return environment.evaluate_state(quality,
LT_EDGE_POS_POSSIBLE_CENTER)
end
)
end
if new_pos ~= nil then
dbg_mobf.pmovement_lvl2(
"MOBF: trying to redirect to safe position .. " .. printpos(new_pos))
local speedfactor = 0.1
local speed_found = false
repeat
movement_state.accel_to_set =
movement_generic.get_accel_to(new_pos, entity, nil,
entity.data.movement.max_accel*speedfactor)
local next_pos =
movement_generic.predict_next_block(
movement_state.basepos,
movement_state.current_velocity,
movement_state.accel_to_set)
local next_quality = environment.pos_quality(
next_pos,
entity
)
if environment.evaluate_state(next_quality,
LT_EDGE_POS_POSSIBLE_CENTER) then
speed_found = true
end
speedfactor = speedfactor +0.1
until ( speedfactor > 1 or speed_found)
-- try if our state would at least keep same if we walk towards
-- the good pos
if not speed_found then
dbg_mobf.pmovement_lvl2("MOBF: trying min speed towards good pos")
movement_state.accel_to_set =
movement_generic.get_accel_to(new_pos, entity, nil,
entity.data.movement.min_accel)
local next_pos =
movement_generic.predict_next_block(
movement_state.basepos,
movement_state.current_velocity,
movement_state.accel_to_set)
local next_quality = environment.pos_quality(
next_pos,
entity
)
if ((mobf_calc_distance(next_pos,new_pos) <
(mobf_calc_distance(movement_state.basepos,new_pos))) and
environment.evaluate_state(next_quality,
LT_DROP_PENDING)) then
speed_found = true
end
end
if speed_found then
dbg_mobf.pmovement_lvl2("MOBF: redirecting to safe position .. "
.. printpos(new_pos))
movement_state.changed = true
return
end
end
if new_pos == nil then
dbg_mobf.pmovement_lvl2("MOBF: no suitable pos found")
else
dbg_mobf.pmovement_lvl2("MOBF: didn't find a way to suitable pos")
end
--no suitable pos found, if mob is safe atm just stop it
if mob_is_safe then
if movement_state.current_quality == GQ_FULL then
local targetpos = {x= movement_state.basepos.x,
y=movement_state.basepos.y,
z=movement_state.basepos.z}
targetpos.x = targetpos.x - movement_state.current_velocity.x
targetpos.z = targetpos.z - movement_state.current_velocity.z
movement_state.accel_to_set =
movement_generic.get_accel_to(targetpos, entity, nil,
entity.data.movement.min_accel)
dbg_mobf.pmovement_lvl2(
"MOBF: good pos, slowing down")
movement_state.changed = true
return
else --stop immediatlely
entity.object:setvelocity({x=0,y=0,z=0})
movement_state.accel_to_set = {x=0,y=nil,z=0}
dbg_mobf.pmovement_lvl2(
"MOBF: stopping at safe pos")
movement_state.changed = true
return
end
end
dbg_mobf.pmovement_lvl2("MOBF: mob " .. entity.data.name ..
" didn't find a way to fix drop trying random")
--make mgen change direction randomly
movement_state.force_change = true
return
end
--check if mob is going to be somewhere where it can't be
if pos_predicted_quality.media_quality ~= MQ_IN_MEDIA then
dbg_mobf.pmovement_lvl2("MOBF: collision pending "
.. printpos(movement_state.basepos) .. "-->"
.. printpos(pos_predicted))
--try to find a better position at same level
local new_pos =
environment.get_suitable_pos_same_level(movement_state.basepos,1,entity)
if new_pos == nil then
new_pos =
environment.get_suitable_pos_same_level(
movement_state.basepos,1,entity,true)
end
--there is at least one direction to go
if new_pos ~= nil then
dbg_mobf.pmovement_lvl2("MOBF: mob " ..entity.data.name
.. " redirecting to:" .. printpos(new_pos))
local new_predicted_state = nil
local new_predicted_pos = nil
for i=1,5,1 do
movement_state.accel_to_set =
movement_generic.get_accel_to(new_pos,entity)
--TODO check if acceleration is enough
new_predicted_pos =
movement_generic.predict_enter_next_block( entity,
movement_state.basepos,
movement_state.current_velocity,
movement_state.accel_to_set)
new_predicted_state = environment.pos_quality(
new_predicted_pos,
entity
)
if new_predicted_state.media_quality == MQ_IN_MEDIA then
break
end
end
if new_predicted_state.media_quality ~= MQ_IN_MEDIA then
movement_state.accel_to_set = movement_state.current_acceleration
dbg_mobf.pmovement_lvl2("MOBF: mob " ..entity.data.name
.. " acceleration not enough to avoid collision try to jump")
if math.random() <
( entity.dynamic_data.movement.mpattern.jump_up *
PER_SECOND_CORRECTION_FACTOR) then
local upper_pos = {
x= pos_predicted.x,
y= pos_predicted.y +1,
z= pos_predicted.z
}
local upper_quality = environment.pos_quality(
upper_pos,
entity
)
if environment.evaluate_state( upper_quality,LT_EDGE_POS) then
entity.object:setvelocity(
{x=movement_state.current_velocity.x,
y=5,
z=movement_state.current_velocity.z})
end
end
end
movement_state.changed = true
return
end
--try to find a better position above
new_pos = environment.get_suitable_pos_same_level({ x=movement_state.basepos.x,
y=movement_state.basepos.y+1,
z=movement_state.basepos.z},
1,entity)
if new_pos == nil then
new_pos = environment.get_suitable_pos_same_level({ x=movement_state.basepos.x,
y=movement_state.basepos.y+1,
z=movement_state.basepos.z},
1,entity)
end
if new_pos ~= nil then
dbg_mobf.pmovement_lvl2("MOBF: mob " ..entity.data.name
.. " seems to be locked in, jumping to:" .. printpos(new_pos))
entity.object:setvelocity({x=0,
y=5.5,
z=0})
movement_state.accel_to_set = movement_generic.get_accel_to(new_pos,entity)
movement_state.changed = true
return
end
dbg_mobf.pmovement_lvl2("MOBF: mob " ..entity.data.name
.. " unable to fix collision try random")
--a collision is going to happen force change of direction
movement_state.force_change = true
return
end
local suboptimal_surface =
environment.evaluate_state( pos_predicted_quality,
{ old_state=nil,
min_media=MQ_IN_MEDIA,
min_geom=GQ_PARTIAL,
min_geom_center=nil,
min_min_surface=SQ_WRONG,
min_max_surface=SQ_POSSIBLE,
min_center_surface=nil })
if suboptimal_surface then
dbg_mobf.pmovement_lvl2(
"MOBF: suboptimal positiond detected trying to find better pos")
--try to find a better position at same level
local new_pos =
environment.get_suitable_pos_same_level(
movement_state.basepos,1,entity)
if new_pos ~= nil then
dbg_mobf.pmovement_lvl2(
"MOBF: redirecting to better position .. " .. printpos(new_pos))
movement_state.accel_to_set = movement_generic.get_accel_to(new_pos,entity)
movement_state.changed = true
return
else
-- pos isn't critical don't do anything
return
end
end
local geom_ok =
environment.evaluate_state( pos_predicted_quality,
{ old_state=nil,
min_media=MQ_IN_MEDIA,
min_geom=GQ_PARTIAL,
min_geom_center=nil,
min_min_surface=nil,
min_max_surface=nil,
min_center_surface=nil })
if geom_ok and
pos_predicted_quality.surface_quality_max == SQ_WRONG then
dbg_mobf.pmovement_lvl2(
"MOBF: wrong surface detected trying to find better pos")
local new_pos =
environment.get_suitable_pos_same_level(
movement_state.basepos,1,entity)
if new_pos == nil then
new_pos =
environment.get_suitable_pos_same_level(
movement_state.basepos,2,entity)
end
if new_pos ~= nil then
dbg_mobf.pmovement_lvl2(
"MOBF: redirecting to better position .. " .. printpos(new_pos))
movement_state.accel_to_set =
movement_generic.get_accel_to(new_pos,entity)
movement_state.changed = true
return
else
--try generic
movement_state.force_change = true
return
end
end
dbg_mobf.pmovement_lvl2("MOBF: Unhandled suboptimal state:"
.. pos_predicted_quality.tostring(pos_predicted_quality))
movement_state.force_change = true
end
end
-------------------------------------------------------------------------------
-- name: random_movement_handler(entity,movement_state)
--
--! @brief generate a random y-movement
--! @memberof direction_control
--
--! @param entity mob to apply random jump
--! @param movement_state current movement state
--! @return movement_state is modified!
-------------------------------------------------------------------------------
function direction_control.random_movement_handler(entity,movement_state)
dbg_mobf.pmovement_lvl3("MOBF: random movement handler called")
local rand_value = math.random()
local max_value =
entity.dynamic_data.movement.mpattern.random_acceleration_change
* PER_SECOND_CORRECTION_FACTOR
if movement_state.changed == false and
(rand_value < max_value or
movement_state.force_change) then
movement_state.accel_to_set = direction_control.changeaccel(movement_state.basepos,
entity,movement_state.current_velocity)
if movement_state.accel_to_set ~= nil then
--retain current y acceleration
movement_state.accel_to_set.y = movement_state.current_acceleration.y
movement_state.changed = true
end
dbg_mobf.pmovement_lvl1("MOBF: randomly changing speed from "..
printpos(movement_state.current_acceleration).." to "..
printpos(movement_state.accel_to_set))
else
dbg_mobf.pmovement_lvl3("MOBF:" .. entity.data.name ..
" not changing speed random: " .. rand_value .." >= " .. max_value)
end
end
|
lgpl-2.1
|
mfherbst/spack
|
var/spack/repos/builtin/packages/petsc/package.py
|
16880
|
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# 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 terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
import os
import sys
from spack import *
class Petsc(Package):
"""PETSc is a suite of data structures and routines for the scalable
(parallel) solution of scientific applications modeled by partial
differential equations.
"""
homepage = "http://www.mcs.anl.gov/petsc/index.html"
url = "http://ftp.mcs.anl.gov/pub/petsc/release-snapshots/petsc-3.5.3.tar.gz"
git = "https://bitbucket.org/petsc/petsc.git"
maintainers = ['balay', 'barrysmith', 'jedbrown']
version('develop', branch='master')
version('xsdk-0.2.0', tag='xsdk-0.2.0')
version('3.9.3', '7b71d705f66f9961cb0e2da3f9da79a1')
version('3.9.2', '8bedc0cd8c8603d54bfd99a6e8f77b3d')
version('3.9.1', 'd3a229a188dbeef9b3f29b9a63622fad')
version('3.9.0', '34b8a81814ca050a96d58e53a2f0ac7a')
version('3.8.4', 'd7767fe2919536aa393eb22841899306')
version('3.8.3', '322cbcf2a0f7b7bad562643b05d66f11')
version('3.8.2', '00666e1c4cbfa8dd6eebf91ff8180f79')
version('3.8.1', '3ed75c1147800fc156fe1f1e515a68a7')
version('3.8.0', '02680f1f78a0d4c5a9de80a366793eb8')
version('3.7.7', 'c2cfb76677d32839810c4cf51a2f9cf5')
version('3.7.6', '977aa84b85aa3146c695592cd0a11057')
version('3.7.5', 'f00f6e6a3bac39052350dd47194b58a3')
version('3.7.4', 'aaf94fa54ef83022c14091f10866eedf')
version('3.7.2', '50da49867ce7a49e7a0c1b37f4ec7b34')
version('3.6.4', '7632da2375a3df35b8891c9526dbdde7')
version('3.6.3', '91dd3522de5a5ef039ff8f50800db606')
version('3.5.3', 'd4fd2734661e89f18ac6014b5dd1ef2f')
version('3.5.2', 'ad170802b3b058b5deb9cd1f968e7e13')
version('3.5.1', 'a557e029711ebf425544e117ffa44d8f')
version('3.4.4', '7edbc68aa6d8d6a3295dd5f6c2f6979d')
variant('shared', default=True,
description='Enables the build of shared libraries')
variant('mpi', default=True, description='Activates MPI support')
variant('double', default=True,
description='Switches between single and double precision')
variant('complex', default=False, description='Build with complex numbers')
variant('debug', default=False, description='Compile in debug mode')
variant('metis', default=True,
description='Activates support for metis and parmetis')
variant('hdf5', default=True,
description='Activates support for HDF5 (only parallel)')
variant('hypre', default=True,
description='Activates support for Hypre (only parallel)')
# Mumps is disabled by default, because it depends on Scalapack
# which is not portable to all HPC systems
variant('mumps', default=False,
description='Activates support for MUMPS (only parallel'
' and 32bit indices)')
variant('superlu-dist', default=True,
description='Activates support for SuperluDist (only parallel)')
variant('trilinos', default=False,
description='Activates support for Trilinos (only parallel)')
variant('int64', default=False,
description='Compile with 64bit indices')
variant('clanguage', default='C', values=('C', 'C++'),
description='Specify C (recommended) or C++ to compile PETSc',
multi=False)
variant('suite-sparse', default=False,
description='Activates support for SuiteSparse')
# 3.8.0 has a build issue with MKL - so list this conflict explicitly
conflicts('^intel-mkl', when='@3.8.0')
# temporary workaround Clang 8.1.0 with XCode 8.3 on macOS, see
# https://bitbucket.org/petsc/petsc/commits/4f290403fdd060d09d5cb07345cbfd52670e3cbc
# the patch is an adaptation of the original commit to 3.7.5
if sys.platform == "darwin":
patch('macos-clang-8.1.0.diff',
when='@3.7.5%clang@8.1.0:')
patch('pkg-config-3.7.6-3.8.4.diff', when='@3.7.6:3.8.4')
# Virtual dependencies
# Git repository needs sowing to build Fortran interface
depends_on('sowing', when='@develop')
# PETSc, hypre, superlu_dist when built with int64 use 32 bit integers
# with BLAS/LAPACK
depends_on('blas')
depends_on('lapack')
depends_on('mpi', when='+mpi')
# Build dependencies
depends_on('python@2.6:2.8', type='build')
# Other dependencies
depends_on('metis@5:~int64+real64', when='@:3.7.99+metis~int64+double')
depends_on('metis@5:~int64', when='@:3.7.99+metis~int64~double')
depends_on('metis@5:+int64+real64', when='@:3.7.99+metis+int64+double')
depends_on('metis@5:+int64', when='@:3.7.99+metis+int64~double')
# petsc-3.8+ uses default (float) metis with any (petsc) precision
depends_on('metis@5:~int64', when='@3.8:+metis~int64')
depends_on('metis@5:+int64', when='@3.8:+metis+int64')
depends_on('hdf5+mpi+hl', when='+hdf5+mpi')
depends_on('zlib', when='+hdf5')
depends_on('parmetis', when='+metis+mpi')
# Hypre does not support complex numbers.
# Also PETSc prefer to build it without internal superlu, likely due to
# conflict in headers see
# https://bitbucket.org/petsc/petsc/src/90564b43f6b05485163c147b464b5d6d28cde3ef/config/BuildSystem/config/packages/hypre.py
depends_on('hypre@:2.13.99~internal-superlu~int64', when='@:3.8.99+hypre+mpi~complex~int64')
depends_on('hypre@:2.13.99~internal-superlu+int64', when='@:3.8.99+hypre+mpi~complex+int64')
depends_on('hypre@2.14:~internal-superlu~int64', when='@3.9:+hypre+mpi~complex~int64')
depends_on('hypre@2.14:~internal-superlu+int64', when='@3.9+hypre+mpi~complex+int64')
depends_on('hypre@xsdk-0.2.0~internal-superlu+int64', when='@xsdk-0.2.0+hypre+mpi~complex+int64')
depends_on('hypre@xsdk-0.2.0~internal-superlu~int64', when='@xsdk-0.2.0+hypre+mpi~complex~int64')
depends_on('hypre@develop~internal-superlu+int64', when='@develop+hypre+mpi~complex+int64')
depends_on('hypre@develop~internal-superlu~int64', when='@develop+hypre+mpi~complex~int64')
depends_on('superlu-dist@:4.3~int64', when='@3.4.4:3.6.4+superlu-dist+mpi~int64')
depends_on('superlu-dist@:4.3+int64', when='@3.4.4:3.6.4+superlu-dist+mpi+int64')
depends_on('superlu-dist@5.0.0:~int64', when='@3.7:3.7.99+superlu-dist+mpi~int64')
depends_on('superlu-dist@5.0.0:+int64', when='@3.7:3.7.99+superlu-dist+mpi+int64')
depends_on('superlu-dist@5.2:5.2.99~int64', when='@3.8:3.9.99+superlu-dist+mpi~int64')
depends_on('superlu-dist@5.2:5.2.99+int64', when='@3.8:3.9.99+superlu-dist+mpi+int64')
depends_on('superlu-dist@xsdk-0.2.0~int64', when='@xsdk-0.2.0+superlu-dist+mpi~int64')
depends_on('superlu-dist@xsdk-0.2.0+int64', when='@xsdk-0.2.0+superlu-dist+mpi+int64')
depends_on('superlu-dist@develop~int64', when='@develop+superlu-dist+mpi~int64')
depends_on('superlu-dist@develop+int64', when='@develop+superlu-dist+mpi+int64')
depends_on('mumps+mpi', when='+mumps+mpi~int64')
depends_on('scalapack', when='+mumps+mpi~int64')
depends_on('trilinos@12.6.2:', when='@3.7.0:+trilinos+mpi')
depends_on('trilinos@xsdk-0.2.0', when='@xsdk-0.2.0+trilinos+mpi')
depends_on('trilinos@develop', when='@xdevelop+trilinos+mpi')
depends_on('suite-sparse', when='+suite-sparse')
def mpi_dependent_options(self):
if '~mpi' in self.spec:
compiler_opts = [
'--with-cc=%s' % os.environ['CC'],
'--with-cxx=%s' % (os.environ['CXX']
if self.compiler.cxx is not None else '0'),
'--with-fc=%s' % (os.environ['FC']
if self.compiler.fc is not None else '0'),
'--with-mpi=0'
]
error_message_fmt = \
'\t{library} support requires "+mpi" to be activated'
# If mpi is disabled (~mpi), it's an error to have any of these
# enabled. This generates a list of any such errors.
errors = [
error_message_fmt.format(library=x)
for x in ('hdf5', 'hypre', 'parmetis', 'mumps', 'superlu-dist')
if ('+' + x) in self.spec]
if errors:
errors = ['incompatible variants given'] + errors
raise RuntimeError('\n'.join(errors))
else:
compiler_opts = [
'--with-cc=%s' % self.spec['mpi'].mpicc,
'--with-cxx=%s' % self.spec['mpi'].mpicxx,
'--with-fc=%s' % self.spec['mpi'].mpifc
]
return compiler_opts
def install(self, spec, prefix):
options = ['--with-ssl=0',
'--with-x=0',
'--download-c2html=0',
'--download-sowing=0',
'--download-hwloc=0',
'COPTFLAGS=',
'FOPTFLAGS=',
'CXXOPTFLAGS=']
options.extend(self.mpi_dependent_options())
options.extend([
'--with-precision=%s' % (
'double' if '+double' in spec else 'single'),
'--with-scalar-type=%s' % (
'complex' if '+complex' in spec else 'real'),
'--with-shared-libraries=%s' % ('1' if '+shared' in spec else '0'),
'--with-debugging=%s' % ('1' if '+debug' in spec else '0'),
'--with-64-bit-indices=%s' % ('1' if '+int64' in spec else '0')
])
# Make sure we use exactly the same Blas/Lapack libraries
# across the DAG. To that end list them explicitly
lapack_blas = spec['lapack'].libs + spec['blas'].libs
options.extend([
'--with-blas-lapack-lib=%s' % lapack_blas.joined()
])
if 'trilinos' in spec:
options.append('--with-cxx-dialect=C++11')
if spec.satisfies('^trilinos+boost'):
options.append('--with-boost=1')
if self.spec.satisfies('clanguage=C++'):
options.append('--with-clanguage=C++')
else:
options.append('--with-clanguage=C')
# Help PETSc pick up Scalapack from MKL:
if 'scalapack' in spec:
scalapack = spec['scalapack'].libs
options.extend([
'--with-scalapack-lib=%s' % scalapack.joined(),
'--with-scalapack=1'
])
else:
options.extend([
'--with-scalapack=0'
])
# Activates library support if needed
for library in ('metis', 'hdf5', 'hypre', 'parmetis',
'mumps', 'trilinos'):
options.append(
'--with-{library}={value}'.format(
library=library, value=('1' if library in spec else '0'))
)
if library in spec:
options.append(
'--with-{library}-dir={path}'.format(
library=library, path=spec[library].prefix)
)
# PETSc does not pick up SuperluDist from the dir as they look for
# superlu_dist_4.1.a
if 'superlu-dist' in spec:
options.extend([
'--with-superlu_dist-include=%s' %
spec['superlu-dist'].prefix.include,
'--with-superlu_dist-lib=%s' %
join_path(spec['superlu-dist'].prefix.lib,
'libsuperlu_dist.a'),
'--with-superlu_dist=1'
])
else:
options.append(
'--with-superlu_dist=0'
)
# SuiteSparse: configuring using '--with-suitesparse-dir=...' has some
# issues, so specify directly the include path and the libraries.
if '+suite-sparse' in spec:
ss_spec = 'suite-sparse:umfpack,klu,cholmod,btf,ccolamd,colamd,' \
'camd,amd,suitesparseconfig'
options.extend([
'--with-suitesparse-include=%s' % spec[ss_spec].prefix.include,
'--with-suitesparse-lib=%s' % spec[ss_spec].libs.ld_flags,
'--with-suitesparse=1'
])
else:
options.append('--with-suitesparse=0')
# zlib: configuring using '--with-zlib-dir=...' has some issues with
# SuiteSparse so specify directly the include path and the libraries.
if 'zlib' in spec:
options.extend([
'--with-zlib-include=%s' % spec['zlib'].prefix.include,
'--with-zlib-lib=%s' % spec['zlib'].libs.ld_flags,
'--with-zlib=1'
])
else:
options.append('--with-zlib=0')
python('configure', '--prefix=%s' % prefix, *options)
# PETSc has its own way of doing parallel make.
make('MAKE_NP=%s' % make_jobs, parallel=False)
make("install")
# solve Poisson equation in 2D to make sure nothing is broken:
if ('mpi' in spec) and self.run_tests:
with working_dir('src/ksp/ksp/examples/tutorials'):
env['PETSC_DIR'] = self.prefix
cc = Executable(spec['mpi'].mpicc)
cc('ex50.c', '-I%s' % prefix.include, '-L%s' % prefix.lib,
'-lpetsc', '-lm', '-o', 'ex50')
run = Executable(join_path(spec['mpi'].prefix.bin, 'mpirun'))
# For Spectrum MPI, if -np is omitted, the default behavior is
# to assign one process per process slot, where the default
# process slot allocation is one per core. On systems with
# many cores, the number of processes can exceed the size of
# the grid specified when the testcase is run and the test case
# fails. Specify a small number of processes to prevent
# failure.
# For more information about Spectrum MPI invocation, see URL
# https://www.ibm.com/support/knowledgecenter/en/SSZTET_10.1.0/smpi02/smpi02_mpirun_options.html
if ('spectrum-mpi' in spec):
run.add_default_arg('-np')
run.add_default_arg('4')
run('ex50', '-da_grid_x', '4', '-da_grid_y', '4')
if 'superlu-dist' in spec:
run('ex50',
'-da_grid_x', '4',
'-da_grid_y', '4',
'-pc_type', 'lu',
'-pc_factor_mat_solver_package', 'superlu_dist')
if 'mumps' in spec:
run('ex50',
'-da_grid_x', '4',
'-da_grid_y', '4',
'-pc_type', 'lu',
'-pc_factor_mat_solver_package', 'mumps')
if 'hypre' in spec:
run('ex50',
'-da_grid_x', '4',
'-da_grid_y', '4',
'-pc_type', 'hypre',
'-pc_hypre_type', 'boomeramg')
def setup_environment(self, spack_env, run_env):
# configure fails if these env vars are set outside of Spack
spack_env.unset('PETSC_DIR')
spack_env.unset('PETSC_ARCH')
# Set PETSC_DIR in the module file
run_env.set('PETSC_DIR', self.prefix)
run_env.unset('PETSC_ARCH')
def setup_dependent_environment(self, spack_env, run_env, dependent_spec):
# Set up PETSC_DIR for everyone using PETSc package
spack_env.set('PETSC_DIR', self.prefix)
spack_env.unset('PETSC_ARCH')
@property
def headers(self):
return find_headers('petsc', self.prefix.include, recursive=False) \
or None # return None to indicate failure
# For the 'libs' property - use the default handler.
|
lgpl-2.1
|
kaltsi/qt-mobility
|
src/sensors/qtapsensor.cpp
|
7760
|
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qtapsensor.h"
#include "qtapsensor_p.h"
QTM_BEGIN_NAMESPACE
IMPLEMENT_READING(QTapReading)
/*!
\class QTapReading
\ingroup sensors_reading
\inmodule QtSensors
\since 1.0
\brief The QTapReading class represents one reading from the
tap sensor.
\section2 QTapReading Units
The tap sensor registers tap events along the 3 axes that originate from the phone.
The axes are arranged as follows.
\image sensors-coordinates2.jpg
By default it returns only double tap events. The QTapSensor::returnDoubleTapEvents property
must be set to false to return individual tap events.
*/
/*!
\enum QTapReading::TapDirection
The tap direction is indicated using flags. Applications should check for the presence of
a particular flag as multiple flags may be set at once.
The X, Y and Z flags allow an app to check for taps along an axis without caring about the
direction.
\code
if (reading->tapDirection()&QTapReading::X) {
...
}
\endcode
The *_Pos and *_Neg flags allow checking for taps in a specific direction. Note that some
devices cannot determine the direction of a tap and will set both the _Pos and _Neg flag for
the detected axis. Previous versions of the API did not allow this. Applications that check
for the _Pos and _Neg flags as values should be updated so they can work with all devices.
\oldcode
if (reading->tapDirection() == QTapReading::X_Pos) {
...
}
\newcode
if (reading->tapDirection()&QTapReading::X_Pos) {
...
}
\endcode
\value Undefined This value means that the direction is unknown.
\value X This flag is set if the tap was along the X axis.
\value Y This flag is set if the tap was along the Y axis.
\value Z This flag is set if the tap was along the Z axis.
\value X_Pos This flag is set if the tap was towards the positive X direction.
\value Y_Pos This flag is set if the tap was towards the positive Y direction.
\value Z_Pos This flag is set if the tap was towards the positive Z direction.
\value X_Neg This flag is set if the tap was towards the negative X direction.
\value Y_Neg This flag is set if the tap was towards the negative Y direction.
\value Z_Neg This flag is set if the tap was towards the negative Z direction.
\value X_Both Equivalent to \c{X_Pos|X_Neg}. Returned by devices that cannot detect the direction of a tap.
\value Y_Both Equivalent to \c{Y_Pos|Y_Neg}. Returned by devices that cannot detect the direction of a tap.
\value Z_Both Equivalent to \c{Z_Pos|Z_Neg}. Returned by devices that cannot detect the direction of a tap.
*/
/*!
\property QTapReading::tapDirection
\brief the direction of the tap.
\sa {QTapReading Units}
\since 1.0
*/
QTapReading::TapDirection QTapReading::tapDirection() const
{
return static_cast<QTapReading::TapDirection>(d->tapDirection);
}
/*!
Sets the tap direction to \a tapDirection.
\since 1.0
*/
void QTapReading::setTapDirection(QTapReading::TapDirection tapDirection)
{
switch (tapDirection) {
case X_Pos:
case Y_Pos:
case Z_Pos:
case X_Neg:
case Y_Neg:
case Z_Neg:
case X_Both:
case Y_Both:
case Z_Both:
d->tapDirection = tapDirection;
break;
default:
d->tapDirection = Undefined;
break;
}
}
/*!
\property QTapReading::doubleTap
\brief a value indicating if there was a single or double tap.
\list
\o true - double tap
\o false - single tap
\endlist
\sa {QTapReading Units}
\since 1.0
*/
bool QTapReading::isDoubleTap() const
{
return d->doubleTap;
}
/*!
Sets the double tap status of the reading to \a doubleTap.
\since 1.0
*/
void QTapReading::setDoubleTap(bool doubleTap)
{
d->doubleTap = doubleTap;
}
// =====================================================================
/*!
\class QTapFilter
\ingroup sensors_filter
\inmodule QtSensors
\brief The QTapFilter class is a convenience wrapper around QSensorFilter.
The only difference is that the filter() method features a pointer to QTapReading
instead of QSensorReading.
\since 1.0
*/
/*!
\fn QTapFilter::filter(QTapReading *reading)
Called when \a reading changes. Returns false to prevent the reading from propagating.
\sa QSensorFilter::filter()
\since 1.0
*/
char const * const QTapSensor::type("QTapSensor");
/*!
\class QTapSensor
\ingroup sensors_type
\inmodule QtSensors
\brief The QTapSensor class is a convenience wrapper around QSensor.
The only behavioural difference is that this class sets the type properly.
This class also features a reading() function that returns a QTapReading instead of a QSensorReading.
For details about how the sensor works, see \l QTapReading.
\sa QTapReading
\since 1.0
*/
/*!
\fn QTapSensor::QTapSensor(QObject *parent)
Construct the sensor as a child of \a parent.
\since 1.0
*/
/*!
\fn QTapSensor::~QTapSensor()
Destroy the sensor. Stops the sensor if it has not already been stopped.
\since 1.0
*/
/*!
\fn QTapSensor::reading() const
Returns the reading class for this sensor.
\sa QSensor::reading()
\since 1.0
*/
/*!
\property QTapSensor::returnDoubleTapEvents
\brief a value indicating if double tap events should be reported.
Set to true (the default) to have the sensor report only on double tap events.
Set to false to have the sensor report only on individual tap events.
It is not possible to have the sensor report both single and double tap events.
If both are needed the app should create 2 sensor objects.
Note that you must access this property via QObject::property() and QObject::setProperty().
The property must be set before calling start().
\since 1.0
*/
#include "moc_qtapsensor.cpp"
QTM_END_NAMESPACE
|
lgpl-2.1
|
NavSpark/Arduino-1.5.6-r2-Src-NavSpark
|
build/windows/work/hardware/arduino/leon/cores/arduino/SPI.cpp
|
10716
|
/*
SPI.cpp - C++ file of library for SPI interface
Copyright (c) 2014 NavSpark. All right reserved.
This library is free software; you can redistribute 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.
Created 24 Feb. 2014 by Ming-Jen Chen
$Id$
*/
#include "stdint.h"
#include "Arduino.h"
#include "SPI.h"
// **********************************************************************
// Description: declaration of functions provided in "lib_io.a"
// **********************************************************************
#ifdef __cplusplus
extern "C" {
#endif
void v8_spi_master_init(uint32_t clk_rate, bool en_cs1, bool en_cs2);
void v8_spi_master_config(uint8_t mode, bool intr_en);
uint16_t v8_spi_master_byte_io(uint8_t slv, uint8_t *txd, uint8_t *rxd, uint16_t byteNum);
void v8_spi_slave_init(void);
uint8_t v8_spi_slave_write_s2m_buffer(uint8_t *txd, uint8_t num);
uint8_t v8_spi_slave_read_m2s_buffer(uint8_t *rxd);
void v8_spi_slave_enable_m2s_buffer(void);
void v8_spi_slave_enable_s2m_buffer(void);
void v8_spi_slave_disable_s2m_buffer(void);
#ifdef __cplusplus
}
#endif
// **********************************************************************
// Description: declaration of functions exported in C naming convention
// **********************************************************************
#ifdef __cplusplus
extern "C" {
#endif
void isrSPISlaveFunc(uint8_t type);
#ifdef __cplusplus
}
#endif
// **********************************************************************
// Description: declaration of callback functions
// **********************************************************************
// **********************************************************************
// Description: Instances of SPI master/slave
// **********************************************************************
SPI spiMaster = SPI(SPI_MASTER);
SPI spiSlave = SPI(SPI_SLAVE);
// **********************************************************************
// Description: Wrapper of I2C slave ISR
// **********************************************************************
void isrSPISlaveFunc(uint8_t type)
{
if (spiSlave) spiSlave.isr(type);
}
// **********************************************************************
// Description: Constructor for class "SPI"
// **********************************************************************
SPI::SPI(void)
{
SPI(SPI_MASTER);
};
SPI::SPI(uint8_t type)
{
_spiType = type;
_spiMode = 0;
_clkRate = 1000000; // default 1MHz
_en_slave_cs1 = false;
_en_slave_cs2 = false;
_slave_cs = 0;
enabled = false;
};
// **********************************************************************
// Description: Set the clock rate and mode
// **********************************************************************
void SPI::config(uint8_t spiMode, uint32_t clkRate, bool en_cs1, bool en_cs2)
{
if (_spiType == SPI_MASTER) {
_clkRate = clkRate;
_en_slave_cs1 = en_cs1;
_en_slave_cs2 = en_cs2;
_slave_cs = 0;
if (spiMode < 2) _spiMode = spiMode;
}
}
// **********************************************************************
// Description: Init the SPI object
// **********************************************************************
void SPI::begin(void)
{
// configure the GPIO pins to proper modes
pinMode(GPIO29_SPIMS_SCK, SPECIAL);
pinMode(GPIO30_SPIMS_MOSI, SPECIAL);
pinMode(GPIO31_SPIMS_MISO, SPECIAL);
if (_spiType == SPI_MASTER) {
pinMode(GPIO28_SPIMS_CSN, SPECIAL); // always ON
if (_en_slave_cs1 == true) pinMode(GPIO22_SPISL_MCS1, SPECIAL);
if (_en_slave_cs2 == true) pinMode(GPIO6_WHEEL_TIC_MEAS, SPECIAL);
}
else if (_spiType == SPI_SLAVE) {
gpioConf[GPIO28_SPIMS_CSN].io_mode = SPECIAL;
}
// init the SPI master with specified clock rate
if (_spiType == SPI_MASTER) {
v8_spi_master_init(_clkRate, _en_slave_cs1, _en_slave_cs2);
v8_spi_master_config(_spiMode, false); // no INTR now
s2m_buffer_can_fill = false;
}
else if (_spiType == SPI_SLAVE) {
v8_spi_slave_init();
s2m_buffer_can_fill = true;
}
resetTx();
resetRx();
userFuncForSlaveAfterHostRead = NULL;
userFuncForSlaveAfterHostWrite = NULL;
// set the flag on
enabled = true;
}
// **********************************************************************
// Description:
// **********************************************************************
void SPI::resetTx(void)
{
txdSize = 0;
txdPtr = 0;
}
void SPI::resetRx(void)
{
rxdSize = 0;
rxdPtr = 0;
}
// **********************************************************************
// Description: Throw data to the Tx buffer
// **********************************************************************
size_t SPI::write(uint8_t data)
{
if (txdSize < SPI_BUFFER_SIZE) {
txd[txdSize++] = data;
return 1;
}
else return 0;
}
size_t SPI::write(uint8_t *data, size_t size)
{
uint16_t sz, k;
sz = SPI_BUFFER_SIZE - txdSize; /* free space */
for (k = 0; k < ((size>sz) ? sz : size); k++)
{
txd[txdSize++] = data[k];
}
return k;
}
// **********************************************************************
// Description: function to select which CS pin for remote slave
// **********************************************************************
void SPI::slaveSelect(uint8_t slv){
// NavSpark supports 3 CSNs
if (_spiType == SPI_MASTER) {
switch (slv) {
case 0: _slave_cs = 0; break;
case 1: if (_en_slave_cs1) _slave_cs = 1; break;
case 2: if (_en_slave_cs2) _slave_cs = 2; break;
default: _slave_cs = 0;
}
}
}
// **********************************************************************
// Description: begin SPI data transfer
// **********************************************************************
size_t SPI::transfer(void)
{
uint16_t io_num;
if (_spiType == SPI_MASTER) {
if (txdSize <= 8) {
io_num = v8_spi_master_byte_io(_slave_cs, &txd[txdPtr], &rxd[rxdSize], txdSize);
}
else {
io_num = v8_spi_master_byte_io(_slave_cs, &txd[txdPtr], &rxd[rxdSize], 8);
}
txdPtr += io_num;
txdSize -= io_num;
rxdSize += io_num;
return io_num;
}
else return 0;
}
size_t SPI::transfer(size_t size)
{
txdSize = size;
return transfer();
}
// **********************************************************************
// Description: Return how many bytes are received in Rx buffer
// **********************************************************************
int SPI::available(void)
{
return ((int)rxdSize);
}
// **********************************************************************
// Description: Return how many bytes are still in Tx buffer
// **********************************************************************
int SPI::remaining(void)
{
return ((int)txdSize);
}
// **********************************************************************
// Description: Read out the data received in buffer
// **********************************************************************
int SPI::read(void)
{
int value = -1;
// in case of no more valid data
if (rxdPtr == SPI_BUFFER_SIZE) return value;
if (rxdSize) {
value = (int)rxd[rxdPtr++];
rxdSize --;
}
return value;
}
// **********************************************************************
// Description:
// **********************************************************************
uint8_t SPI::pick(size_t offset)
{
return rxd[offset];
}
// **********************************************************************
// Description:
// **********************************************************************
void SPI::enableBufferForHostWrite(void)
{
if (_spiType == SPI_MASTER) return;
v8_spi_slave_enable_m2s_buffer();
}
// **********************************************************************
// Description:
// **********************************************************************
bool SPI::validBufferForHostRead(void)
{
return s2m_buffer_can_fill;
}
uint8_t SPI::copyDataToBufferForHostRead(void)
{
uint8_t s2m_num;
if (_spiType == SPI_MASTER) return 0;
if (txdSize && (s2m_buffer_can_fill == true)) {
s2m_num = v8_spi_slave_write_s2m_buffer(&txd[txdPtr], txdSize);
txdSize -= s2m_num;
txdPtr += s2m_num;
return s2m_num;
}
return 0;
}
void SPI::enableBufferForHostRead(void)
{
if (_spiType == SPI_MASTER) return;
s2m_buffer_can_fill = false;
v8_spi_slave_enable_s2m_buffer();
}
void SPI::disableBufferForHostRead()
{
if (_spiType == SPI_MASTER) return;
s2m_buffer_can_fill = true;
v8_spi_slave_disable_s2m_buffer();
}
// **********************************************************************
// Description:
// **********************************************************************
void SPI::attachInterrupt(uint8_t type, void (*userFunc)(void))
{
if (_spiType == SPI_MASTER) return;
if (type == IRQ_SPI_SLAVE_HOST_READ_DONE) {
userFuncForSlaveAfterHostRead = userFunc;
}
else if (type == IRQ_SPI_SLAVE_HOST_WRITE_DONE) {
userFuncForSlaveAfterHostWrite = userFunc;
}
}
void SPI::detachInterrupt(uint8_t type)
{
if (_spiType == SPI_MASTER) return;
if (type == IRQ_SPI_SLAVE_HOST_READ_DONE) {
userFuncForSlaveAfterHostRead = NULL;
}
else if (type == IRQ_SPI_SLAVE_HOST_WRITE_DONE) {
userFuncForSlaveAfterHostWrite = NULL;
}
}
// **********************************************************************
// Description:
// **********************************************************************
void SPI::isr(uint8_t type)
{
if (_spiType == SPI_MASTER) { return; } // master mode
if (!enabled) { return; } // object not active
if (type == IRQ_SPI_SLAVE_RESET) { // reset request issued by host
// add your code here
}
if (type == IRQ_SPI_SLAVE_HOST_READ_DONE) { // host read buffer done
// call user-defined function before processing next read
if (userFuncForSlaveAfterHostRead) {
userFuncForSlaveAfterHostRead();
}
// allow fill buffer again for next read
s2m_buffer_can_fill = true;
}
if (type == IRQ_SPI_SLAVE_HOST_WRITE_DONE) { // host wrote buffer done
rxdSize = v8_spi_slave_read_m2s_buffer(rxd);
rxdPtr = 0;
// add your code here
if (userFuncForSlaveAfterHostWrite) {
userFuncForSlaveAfterHostWrite();
}
}
if (type == IRQ_SPI_SLAVE_CMD_CHECK) { // host wrote command done
// add your code here
}
}
// **********************************************************************
// Description:
// **********************************************************************
SPI::operator bool() {
return enabled;
}
|
lgpl-2.1
|
devoxx4kids/materials
|
workshops/minecraft/src/main/java/org/devoxx4kids/forge/mods/OverpoweredIronGolems.java
|
908
|
package org.devoxx4kids.forge.mods;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.monster.EntityIronGolem;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
public class OverpoweredIronGolems {
@SubscribeEvent
public void golemMagic(EntityJoinWorldEvent event) {
if (!(event.getEntity() instanceof EntityIronGolem)) {
return;
}
EntityLiving entity = (EntityLiving) event.getEntity();
entity.addPotionEffect(new PotionEffect(Potion.getPotionById(1), 1000000, 5));
entity.addPotionEffect(new PotionEffect(Potion.getPotionById(5), 1000000, 5));
entity.addPotionEffect(new PotionEffect(Potion.getPotionById(10), 1000000, 5));
entity.addPotionEffect(new PotionEffect(Potion.getPotionById(11), 1000000, 5));
}
}
|
lgpl-2.1
|
mtezzele/dealii
|
tests/mpi/mesh_worker_03.cc
|
6043
|
// ---------------------------------------------------------------------
//
// Copyright (C) 2000 - 2015 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, 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.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
// test meshworker LoopControl
#include "../tests.h"
#include <deal.II/meshworker/loop.h>
#include <deal.II/meshworker/assembler.h>
#include <deal.II/fe/fe_dgp.h>
#include <deal.II/distributed/tria.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/filtered_iterator.h>
#include <fstream>
#include <iomanip>
using namespace dealii;
template <int dim>
class myIntegrator: public dealii::MeshWorker::LocalIntegrator<dim>
{
public:
typedef MeshWorker::IntegrationInfo<dim> CellInfo;
void cell(MeshWorker::DoFInfo<dim> &dinfo, CellInfo &info) const;
void boundary(MeshWorker::DoFInfo<dim> &dinfo, CellInfo &info) const;
void face(MeshWorker::DoFInfo<dim> &dinfo1, MeshWorker::DoFInfo<dim> &dinfo2,
CellInfo &info1, CellInfo &info2) const;
};
template <int dim>
void
myIntegrator<dim>::cell(MeshWorker::DoFInfo<dim> &info, CellInfo &) const
{
deallog << "C " << info.cell->id() << std::endl;
}
template <int dim>
void
myIntegrator<dim>::boundary(MeshWorker::DoFInfo<dim> &info, CellInfo &) const
{
//deallog << "B cell = " << info.cell->id() << " face = " << info.face_number << std::endl;
}
template <int dim>
void
myIntegrator<dim>::face(MeshWorker::DoFInfo<dim> &info1, MeshWorker::DoFInfo<dim> &info2,
CellInfo &, CellInfo &) const
{
deallog << "F cell1 = " << info1.cell->id()
<< " face = " << info1.face_number
<< " cell2 = " << info2.cell->id()
<< " face2 = " << info2.face_number
<< std::endl;
}
class DoNothingAssembler
{
public:
template <class DOFINFO>
void initialize_info(DOFINFO &info, bool face) const {}
template<class DOFINFO>
void assemble(const DOFINFO &info){}
template<class DOFINFO>
void assemble(const DOFINFO &info1,
const DOFINFO &info2) {}
};
template <int dim>
void
test_simple(DoFHandler<dim> &dofs, MeshWorker::LoopControl &lctrl)
{
myIntegrator<dim> local;
DoNothingAssembler assembler;
MeshWorker::IntegrationInfoBox<dim> info_box;
MeshWorker::DoFInfo<dim> dof_info(dofs.block_info());
// integration_loop(ITERATOR begin,
// typename identity<ITERATOR>::type end,
// DOFINFO &dinfo,
// INFOBOX &info,
// const std_cxx11::function<void (DOFINFO &, typename INFOBOX::CellInfo &)> &cell_worker,
// const std_cxx11::function<void (DOFINFO &, typename INFOBOX::CellInfo &)> &boundary_worker,
// const std_cxx11::function<void (DOFINFO &, DOFINFO &,
// typename INFOBOX::CellInfo &,
// typename INFOBOX::CellInfo &)> &face_worker,
// ASSEMBLER &assembler,
// const LoopControl &lctrl)
//
MeshWorker::integration_loop<dim, dim, typename DoFHandler<dim>::active_cell_iterator, DoNothingAssembler>
(dofs.begin_active(), dofs.end(),
dof_info, info_box,
local,
assembler,
lctrl);
// MeshWorker::loop<dim, dim, MeshWorker::DoFInfo<dim>, MeshWorker::IntegrationInfoBox<dim> >
// (dofs.begin_active(), dofs.end(),
// dof_info, info_box,
// std_cxx11::bind (&Integrator<dim>::cell, local, std_cxx11::_1, std_cxx11::_2),
// std_cxx11::bind (&Integrator<dim>::bdry, local, std_cxx11::_1, std_cxx11::_2),
// std_cxx11::bind (&Integrator<dim>::face, local, std_cxx11::_1, std_cxx11::_2, std_cxx11::_3, std_cxx11::_4),
// local,
// lctrl);
}
std::string id_to_string(const CellId &id)
{
std::ostringstream ss;
ss << id;
return ss.str();
}
template<int dim>
void test_loop(DoFHandler<dim> &dofs, MeshWorker::LoopControl &lctrl)
{
deallog << "* own_cells=" << lctrl.own_cells
<< " ghost_cells=" << lctrl.ghost_cells
<< " own_faces=" << lctrl.own_faces
<< " faces_to_ghost=" << lctrl.faces_to_ghost
<< std::endl;
test_simple(dofs, lctrl);
}
template<int dim>
void
test()
{
parallel::distributed::Triangulation<dim> tr(MPI_COMM_WORLD,
Triangulation<dim>::none/*,
parallel::distributed::Triangulation<dim>::construct_multigrid_hierarchy*/);
GridGenerator::hyper_cube(tr);
tr.refine_global(1);
unsigned int myid=Utilities::MPI::this_mpi_process(MPI_COMM_WORLD);
if (myid==0)
{
typename parallel::distributed::Triangulation<dim>::active_cell_iterator
it = tr.begin_active();
it->set_refine_flag();
++it;++it;++it;
it->set_refine_flag();
}
tr.execute_coarsening_and_refinement();
FE_DGP<dim> fe(0);
DoFHandler<dim> dofs(tr);
dofs.distribute_dofs(fe);
dofs.initialize_local_block_info();
deallog << "DoFHandler ndofs=" << dofs.n_dofs() << std::endl;
MeshWorker::LoopControl lctrl;
lctrl.own_cells = false;
lctrl.ghost_cells = false;
lctrl.own_faces = MeshWorker::LoopControl::one;
lctrl.faces_to_ghost = MeshWorker::LoopControl::never;
test_loop(dofs, lctrl);
lctrl.own_faces = MeshWorker::LoopControl::never;
lctrl.faces_to_ghost = MeshWorker::LoopControl::one;
test_loop(dofs, lctrl);
lctrl.own_faces = MeshWorker::LoopControl::never;
lctrl.faces_to_ghost = MeshWorker::LoopControl::both;
test_loop(dofs, lctrl);
}
int main (int argc, char **argv)
{
Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1);
MPILogInitAll log;
test<2>();
}
|
lgpl-2.1
|
AgNO3/jcifs-ng
|
src/main/java/jcifs/internal/smb2/ioctl/SrvPipePeekResponse.java
|
2747
|
/*
* © 2017 AgNO3 Gmbh & Co. KG
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package jcifs.internal.smb2.ioctl;
import jcifs.Decodable;
import jcifs.internal.SMBProtocolDecodingException;
import jcifs.internal.util.SMBUtil;
/**
* @author svella
*
*/
public class SrvPipePeekResponse implements Decodable {
// see https://msdn.microsoft.com/en-us/library/dd414577.aspx
private int namedPipeState;
private int readDataAvailable;
private int numberOfMessages;
private int messageLength;
private byte[] data;
/**
* @return the chunkBytesWritten
*/
public int getNamedPipeState () {
return this.namedPipeState;
}
/**
* @return the chunksWritten
*/
public int getReadDataAvailable () {
return this.readDataAvailable;
}
/**
* @return the totalBytesWritten
*/
public int getNumberOfMessages () {
return this.numberOfMessages;
}
/**
* @return the totalBytesWritten
*/
public int getMessageLength () {
return this.messageLength;
}
/**
* @return the totalBytesWritten
*/
public byte[] getData () {
return this.data;
}
/**
* {@inheritDoc}
*
* @see Decodable#decode(byte[], int, int)
*/
@Override
public int decode ( byte[] buffer, int bufferIndex, int len ) throws SMBProtocolDecodingException {
int start = bufferIndex;
this.namedPipeState = SMBUtil.readInt4(buffer, bufferIndex);
bufferIndex += 4;
this.readDataAvailable = SMBUtil.readInt4(buffer, bufferIndex);
bufferIndex += 4;
this.numberOfMessages = SMBUtil.readInt4(buffer, bufferIndex);
bufferIndex += 4;
this.messageLength = SMBUtil.readInt4(buffer, bufferIndex);
bufferIndex += 4;
this.data = new byte[len - 16];
if ( this.data.length > 0 ) {
System.arraycopy(buffer, bufferIndex, this.data, 0, this.data.length);
}
return bufferIndex - start;
}
}
|
lgpl-2.1
|
huoxudong125/Zongsoft.CoreLibrary
|
src/IO/StorageBucketInfo.cs
|
5001
|
/*
* Authors:
* 钟峰(Popeye Zhong) <zongsoft@gmail.com>
*
* Copyright (C) 2014-2015 Zongsoft Corporation <http://www.zongsoft.com>
*
* This file is part of Zongsoft.CoreLibrary.
*
* Zongsoft.CoreLibrary 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.
*
* Zongsoft.CoreLibrary 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.
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Zongsoft.CoreLibrary; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Collections;
using System.Collections.Generic;
using Zongsoft.Collections;
namespace Zongsoft.IO
{
/// <summary>
/// 表示存储文件的容器信息类。
/// </summary>
[Serializable]
[Obsolete("Please use Aliyun-OSS providr of filesystem.")]
public class StorageBucketInfo : MarshalByRefObject
{
#region 成员字段
private int _bucketId;
private string _name;
private string _path;
private string _title;
private DateTime _createdTime;
private DateTime? _modifiedTime;
#endregion
#region 构造函数
public StorageBucketInfo()
{
_createdTime = DateTime.Now;
}
public StorageBucketInfo(int bucketId)
{
_createdTime = DateTime.Now;
}
#endregion
#region 公共属性
/// <summary>
/// 获取或设置文件存储容器的编号。
/// </summary>
public int BucketId
{
get
{
return _bucketId;
}
set
{
_bucketId = value;
}
}
/// <summary>
/// 获取或设置文件存储容器的名称。
/// </summary>
public string Name
{
get
{
return _name;
}
set
{
_name = value == null ? string.Empty : value.Trim();
}
}
/// <summary>
/// 获取或设置文件容器的存储路径。
/// </summary>
public string Path
{
get
{
return _path;
}
set
{
_path = value;
}
}
/// <summary>
/// 获取或设置文件存储容器的标题。
/// </summary>
public string Title
{
get
{
return _title;
}
set
{
_title = value;
}
}
/// <summary>
/// 获取或设置文件存储容器的创建时间。
/// </summary>
public DateTime CreatedTime
{
get
{
return _createdTime;
}
set
{
_createdTime = value;
}
}
/// <summary>
/// 获取或设置文件存储容器的修改时间。
/// </summary>
public DateTime? ModifiedTime
{
get
{
return _modifiedTime;
}
set
{
_modifiedTime = value;
}
}
#endregion
#region 公共方法
public IDictionary<string, object> ToDictionary()
{
return new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase)
{
{ "BucketId", _bucketId },
{ "Name", _name },
{ "Path", _path },
{ "Title", _title },
{ "CreatedTime", _createdTime },
{ "ModifiedTime", _modifiedTime },
};
}
public static StorageBucketInfo FromDictionary(IDictionary dictionary)
{
if(dictionary == null || dictionary.Count < 1)
return null;
object bucketId, name, title, path, createdTime, modifiedTime;
if(!dictionary.TryGetValue("BucketId", out bucketId))
return null;
if(!dictionary.TryGetValue("Name", out name))
return null;
dictionary.TryGetValue("Path", out path);
dictionary.TryGetValue("Title", out title);
dictionary.TryGetValue("CreatedTime", out createdTime);
dictionary.TryGetValue("ModifiedTime", out modifiedTime);
return new StorageBucketInfo(Zongsoft.Common.Convert.ConvertValue<int>(bucketId))
{
Name = Zongsoft.Common.Convert.ConvertValue<string>(name),
Path = Zongsoft.Common.Convert.ConvertValue<string>(path),
Title = Zongsoft.Common.Convert.ConvertValue<string>(title),
CreatedTime = Zongsoft.Common.Convert.ConvertValue<DateTime>(createdTime),
ModifiedTime = Zongsoft.Common.Convert.ConvertValue<DateTime?>(modifiedTime),
};
}
#endregion
#region 重写方法
public override int GetHashCode()
{
return _bucketId;
}
public override bool Equals(object obj)
{
if(obj == null || obj.GetType() != this.GetType())
return false;
return ((StorageBucketInfo)obj).BucketId == this.BucketId;
}
public override string ToString()
{
if(string.IsNullOrWhiteSpace(_path))
return string.Format("#{0} {1}", _bucketId.ToString(), _name);
else
return string.Format("#{0} {1} ({2})", _bucketId.ToString(), _name, _path);
}
#endregion
}
}
|
lgpl-2.1
|
qtproject/qt-mobility
|
tests/auto/qmediaimageviewer/tst_qmediaimageviewer.cpp
|
37056
|
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
//TESTED_COMPONENT=src/multimedia
#include <qmobilityglobal.h>
#include <QtTest/QtTest>
#include <QtCore/qdir.h>
#include <qgraphicsvideoitem.h>
#include <qmediaimageviewer.h>
#include <qmediaimageviewerservice_p.h>
#include <qmediaplaylist.h>
#include <qmediaservice.h>
#include <qvideorenderercontrol.h>
#include <qvideowidget.h>
#include <qvideowidgetcontrol.h>
#include <QtCore/qfile.h>
#include <QtNetwork/qnetworkaccessmanager.h>
#include <QtNetwork/qnetworkreply.h>
#include <qabstractvideosurface.h>
#include <qvideosurfaceformat.h>
QT_USE_NAMESPACE
class QtTestNetworkAccessManager;
class tst_QMediaImageViewer : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void isValid();
void timeout();
void setMedia_data();
void setMedia();
void setConsecutiveMedia();
void setInvalidMedia();
void playlist();
void multiplePlaylists();
void invalidPlaylist();
void elapsedTime();
void rendererControl();
void setVideoOutput();
void debugEnums();
void mediaChanged_signal();
public:
tst_QMediaImageViewer() : m_network(0) {}
private:
QUrl imageUrl(const char *fileName) const {
return QUrl(QLatin1String("qrc:///images/") + QLatin1String(fileName)); }
QString imageFileName(const char *fileName) {
return QLatin1String(":/images/") + QLatin1String(fileName); }
QtTestNetworkAccessManager *m_network;
QString m_fileProtocol;
};
class QtTestVideoSurface : public QAbstractVideoSurface
{
public:
QList<QVideoFrame::PixelFormat> supportedPixelFormats(
QAbstractVideoBuffer::HandleType handleType) const {
QList<QVideoFrame::PixelFormat> formats;
if (handleType == QAbstractVideoBuffer::NoHandle) {
formats << QVideoFrame::Format_RGB32;
}
return formats;
}
QVideoFrame frame() const { return m_frame; }
bool present(const QVideoFrame &frame) { m_frame = frame; return true; }
private:
QVideoFrame m_frame;
};
class QtTestNetworkReply : public QNetworkReply
{
public:
QtTestNetworkReply(
const QNetworkRequest &request,
const QByteArray &mimeType,
QObject *parent)
: QNetworkReply(parent)
{
setRequest(request);
setOperation(QNetworkAccessManager::HeadOperation);
setRawHeader("content-type", mimeType);
QCoreApplication::postEvent(this, new QEvent(QEvent::User));
}
QtTestNetworkReply(
const QNetworkRequest &request,
const QByteArray &mimeType,
const QString &fileName,
QObject *parent)
: QNetworkReply(parent)
, m_file(fileName)
{
setRequest(request);
setOperation(QNetworkAccessManager::GetOperation);
setRawHeader("content-type", mimeType);
if (m_file.open(QIODevice::ReadOnly | QIODevice::Unbuffered)) {
setOpenMode(QIODevice::ReadOnly);
}
QCoreApplication::postEvent(this, new QEvent(QEvent::User));
}
void abort() { m_file.close(); }
bool atEnd () const { return m_file.atEnd(); }
qint64 bytesAvailable() const { return m_file.bytesAvailable() + QIODevice::bytesAvailable(); }
void close() { m_file.close(); setOpenMode(QIODevice::NotOpen); }
bool isSequential() const { return true; }
bool open(OpenMode) { return false; }
qint64 pos() const { return 0; }
bool seek(qint64) { return false; }
qint64 size() const { return m_file.size(); }
qint64 readData(char * data, qint64 maxSize) { return m_file.read(data, maxSize); }
qint64 writeData(const char *, qint64) { return -1; }
protected:
void customEvent(QEvent *event)
{
if (event->type() == QEvent::User) {
event->accept();
emit finished();
}
}
private:
QFile m_file;
};
class QtTestNetworkAccessManager : public QNetworkAccessManager
{
public:
QtTestNetworkAccessManager(QObject *parent = 0)
: QNetworkAccessManager(parent)
{
}
void appendDocument(const QUrl &url, const QByteArray &mimeType, const QString &fileName)
{
m_documents.append(Document(url, mimeType, fileName));
}
protected:
QNetworkReply *createRequest(
Operation op, const QNetworkRequest &request, QIODevice *outgoingData = 0)
{
foreach (const Document &document, m_documents) {
if (document.url == request.url()) {
if (op == GetOperation) {
return new QtTestNetworkReply(
request, document.mimeType, document.fileName, this);
} else if (op == HeadOperation) {
return new QtTestNetworkReply(request, document.mimeType, this);
}
}
}
return QNetworkAccessManager::createRequest(op, request, outgoingData);
}
private:
struct Document
{
Document(const QUrl url, const QByteArray mimeType, const QString &fileName)
: url(url), mimeType(mimeType), fileName(fileName)
{
}
QUrl url;
QByteArray mimeType;
QString fileName;
};
QList<Document> m_documents;
};
void tst_QMediaImageViewer::initTestCase()
{
qRegisterMetaType<QMediaImageViewer::State>();
qRegisterMetaType<QMediaImageViewer::MediaStatus>();
m_network = new QtTestNetworkAccessManager(this);
m_network->appendDocument(
QUrl(QLatin1String("test://image/png?id=1")),
"image/png",
imageFileName("image.png"));
m_network->appendDocument(
QUrl(QLatin1String("test://image/png?id=2")),
QByteArray(),
imageFileName("image.png"));
m_network->appendDocument(
QUrl(QLatin1String("test://image/invalid?id=1")),
"image/png",
imageFileName("invalid.png"));
m_network->appendDocument(
QUrl(QLatin1String("test://image/invalid?id=2")),
QByteArray(),
imageFileName("invalid.png"));
#ifdef QTEST_HAVE_JPEG
m_network->appendDocument(
QUrl(QLatin1String("test://image/jpeg?id=1")),
"image/jpeg",
imageFileName("image.jpg"));
#endif
m_network->appendDocument(
QUrl(QLatin1String("test://music/songs/mp3?id=1")),
"audio/mpeg",
QString());
m_network->appendDocument(
QUrl(QLatin1String("test://music/covers/small?id=1")),
"image/png",
imageFileName("coverart.png"));
m_network->appendDocument(
QUrl(QLatin1String("test://music/covers/large?id=1")),
"image/png",
imageFileName("coverart.png"));
m_network->appendDocument(
QUrl(QLatin1String("test://video/movies/mp4?id=1")),
"video/mp4",
QString());
m_network->appendDocument(
QUrl(QLatin1String("test://video/posters/png?id=1")),
"image/png",
imageFileName("poster.png"));
}
void tst_QMediaImageViewer::isValid()
{
QMediaImageViewer viewer;
QVERIFY(viewer.service() != 0);
}
void tst_QMediaImageViewer::timeout()
{
QMediaImageViewer viewer;
QCOMPARE(viewer.timeout(), 3000);
viewer.setTimeout(0);
QCOMPARE(viewer.timeout(), 0);
viewer.setTimeout(45);
QCOMPARE(viewer.timeout(), 45);
viewer.setTimeout(-3000);
QCOMPARE(viewer.timeout(), 0);
}
void tst_QMediaImageViewer::setMedia_data()
{
QTest::addColumn<QMediaContent>("media");
{
QMediaContent media(imageUrl("image.png"));
QTest::newRow("file: png image")
<< media;
} {
QMediaContent media(QUrl(QLatin1String("test://image/png?id=1")));
QTest::newRow("network: png image")
<< media;
} {
QMediaContent media(QMediaResource(
QUrl(QLatin1String("test://image/png?id=1")), QLatin1String("image/png")));
QTest::newRow("network: png image, explicit mime type")
<< media;
} {
QMediaContent media(QUrl(QLatin1String("test://image/png?id=2")));
QTest::newRow("network: png image, no mime type")
<< media;
#ifdef QTEST_HAVE_JPEG
} {
QMediaContent media(imageUrl("image.jpg"));
QTest::newRow("file: jpg image")
<< media;
} {
QMediaContent media(QUrl(QLatin1String("test://image/jpeg?id=1")));
QTest::newRow("network: jpg image")
<< media;
#endif
}
}
void tst_QMediaImageViewer::setMedia()
{
QFETCH(QMediaContent, media);
QMediaImageViewer viewer;
QMediaImageViewerService *service = qobject_cast<QMediaImageViewerService *>(viewer.service());
service->setNetworkManager(m_network);
connect(&viewer, SIGNAL(mediaStatusChanged(QMediaImageViewer::MediaStatus)),
&QTestEventLoop::instance(), SLOT(exitLoop()));
viewer.setMedia(media);
QCOMPARE(viewer.media(), media);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadingMedia);
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadedMedia);
}
void tst_QMediaImageViewer::setConsecutiveMedia()
{
QMediaContent fileMedia1(imageUrl("image.png"));
QMediaContent fileMedia2(imageUrl("coverart.png"));
QMediaContent networkMedia1(QUrl(QLatin1String("test://image/png?id=1")));
QMediaContent networkMedia2(QUrl(QLatin1String("test://image/png?id=2")));
QMediaImageViewer viewer;
connect(&viewer, SIGNAL(mediaStatusChanged(QMediaImageViewer::MediaStatus)),
&QTestEventLoop::instance(), SLOT(exitLoop()));
viewer.setMedia(fileMedia1);
viewer.setMedia(fileMedia2);
QCOMPARE(viewer.media(), fileMedia2);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadingMedia);
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.media(), fileMedia2);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadedMedia);
QMediaImageViewerService *service = qobject_cast<QMediaImageViewerService *>(viewer.service());
service->setNetworkManager(m_network);
viewer.setMedia(networkMedia2);
viewer.setMedia(networkMedia1);
QCOMPARE(viewer.media(), networkMedia1);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadingMedia);
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.media(), networkMedia1);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadedMedia);
viewer.setMedia(fileMedia1);
viewer.setMedia(networkMedia2);
QCOMPARE(viewer.media(), networkMedia2);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadingMedia);
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.media(), networkMedia2);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadedMedia);
viewer.setMedia(fileMedia1);
viewer.setMedia(networkMedia2);
QCOMPARE(viewer.media(), networkMedia2);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadingMedia);
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.media(), networkMedia2);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadedMedia);
viewer.setMedia(networkMedia1);
viewer.setMedia(fileMedia2);
QCOMPARE(viewer.media(), fileMedia2);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadingMedia);
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.media(), fileMedia2);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadedMedia);
}
void tst_QMediaImageViewer::setInvalidMedia()
{
QMediaImageViewer viewer;
viewer.setTimeout(250);
QMediaImageViewerService *service = qobject_cast<QMediaImageViewerService *>(viewer.service());
service->setNetworkManager(m_network);
connect(&viewer, SIGNAL(mediaStatusChanged(QMediaImageViewer::MediaStatus)),
&QTestEventLoop::instance(), SLOT(exitLoop()));
{
QMediaContent media(imageUrl("invalid.png"));
viewer.setMedia(media);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadingMedia);
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::InvalidMedia);
QCOMPARE(viewer.media(), media);
} {
QMediaContent media(imageUrl("deleted.png"));
viewer.setMedia(media);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadingMedia);
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::InvalidMedia);
QCOMPARE(viewer.media(), media);
} {
QMediaResource invalidResource(imageUrl("invalid.png"));
QMediaResource deletedResource(imageUrl("deleted.png"));
QMediaContent media(QMediaResourceList() << invalidResource << deletedResource);
viewer.setMedia(media);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadingMedia);
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::InvalidMedia);
QCOMPARE(viewer.media(), media);
} {
QMediaResource resource(imageUrl("image.png"), QLatin1String("audio/mpeg"));
QMediaContent media(resource);
viewer.setMedia(media);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::InvalidMedia);
QCOMPARE(viewer.media(), media);
} {
QMediaResource audioResource(imageUrl("image.png"), QLatin1String("audio/mpeg"));
QMediaResource invalidResource(imageUrl("invalid.png"));
QMediaContent media(QMediaResourceList() << audioResource << invalidResource);
viewer.setMedia(media);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadingMedia);
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::InvalidMedia);
QCOMPARE(viewer.media(), media);
} {
QMediaContent media(QUrl(QLatin1String("test://image/invalid?id=1")));
viewer.setMedia(media);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadingMedia);
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::InvalidMedia);
QCOMPARE(viewer.media(), media);
} {
QMediaContent media(QUrl(QLatin1String("test://image/invalid?id=2")));
viewer.setMedia(media);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadingMedia);
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::InvalidMedia);
QCOMPARE(viewer.media(), media);
} {
QMediaContent media(QUrl(QLatin1String("test://image/invalid?id=3")));
viewer.setMedia(media);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadingMedia);
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::InvalidMedia);
QCOMPARE(viewer.media(), media);
}
}
void tst_QMediaImageViewer::playlist()
{
QMediaContent imageMedia(imageUrl("image.png"));
QMediaContent posterMedia(imageUrl("poster.png"));
QMediaContent coverArtMedia(imageUrl("coverart.png"));
QMediaImageViewer viewer;
viewer.setTimeout(250);
connect(&viewer, SIGNAL(mediaStatusChanged(QMediaImageViewer::MediaStatus)),
&QTestEventLoop::instance(), SLOT(exitLoop()));
QSignalSpy stateSpy(&viewer, SIGNAL(stateChanged(QMediaImageViewer::State)));
QCOMPARE(viewer.state(), QMediaImageViewer::StoppedState);
// No playlist so can't exit stopped state.
viewer.play();
QCOMPARE(viewer.state(), QMediaImageViewer::StoppedState);
QCOMPARE(stateSpy.count(), 0);
viewer.pause();
QCOMPARE(viewer.state(), QMediaImageViewer::StoppedState);
QCOMPARE(stateSpy.count(), 0);
QMediaPlaylist playlist;
viewer.setPlaylist(&playlist);
// Empty playlist so can't exit stopped state.
viewer.play();
QCOMPARE(viewer.state(), QMediaImageViewer::StoppedState);
QCOMPARE(stateSpy.count(), 0);
viewer.pause();
QCOMPARE(viewer.state(), QMediaImageViewer::StoppedState);
QCOMPARE(stateSpy.count(), 0);
playlist.addMedia(imageMedia);
playlist.addMedia(posterMedia);
playlist.addMedia(coverArtMedia);
// Play progresses immediately to the first image and starts loading.
viewer.play();
QCOMPARE(viewer.state(), QMediaImageViewer::PlayingState);
QCOMPARE(stateSpy.count(), 1);
QCOMPARE(qvariant_cast<QMediaImageViewer::State>(stateSpy.last().value(0)),
QMediaImageViewer::PlayingState);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadingMedia);
QCOMPARE(playlist.currentIndex(), 0);
QCOMPARE(viewer.media(), imageMedia);
// Image is loaded asynchronously.
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadedMedia);
QCOMPARE(playlist.currentIndex(), 0);
// Time out causes progression to second image, which starts loading.
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadingMedia);
QCOMPARE(playlist.currentIndex(), 1);
QCOMPARE(viewer.media(), posterMedia);
// Image is loaded asynchronously.
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.state(), QMediaImageViewer::PlayingState);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadedMedia);
QCOMPARE(playlist.currentIndex(), 1);
// Pausing stops progression at current image.
viewer.pause();
QCOMPARE(viewer.state(), QMediaImageViewer::PausedState);
QCOMPARE(stateSpy.count(), 2);
QCOMPARE(qvariant_cast<QMediaImageViewer::State>(stateSpy.last().value(0)),
QMediaImageViewer::PausedState);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadedMedia);
QCOMPARE(playlist.currentIndex(), 1);
// No time out.
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.state(), QMediaImageViewer::PausedState);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadedMedia);
QCOMPARE(playlist.currentIndex(), 1);
// Resuming playback does not immediately progress to the next item
viewer.play();
QCOMPARE(viewer.state(), QMediaImageViewer::PlayingState);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadedMedia);
QCOMPARE(playlist.currentIndex(), 1);
// Time out causes progression to next image, which starts loading.
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadingMedia);
QCOMPARE(playlist.currentIndex(), 2);
QCOMPARE(viewer.media(), coverArtMedia);
// Image is loaded asynchronously.
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadedMedia);
QCOMPARE(playlist.currentIndex(), 2);
// Time out causes progression to end of list
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.state(), QMediaImageViewer::StoppedState);
QCOMPARE(stateSpy.count(), 4);
QCOMPARE(qvariant_cast<QMediaImageViewer::State>(stateSpy.last().value(0)),
QMediaImageViewer::StoppedState);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::NoMedia);
QCOMPARE(playlist.currentIndex(), -1);
QCOMPARE(viewer.media(), QMediaContent());
// Stopped, no time out.
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.state(), QMediaImageViewer::StoppedState);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::NoMedia);
QCOMPARE(playlist.currentIndex(), -1);
// Play progresses immediately to the first image and starts loading.
viewer.play();
QCOMPARE(viewer.state(), QMediaImageViewer::PlayingState);
QCOMPARE(stateSpy.count(), 5);
QCOMPARE(qvariant_cast<QMediaImageViewer::State>(stateSpy.last().value(0)),
QMediaImageViewer::PlayingState);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadingMedia);
QCOMPARE(playlist.currentIndex(), 0);
QCOMPARE(viewer.media(), imageMedia);
// Image is loaded asynchronously.
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadedMedia);
QCOMPARE(playlist.currentIndex(), 0);
// Stop ends progress, but retains current index.
viewer.stop();
QCOMPARE(viewer.state(), QMediaImageViewer::StoppedState);
QCOMPARE(stateSpy.count(), 6);
QCOMPARE(qvariant_cast<QMediaImageViewer::State>(stateSpy.last().value(0)),
QMediaImageViewer::StoppedState);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadedMedia);
QCOMPARE(playlist.currentIndex(), 0);
QCOMPARE(viewer.media(), imageMedia);
// Stoppped, No time out.
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.state(), QMediaImageViewer::StoppedState);
QCOMPARE(playlist.currentIndex(), 0);
QCOMPARE(viewer.media(), imageMedia);
// Stop when already stopped doesn't emit additional signals.
viewer.stop();
QCOMPARE(viewer.state(), QMediaImageViewer::StoppedState);
QCOMPARE(stateSpy.count(), 6);
viewer.play();
QCOMPARE(stateSpy.count(), 7);
// Play when already playing doesn't emit additional signals.
viewer.play();
QCOMPARE(viewer.state(), QMediaImageViewer::PlayingState);
QCOMPARE(stateSpy.count(), 7);
playlist.next();
QCOMPARE(viewer.state(), QMediaImageViewer::PlayingState);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadingMedia);
// Pausing while loading, doesn't stop loading.
viewer.pause();
QCOMPARE(viewer.state(), QMediaImageViewer::PausedState);
QCOMPARE(stateSpy.count(), 8);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadingMedia);
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.state(), QMediaImageViewer::PausedState);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadedMedia);
// Pause while paused doesn't emit additional signals.
viewer.pause();
QCOMPARE(viewer.state(), QMediaImageViewer::PausedState);
QCOMPARE(stateSpy.count(), 8);
// Calling setMedia stops the playlist.
viewer.setMedia(imageMedia);
QCOMPARE(viewer.media(), imageMedia);
QCOMPARE(viewer.state(), QMediaImageViewer::StoppedState);
QCOMPARE(stateSpy.count(), 9);
QCOMPARE(qvariant_cast<QMediaImageViewer::State>(stateSpy.last().value(0)),
QMediaImageViewer::StoppedState);
}
void tst_QMediaImageViewer::multiplePlaylists()
{
QMediaContent imageMedia(imageUrl("image.png"));
QMediaContent posterMedia(imageUrl("poster.png"));
QMediaContent coverArtMedia(imageUrl("coverart.png"));
QMediaImageViewer viewer;
QMediaPlaylist *playlist1 = new QMediaPlaylist;
viewer.setPlaylist(playlist1);
playlist1->addMedia(imageMedia);
playlist1->addMedia(posterMedia);
playlist1->setCurrentIndex(0);
QCOMPARE(viewer.media(), imageMedia);
QMediaPlaylist *playlist2 = new QMediaPlaylist;
viewer.setPlaylist(playlist2);
playlist2->addMedia(coverArtMedia);
QVERIFY(viewer.media().isNull());
playlist2->setCurrentIndex(0);
QCOMPARE(viewer.media(), coverArtMedia);
delete playlist2;
QVERIFY(viewer.media().isNull());
QCOMPARE(viewer.state(), QMediaImageViewer::StoppedState);
viewer.setPlaylist(playlist1);
playlist1->setCurrentIndex(0);
QCOMPARE(viewer.media(), imageMedia);
viewer.play();
QCOMPARE(viewer.state(), QMediaImageViewer::PlayingState);
delete playlist1;
QCOMPARE(viewer.state(), QMediaImageViewer::StoppedState);
}
void tst_QMediaImageViewer::invalidPlaylist()
{
QMediaContent imageMedia(imageUrl("image.png"));
QMediaContent invalidMedia(imageUrl("invalid.png"));
QMediaImageViewer viewer;
viewer.setTimeout(250);
connect(&viewer, SIGNAL(mediaStatusChanged(QMediaImageViewer::MediaStatus)),
&QTestEventLoop::instance(), SLOT(exitLoop()));
QSignalSpy stateSpy(&viewer, SIGNAL(stateChanged(QMediaImageViewer::State)));
QSignalSpy statusSpy(&viewer, SIGNAL(mediaStatusChanged(QMediaImageViewer::MediaStatus)));
QMediaPlaylist playlist;
viewer.setPlaylist(&playlist);
playlist.addMedia(invalidMedia);
playlist.addMedia(imageMedia);
playlist.addMedia(invalidMedia);
// Test play initially tries to load the first invalid image.
viewer.play();
QCOMPARE(viewer.state(), QMediaImageViewer::PlayingState);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadingMedia);
QCOMPARE(viewer.media(), invalidMedia);
QCOMPARE(playlist.currentIndex(), 0);
QCOMPARE(statusSpy.count(), 1);
QCOMPARE(qvariant_cast<QMediaImageViewer::MediaStatus>(statusSpy.value(0).value(0)),
QMediaImageViewer::LoadingMedia);
// Test status is changed to InvalidMedia, and loading of the next image is started immediately.
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.state(), QMediaImageViewer::PlayingState);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::LoadingMedia);
QCOMPARE(viewer.media(), imageMedia);
QCOMPARE(playlist.currentIndex(), 1);
QCOMPARE(statusSpy.count(), 3);
QCOMPARE(qvariant_cast<QMediaImageViewer::MediaStatus>(statusSpy.value(1).value(0)),
QMediaImageViewer::InvalidMedia);
QCOMPARE(qvariant_cast<QMediaImageViewer::MediaStatus>(statusSpy.value(2).value(0)),
QMediaImageViewer::LoadingMedia);
// Test if the last image is invalid, the image viewer is stopped.
playlist.next();
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.state(), QMediaImageViewer::StoppedState);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::NoMedia);
QCOMPARE(playlist.currentIndex(), -1);
QCOMPARE(stateSpy.count(), 2);
playlist.setCurrentIndex(2);
QTestEventLoop::instance().enterLoop(2);
// Test play immediately moves to the next item if the current one is invalid, and no state
// change signals are emitted if the viewer never effectively moves from the StoppedState.
viewer.play();
QCOMPARE(viewer.state(), QMediaImageViewer::StoppedState);
QCOMPARE(viewer.mediaStatus(), QMediaImageViewer::NoMedia);
QCOMPARE(playlist.currentIndex(), -1);
QCOMPARE(stateSpy.count(), 2);
}
void tst_QMediaImageViewer::elapsedTime()
{
QMediaContent imageMedia(imageUrl("image.png"));
QMediaImageViewer viewer;
viewer.setTimeout(250);
viewer.setNotifyInterval(150);
QSignalSpy spy(&viewer, SIGNAL(elapsedTimeChanged(int)));
connect(&viewer, SIGNAL(elapsedTimeChanged(int)),
&QTestEventLoop::instance(), SLOT(exitLoop()));
QMediaPlaylist playlist;
viewer.setPlaylist(&playlist);
playlist.addMedia(imageMedia);
QCOMPARE(viewer.elapsedTime(), 0);
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(spy.count(), 0);
viewer.play();
QCOMPARE(viewer.elapsedTime(), 0);
// Emits an initial elapsed time at 0 milliseconds signal when the image is loaded.
QTestEventLoop::instance().enterLoop(1);
QCOMPARE(spy.count(), 1);
QCOMPARE(spy.last().value(0).toInt(), 0);
// Emits a scheduled signal after the notify interval is up. The exact time will be a little
// fuzzy.
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(spy.count(), 2);
QVERIFY(spy.last().value(0).toInt() != 0);
// Pausing will emit a signal with the elapsed time when paused.
viewer.pause();
QCOMPARE(spy.count(), 3);
QCOMPARE(viewer.elapsedTime(), spy.last().value(0).toInt());
// No elapsed time signals will be emitted while paused.
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(spy.count(), 3);
// Stopping a paused viewer resets the elapsed time to 0 with signals emitted.
viewer.stop();
QCOMPARE(viewer.elapsedTime(), 0);
QCOMPARE(spy.count(), 4);
QCOMPARE(spy.last().value(0).toInt(), 0);
disconnect(&viewer, SIGNAL(elapsedTimeChanged(int)),
&QTestEventLoop::instance(), SLOT(exitLoop()));
connect(&viewer, SIGNAL(mediaStatusChanged(QMediaImageViewer::MediaStatus)),
&QTestEventLoop::instance(), SLOT(exitLoop()));
// Play until end.
viewer.play();
QTestEventLoop::instance().enterLoop(2);
// Verify at least two more signals are emitted.
// The second to last at the instant the timeout expired, and the last as it's reset when the
// current media is cleared.
QVERIFY(spy.count() >= 5);
QCOMPARE(spy.value(spy.count() - 2).value(0).toInt(), 250);
QCOMPARE(spy.value(spy.count() - 1).value(0).toInt(), 0);
viewer.play();
QTestEventLoop::instance().enterLoop(2);
// Test extending the timeout applies to an already loaded image.
viewer.setTimeout(10000);
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.state(), QMediaImageViewer::PlayingState);
// Test reducing the timeout applies to an already loaded image.
viewer.setTimeout(1000);
QTestEventLoop::instance().enterLoop(2);
QCOMPARE(viewer.state(), QMediaImageViewer::StoppedState);
}
void tst_QMediaImageViewer::rendererControl()
{
QtTestVideoSurface surfaceA;
QtTestVideoSurface surfaceB;
QAbstractVideoSurface *nullSurface = 0;
QMediaImageViewer viewer;
QMediaService *service = viewer.service();
if (service == 0)
QSKIP("Image viewer object has no service.", SkipSingle);
QMediaControl *mediaControl = service->requestControl(QVideoRendererControl_iid);
QVERIFY(mediaControl != 0);
QVideoRendererControl *rendererControl = qobject_cast<QVideoRendererControl *>(mediaControl);
QVERIFY(rendererControl != 0);
rendererControl->setSurface(&surfaceA);
QCOMPARE(rendererControl->surface(), (QAbstractVideoSurface *)&surfaceA);
// Load an image so the viewer has some dimensions to work with.
viewer.setMedia(QMediaContent(imageUrl("image.png")));
connect(&viewer, SIGNAL(mediaStatusChanged(QMediaImageViewer::MediaStatus)),
&QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(2);
if (viewer.mediaStatus() != QMediaImageViewer::LoadedMedia)
QSKIP("failed to load test image", SkipSingle);
QCOMPARE(surfaceA.isActive(), true);
{
QVideoSurfaceFormat format = surfaceA.surfaceFormat();
QCOMPARE(format.handleType(), QAbstractVideoBuffer::NoHandle);
QCOMPARE(format.pixelFormat(), QVideoFrame::Format_RGB32);
QCOMPARE(format.frameSize(), QSize(75, 50));
QVideoFrame frame = surfaceA.frame();
QCOMPARE(frame.handleType(), QAbstractVideoBuffer::NoHandle);
QCOMPARE(frame.pixelFormat(), QVideoFrame::Format_RGB32);
QCOMPARE(frame.size(), QSize(75, 50));
}
// Test clearing the output stops the video surface.
service->releaseControl(rendererControl);
QCOMPARE(surfaceA.isActive(), false);
// Test reseting the output restarts it.
mediaControl = service->requestControl(QVideoRendererControl_iid);
QVERIFY(mediaControl != 0);
rendererControl = qobject_cast<QVideoRendererControl *>(mediaControl);
rendererControl->setSurface(&surfaceA);
QVERIFY(rendererControl != 0);
{
QVideoSurfaceFormat format = surfaceA.surfaceFormat();
QCOMPARE(format.handleType(), QAbstractVideoBuffer::NoHandle);
QCOMPARE(format.pixelFormat(), QVideoFrame::Format_RGB32);
QCOMPARE(format.frameSize(), QSize(75, 50));
QVideoFrame frame = surfaceA.frame();
QCOMPARE(frame.handleType(), QAbstractVideoBuffer::NoHandle);
QCOMPARE(frame.pixelFormat(), QVideoFrame::Format_RGB32);
QCOMPARE(frame.size(), QSize(75, 50));
}
// Test changing the surface while viewing an image stops the old surface and starts
// the new one and presents the image.
rendererControl->setSurface(&surfaceB);
QCOMPARE(rendererControl->surface(), (QAbstractVideoSurface*)&surfaceB);
QCOMPARE(surfaceA.isActive(), false);
QCOMPARE(surfaceB.isActive(), true);
QVideoSurfaceFormat format = surfaceB.surfaceFormat();
QCOMPARE(format.handleType(), QAbstractVideoBuffer::NoHandle);
QCOMPARE(format.pixelFormat(), QVideoFrame::Format_RGB32);
QCOMPARE(format.frameSize(), QSize(75, 50));
QVideoFrame frame = surfaceB.frame();
QCOMPARE(frame.handleType(), QAbstractVideoBuffer::NoHandle);
QCOMPARE(frame.pixelFormat(), QVideoFrame::Format_RGB32);
QCOMPARE(frame.size(), QSize(75, 50));
// Test setting null media stops the surface.
viewer.setMedia(QMediaContent());
QCOMPARE(surfaceB.isActive(), false);
// Test the renderer control accepts a null surface.
rendererControl->setSurface(0);
QCOMPARE(rendererControl->surface(), nullSurface);
}
void tst_QMediaImageViewer::setVideoOutput()
{
QMediaImageViewer imageViewer;
imageViewer.setMedia(QMediaContent(imageUrl("image.png")));
connect(&imageViewer, SIGNAL(mediaStatusChanged(QMediaImageViewer::MediaStatus)),
&QTestEventLoop::instance(), SLOT(exitLoop()));
QTestEventLoop::instance().enterLoop(2);
if (imageViewer.mediaStatus() != QMediaImageViewer::LoadedMedia)
QSKIP("failed to load test image", SkipSingle);
QVideoWidget widget;
QGraphicsVideoItem item;
QtTestVideoSurface surface;
imageViewer.setVideoOutput(&widget);
QVERIFY(widget.mediaObject() == &imageViewer);
imageViewer.setVideoOutput(&item);
QVERIFY(widget.mediaObject() == 0);
QVERIFY(item.mediaObject() == &imageViewer);
imageViewer.setVideoOutput(reinterpret_cast<QVideoWidget *>(0));
QVERIFY(item.mediaObject() == 0);
imageViewer.setVideoOutput(&widget);
QVERIFY(widget.mediaObject() == &imageViewer);
imageViewer.setVideoOutput(reinterpret_cast<QGraphicsVideoItem *>(0));
QVERIFY(widget.mediaObject() == 0);
imageViewer.setVideoOutput(&surface);
QVERIFY(surface.isActive());
imageViewer.setVideoOutput(reinterpret_cast<QAbstractVideoSurface *>(0));
QVERIFY(!surface.isActive());
imageViewer.setVideoOutput(&surface);
QVERIFY(surface.isActive());
imageViewer.setVideoOutput(&widget);
QVERIFY(!surface.isActive());
QVERIFY(widget.mediaObject() == &imageViewer);
imageViewer.setVideoOutput(&surface);
QVERIFY(surface.isActive());
QVERIFY(widget.mediaObject() == 0);
}
void tst_QMediaImageViewer::debugEnums()
{
QTest::ignoreMessage(QtDebugMsg, "QMediaImageViewer::PlayingState ");
qDebug() << QMediaImageViewer::PlayingState;
QTest::ignoreMessage(QtDebugMsg, "QMediaImageViewer::NoMedia ");
qDebug() << QMediaImageViewer::NoMedia;
}
void tst_QMediaImageViewer::mediaChanged_signal()
{
QMediaContent imageMedia(imageUrl("image.png"));
QMediaImageViewer viewer;
viewer.setTimeout(250);
viewer.setNotifyInterval(150);
QSignalSpy spy(&viewer, SIGNAL(mediaChanged(QMediaContent)));
QVERIFY(spy.size() == 0);
viewer.setMedia(imageMedia);
QVERIFY(spy.size() == 1);
}
QTEST_MAIN(tst_QMediaImageViewer)
#include "tst_qmediaimageviewer.moc"
|
lgpl-2.1
|
poppogbr/genropy
|
dojo_libs/dojo_11/dojo/dojo/fx.js
|
7088
|
/*
Copyright (c) 2004-2008, The Dojo Foundation
All Rights Reserved.
Licensed under the Academic Free License version 2.1 or above OR the
modified BSD license. For more information on Dojo licensing, see:
http://dojotoolkit.org/book/dojo-book-0-9/introduction/licensing
*/
if(!dojo._hasResource["dojo.fx"]){
dojo._hasResource["dojo.fx"]=true;
dojo.provide("dojo.fx");
dojo.provide("dojo.fx.Toggler");
(function(){
var _1={_fire:function(_2,_3){
if(this[_2]){
this[_2].apply(this,_3||[]);
}
return this;
}};
var _4=function(_5){
this._index=-1;
this._animations=_5||[];
this._current=this._onAnimateCtx=this._onEndCtx=null;
this.duration=0;
dojo.forEach(this._animations,function(a){
this.duration+=a.duration;
if(a.delay){
this.duration+=a.delay;
}
},this);
};
dojo.extend(_4,{_onAnimate:function(){
this._fire("onAnimate",arguments);
},_onEnd:function(){
dojo.disconnect(this._onAnimateCtx);
dojo.disconnect(this._onEndCtx);
this._onAnimateCtx=this._onEndCtx=null;
if(this._index+1==this._animations.length){
this._fire("onEnd");
}else{
this._current=this._animations[++this._index];
this._onAnimateCtx=dojo.connect(this._current,"onAnimate",this,"_onAnimate");
this._onEndCtx=dojo.connect(this._current,"onEnd",this,"_onEnd");
this._current.play(0,true);
}
},play:function(_7,_8){
if(!this._current){
this._current=this._animations[this._index=0];
}
if(!_8&&this._current.status()=="playing"){
return this;
}
var _9=dojo.connect(this._current,"beforeBegin",this,function(){
this._fire("beforeBegin");
}),_a=dojo.connect(this._current,"onBegin",this,function(_b){
this._fire("onBegin",arguments);
}),_c=dojo.connect(this._current,"onPlay",this,function(_d){
this._fire("onPlay",arguments);
dojo.disconnect(_9);
dojo.disconnect(_a);
dojo.disconnect(_c);
});
if(this._onAnimateCtx){
dojo.disconnect(this._onAnimateCtx);
}
this._onAnimateCtx=dojo.connect(this._current,"onAnimate",this,"_onAnimate");
if(this._onEndCtx){
dojo.disconnect(this._onEndCtx);
}
this._onEndCtx=dojo.connect(this._current,"onEnd",this,"_onEnd");
this._current.play.apply(this._current,arguments);
return this;
},pause:function(){
if(this._current){
var e=dojo.connect(this._current,"onPause",this,function(_f){
this._fire("onPause",arguments);
dojo.disconnect(e);
});
this._current.pause();
}
return this;
},gotoPercent:function(_10,_11){
this.pause();
var _12=this.duration*_10;
this._current=null;
dojo.some(this._animations,function(a){
if(a.duration<=_12){
this._current=a;
return true;
}
_12-=a.duration;
return false;
});
if(this._current){
this._current.gotoPercent(_12/_current.duration,_11);
}
return this;
},stop:function(_14){
if(this._current){
if(_14){
for(;this._index+1<this._animations.length;++this._index){
this._animations[this._index].stop(true);
}
this._current=this._animations[this._index];
}
var e=dojo.connect(this._current,"onStop",this,function(arg){
this._fire("onStop",arguments);
dojo.disconnect(e);
});
this._current.stop();
}
return this;
},status:function(){
return this._current?this._current.status():"stopped";
},destroy:function(){
if(this._onAnimateCtx){
dojo.disconnect(this._onAnimateCtx);
}
if(this._onEndCtx){
dojo.disconnect(this._onEndCtx);
}
}});
dojo.extend(_4,_1);
dojo.fx.chain=function(_17){
return new _4(_17);
};
var _18=function(_19){
this._animations=_19||[];
this._connects=[];
this._finished=0;
this.duration=0;
dojo.forEach(_19,function(a){
var _1b=a.duration;
if(a.delay){
_1b+=a.delay;
}
if(this.duration<_1b){
this.duration=_1b;
}
this._connects.push(dojo.connect(a,"onEnd",this,"_onEnd"));
},this);
this._pseudoAnimation=new dojo._Animation({curve:[0,1],duration:this.duration});
dojo.forEach(["beforeBegin","onBegin","onPlay","onAnimate","onPause","onStop"],function(evt){
this._connects.push(dojo.connect(this._pseudoAnimation,evt,dojo.hitch(this,"_fire",evt)));
},this);
};
dojo.extend(_18,{_doAction:function(_1d,_1e){
dojo.forEach(this._animations,function(a){
a[_1d].apply(a,_1e);
});
return this;
},_onEnd:function(){
if(++this._finished==this._animations.length){
this._fire("onEnd");
}
},_call:function(_20,_21){
var t=this._pseudoAnimation;
t[_20].apply(t,_21);
},play:function(_23,_24){
this._finished=0;
this._doAction("play",arguments);
this._call("play",arguments);
return this;
},pause:function(){
this._doAction("pause",arguments);
this._call("pause",arguments);
return this;
},gotoPercent:function(_25,_26){
var ms=this.duration*_25;
dojo.forEach(this._animations,function(a){
a.gotoPercent(a.duration<ms?1:(ms/a.duration),_26);
});
this._call("gotoProcent",arguments);
return this;
},stop:function(_29){
this._doAction("stop",arguments);
this._call("stop",arguments);
return this;
},status:function(){
return this._pseudoAnimation.status();
},destroy:function(){
dojo.forEach(this._connects,dojo.disconnect);
}});
dojo.extend(_18,_1);
dojo.fx.combine=function(_2a){
return new _18(_2a);
};
})();
dojo.declare("dojo.fx.Toggler",null,{constructor:function(_2b){
var _t=this;
dojo.mixin(_t,_2b);
_t.node=_2b.node;
_t._showArgs=dojo.mixin({},_2b);
_t._showArgs.node=_t.node;
_t._showArgs.duration=_t.showDuration;
_t.showAnim=_t.showFunc(_t._showArgs);
_t._hideArgs=dojo.mixin({},_2b);
_t._hideArgs.node=_t.node;
_t._hideArgs.duration=_t.hideDuration;
_t.hideAnim=_t.hideFunc(_t._hideArgs);
dojo.connect(_t.showAnim,"beforeBegin",dojo.hitch(_t.hideAnim,"stop",true));
dojo.connect(_t.hideAnim,"beforeBegin",dojo.hitch(_t.showAnim,"stop",true));
},node:null,showFunc:dojo.fadeIn,hideFunc:dojo.fadeOut,showDuration:200,hideDuration:200,show:function(_2d){
return this.showAnim.play(_2d||0);
},hide:function(_2e){
return this.hideAnim.play(_2e||0);
}});
dojo.fx.wipeIn=function(_2f){
_2f.node=dojo.byId(_2f.node);
var _30=_2f.node,s=_30.style;
var _32=dojo.animateProperty(dojo.mixin({properties:{height:{start:function(){
s.overflow="hidden";
if(s.visibility=="hidden"||s.display=="none"){
s.height="1px";
s.display="";
s.visibility="";
return 1;
}else{
var _33=dojo.style(_30,"height");
return Math.max(_33,1);
}
},end:function(){
return _30.scrollHeight;
}}}},_2f));
dojo.connect(_32,"onEnd",function(){
s.height="auto";
});
return _32;
};
dojo.fx.wipeOut=function(_34){
var _35=_34.node=dojo.byId(_34.node);
var s=_35.style;
var _37=dojo.animateProperty(dojo.mixin({properties:{height:{end:1}}},_34));
dojo.connect(_37,"beforeBegin",function(){
s.overflow="hidden";
s.display="";
});
dojo.connect(_37,"onEnd",function(){
s.height="auto";
s.display="none";
});
return _37;
};
dojo.fx.slideTo=function(_38){
var _39=(_38.node=dojo.byId(_38.node));
var top=null;
var _3b=null;
var _3c=(function(n){
return function(){
var cs=dojo.getComputedStyle(n);
var pos=cs.position;
top=(pos=="absolute"?n.offsetTop:parseInt(cs.top)||0);
_3b=(pos=="absolute"?n.offsetLeft:parseInt(cs.left)||0);
if(pos!="absolute"&&pos!="relative"){
var ret=dojo.coords(n,true);
top=ret.y;
_3b=ret.x;
n.style.position="absolute";
n.style.top=top+"px";
n.style.left=_3b+"px";
}
};
})(_39);
_3c();
var _41=dojo.animateProperty(dojo.mixin({properties:{top:{end:_38.top||0},left:{end:_38.left||0}}},_38));
dojo.connect(_41,"beforeBegin",_41,_3c);
return _41;
};
}
|
lgpl-2.1
|
maddingo/checkstyle
|
src/checkstyle/com/puppycrawl/tools/checkstyle/api/AutomaticBean.java
|
12262
|
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2012 Oliver Burn
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.api;
import com.google.common.collect.Lists;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.ConvertUtilsBean;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.apache.commons.beanutils.converters.ArrayConverter;
import org.apache.commons.beanutils.converters.BooleanConverter;
import org.apache.commons.beanutils.converters.ByteConverter;
import org.apache.commons.beanutils.converters.CharacterConverter;
import org.apache.commons.beanutils.converters.DoubleConverter;
import org.apache.commons.beanutils.converters.FloatConverter;
import org.apache.commons.beanutils.converters.IntegerConverter;
import org.apache.commons.beanutils.converters.LongConverter;
import org.apache.commons.beanutils.converters.ShortConverter;
/**
* A Java Bean that implements the component lifecycle interfaces by
* calling the bean's setters for all configuration attributes.
* @author lkuehne
*/
public class AutomaticBean
implements Configurable, Contextualizable
{
/** the configuration of this bean */
private Configuration mConfiguration;
/**
* Creates a BeanUtilsBean that is configured to use
* type converters that throw a ConversionException
* instead of using the default value when something
* goes wrong.
*
* @return a configured BeanUtilsBean
*/
private static BeanUtilsBean createBeanUtilsBean()
{
final ConvertUtilsBean cub = new ConvertUtilsBean();
// TODO: is there a smarter way to tell beanutils not to use defaults?
cub.register(new BooleanConverter(), Boolean.TYPE);
cub.register(new BooleanConverter(), Boolean.class);
cub.register(new ArrayConverter(
boolean[].class, new BooleanConverter()), boolean[].class);
cub.register(new ByteConverter(), Byte.TYPE);
cub.register(new ByteConverter(), Byte.class);
cub.register(new ArrayConverter(byte[].class, new ByteConverter()),
byte[].class);
cub.register(new CharacterConverter(), Character.TYPE);
cub.register(new CharacterConverter(), Character.class);
cub.register(new ArrayConverter(char[].class, new CharacterConverter()),
char[].class);
cub.register(new DoubleConverter(), Double.TYPE);
cub.register(new DoubleConverter(), Double.class);
cub.register(new ArrayConverter(double[].class, new DoubleConverter()),
double[].class);
cub.register(new FloatConverter(), Float.TYPE);
cub.register(new FloatConverter(), Float.class);
cub.register(new ArrayConverter(float[].class, new FloatConverter()),
float[].class);
cub.register(new IntegerConverter(), Integer.TYPE);
cub.register(new IntegerConverter(), Integer.class);
cub.register(new ArrayConverter(int[].class, new IntegerConverter()),
int[].class);
cub.register(new LongConverter(), Long.TYPE);
cub.register(new LongConverter(), Long.class);
cub.register(new ArrayConverter(long[].class, new LongConverter()),
long[].class);
cub.register(new ShortConverter(), Short.TYPE);
cub.register(new ShortConverter(), Short.class);
cub.register(new ArrayConverter(short[].class, new ShortConverter()),
short[].class);
cub.register(new RelaxedStringArrayConverter(), String[].class);
// BigDecimal, BigInteger, Class, Date, String, Time, TimeStamp
// do not use defaults in the default configuration of ConvertUtilsBean
return new BeanUtilsBean(cub, new PropertyUtilsBean());
}
/**
* Implements the Configurable interface using bean introspection.
*
* Subclasses are allowed to add behaviour. After the bean
* based setup has completed first the method
* {@link #finishLocalSetup finishLocalSetup}
* is called to allow completion of the bean's local setup,
* after that the method {@link #setupChild setupChild}
* is called for each {@link Configuration#getChildren child Configuration}
* of <code>aConfiguration</code>.
*
* @param aConfiguration {@inheritDoc}
* @throws CheckstyleException {@inheritDoc}
* @see Configurable
*/
public final void configure(Configuration aConfiguration)
throws CheckstyleException
{
mConfiguration = aConfiguration;
final BeanUtilsBean beanUtils = createBeanUtilsBean();
// TODO: debug log messages
final String[] attributes = aConfiguration.getAttributeNames();
for (final String key : attributes) {
final String value = aConfiguration.getAttribute(key);
try {
// BeanUtilsBean.copyProperties silently ignores missing setters
// for key, so we have to go through great lengths here to
// figure out if the bean property really exists.
final PropertyDescriptor pd =
PropertyUtils.getPropertyDescriptor(this, key);
if ((pd == null) || (pd.getWriteMethod() == null)) {
throw new CheckstyleException(
"Property '" + key + "' in module "
+ aConfiguration.getName()
+ " does not exist, please check the documentation");
}
// finally we can set the bean property
beanUtils.copyProperty(this, key, value);
}
catch (final InvocationTargetException e) {
throw new CheckstyleException(
"Cannot set property '" + key + "' in module "
+ aConfiguration.getName() + " to '" + value
+ "': " + e.getTargetException().getMessage(), e);
}
catch (final IllegalAccessException e) {
throw new CheckstyleException(
"cannot access " + key + " in "
+ this.getClass().getName(), e);
}
catch (final NoSuchMethodException e) {
throw new CheckstyleException(
"cannot access " + key + " in "
+ this.getClass().getName(), e);
}
catch (final IllegalArgumentException e) {
throw new CheckstyleException(
"illegal value '" + value + "' for property '" + key
+ "' of module " + aConfiguration.getName(), e);
}
catch (final ConversionException e) {
throw new CheckstyleException(
"illegal value '" + value + "' for property '" + key
+ "' of module " + aConfiguration.getName(), e);
}
}
finishLocalSetup();
final Configuration[] childConfigs = aConfiguration.getChildren();
for (final Configuration childConfig : childConfigs) {
setupChild(childConfig);
}
}
/**
* Implements the Contextualizable interface using bean introspection.
* @param aContext {@inheritDoc}
* @throws CheckstyleException {@inheritDoc}
* @see Contextualizable
*/
public final void contextualize(Context aContext)
throws CheckstyleException
{
final BeanUtilsBean beanUtils = createBeanUtilsBean();
// TODO: debug log messages
final Collection<String> attributes = aContext.getAttributeNames();
for (final String key : attributes) {
final Object value = aContext.get(key);
try {
beanUtils.copyProperty(this, key, value);
}
catch (final InvocationTargetException e) {
// TODO: log.debug("The bean " + this.getClass()
// + " is not interested in " + value)
throw new CheckstyleException("cannot set property "
+ key + " to value " + value + " in bean "
+ this.getClass().getName(), e);
}
catch (final IllegalAccessException e) {
throw new CheckstyleException(
"cannot access " + key + " in "
+ this.getClass().getName(), e);
}
catch (final IllegalArgumentException e) {
throw new CheckstyleException(
"illegal value '" + value + "' for property '" + key
+ "' of bean " + this.getClass().getName(), e);
}
catch (final ConversionException e) {
throw new CheckstyleException(
"illegal value '" + value + "' for property '" + key
+ "' of bean " + this.getClass().getName(), e);
}
}
}
/**
* Returns the configuration that was used to configure this component.
* @return the configuration that was used to configure this component.
*/
protected final Configuration getConfiguration()
{
return mConfiguration;
}
/**
* Provides a hook to finish the part of this component's setup that
* was not handled by the bean introspection.
* <p>
* The default implementation does nothing.
* </p>
* @throws CheckstyleException if there is a configuration error.
*/
protected void finishLocalSetup() throws CheckstyleException
{
}
/**
* Called by configure() for every child of this component's Configuration.
* <p>
* The default implementation does nothing.
* </p>
* @param aChildConf a child of this component's Configuration
* @throws CheckstyleException if there is a configuration error.
* @see Configuration#getChildren
*/
protected void setupChild(Configuration aChildConf)
throws CheckstyleException
{
}
/**
* A converter that does not care whether the array elements contain String
* characters like '*' or '_'. The normal ArrayConverter class has problems
* with this characters.
*/
private static class RelaxedStringArrayConverter implements Converter
{
/** {@inheritDoc} */
public Object convert(@SuppressWarnings("rawtypes") Class aType,
Object aValue)
{
if (null == aType) {
throw new ConversionException("Cannot convert from null.");
}
// Convert to a String and trim it for the tokenizer.
final StringTokenizer st = new StringTokenizer(
aValue.toString().trim(), ",");
final List<String> result = Lists.newArrayList();
while (st.hasMoreTokens()) {
final String token = st.nextToken();
result.add(token.trim());
}
return result.toArray(new String[result.size()]);
}
}
}
|
lgpl-2.1
|
sgeh/JSTools.net
|
Branches/JSTools 0.41/JSTools.Config/JSTools/Config/IJSToolsRenderHandler.cs
|
1955
|
/*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using JSTools.Config.ExceptionHandling;
using JSTools.Config.ScriptFileManagement;
namespace JSTools.Config
{
/// <summary>
/// This interface is used to render a JSTools section. To enable A IJSToolsRenderHandler,
/// you have to add it to a RenderProcessTicket object.
/// </summary>
public interface IJSToolsRenderHandler
{
//--------------------------------------------------------------------
// Properties
//--------------------------------------------------------------------
/// <summary>
/// Name of the section to render with this render handler.
/// </summary>
string SectionName
{
get;
}
//--------------------------------------------------------------------
// Methods
//--------------------------------------------------------------------
/// <summary>
/// The configuration will call this method to render the section with the name
/// given by the SectionName attribute.
/// </summary>
/// <param name="ticket">Ticket, which contains the render informations.</param>
/// <param name="sectionToRender">Configuration section to render.</param>
void RenderSection(RenderProcessTicket ticket, AJSToolsSection sectionToRender);
}
}
|
lgpl-2.1
|
igor-sfdc/qt-wk
|
tools/configure/environment.cpp
|
16833
|
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the tools applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "environment.h"
#include <process.h>
#include <iostream>
#include <qdebug.h>
#include <QDir>
#include <QStringList>
#include <QMap>
#include <QDir>
#include <QFile>
#include <QFileInfo>
//#define CONFIGURE_DEBUG_EXECUTE
//#define CONFIGURE_DEBUG_CP_DIR
using namespace std;
#ifdef Q_OS_WIN32
#include <qt_windows.h>
#endif
#include <symbian/epocroot.h> // from tools/shared
#include <windows/registry.h> // from tools/shared
QT_BEGIN_NAMESPACE
struct CompilerInfo{
Compiler compiler;
const char *compilerStr;
const char *regKey;
const char *executable;
} compiler_info[] = {
// The compilers here are sorted in a reversed-preferred order
{CC_BORLAND, "Borland C++", 0, "bcc32.exe"},
{CC_MINGW, "MinGW (Minimalist GNU for Windows)", 0, "g++.exe"},
{CC_INTEL, "Intel(R) C++ Compiler for 32-bit applications", 0, "icl.exe"}, // xilink.exe, xilink5.exe, xilink6.exe, xilib.exe
{CC_MSVC6, "Microsoft (R) 32-bit C/C++ Optimizing Compiler (6.x)", "Software\\Microsoft\\VisualStudio\\6.0\\Setup\\Microsoft Visual C++\\ProductDir", "cl.exe"}, // link.exe, lib.exe
{CC_NET2002, "Microsoft (R) 32-bit C/C++ Optimizing Compiler.NET 2002 (7.0)", "Software\\Microsoft\\VisualStudio\\7.0\\Setup\\VC\\ProductDir", "cl.exe"}, // link.exe, lib.exe
{CC_NET2003, "Microsoft (R) 32-bit C/C++ Optimizing Compiler.NET 2003 (7.1)", "Software\\Microsoft\\VisualStudio\\7.1\\Setup\\VC\\ProductDir", "cl.exe"}, // link.exe, lib.exe
{CC_NET2005, "Microsoft (R) 32-bit C/C++ Optimizing Compiler.NET 2005 (8.0)", "Software\\Microsoft\\VisualStudio\\SxS\\VC7\\8.0", "cl.exe"}, // link.exe, lib.exe
{CC_NET2008, "Microsoft (R) 32-bit C/C++ Optimizing Compiler.NET 2008 (9.0)", "Software\\Microsoft\\VisualStudio\\SxS\\VC7\\9.0", "cl.exe"}, // link.exe, lib.exe
{CC_NET2010, "Microsoft (R) 32-bit C/C++ Optimizing Compiler.NET 2010 (10.0)", "Software\\Microsoft\\VisualStudio\\SxS\\VC7\\10.0", "cl.exe"}, // link.exe, lib.exe
{CC_UNKNOWN, "Unknown", 0, 0},
};
// Initialize static variables
Compiler Environment::detectedCompiler = CC_UNKNOWN;
/*!
Returns the pointer to the CompilerInfo for a \a compiler.
*/
CompilerInfo *Environment::compilerInfo(Compiler compiler)
{
int i = 0;
while(compiler_info[i].compiler != compiler && compiler_info[i].compiler != CC_UNKNOWN)
++i;
return &(compiler_info[i]);
}
/*!
Returns the qmakespec for the compiler detected on the system.
*/
QString Environment::detectQMakeSpec()
{
QString spec;
switch (detectCompiler()) {
case CC_NET2010:
spec = "win32-msvc2010";
break;
case CC_NET2008:
spec = "win32-msvc2008";
break;
case CC_NET2005:
spec = "win32-msvc2005";
break;
case CC_NET2003:
spec = "win32-msvc2003";
break;
case CC_NET2002:
spec = "win32-msvc2002";
break;
case CC_MSVC4:
case CC_MSVC5:
case CC_MSVC6:
spec = "win32-msvc";
break;
case CC_INTEL:
spec = "win32-icc";
break;
case CC_MINGW:
spec = "win32-g++";
break;
case CC_BORLAND:
spec = "win32-borland";
break;
default:
break;
}
return spec;
}
/*!
Returns the enum of the compiler which was detected on the system.
The compilers are detected in the order as entered into the
compiler_info list.
If more than one compiler is found, CC_UNKNOWN is returned.
*/
Compiler Environment::detectCompiler()
{
#ifndef Q_OS_WIN32
return MSVC6; // Always generate MSVC 6.0 versions on other platforms
#else
if(detectedCompiler != CC_UNKNOWN)
return detectedCompiler;
int installed = 0;
// Check for compilers in registry first, to see which version is in PATH
QString paths = qgetenv("PATH");
QStringList pathlist = paths.toLower().split(";");
for(int i = 0; compiler_info[i].compiler; ++i) {
QString productPath = readRegistryKey(HKEY_LOCAL_MACHINE, compiler_info[i].regKey).toLower();
if (productPath.length()) {
QStringList::iterator it;
for(it = pathlist.begin(); it != pathlist.end(); ++it) {
if((*it).contains(productPath)) {
++installed;
detectedCompiler = compiler_info[i].compiler;
break;
}
}
}
}
// Now just go looking for the executables, and accept any executable as the lowest version
if (!installed) {
for(int i = 0; compiler_info[i].compiler; ++i) {
QString executable = QString(compiler_info[i].executable).toLower();
if (executable.length() && Environment::detectExecutable(executable)) {
++installed;
detectedCompiler = compiler_info[i].compiler;
break;
}
}
}
if (installed > 1) {
cout << "Found more than one known compiler! Using \"" << compilerInfo(detectedCompiler)->compilerStr << "\"" << endl;
detectedCompiler = CC_UNKNOWN;
}
return detectedCompiler;
#endif
};
/*!
Returns true if the \a executable could be loaded, else false.
This means that the executable either is in the current directory
or in the PATH.
*/
bool Environment::detectExecutable(const QString &executable)
{
PROCESS_INFORMATION procInfo;
memset(&procInfo, 0, sizeof(procInfo));
STARTUPINFO startInfo;
memset(&startInfo, 0, sizeof(startInfo));
startInfo.cb = sizeof(startInfo);
bool couldExecute = CreateProcess(0, (wchar_t*)executable.utf16(),
0, 0, false,
CREATE_NO_WINDOW | CREATE_SUSPENDED,
0, 0, &startInfo, &procInfo);
if (couldExecute) {
CloseHandle(procInfo.hThread);
TerminateProcess(procInfo.hProcess, 0);
CloseHandle(procInfo.hProcess);
}
return couldExecute;
}
/*!
Creates a commandling from \a program and it \a arguments,
escaping characters that needs it.
*/
static QString qt_create_commandline(const QString &program, const QStringList &arguments)
{
QString programName = program;
if (!programName.startsWith("\"") && !programName.endsWith("\"") && programName.contains(" "))
programName = "\"" + programName + "\"";
programName.replace("/", "\\");
QString args;
// add the prgram as the first arrg ... it works better
args = programName + " ";
for (int i=0; i<arguments.size(); ++i) {
QString tmp = arguments.at(i);
// in the case of \" already being in the string the \ must also be escaped
tmp.replace( "\\\"", "\\\\\"" );
// escape a single " because the arguments will be parsed
tmp.replace( "\"", "\\\"" );
if (tmp.isEmpty() || tmp.contains(' ') || tmp.contains('\t')) {
// The argument must not end with a \ since this would be interpreted
// as escaping the quote -- rather put the \ behind the quote: e.g.
// rather use "foo"\ than "foo\"
QString endQuote("\"");
int i = tmp.length();
while (i>0 && tmp.at(i-1) == '\\') {
--i;
endQuote += "\\";
}
args += QString(" \"") + tmp.left(i) + endQuote;
} else {
args += ' ' + tmp;
}
}
return args;
}
/*!
Creates a QByteArray of the \a environment.
*/
static QByteArray qt_create_environment(const QStringList &environment)
{
QByteArray envlist;
if (environment.isEmpty())
return envlist;
int pos = 0;
// add PATH if necessary (for DLL loading)
QByteArray path = qgetenv("PATH");
if (environment.filter(QRegExp("^PATH=",Qt::CaseInsensitive)).isEmpty() && !path.isNull()) {
QString tmp = QString(QLatin1String("PATH=%1")).arg(QString::fromLocal8Bit(path));
uint tmpSize = sizeof(wchar_t) * (tmp.length() + 1);
envlist.resize(envlist.size() + tmpSize);
memcpy(envlist.data() + pos, tmp.utf16(), tmpSize);
pos += tmpSize;
}
// add the user environment
for (QStringList::ConstIterator it = environment.begin(); it != environment.end(); it++ ) {
QString tmp = *it;
uint tmpSize = sizeof(wchar_t) * (tmp.length() + 1);
envlist.resize(envlist.size() + tmpSize);
memcpy(envlist.data() + pos, tmp.utf16(), tmpSize);
pos += tmpSize;
}
// add the 2 terminating 0 (actually 4, just to be on the safe side)
envlist.resize(envlist.size() + 4);
envlist[pos++] = 0;
envlist[pos++] = 0;
envlist[pos++] = 0;
envlist[pos++] = 0;
return envlist;
}
/*!
Executes the command described in \a arguments, in the
environment inherited from the parent process, with the
\a additionalEnv settings applied.
\a removeEnv removes the specified environment variables from
the environment of the executed process.
Returns the exit value of the process, or -1 if the command could
not be executed.
This function uses _(w)spawnvpe to spawn a process by searching
through the PATH environment variable.
*/
int Environment::execute(QStringList arguments, const QStringList &additionalEnv, const QStringList &removeEnv)
{
#ifdef CONFIGURE_DEBUG_EXECUTE
qDebug() << "About to Execute: " << arguments;
qDebug() << " " << QDir::currentPath();
qDebug() << " " << additionalEnv;
qDebug() << " " << removeEnv;
#endif
// Create the full environment from the current environment and
// the additionalEnv strings, then remove all variables defined
// in removeEnv
QMap<QString, QString> fullEnvMap;
LPWSTR envStrings = GetEnvironmentStrings();
if (envStrings) {
int strLen = 0;
for (LPWSTR envString = envStrings; *(envString); envString += strLen + 1) {
strLen = wcslen(envString);
QString str = QString((const QChar*)envString, strLen);
if (!str.startsWith("=")) { // These are added by the system
int sepIndex = str.indexOf('=');
fullEnvMap.insert(str.left(sepIndex).toUpper(), str.mid(sepIndex +1));
}
}
}
FreeEnvironmentStrings(envStrings);
// Add additionalEnv variables
for (int i = 0; i < additionalEnv.count(); ++i) {
const QString &str = additionalEnv.at(i);
int sepIndex = str.indexOf('=');
fullEnvMap.insert(str.left(sepIndex).toUpper(), str.mid(sepIndex +1));
}
// Remove removeEnv variables
for (int j = 0; j < removeEnv.count(); ++j)
fullEnvMap.remove(removeEnv.at(j).toUpper());
// Add all variables to a QStringList
QStringList fullEnv;
QMapIterator<QString, QString> it(fullEnvMap);
while (it.hasNext()) {
it.next();
fullEnv += QString(it.key() + "=" + it.value());
}
// ----------------------------
QString program = arguments.takeAt(0);
QString args = qt_create_commandline(program, arguments);
QByteArray envlist = qt_create_environment(fullEnv);
DWORD exitCode = DWORD(-1);
PROCESS_INFORMATION procInfo;
memset(&procInfo, 0, sizeof(procInfo));
STARTUPINFO startInfo;
memset(&startInfo, 0, sizeof(startInfo));
startInfo.cb = sizeof(startInfo);
bool couldExecute = CreateProcess(0, (wchar_t*)args.utf16(),
0, 0, true, CREATE_UNICODE_ENVIRONMENT,
envlist.isEmpty() ? 0 : envlist.data(),
0, &startInfo, &procInfo);
if (couldExecute) {
WaitForSingleObject(procInfo.hProcess, INFINITE);
GetExitCodeProcess(procInfo.hProcess, &exitCode);
CloseHandle(procInfo.hThread);
CloseHandle(procInfo.hProcess);
}
if (exitCode == DWORD(-1)) {
switch(GetLastError()) {
case E2BIG:
cerr << "execute: Argument list exceeds 1024 bytes" << endl;
foreach(QString arg, arguments)
cerr << " (" << arg.toLocal8Bit().constData() << ")" << endl;
break;
case ENOENT:
cerr << "execute: File or path is not found (" << program.toLocal8Bit().constData() << ")" << endl;
break;
case ENOEXEC:
cerr << "execute: Specified file is not executable or has invalid executable-file format (" << program.toLocal8Bit().constData() << ")" << endl;
break;
case ENOMEM:
cerr << "execute: Not enough memory is available to execute new process." << endl;
break;
default:
cerr << "execute: Unknown error" << endl;
foreach(QString arg, arguments)
cerr << " (" << arg.toLocal8Bit().constData() << ")" << endl;
break;
}
}
return exitCode;
}
bool Environment::cpdir(const QString &srcDir, const QString &destDir)
{
QString cleanSrcName = QDir::cleanPath(srcDir);
QString cleanDstName = QDir::cleanPath(destDir);
#ifdef CONFIGURE_DEBUG_CP_DIR
qDebug() << "Attempt to cpdir " << cleanSrcName << "->" << cleanDstName;
#endif
if(!QFile::exists(cleanDstName) && !QDir().mkpath(cleanDstName)) {
qDebug() << "cpdir: Failure to create " << cleanDstName;
return false;
}
bool result = true;
QDir dir = QDir(cleanSrcName);
QFileInfoList allEntries = dir.entryInfoList(QDir::AllDirs | QDir::Files | QDir::NoDotAndDotDot);
for (int i = 0; result && (i < allEntries.count()); ++i) {
QFileInfo entry = allEntries.at(i);
bool intermediate = true;
if (entry.isDir()) {
intermediate = cpdir(QString("%1/%2").arg(cleanSrcName).arg(entry.fileName()),
QString("%1/%2").arg(cleanDstName).arg(entry.fileName()));
} else {
QString destFile = QString("%1/%2").arg(cleanDstName).arg(entry.fileName());
#ifdef CONFIGURE_DEBUG_CP_DIR
qDebug() << "About to cp (file)" << entry.absoluteFilePath() << "->" << destFile;
#endif
QFile::remove(destFile);
intermediate = QFile::copy(entry.absoluteFilePath(), destFile);
SetFileAttributes((wchar_t*)destFile.utf16(), FILE_ATTRIBUTE_NORMAL);
}
if(!intermediate) {
qDebug() << "cpdir: Failure for " << entry.fileName() << entry.isDir();
result = false;
}
}
return result;
}
bool Environment::rmdir(const QString &name)
{
bool result = true;
QString cleanName = QDir::cleanPath(name);
QDir dir = QDir(cleanName);
QFileInfoList allEntries = dir.entryInfoList(QDir::AllDirs | QDir::Files | QDir::NoDotAndDotDot);
for (int i = 0; result && (i < allEntries.count()); ++i) {
QFileInfo entry = allEntries.at(i);
if (entry.isDir()) {
result &= rmdir(entry.absoluteFilePath());
} else {
result &= QFile::remove(entry.absoluteFilePath());
}
}
result &= dir.rmdir(cleanName);
return result;
}
QString Environment::symbianEpocRoot()
{
// Call function defined in tools/shared/symbian/epocroot.h
return ::epocRoot();
}
QT_END_NAMESPACE
|
lgpl-2.1
|
TelepathyIM/telepathy-qt
|
tests/channel-class-spec.cpp
|
5001
|
#include <QtTest/QtTest>
#include <TelepathyQt/Constants>
#include <TelepathyQt/Debug>
#include <TelepathyQt/ChannelClassSpec>
#include <TelepathyQt/Types>
using namespace Tp;
namespace {
ChannelClassSpecList reverse(const ChannelClassSpecList &list)
{
ChannelClassSpecList ret(list);
for (int k = 0; k < (list.size() / 2); k++) {
ret.swap(k, list.size() - (1 + k));
}
return ret;
}
};
class TestChannelClassSpec : public QObject
{
Q_OBJECT
public:
TestChannelClassSpec(QObject *parent = nullptr);
private Q_SLOTS:
void testChannelClassSpecHash();
void testServiceLeaks();
};
TestChannelClassSpec::TestChannelClassSpec(QObject *parent)
: QObject(parent)
{
Tp::enableDebug(true);
Tp::enableWarnings(true);
}
void TestChannelClassSpec::testChannelClassSpecHash()
{
ChannelClassSpec st1 = ChannelClassSpec::textChat();
ChannelClassSpec st2 = ChannelClassSpec::textChat();
ChannelClassSpec ssm1 = ChannelClassSpec::streamedMediaCall();
ChannelClassSpec ssm2 = ChannelClassSpec::streamedMediaCall();
QCOMPARE(qHash(st1), qHash(st2));
QCOMPARE(qHash(ssm1), qHash(ssm2));
QVERIFY(qHash(st1) != qHash(ssm1));
// hash of list with duplicated elements should be the same as hash of the list of same items
// but with no duplicates
ChannelClassSpecList sl1;
sl1 << st1 << st2;
ChannelClassSpecList sl2;
sl2 << st1;
QCOMPARE(qHash(sl1), qHash(sl2));
// hash of list with same elements but different order should be the same
sl1.clear();
sl2.clear();
sl1 << st1 << ssm1;
sl2 << ssm1 << st1;
QCOMPARE(qHash(sl1), qHash(sl2));
// still the same but with duplicated elements
sl2 << ssm2 << st2;
QCOMPARE(qHash(sl1), qHash(sl2));
sl1 << st2;
QCOMPARE(qHash(sl1), qHash(sl2));
// now sl2 is different from sl1, hash should be different
sl2 << ChannelClassSpec::unnamedTextChat();
QVERIFY(qHash(sl1) != qHash(sl2));
// same again
sl1.prepend(ChannelClassSpec::unnamedTextChat());
QCOMPARE(qHash(sl1), qHash(sl2));
sl1.clear();
sl2.clear();
for (int i = 0; i < 100; ++i) {
sl1 << ChannelClassSpec::textChat() <<
ChannelClassSpec::streamedMediaCall() <<
ChannelClassSpec::unnamedTextChat();
}
ChannelClassSpec specs[3] = {
ChannelClassSpec::textChat(),
ChannelClassSpec::streamedMediaCall(),
ChannelClassSpec::unnamedTextChat()
};
for (int i = 0; i < 3; ++i) {
ChannelClassSpec spec = specs[i];
for (int j = 0; j < 100; ++j) {
sl2 << spec;
}
}
QCOMPARE(qHash(sl1), qHash(ChannelClassSpecList() <<
ChannelClassSpec::unnamedTextChat() <<
ChannelClassSpec::streamedMediaCall() <<
ChannelClassSpec::textChat()));
for (int i = 0; i < 1000; ++i) {
ChannelClassSpec spec = ChannelClassSpec::outgoingStreamTube(QString::number(i));
sl1 << spec;
sl2.prepend(spec);
}
QCOMPARE(qHash(sl1), qHash(sl2));
sl1 = reverse(sl1);
sl2 = reverse(sl2);
QCOMPARE(qHash(sl1), qHash(sl2));
sl2 << ChannelClassSpec::outgoingFileTransfer();
QVERIFY(qHash(sl1) != qHash(sl2));
}
void TestChannelClassSpec::testServiceLeaks()
{
ChannelClassSpec bareTube = ChannelClassSpec::outgoingStreamTube();
QVERIFY(!bareTube.allProperties().contains(TP_QT_IFACE_CHANNEL_TYPE_STREAM_TUBE +
QString::fromLatin1(".Service")));
ChannelClassSpec ftpTube = ChannelClassSpec::outgoingStreamTube(QLatin1String("ftp"));
QVERIFY(ftpTube.allProperties().contains(TP_QT_IFACE_CHANNEL_TYPE_STREAM_TUBE +
QString::fromLatin1(".Service")));
QCOMPARE(ftpTube.allProperties().value(TP_QT_IFACE_CHANNEL_TYPE_STREAM_TUBE +
QString::fromLatin1(".Service")).toString(), QString::fromLatin1("ftp"));
QVERIFY(!bareTube.allProperties().contains(TP_QT_IFACE_CHANNEL_TYPE_STREAM_TUBE +
QString::fromLatin1(".Service")));
ChannelClassSpec httpTube = ChannelClassSpec::outgoingStreamTube(QLatin1String("http"));
QVERIFY(httpTube.allProperties().contains(TP_QT_IFACE_CHANNEL_TYPE_STREAM_TUBE +
QString::fromLatin1(".Service")));
QVERIFY(ftpTube.allProperties().contains(TP_QT_IFACE_CHANNEL_TYPE_STREAM_TUBE +
QString::fromLatin1(".Service")));
QCOMPARE(httpTube.allProperties().value(TP_QT_IFACE_CHANNEL_TYPE_STREAM_TUBE +
QString::fromLatin1(".Service")).toString(), QString::fromLatin1("http"));
QCOMPARE(ftpTube.allProperties().value(TP_QT_IFACE_CHANNEL_TYPE_STREAM_TUBE +
QString::fromLatin1(".Service")).toString(), QString::fromLatin1("ftp"));
QVERIFY(!bareTube.allProperties().contains(TP_QT_IFACE_CHANNEL_TYPE_STREAM_TUBE +
QString::fromLatin1(".Service")));
}
QTEST_MAIN(TestChannelClassSpec)
#include "_gen/channel-class-spec.cpp.moc.hpp"
|
lgpl-2.1
|
olvidalo/exist
|
exist-testkit/src/main/java/org/exist/ant/AntUnitTestRunner.java
|
2399
|
/*
* eXist Open Source Native XML Database
* Copyright (C) 2009-2012 The eXist-db Project
* http://exist-db.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* $Id$
*/
package org.exist.ant;
import org.exist.test.ExistXmldbEmbeddedServer;
import org.junit.*;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DefaultLogger;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
*
* @author jimfuller
*/
public class AntUnitTestRunner {
@ClassRule
public static final ExistXmldbEmbeddedServer existEmbeddedServer = new ExistXmldbEmbeddedServer(false, true);
@Test
public void testAntUnit() throws BuildException {
final Path buildFile = Paths.get("exist-core/src/test/resources/ant/build.xml");
final Project p = new Project();
p.setUserProperty("ant.file", buildFile.toAbsolutePath().toString());
final DefaultLogger consoleLogger = new DefaultLogger();
consoleLogger.setErrorPrintStream(System.err);
consoleLogger.setOutputPrintStream(System.out);
consoleLogger.setMessageOutputLevel(Project.MSG_INFO);
p.addBuildListener(consoleLogger);
try {
p.fireBuildStarted();
p.init();
ProjectHelper helper = ProjectHelper.getProjectHelper();
p.addReference("ant.projectHelper", helper);
helper.parse(p, buildFile.toFile());
p.executeTarget(p.getDefaultTarget());
p.fireBuildFinished(null);
} catch (final BuildException e) {
p.fireBuildFinished(e);
throw e;
}
}
}
|
lgpl-2.1
|
MikeMcShaffry/gamecode3
|
Dev/Source/3rdParty/bullet-2.73/Extras/obsolete/BulletX/Source/XnaDevRu.BulletX/Source/XnaDevRu.BulletX/Collision/BroadphaseCollision/BroadphaseNativeTypes.cs
|
1990
|
/*
Bullet for XNA Copyright (c) 2003-2007 Vsevolod Klementjev http://www.codeplex.com/xnadevru
Bullet original C++ version Copyright (c) 2003-2007 Erwin Coumans http://bulletphysics.com
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace XnaDevRu.BulletX
{
/// Dispatcher uses these types
/// IMPORTANT NOTE:The types are ordered polyhedral, implicit convex and concave
/// to facilitate type checking
public enum BroadphaseNativeTypes
{
// polyhedral convex shapes
Box,
Triangle,
Tetrahedral,
ConvexTriangleMesh,
ConvexHull,
//implicit convex shapes
ImplicitConvexShapes,
Sphere,
MultiSphere,
Capsule,
Cone,
Convex,
Cylinder,
MinkowskiSum,
MinkowskiDifference,
//concave shapes
ConcaveShapesStart,
//keep all the convex shapetype below here, for the check IsConvexShape in broadphase proxy!
TriangleMesh,
//used for demo integration FAST/Swift collision library and Bullet
FastConcaveMesh,
//terrain
Terrain,
//Used for GIMPACT Trimesh integration
Gimpact,
Empty,
StaticPlane,
ConcaveShapesEnd,
Compound,
MaxBroadphaseCollisionTypes,
}
}
|
lgpl-2.1
|
jflash49/mits_intern_app
|
js/dir_.js
|
82
|
$(document).ready(function(){
var iframe = $('iframe')
iframe.scrollTo("")
})
|
lgpl-2.1
|
ElevenPaths/SealSignBSSAndroidSDKSamples
|
SealSignBSSBackendSample/src/es/sealsign/bss/BSBSignatureReference.java
|
11503
|
package es.sealsign.bss;
//----------------------------------------------------
//
// Generated by www.easywsdl.com
// Version: 4.1.7.0
//
// Created by Quasar Development at 15-06-2015
//
//---------------------------------------------------
import java.util.Hashtable;
import org.ksoap2.serialization.*;
import java.util.EnumSet;
public class BSBSignatureReference extends AttributeContainer implements KvmSerializable
{
public BSBArrayOfSignatureReference counterSignatures=new BSBArrayOfSignatureReference();
public BSBEnums.HashAlgorithm hashAlgorithm;
public byte[] signatureCertificate;
public EnumSet<BSBEnums.SignatureFlags> signatureFlags;
public String signatureID;
public BSBEnums.SignatureProfile signatureProfile;
public BSBEnums.VerificationStatus signatureStatus;
public BSBEnums.SignatureType signatureType;
public org.joda.time.DateTime signingTime;
public BSBArrayOfTimestampReference timestamps=new BSBArrayOfTimestampReference();
public BSBArrayOfTimestampReference validationTimestamps=new BSBArrayOfTimestampReference();
public BSBSignatureReference ()
{
}
public BSBSignatureReference (java.lang.Object paramObj,BSBExtendedSoapSerializationEnvelope __envelope)
{
if (paramObj == null)
return;
AttributeContainer inObj=(AttributeContainer)paramObj;
SoapObject soapObject=(SoapObject)inObj;
if (soapObject.hasProperty("counterSignatures"))
{
java.lang.Object j = soapObject.getProperty("counterSignatures");
this.counterSignatures = new BSBArrayOfSignatureReference(j,__envelope);
}
if (soapObject.hasProperty("hashAlgorithm"))
{
java.lang.Object obj = soapObject.getProperty("hashAlgorithm");
if (obj != null && obj.getClass().equals(SoapPrimitive.class))
{
SoapPrimitive j =(SoapPrimitive) obj;
if(j.toString()!=null)
{
this.hashAlgorithm = BSBEnums.HashAlgorithm.fromString(j.toString());
}
}
else if (obj!= null && obj instanceof BSBEnums.HashAlgorithm){
this.hashAlgorithm = (BSBEnums.HashAlgorithm)obj;
}
}
if (soapObject.hasProperty("signatureCertificate"))
{
java.lang.Object j = soapObject.getProperty("signatureCertificate");
this.signatureCertificate = BSBHelper.getBinary(j,false);
}
if (soapObject.hasProperty("signatureFlags"))
{
java.lang.Object obj = soapObject.getProperty("signatureFlags");
if (obj != null && obj.getClass().equals(SoapPrimitive.class))
{
SoapPrimitive j =(SoapPrimitive) obj;
if(j.toString()!=null)
{
this.signatureFlags = BSBEnums.SignatureFlags.getStatusFlags(j.toString());
}
}
}
if (soapObject.hasProperty("signatureID"))
{
java.lang.Object obj = soapObject.getProperty("signatureID");
if (obj != null && obj.getClass().equals(SoapPrimitive.class))
{
SoapPrimitive j =(SoapPrimitive) obj;
if(j.toString()!=null)
{
this.signatureID = j.toString();
}
}
else if (obj!= null && obj instanceof String){
this.signatureID = (String)obj;
}
}
if (soapObject.hasProperty("signatureProfile"))
{
java.lang.Object obj = soapObject.getProperty("signatureProfile");
if (obj != null && obj.getClass().equals(SoapPrimitive.class))
{
SoapPrimitive j =(SoapPrimitive) obj;
if(j.toString()!=null)
{
this.signatureProfile = BSBEnums.SignatureProfile.fromString(j.toString());
}
}
else if (obj!= null && obj instanceof BSBEnums.SignatureProfile){
this.signatureProfile = (BSBEnums.SignatureProfile)obj;
}
}
if (soapObject.hasProperty("signatureStatus"))
{
java.lang.Object obj = soapObject.getProperty("signatureStatus");
if (obj != null && obj.getClass().equals(SoapPrimitive.class))
{
SoapPrimitive j =(SoapPrimitive) obj;
if(j.toString()!=null)
{
this.signatureStatus = BSBEnums.VerificationStatus.fromString(j.toString());
}
}
else if (obj!= null && obj instanceof BSBEnums.VerificationStatus){
this.signatureStatus = (BSBEnums.VerificationStatus)obj;
}
}
if (soapObject.hasProperty("signatureType"))
{
java.lang.Object obj = soapObject.getProperty("signatureType");
if (obj != null && obj.getClass().equals(SoapPrimitive.class))
{
SoapPrimitive j =(SoapPrimitive) obj;
if(j.toString()!=null)
{
this.signatureType = BSBEnums.SignatureType.fromString(j.toString());
}
}
else if (obj!= null && obj instanceof BSBEnums.SignatureType){
this.signatureType = (BSBEnums.SignatureType)obj;
}
}
if (soapObject.hasProperty("signingTime"))
{
java.lang.Object obj = soapObject.getProperty("signingTime");
if (obj != null && obj.getClass().equals(SoapPrimitive.class))
{
SoapPrimitive j =(SoapPrimitive) obj;
if(j.toString()!=null)
{
this.signingTime = BSBHelper.ConvertFromWebService(j.toString());
}
}
else if (obj!= null && obj instanceof org.joda.time.DateTime){
this.signingTime = (org.joda.time.DateTime)obj;
}
}
if (soapObject.hasProperty("timestamps"))
{
java.lang.Object j = soapObject.getProperty("timestamps");
this.timestamps = new BSBArrayOfTimestampReference(j,__envelope);
}
if (soapObject.hasProperty("validationTimestamps"))
{
java.lang.Object j = soapObject.getProperty("validationTimestamps");
this.validationTimestamps = new BSBArrayOfTimestampReference(j,__envelope);
}
}
@Override
public java.lang.Object getProperty(int propertyIndex) {
//!!!!! If you have a compilation error here then you are using old version of ksoap2 library. Please upgrade to the latest version.
//!!!!! You can find a correct version in Lib folder from generated zip file!!!!!
if(propertyIndex==0)
{
return this.counterSignatures!=null?this.counterSignatures:SoapPrimitive.NullSkip;
}
if(propertyIndex==1)
{
return this.hashAlgorithm!=null?this.hashAlgorithm.toString():SoapPrimitive.NullSkip;
}
if(propertyIndex==2)
{
return this.signatureCertificate!=null?org.kobjects.base64.Base64.encode(this.signatureCertificate):SoapPrimitive.NullSkip;
}
if(propertyIndex==3)
{
return BSBEnums.SignatureFlags.getFlagValue(signatureFlags);
}
if(propertyIndex==4)
{
return this.signatureID!=null?this.signatureID:SoapPrimitive.NullSkip;
}
if(propertyIndex==5)
{
return this.signatureProfile!=null?this.signatureProfile.toString():SoapPrimitive.NullSkip;
}
if(propertyIndex==6)
{
return this.signatureStatus!=null?this.signatureStatus.toString():SoapPrimitive.NullSkip;
}
if(propertyIndex==7)
{
return this.signatureType!=null?this.signatureType.toString():SoapPrimitive.NullSkip;
}
if(propertyIndex==8)
{
return this.signingTime!=null?this.signingTime.toString():SoapPrimitive.NullSkip;
}
if(propertyIndex==9)
{
return this.timestamps!=null?this.timestamps:SoapPrimitive.NullSkip;
}
if(propertyIndex==10)
{
return this.validationTimestamps!=null?this.validationTimestamps:SoapPrimitive.NullSkip;
}
return null;
}
@Override
public int getPropertyCount() {
return 11;
}
@Override
public void getPropertyInfo(int propertyIndex, @SuppressWarnings("rawtypes") Hashtable arg1, PropertyInfo info)
{
if(propertyIndex==0)
{
info.type = PropertyInfo.VECTOR_CLASS;
info.name = "counterSignatures";
info.namespace= "http://schemas.datacontract.org/2004/07/SealSignDSSTypes";
}
if(propertyIndex==1)
{
info.type = PropertyInfo.STRING_CLASS;
info.name = "hashAlgorithm";
info.namespace= "http://schemas.datacontract.org/2004/07/SealSignDSSTypes";
}
if(propertyIndex==2)
{
info.type = PropertyInfo.STRING_CLASS;
info.name = "signatureCertificate";
info.namespace= "http://schemas.datacontract.org/2004/07/SealSignDSSTypes";
}
if(propertyIndex==3)
{
info.type = PropertyInfo.STRING_CLASS;
info.name = "signatureFlags";
info.namespace= "http://schemas.datacontract.org/2004/07/SealSignDSSTypes";
}
if(propertyIndex==4)
{
info.type = PropertyInfo.STRING_CLASS;
info.name = "signatureID";
info.namespace= "http://schemas.datacontract.org/2004/07/SealSignDSSTypes";
}
if(propertyIndex==5)
{
info.type = PropertyInfo.STRING_CLASS;
info.name = "signatureProfile";
info.namespace= "http://schemas.datacontract.org/2004/07/SealSignDSSTypes";
}
if(propertyIndex==6)
{
info.type = PropertyInfo.STRING_CLASS;
info.name = "signatureStatus";
info.namespace= "http://schemas.datacontract.org/2004/07/SealSignDSSTypes";
}
if(propertyIndex==7)
{
info.type = PropertyInfo.STRING_CLASS;
info.name = "signatureType";
info.namespace= "http://schemas.datacontract.org/2004/07/SealSignDSSTypes";
}
if(propertyIndex==8)
{
info.type = PropertyInfo.STRING_CLASS;
info.name = "signingTime";
info.namespace= "http://schemas.datacontract.org/2004/07/SealSignDSSTypes";
}
if(propertyIndex==9)
{
info.type = PropertyInfo.VECTOR_CLASS;
info.name = "timestamps";
info.namespace= "http://schemas.datacontract.org/2004/07/SealSignDSSTypes";
}
if(propertyIndex==10)
{
info.type = PropertyInfo.VECTOR_CLASS;
info.name = "validationTimestamps";
info.namespace= "http://schemas.datacontract.org/2004/07/SealSignDSSTypes";
}
}
@Override
public void setProperty(int arg0, java.lang.Object arg1)
{
}
@Override
public String getInnerText() {
return null;
}
@Override
public void setInnerText(String s) {
}
}
|
lgpl-2.1
|
azat/qtcreator
|
src/plugins/analyzerbase/startremotedialog.cpp
|
5329
|
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "startremotedialog.h"
#include "ui_startremotedialog.h"
#include <coreplugin/icore.h>
#include <utils/ssh/sshconnection.h>
#include <QPushButton>
namespace Analyzer {
StartRemoteDialog::StartRemoteDialog(QWidget *parent)
: QDialog(parent)
, m_ui(new Internal::Ui::StartRemoteDialog)
{
m_ui->setupUi(this);
m_ui->keyFile->setExpectedKind(Utils::PathChooser::File);
QSettings *settings = Core::ICore::settings();
settings->beginGroup(QLatin1String("AnalyzerStartRemoteDialog"));
m_ui->host->setText(settings->value(QLatin1String("host")).toString());
m_ui->port->setValue(settings->value(QLatin1String("port"), 22).toInt());
m_ui->user->setText(settings->value(QLatin1String("user"), qgetenv("USER")).toString());
m_ui->keyFile->setPath(settings->value(QLatin1String("keyFile")).toString());
m_ui->executable->setText(settings->value(QLatin1String("executable")).toString());
m_ui->workingDirectory->setText(settings->value(QLatin1String("workingDirectory")).toString());
m_ui->arguments->setText(settings->value(QLatin1String("arguments")).toString());
settings->endGroup();
connect(m_ui->host, SIGNAL(textChanged(QString)),
this, SLOT(validate()));
connect(m_ui->port, SIGNAL(valueChanged(int)),
this, SLOT(validate()));
connect(m_ui->password, SIGNAL(textChanged(QString)),
this, SLOT(validate()));
connect(m_ui->keyFile, SIGNAL(changed(QString)),
this, SLOT(validate()));
connect(m_ui->executable, SIGNAL(textChanged(QString)),
this, SLOT(validate()));
connect(m_ui->workingDirectory, SIGNAL(textChanged(QString)),
this, SLOT(validate()));
connect(m_ui->arguments, SIGNAL(textChanged(QString)),
this, SLOT(validate()));
connect(m_ui->buttonBox, SIGNAL(accepted()),
this, SLOT(accept()));
connect(m_ui->buttonBox, SIGNAL(rejected()),
this, SLOT(reject()));
validate();
}
StartRemoteDialog::~StartRemoteDialog()
{
delete m_ui;
}
void StartRemoteDialog::accept()
{
QSettings *settings = Core::ICore::settings();
settings->beginGroup(QLatin1String("AnalyzerStartRemoteDialog"));
settings->setValue(QLatin1String("host"), m_ui->host->text());
settings->setValue(QLatin1String("port"), m_ui->port->value());
settings->setValue(QLatin1String("user"), m_ui->user->text());
settings->setValue(QLatin1String("keyFile"), m_ui->keyFile->path());
settings->setValue(QLatin1String("executable"), m_ui->executable->text());
settings->setValue(QLatin1String("workingDirectory"), m_ui->workingDirectory->text());
settings->setValue(QLatin1String("arguments"), m_ui->arguments->text());
settings->endGroup();
QDialog::accept();
}
void StartRemoteDialog::validate()
{
bool valid = !m_ui->host->text().isEmpty() && !m_ui->user->text().isEmpty()
&& !m_ui->executable->text().isEmpty();
valid = valid && (!m_ui->password->text().isEmpty() || m_ui->keyFile->isValid());
m_ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(valid);
}
Utils::SshConnectionParameters StartRemoteDialog::sshParams() const
{
Utils::SshConnectionParameters params;
params.host = m_ui->host->text();
params.userName = m_ui->user->text();
if (m_ui->keyFile->isValid()) {
params.authenticationType = Utils::SshConnectionParameters::AuthenticationByKey;
params.privateKeyFile = m_ui->keyFile->path();
} else {
params.authenticationType = Utils::SshConnectionParameters::AuthenticationByPassword;
params.password = m_ui->password->text();
}
params.port = m_ui->port->value();
params.timeout = 10;
return params;
}
QString StartRemoteDialog::executable() const
{
return m_ui->executable->text();
}
QString StartRemoteDialog::arguments() const
{
return m_ui->arguments->text();
}
QString StartRemoteDialog::workingDirectory() const
{
return m_ui->workingDirectory->text();
}
} // namespace Analyzer
|
lgpl-2.1
|
gpickin/Lucee
|
loader/src/main/java/lucee/runtime/util/VariableUtil.java
|
7589
|
/**
* Copyright (c) 2014, the Railo Company Ltd.
* Copyright (c) 2015, Lucee Assosication Switzerland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
package lucee.runtime.util;
import lucee.runtime.PageContext;
import lucee.runtime.exp.PageException;
import lucee.runtime.type.Collection;
import lucee.runtime.type.Struct;
/**
* Variable Util
*/
public interface VariableUtil {
/**
* return a property from the given Object, when property doesn't exists
* return null
*
* @param pc
* @param coll Collection to check
* @param key to get from Collection
* @return value or null
*/
public abstract Object getCollection(PageContext pc, Object coll,
String key, Object defaultValue);
/**
* return a property from the given Object, when property doesn't exists
* return null
*
* @param pc
* @param coll Collection to check
* @param key to get from Collection
* @return value or null
* @deprecated use instead
* <code>get(PageContext pc, Object coll, Collection.Key key, Object defaultValue);</code>
*/
@Deprecated
public abstract Object get(PageContext pc, Object coll, String key,
Object defaultValue);
/**
* return a property from the given Object, when property doesn't exists
* return null
*
* @param pc
* @param coll Collection to check
* @param key to get from Collection
* @return value or null
*/
public abstract Object get(PageContext pc, Object coll, Collection.Key key,
Object defaultValue);
/**
* return a property from the given Object, when property doesn't exists
* return null
*
* @param pc
* @param coll Collection to check
* @param key to get from Collection
* @return value or null
*/
public abstract Object getLight(PageContext pc, Object coll, String key,
Object defaultValue);
/**
* return a property from the given Object, when coll is a query return a
* Column,when property doesn't exists throw exception
*
* @param pc
* @param coll Collection to check
* @param key to get from Collection
* @return value value to get
* @throws PageException
*/
public abstract Object getCollection(PageContext pc, Object coll, String key)
throws PageException;
/**
* return a property from the given Object, when property doesn't exists
* throw exception
*
* @param pc
* @param coll Collection to check
* @param key to get from Collection
* @return value value to get
* @throws PageException
*/
public abstract Object get(PageContext pc, Object coll, String key)
throws PageException;
/**
* sets a value to the Object
*
* @param pc
* @param coll Collection to check
* @param key to get from Collection
* @param value Value to set
* @return value setted
* @throws PageException
* @deprecated use instead
* <code>set(PageContext pc, Object coll, Collection.Key key,Object value)</code>
*/
@Deprecated
public Object set(PageContext pc, Object coll, String key, Object value)
throws PageException;
public Object set(PageContext pc, Object coll, Collection.Key key,
Object value) throws PageException;
/**
* sets a value to the Object
*
* @param pc
* @param coll Collection to check
* @param key to get from Collection
* @param value Value to set
* @return value setted or null if can't set
* @deprecated use instead
* <code>setEL(PageContext pc, Object coll, Collection.Key key,Object value);</code>
*/
@Deprecated
public abstract Object setEL(PageContext pc, Object coll, String key,
Object value);
/**
* sets a value to the Object
*
* @param pc
* @param coll Collection to check
* @param key to get from Collection
* @param value Value to set
* @return value setted or null if can't set
*/
public abstract Object setEL(PageContext pc, Object coll,
Collection.Key key, Object value);
/**
* remove value from Collection
*
* @param coll
* @param key
* @return has cleared or not
*/
@Deprecated
public abstract Object removeEL(Object coll, String key);
public abstract Object removeEL(Object coll, Collection.Key key);
/**
* clear value from Collection
*
* @param coll
* @param key
* @return has cleared or not
* @throws PageException
*/
@Deprecated
public abstract Object remove(Object coll, String key) throws PageException;
public abstract Object remove(Object coll, Collection.Key key)
throws PageException;
/**
* call a Function (UDF, Method) with or witout named values
*
* @param pc
* @param coll Collection of the UDF Function
* @param key name of the function
* @param args arguments to call the function
* @return return value of the function
* @throws PageException
*/
public abstract Object callFunction(PageContext pc, Object coll,
String key, Object[] args) throws PageException;
/**
* call a Function (UDF, Method) without Named Values
*
* @param pc
* @param coll Collection of the UDF Function
* @param key name of the function
* @param args arguments to call the function
* @return return value of the function
* @throws PageException
* @deprecated use instead
* <code>callFunctionWithoutNamedValues(PageContext pc, Object coll, Collection.Key key, Object[] args)</code>
*/
@Deprecated
public abstract Object callFunctionWithoutNamedValues(PageContext pc,
Object coll, String key, Object[] args) throws PageException;
/**
* call a Function (UDF, Method) without Named Values
*
* @param pc
* @param coll Collection of the UDF Function
* @param key name of the function
* @param args arguments to call the function
* @return return value of the function
* @throws PageException
*/
public Object callFunctionWithoutNamedValues(PageContext pc, Object coll,
Collection.Key key, Object[] args) throws PageException;
/**
* call a Function (UDF, Method) with Named Values
*
* @param pc
* @param coll Collection of the UDF Function
* @param key name of the function
* @param args arguments to call the function
* @return return value of the function
* @throws PageException
* @deprecated use instead
* <code>callFunctionWithNamedValues(PageContext pc, Object coll, Collection.Key key, Object[] args)</code>
*/
@Deprecated
public abstract Object callFunctionWithNamedValues(PageContext pc,
Object coll, String key, Object[] args) throws PageException;
/**
* call a Function (UDF, Method) with Named Values
*
* @param pc
* @param coll Collection of the UDF Function
* @param key name of the function
* @param args arguments to call the function
* @return return value of the function
* @throws PageException
*/
public Object callFunctionWithNamedValues(PageContext pc, Object coll,
Collection.Key key, Object[] args) throws PageException;
public Object callFunctionWithNamedValues(PageContext pc, Object coll,
Collection.Key key, Struct args) throws PageException;
}
|
lgpl-2.1
|
RSATom/WebChimera
|
src/JSRootQmlAPI.cpp
|
1642
|
/*****************************************************************************
* Copyright © 2014 Sergey Radionov <rsatom_gmail.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include "JSRootQmlAPI.h"
std::string JSRootQmlAPI::get_qmlError()
{
QmlChimeraPtr plg = boost::static_pointer_cast<QmlChimera>( getPlugin() );
return plg->getQmlError();
}
std::string JSRootQmlAPI::get_qml()
{
ChimeraPtr plg = getPlugin();
const vlc_player_options& o = plg->get_options();
return o.get_qml();
}
void JSRootQmlAPI::set_qml( const std::string& qml )
{
ChimeraPtr plg = getPlugin();
vlc_player_options& o = plg->get_options();
o.set_qml( qml );
}
void JSRootQmlAPI::emitJsMessage( const std::string& message )
{
QmlChimeraPtr plg = boost::static_pointer_cast<QmlChimera>( getPlugin() );
plg->emitJsMessage( message );
}
|
lgpl-2.1
|
sribits/libsigc
|
tests/test_bind_return.cc
|
1746
|
// -*- c++ -*-
/* Copyright 2002, The libsigc++ Development Team
* Assigned to public domain. Use as you wish without restriction.
*/
#include <sigc++/adaptors/bind_return.h>
#include <sigc++/functors/slot.h>
#include <iostream>
#include <string>
SIGC_USING_STD(cout)
SIGC_USING_STD(endl)
SIGC_USING_STD(string)
struct foo
{
void operator()(int i)
{std::cout << "foo(int "<<i<<")"<<std::endl; }
float operator()(float i)
{std::cout << "foo(float "<<i<<")"<<std::endl; return i*5;}
};
struct bar : public sigc::trackable
{
bar(int i=0) : i_(i) {}
operator int() {return i_;}
int i_;
};
int main()
{
std::cout << sigc::bind_return(foo(),-12345)(5) << std::endl;
// Here we just build a functor, not a slot. There is no such thing as a
// default functor, or an invalidated functor. As such, functors can return
// references.
std::string str("guest book");
// A convoluted way to do
// sigc::bind_return(foo(), sigc::ref(str))(6) = "main";
sigc::bind_return<sigc::reference_wrapper<std::string> >(foo(), sigc::ref(str))(6) = "main";
std::cout << str << std::endl;
// Here we build a slot (constructed from a functor). Slots cannot return
// references: if they could, then what would be the return value of the
// default slot or of an invalidated slot? On the other hand, slots are
// guaranteed to be able to construct and return a valid default instance as
// long as there exists a default constructor for it.
//
// Therefore, we use 'bar', and not 'bar &' for this slot signature.
sigc::slot<bar,int> sl;
{
bar choco(-1);
sl = sigc::bind_return(foo(),sigc::ref(choco));
std::cout << sl(7) << std::endl;
} // auto-disconnect
std::cout << sl(8) << std::endl;
}
|
lgpl-2.1
|
yinyunqiao/qtcreator
|
src/libs/extensionsystem/test/manual/pluginview/plugins/plugin1/plugin1.cpp
|
2708
|
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "plugin1.h"
#include <extensionsystem/pluginmanager.h>
#include <QtCore/qplugin.h>
#include <QtCore/QObject>
using namespace Plugin1;
MyPlugin1::MyPlugin1()
: initializeCalled(false)
{
}
bool MyPlugin1::initialize(const QStringList & /*arguments*/, QString *errorString)
{
initializeCalled = true;
QObject *obj = new QObject(this);
obj->setObjectName("MyPlugin1");
addAutoReleasedObject(obj);
bool found2 = false;
bool found3 = false;
foreach (QObject *object, ExtensionSystem::PluginManager::instance()->allObjects()) {
if (object->objectName() == "MyPlugin2")
found2 = true;
else if (object->objectName() == "MyPlugin3")
found3 = true;
}
if (found2 && found3)
return true;
if (errorString) {
QString error = "object(s) missing from plugin(s):";
if (!found2)
error.append(" plugin2");
if (!found3)
error.append(" plugin3");
*errorString = error;
}
return false;
}
void MyPlugin1::extensionsInitialized()
{
if (!initializeCalled)
return;
// don't do this at home, it's just done here for the test
QObject *obj = new QObject(this);
obj->setObjectName("MyPlugin1_running");
addAutoReleasedObject(obj);
}
Q_EXPORT_PLUGIN(MyPlugin1)
|
lgpl-2.1
|
JaredCJR/mri
|
tests/tests/cmd_stepTests.cpp
|
2430
|
/* Copyright 2014 Adam Green (http://mbed.org/users/AdamGreen/)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
extern "C"
{
#include <try_catch.h>
#include <mri.h>
#include <platforms.h>
void __mriDebugException(void);
}
#include <platformMock.h>
// Include C++ headers for test harness.
#include "CppUTest/TestHarness.h"
TEST_GROUP(cmdStep)
{
int m_expectedException;
void setup()
{
m_expectedException = noException;
platformMock_Init();
__mriInit("MRI_UART_MBED_USB");
}
void teardown()
{
LONGS_EQUAL ( m_expectedException, getExceptionCode() );
clearExceptionCode();
platformMock_Uninit();
}
void validateExceptionCode(int expectedExceptionCode)
{
m_expectedException = expectedExceptionCode;
LONGS_EQUAL ( expectedExceptionCode, getExceptionCode() );
}
};
TEST(cmdStep, BasicSingleStep)
{
CHECK_FALSE ( Platform_IsSingleStepping() );
platformMock_CommInitReceiveChecksummedData("+$s#");
__mriDebugException();
CHECK_TRUE ( Platform_IsSingleStepping() );
CHECK_TRUE ( platformMock_CommDoesTransmittedDataEqual("$T05responseT#7c+") );
CHECK_EQUAL( 0, platformMock_AdvanceProgramCounterToNextInstructionCalls() );
}
TEST(cmdStep, SingleStepOverHardcodedBreakpoints_MustContinueAfterToExit)
{
platformMock_SetTypeOfCurrentInstruction(MRI_PLATFORM_INSTRUCTION_HARDCODED_BREAKPOINT);
platformMock_CommInitReceiveChecksummedData("+$s#", "+$c#");
__mriDebugException();
CHECK_TRUE ( platformMock_CommDoesTransmittedDataEqual("$T05responseT#7c+$T05responseT#7c+") );
CHECK_EQUAL( 2, platformMock_AdvanceProgramCounterToNextInstructionCalls() );
CHECK_EQUAL( INITIAL_PC + 8, platformMock_GetProgramCounterValue() );
}
|
lgpl-3.0
|
cadegenn/com_velo_j30
|
admin/views/monvelo/tmpl/edit.php
|
5197
|
<?php
// No direct access
defined('_JEXEC') or die('Restricted access');
JHtml::_('behavior.tooltip');
// Import library dependencies
JLoader::register('veloFunctions', JPATH_COMPONENT_ADMINISTRATOR . '/helpers/functions.php');
JLoader::register('veloControls', JPATH_COMPONENT_ADMINISTRATOR . '/helpers/controls.php');
JLoader::register('velodb', JPATH_COMPONENT_ADMINISTRATOR . '/helpers/db.php');
?>
<form action="<?php echo JRoute::_('index.php?option=com_velo&layout=edit&id='.(int) $this->item->id); ?>"
method="post" name="adminForm" id="model-form">
<div class='width-60 fltlft'>
<fieldset class="adminform">
<legend><?php echo JText::_( 'COM_VELO_VELO_DETAILS' ); ?> <small>(<?php echo $this->item->id; ?>)</small></legend>
<div class="ttr">
<div class="ttd"><?php echo $this->form->getField("label")->label; ?></div><div class="ttd"><?php echo $this->form->getField("label")->input; ?></div>
<div class="ttd"><?php echo $this->form->getField("type_id")->label; ?></div><div class="ttd"><?php echo $this->form->getField("type_id")->input; ?></div>
</div>
<div class="ttr">
<div class="ttd"><?php echo $this->form->getField("owner")->label; ?></div><div class="ttd"><?php echo $this->form->getField("owner")->input; ?></div>
<div class="ttd"><?php echo $this->form->getField("bicycode")->label; ?></div><div class="ttd"><?php echo $this->form->getField("bicycode")->input; ?></div>
</div>
<div class="tr">
<div class="td"><?php echo $this->form->getField("commentaires")->label; ?></div><div class="td"><?php echo $this->form->getField("commentaires")->input; ?></div>
</div>
</fieldset>
</div>
<div class='width-40 fltrt'>
<?php echo JHtml::_('sliders.start', 'content-sliders-'.$this->item->id, array('useCookie'=>1)); ?>
<?php echo JHtml::_('sliders.panel', JText::_('COM_VELO_COMPOSANT_DETAILS'), 'meta-options'); ?>
<fieldset class="panelform">
<ul class="adminformlist">
<li><?php echo $this->form->getLabel('created_by'); ?>
<?php echo $this->form->getField("created_by")->input; ?></li>
<li><?php echo $this->form->getLabel('marque_id'); ?>
<?php echo $this->form->getField("marque_id")->input; ?></li>
<li><?php echo $this->form->getLabel('model_id'); ?>
<?php echo $this->form->getField("model_id")->input; ?></li>
<li><?php echo $this->form->getLabel('specs'); ?>
<?php echo $this->form->getField("specs")->input; ?></li>
<li><?php echo $this->form->getLabel('date_achat'); ?>
<?php echo $this->form->getField("date_achat")->input; ?></li>
<li><?php echo $this->form->getLabel('prix_achat'); ?>
<?php echo $this->form->getField("prix_achat")->input; ?></li>
<li><?php echo $this->form->getLabel('distance_achat'); ?>
<?php echo $this->form->getField("distance_achat")->input; ?></li>
<li><?php echo $this->form->getLabel('date_vente'); ?>
<?php echo $this->form->getField("date_vente")->input; ?></li>
<li><?php echo $this->form->getLabel('prix_vente'); ?>
<?php echo $this->form->getField("prix_vente")->input; ?></li>
<li><?php echo $this->form->getLabel('distance_vente'); ?>
<?php echo $this->form->getField("distance_vente")->input; ?></li>
<li><?php echo $this->form->getLabel('published'); ?>
<?php echo $this->form->getField("published")->input; ?></li>
<li><?php echo $this->form->getLabel('commentaires'); ?>
<?php echo $this->form->getField("commentaires")->input; ?></li>
</ul>
</fieldset>
<?php echo JHtml::_('sliders.end'); ?>
</div>
<!-- begin ACL definition-->
<div class="clr"></div>
<?php //if ($this->canDo->get('core.admin')): ?>
<?php if (JFactory::getUser()->authorise($this->option.'.core.admin')): ?>
<div class="width-100 fltlft">
<?php echo JHtml::_('sliders.start', 'permissions-sliders-'.$this->item->id, array('useCookie'=>1)); ?>
<?php echo JHtml::_('sliders.panel', JText::_('COM_VELO_FIELDSET_RULES'), 'access-rules'); ?>
<fieldset class="panelform">
<?php echo $this->form->getLabel('rules'); ?>
<?php echo $this->form->getInput('rules'); ?>
</fieldset>
<?php echo JHtml::_('sliders.end'); ?>
</div>
<?php endif; ?>
<?php if (JFactory::getUser()->authorise($this->option.'.monvelo.core.admin')): ?>
<div class="width-100 fltlft">
<?php echo JHtml::_('sliders.start', 'permissions-sliders-'.$this->item->id, array('useCookie'=>1)); ?>
<?php echo JHtml::_('sliders.panel', JText::_('COM_VELO_FIELDSET_RULES'), 'access-rules'); ?>
<fieldset class="panelform">
<?php echo $this->form->getLabel('rules'); ?>
<?php echo $this->form->getInput('rules'); ?>
</fieldset>
<?php echo JHtml::_('sliders.end'); ?>
</div>
<?php endif; ?>
<!-- end ACL definition-->
<div>
<input type="hidden" name="task" value="monvelo.edit" />
<?php JFactory::getApplication()->setUserState('com_velo.edit.monvelo.id', (int) $this->item->id); ?>
<?php echo JHtml::_('form.token'); ?>
</div>
</form>
<!--<pre>
<?php //echo var_dump($this); ?>
</pre>-->
|
lgpl-3.0
|
janhancic/brjs
|
brjs-sdk/sdk/system-applications/dashboard/dashboard-bladeset/blades/app/src/brjs/dashboard/app/service/request/XHRFactory.js
|
187
|
brjs.dashboard.app.service.request.XHRFactory = function()
{
};
brjs.dashboard.app.service.request.XHRFactory.prototype.getRequestObject = function()
{
return new XMLHttpRequest();
};
|
lgpl-3.0
|
janhancic/brjs
|
brjs-sdk/sdk/system-applications/dashboard/dashboard-bladeset/blades/app/src/brjs/dashboard/app/service/url/PageUrlProviderStub.js
|
559
|
brjs.dashboard.app.service.url.PageUrlProviderStub = function(sRootUrl)
{
// call super constructor
brjs.dashboard.app.service.url.PageUrlProvider.call(this);
this.m_sRootUrl = sRootUrl;
};
br.Core.inherit(brjs.dashboard.app.service.url.PageUrlProviderStub, brjs.dashboard.app.service.url.PageUrlProvider);
brjs.dashboard.app.service.url.PageUrlProviderStub.prototype.getRootUrl = function()
{
return this.m_sRootUrl;
};
brjs.dashboard.app.service.url.PageUrlProviderStub.prototype.setPageUrl = function(sPageUrl)
{
this._updatePageUrl(sPageUrl);
};
|
lgpl-3.0
|
tschroedter/MyCodingExamples
|
Brainteaser/TestCodibility/TestCodibility/Program.cs
|
122
|
namespace TestCodibility
{
class Program
{
static void Main(string[] args)
{
}
}
}
|
lgpl-3.0
|
TrimbleSolutionsCorporation/VSSonarQubeExtension
|
VSSonarExtensionUi/View/Helpers/QuestionUser.xaml.cs
|
2135
|
using System.Windows;
namespace VSSonarExtensionUi.View.Helpers
{
/// <summary>
/// Interaction logic for UserInputWindow.xaml
/// </summary>
public partial class QuestionUser
{
/// <summary>
/// Initializes a new instance of the <see cref="UserInputWindow" /> class.
/// </summary>
/// <param name="question">The question.</param>
/// <param name="defaultAnswer">The default answer.</param>
public QuestionUser(string message)
{
InitializeComponent();
this.lblQuestion.Text = message;
}
/// <summary>
/// The show.
/// </summary>
/// <param name="question">The question.</param>
/// <returns>answer or empty if cancel</returns>
public static bool GetInput(string question)
{
bool answer = false;
Application.Current.Dispatcher.Invoke(
delegate
{
var box = new QuestionUser(question);
box.ShowDialog();
answer = (bool)box.DialogResult;
});
return answer;
}
/// <summary>
/// Handles the Click event of the btnDialogOk control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="RoutedEventArgs" /> instance containing the event data.</param>
private void BtnDialogOkClick(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
this.Close();
}
/// <summary>
/// Handles the Click event of the btnDialogOk control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="RoutedEventArgs" /> instance containing the event data.</param>
private void BtnDialogOkCancel(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
this.Close();
}
}
}
|
lgpl-3.0
|
christianhujer/japi
|
historic/libs/util/src/prj/net/sf/japi/util/filter/NotFilter.java
|
1515
|
/*
* Copyright (C) 2009 Christian Hujer.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.sf.japi.util.filter;
/** A Filter that is the negation of another filter.
* @param <T> Type of filter.
* @author <a href="mailto:cher@riedquat.de">Christian Hujer</a>
* @since 0.1
*/
final class NotFilter<T> implements Filter<T> {
/** The filter to negate. */
private final Filter<T> filter;
/** Create a NotFilter.
* @param filter Filter to negate
*/
NotFilter(final Filter<T> filter) {
this.filter = filter;
}
/** {@inheritDoc} */
@Override public String toString() {
return "NotFilter[" + super.toString() + ']';
}
/** {@inheritDoc} */
public boolean accept(final T o) {
return !filter.accept(o);
}
} // class NotFilter
|
lgpl-3.0
|
jacky8hyf/musique
|
dependencies/jaudiotagger/src/main/java/org/jaudiotagger/audio/generic/Utils.java
|
10658
|
/*
* Entagged Audio Tag library
* Copyright (c) 2003-2005 Raphael Slinckx <raphael@slinckx.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.jaudiotagger.audio.generic;
import org.jaudiotagger.audio.AudioFile;
import java.io.DataInput;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
/**
* Contains various frequently used static functions in the different tag
* formats
*
* @author Raphael Slinckx
*/
public class Utils {
/**
* Copies the bytes of <code>srd</code> to <code>dst</code> at the
* specified offset.
*
* @param src The byte to be copied.
* @param dst The array to copy to
* @param dstOffset The start offset for the bytes to be copied.
*/
public static void copy(byte[] src, byte[] dst, int dstOffset) {
System.arraycopy(src, 0, dst, dstOffset, src.length);
}
/**
* Returns {@link String#getBytes()}.<br>
*
* @param s The String to call, decode bytes using the specfied charset
* @return The bytes.
*/
public static byte[] getDefaultBytes(String s, String charSet) {
try {
return s.getBytes(charSet);
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException(uee);
}
}
/*
* Returns the extension of the given file.
* The extension is empty if there is no extension
* The extension is the string after the last "."
*
* @param f The file whose extension is requested
* @return The extension of the given file
*/
public static String getExtension(File f) {
String name = f.getName().toLowerCase();
int i = name.lastIndexOf(".");
if (i == -1) {
return "";
}
return name.substring(i + 1);
}
/*
* Computes a number whereby the 1st byte is the least signifcant and the last
* byte is the most significant.
*
* @param b The byte array @param start The starting offset in b
* (b[offset]). The less significant byte @param end The end index
* (included) in b (b[end]). The most significant byte @return a long number
* represented by the byte sequence.
*
* So if storing a number which only requires one byte it will be stored in the first
* byte.
*/
public static long getLongLE(ByteBuffer b, int start, int end) {
long number = 0;
for (int i = 0; i < (end - start + 1); i++) {
number += ((b.get(start + i) & 0xFF) << i * 8);
}
return number;
}
/*
* Computes a number whereby the 1st byte is the most significant and the last
* byte is the least significant.
*
* So if storing a number which only requires one byte it will be stored in the last
* byte.
*/
public static long getLongBE(ByteBuffer b, int start, int end) {
int number = 0;
for (int i = 0; i < (end - start + 1); i++) {
number += ((b.get(end - i) & 0xFF) << i * 8);
}
return number;
}
public static int getIntLE(byte[] b) {
return (int) getLongLE(ByteBuffer.wrap(b), 0, b.length - 1);
}
/*
* same as above, but returns an int instead of a long @param b The byte
* array @param start The starting offset in b (b[offset]). The less
* significant byte @param end The end index (included) in b (b[end]). The
* most significant byte @return a int number represented by the byte
* sequence.
*/
public static int getIntLE(byte[] b, int start, int end) {
return (int) getLongLE(ByteBuffer.wrap(b), start, end);
}
public static int getIntBE(byte[] b, int start, int end) {
return (int) getLongBE(ByteBuffer.wrap(b), start, end);
}
public static int getIntBE(ByteBuffer b, int start, int end) {
return (int) getLongBE(b, start, end);
}
public static short getShortBE(ByteBuffer b, int start, int end) {
return (short) getIntBE(b, start, end);
}
/**
* Convert int to byte representation - Big Endian (as used by mp4)
*
* @param size
* @return byte represenetation
*/
public static byte[] getSizeBEInt32(int size) {
byte[] b = new byte[4];
b[0] = (byte) ((size >> 24) & 0xFF);
b[1] = (byte) ((size >> 16) & 0xFF);
b[2] = (byte) ((size >> 8) & 0xFF);
b[3] = (byte) (size & 0xFF);
return b;
}
/**
* Convert short to byte representation - Big Endian (as used by mp4)
*
* @param size
* @return byte represenetation
*/
public static byte[] getSizeBEInt16(short size) {
byte[] b = new byte[2];
b[0] = (byte) ((size >> 8) & 0xFF);
b[1] = (byte) (size & 0xFF);
return b;
}
/**
* Convert int to byte representation - Little Endian (as used by ogg vorbis)
*
* @param size
* @return byte represenetation
*/
public static byte[] getSizeLEInt32(int size) {
byte[] b = new byte[4];
b[0] = (byte) (size & 0xff);
b[1] = (byte) ((size >>> 8) & 0xffL);
b[2] = (byte) ((size >>> 16) & 0xffL);
b[3] = (byte) ((size >>> 24) & 0xffL);
return b;
}
/**
* Create String starting from offset upto length using encoding
*
* @param b
* @param offset
* @param length
* @param encoding
* @return
* @throws UnsupportedEncodingException
*/
public static String getString(byte[] b, int offset, int length, String encoding) {
try {
return new String(b, offset, length, encoding);
} catch (UnsupportedEncodingException ue) {
//Shouldnt have to worry about this exception as should only be calling with well defined charsets
throw new RuntimeException(ue);
}
}
/**
* Create String offset from position by offset upto length using encoding, and position of buffer
* is moved to after position + offset + length
*
* @param buffer
* @param offset
* @param length
* @param encoding
* @return
*/
public static String getString(ByteBuffer buffer, int offset, int length, String encoding) {
byte[] b = new byte[length];
buffer.position(buffer.position() + offset);
buffer.get(b);
try {
return new String(b, 0, length, encoding);
} catch (UnsupportedEncodingException uee) {
//TODO, will we ever use unsupported encodings
throw new RuntimeException(uee);
}
}
/*
* Tries to convert a string into an UTF8 array of bytes If the conversion
* fails, return the string converted with the default encoding.
*
* @param s The string to convert @return The byte array representation of
* this string in UTF8 encoding
*/
public static byte[] getUTF8Bytes(String s) throws UnsupportedEncodingException {
return s.getBytes("UTF-8");
}
/**
* Overflow checking since java can't handle unsigned numbers.
*/
public static int readUint32AsInt(DataInput di) throws IOException {
final long l = readUint32(di);
if (l > Integer.MAX_VALUE) {
throw new IOException("uint32 value read overflows int");
}
return (int) l;
}
public static long readUint32(DataInput di) throws IOException {
final byte[] buf8 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
di.readFully(buf8, 4, 4);
final long l = ByteBuffer.wrap(buf8).getLong();
return l;
}
public static int readUint16(DataInput di) throws IOException {
final byte[] buf = {0x00, 0x00, 0x00, 0x00};
di.readFully(buf, 2, 2);
final int i = ByteBuffer.wrap(buf).getInt();
return i;
}
public static String readString(DataInput di, int charsToRead) throws IOException {
final byte[] buf = new byte[charsToRead];
di.readFully(buf);
return new String(buf);
}
public static long readUInt64(ByteBuffer b) {
long result = 0;
result += (readUBEInt32(b) << 32);
result += readUBEInt32(b);
return result;
}
public static int readUBEInt32(ByteBuffer b) {
int result = 0;
result += readUBEInt16(b) << 16;
result += readUBEInt16(b);
return result;
}
public static int readUBEInt24(ByteBuffer b) {
int result = 0;
result += readUBEInt16(b) << 16;
result += readUInt8(b);
return result;
}
public static int readUBEInt16(ByteBuffer b) {
int result = 0;
result += readUInt8(b) << 8;
result += readUInt8(b);
return result;
}
public static int readUInt8(ByteBuffer b) {
return read(b);
}
public static int read(ByteBuffer b) {
int result = (b.get() & 0xFF);
return result;
}
/**
* @param file
* @return filename with audioformat seperator stripped of, lengthened to ensure not too small for calid tempfile
* creation.
*/
public static String getMinBaseFilenameAllowedForTempFile(File file) {
String s = AudioFile.getBaseFilename(file);
if (s.length() >= 3) {
return s;
}
if (s.length() == 1) {
return s + "000";
} else if (s.length() == 1) {
return s + "00";
} else if (s.length() == 2) {
return s + "0";
}
return s;
}
}
|
lgpl-3.0
|
openlecturnity/os45
|
lecturnity/common/lsutl32/CustomPropPage.cpp
|
1528
|
// CustomPropPage.cpp: Implementierung der Klasse CCustomPropPage.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "stdafx.h"
#include "CustomPropPage.h"
//////////////////////////////////////////////////////////////////////
// Konstruktion/Destruktion
//////////////////////////////////////////////////////////////////////
CCustomPropPage::CCustomPropPage(UINT nID, CWnd *pWndParent /*=NULL*/) :
CDialog(nID, pWndParent)
{
//{{AFX_DATA_INIT(CCustomPropPage)
// HINWEIS: Der Klassen-Assistent fügt hier Elementinitialisierung ein
//}}AFX_DATA_INIT
m_bBrushInited = false;
m_nResID = nID;
}
CCustomPropPage::~CCustomPropPage()
{
}
BEGIN_MESSAGE_MAP(CCustomPropPage, CDialog)
//{{AFX_MSG_MAP(CCustomPropPage)
ON_WM_CTLCOLOR()
ON_WM_ERASEBKGND()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
BOOL CCustomPropPage::Create(CWnd *pWndParent)
{
return CDialog::Create(m_nResID, pWndParent);
}
HBRUSH CCustomPropPage::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
/*
if (!m_bBrushInited)
{
m_bgBrush.CreateSolidBrush(::GetSysColor(COLOR_WINDOW));
m_bBrushInited = true;
}
HBRUSH hbr = (HBRUSH) m_bgBrush.m_hObject;
pDC->SetBkMode(TRANSPARENT);
return hbr;
*/
return CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
}
BOOL CCustomPropPage::OnEraseBkgnd(CDC* pDC)
{
// TODO: Code für die Behandlungsroutine für Nachrichten hier einfügen und/oder Standard aufrufen
//return TRUE;
return CDialog::OnEraseBkgnd(pDC);
}
|
lgpl-3.0
|
tvsonar/sonarlint-roslyn-analyzer
|
src/SonarAnalyzer.CSharp/Helpers/MethodParameterLookup.cs
|
3737
|
/*
* SonarAnalyzer for .NET
* Copyright (C) 2015-2016 SonarSource SA
* mailto:contact@sonarsource.com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis;
using System.Collections.Generic;
namespace SonarAnalyzer.Helpers
{
// todo: this should come from the Roslyn API (https://github.com/dotnet/roslyn/issues/9)
internal class MethodParameterLookup
{
private readonly InvocationExpressionSyntax invocation;
public IMethodSymbol MethodSymbol { get; }
public MethodParameterLookup(InvocationExpressionSyntax invocation, SemanticModel semanticModel)
{
this.invocation = invocation;
MethodSymbol = semanticModel.GetSymbolInfo(invocation).Symbol as IMethodSymbol;
}
public static bool TryGetParameterSymbol(ArgumentSyntax argument, ArgumentListSyntax argumentList,
IMethodSymbol method, out IParameterSymbol parameter)
{
parameter = null;
if (!argumentList.Arguments.Contains(argument) ||
method == null ||
method.IsVararg)
{
return false;
}
if (argument.NameColon != null)
{
parameter = method.Parameters
.FirstOrDefault(symbol => symbol.Name == argument.NameColon.Name.Identifier.ValueText);
return parameter != null;
}
var argumentIndex = argumentList.Arguments.IndexOf(argument);
var parameterIndex = argumentIndex;
if (parameterIndex >= method.Parameters.Length)
{
var lastParameter = method.Parameters.Last();
parameter = lastParameter.IsParams ? lastParameter : null;
return parameter != null;
}
parameter = method.Parameters[parameterIndex];
return true;
}
public bool TryGetParameterSymbol(ArgumentSyntax argument, out IParameterSymbol parameter)
{
return TryGetParameterSymbol(argument, invocation.ArgumentList, MethodSymbol, out parameter);
}
internal IEnumerable<ArgumentParameterMapping> GetAllArgumentParameterMappings()
{
foreach (var argument in invocation.ArgumentList.Arguments)
{
IParameterSymbol parameter;
if (TryGetParameterSymbol(argument, out parameter))
{
yield return new ArgumentParameterMapping(argument, parameter);
}
}
}
public class ArgumentParameterMapping
{
public ArgumentSyntax Argument { get; set; }
public IParameterSymbol Parameter { get; set; }
public ArgumentParameterMapping(ArgumentSyntax argument, IParameterSymbol parameter)
{
Argument = argument;
Parameter = parameter;
}
}
}
}
|
lgpl-3.0
|
haisamido/SFDaaS
|
src/net/spy/memcached/vbucket/config/Config.java
|
688
|
package net.spy.memcached.vbucket.config;
import java.util.List;
import net.spy.memcached.HashAlgorithm;
public interface Config {
// Config access
int getReplicasCount();
int getVbucketsCount();
int getServersCount();
HashAlgorithm getHashAlgorithm();
String getServer(int serverIndex);
// VBucket access
int getVbucketByKey(String key);
int getMaster(int vbucketIndex);
int getReplica(int vbucketIndex, int replicaIndex);
int foundIncorrectMaster(int vbucket, int wrongServer);
ConfigDifference compareTo(Config config);
List<String> getServers();
List<VBucket> getVbuckets();
ConfigType getConfigType();
}
|
lgpl-3.0
|
KalikoCMS/KalikoCMS.Core
|
KalikoCMS.Engine/Core/PropertyDefinition.cs
|
1236
|
#region License and copyright notice
/*
* Kaliko Content Management System
*
* Copyright (c) Fredrik Schultz
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 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.
* http://www.gnu.org/licenses/lgpl-3.0.html
*/
#endregion
namespace KalikoCMS.Core {
using System;
public class PropertyDefinition {
public int PropertyId { get; set; }
public Guid PropertyTypeId { get; set; }
public int PageTypeId { get; set; }
public string Name { get; set; }
public string Header { get; set; }
public bool ShowInAdmin { get; set; }
public int SortOrder { get; set; }
public string Parameters { get; set; }
public bool Required { get; set; }
public string TabGroup { get; set; }
}
}
|
lgpl-3.0
|
phingofficial/phing
|
tests/Phing/Task/System/SwitchTaskTest.php
|
1654
|
<?php
/**
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information please see
* <http://phing.info>.
*/
namespace Phing\Test\Task\System;
use Phing\Test\Support\BuildFileTest;
/**
* Tests the Switch Task.
*
* @author Siad Ardroumli <siad.ardroumli@gmail.com>
*
* @internal
*/
class SwitchTaskTest extends BuildFileTest
{
public function setUp(): void
{
$this->configureProject(
PHING_TEST_BASE . '/etc/tasks/system/SwitchTest.xml'
);
}
public function testSwitchCase(): void
{
$this->expectLogContaining(__FUNCTION__, 'The value of property foo is bar');
}
public function testSwitchDefault(): void
{
$this->expectLogContaining(__FUNCTION__, 'The value of property bar is not sensible');
}
}
|
lgpl-3.0
|
comptech/atrex
|
docs/html/search/all_65.js
|
111
|
var searchData=
[
['error',['Error',['../classtifffile_1_1TiffTag_1_1Error.html',1,'tifffile::TiffTag']]]
];
|
lgpl-3.0
|
dmolineus/metamodels-core
|
src/system/modules/metamodels/ModuleMetaModelFrontendFilter.php
|
1751
|
<?php
/**
* The MetaModels extension allows the creation of multiple collections of custom items,
* each with its own unique set of selectable attributes, with attribute extendability.
* The Front-End modules allow you to build powerful listing and filtering of the
* data in each collection.
*
* PHP version 5
* @package MetaModels
* @subpackage FrontendFilter
* @author Christian de la Haye <service@delahaye.de>
* @copyright The MetaModels team.
* @license LGPL.
* @filesource
*/
/**
* FE-module for FE-filtering
*
* @package MetaModels
* @subpackage FrontendFilter
* @author Christian de la Haye <service@delahaye.de>
*/
class ModuleMetaModelFrontendFilter extends Module
{
/**
* Template
* @var string
*/
protected $strTemplate = 'mm_filter_default';
/**
* Display a wildcard in the back end
* @return string
*/
public function generate()
{
if (TL_MODE == 'BE')
{
$objTemplate = new BackendTemplate('be_wildcard');
$objTemplate->wildcard = '### METAMODELS FE-FILTERBLOCK ###';
$objTemplate->title = $this->headline;
$objTemplate->id = $this->id;
$objTemplate->link = $this->title;
$objTemplate->href = 'contao/main.php?do=themes&table=tl_module&act=edit&id=' . $this->id;
return $objTemplate->parse();
}
// get template
if ($this->metamodel_fef_template)
{
$this->strTemplate = $this->metamodel_fef_template;
}
return parent::generate();
}
/**
* Generate module
*/
protected function compile()
{
// get filter data
$objFilter = new MetaModelFrontendFilter();
$arrFilter = $objFilter->getMetaModelFrontendFilter($this);
$this->Template->setData($arrFilter);
$this->Template->submit = $arrFilter['submit'];
}
}
|
lgpl-3.0
|
smgallo/xdmod
|
html/gui/js/report_builder/ChartDateEditor.js
|
18081
|
Ext.namespace('XDMoD.Reporting');
// XDMoD.Reporting.ChartDateEditor
//
// Panel for editing / updating of timeframes for charts in any given report.
// ============================================================
function dateRangeValidator(start_date, end_date) {
var date_utils = new DateUtilities();
date_utils.isValidDateFormat(start_date);
if (!date_utils.isValidDateFormat(start_date)) {
return {success: false, message: 'Valid start date required' };
}
if (!date_utils.isValidDateFormat(end_date)) {
return {success: false, message: 'Valid end date required' };
}
if (start_date >= end_date) {
return {success: false, message: 'The start date must be earlier than the end date' };
}
if (start_date > date_utils.getCurrentDate()) {
return {success: false, message: 'The start date cannot be ahead of today' };
}
return {success: true};
}//dateRangeValidator
// ============================================================
XDMoD.Reporting.ChartDateEditor = Ext.extend(Ext.Window, {
title: 'Edit Chart Timeframe',
width: 300,
height: 110,
resizable: false,
modal: true,
draggable: false,
layout: 'fit',
bodyStyle: 'padding: 5px;',
closeAction: 'hide',
cls: 'chart_date_editor',
activeChartID: -1,
reportCreatorPanel: null,
// -----------------------------
// setCreatorPanel: used to assign the instance of ReportCreator (reference) so the ChartDateEditor knows
// what store to consult during date updates.
setCreatorPanel: function(creatorPanel) {
this.reportCreatorPanel = creatorPanel;
},
getDefaultChartTimeframe: function(chart_id) {
var recorded_timeframe_label = XDMoD.Reporting.getParamIn('timeframe_label', chart_id, '&');
var timeframe = {};
// ====================================
if (recorded_timeframe_label.toLowerCase() == 'user defined') {
// If the original timeframe was user-defined, then the respective start/end dates will be found
// in the chart id itself
timeframe.start_date = XDMoD.Reporting.getParamIn('start_date', chart_id, '&');
timeframe.end_date = XDMoD.Reporting.getParamIn('end_date', chart_id, '&');
}
else {
var date_utils = new DateUtilities();
var endpoints = date_utils.getEndpoints(recorded_timeframe_label);
timeframe.start_date = endpoints.start_date;
timeframe.end_date = endpoints.end_date;
}
timeframe.type = recorded_timeframe_label;
return timeframe;
},
reset: function (config, store_id, record_id) {
var default_timeframe = this.getDefaultChartTimeframe(config.chart_id);
var trackingConfig = XDMoD.Reporting.GetTrackingConfig(store_id, record_id, {
original_chart_timeframe_type: default_timeframe.type,
original_start_date: default_timeframe.start_date,
original_end_date: default_timeframe.end_date
});
XDMoD.TrackEvent('Report Generator (Report Editor)', 'Clicked on the Reset Timeframe icon', Ext.encode(trackingConfig));
// ====================================
this.updateChartEntry({
chart_id: config.chart_id,
timeframe_type: default_timeframe.type,
start_date: default_timeframe.start_date,
end_date: default_timeframe.end_date
});
this.reportCreatorPanel.dirtyConfig();
},
updateChartEntry: function (config) {
// Targets an entry in the store (associated with the 'Included Charts' grid) by config.chart_id, and
// updates that entry's timeframe information, chart date description, and chart thumbnail link with the
// proper information (denoted by the remaining parameters in config:)
// config: {chart_id: ..., timeframe_type: ..., start_date: ...., end_date: ... }
// Only the local (cached) data of the store is altered, then reloaded so the grid bound to the store gets
// updated with these (local) changes.
var store = this.reportCreatorPanel.reportCharts.reportStore;
var localContent = {};
localContent.queue = [];
var editor_ref = this;
store.data.each(function() {
if (config.chart_id == this.data['chart_id']) {
// Update chart date description and thumbnail link so the grid cell renderer can show the updated timeframe and thumbnail
this.data['timeframe_type'] = config.timeframe_type;
this.data['chart_date_description'] = config.start_date + ' to ' + config.end_date;
var renderer_params = '&start=' + config.start_date + '&end=' + config.end_date;
// Case when a chart, already saved to a report, has its timeframe adjusted (and prior to re-saving with the new timeframe)
this.data['thumbnail_link'] = this.data['thumbnail_link'].replace('type=report', 'type=cached' + renderer_params);
this.data['thumbnail_link'] = this.data['thumbnail_link'].replace(/type=cached&start=(.+)&end=(.+)&ref=/, 'type=cached' + renderer_params + '&ref=');
// Case when a chart is dragged in from the 'Available Charts' area and, prior to saving the report, the timeframe has been adjusted.
if (this.data['thumbnail_link'].indexOf('start=') == -1)
this.data['thumbnail_link'] = this.data['thumbnail_link'].replace('type=volatile', 'type=volatile' + renderer_params);
this.data['thumbnail_link'] = this.data['thumbnail_link'].replace(/type=volatile&start=(.+)&end=(.+)&ref=/, 'type=volatile' + renderer_params + '&ref=');
}//if (config.chart_id == this.data['chart_id'])
localContent.queue.push(this.data);
});//store.data.each
store.loadData(localContent);
},
mnuPeriodicTimeframe: null,
start_date_field: null,
end_date_field: null,
// -----------------------------
initComponent: function(){
var self = this;
var today = new Date();
var date_utils = new DateUtilities();
// ---------------------------
self.getMode = function() {
if (rdoGrpTimeframeMode.items.get(0).getValue())
return 'Specific';
if (rdoGrpTimeframeMode.items.get(1).getValue())
return 'Periodic';
};//self.getMode
// ---------------------------
self.present = function(config, store_id, record_id, batch_mode) {
var coords = Ext.EventObject.getXY();
var x_offset = coords[0];
var y_offset = coords[1];
var chart_config;
this.show();
this.setPagePosition(x_offset, y_offset - this.height - 10);
// ================================
if(batch_mode == undefined) batch_mode = false;
this.batchMode = batch_mode;
if (batch_mode == true) {
this.setTitle('Edit Multiple Chart Timeframes');
this.batchItems = config;
XDMoD.TrackEvent('Report Generator (Report Editor)', 'Opened Chart Date Editor (batch mode)', this.batchItems.length + ' entries');
chart_config = config[0];
}
else {
var trackingConfig = XDMoD.Reporting.GetTrackingConfig(store_id, record_id);
XDMoD.TrackEvent('Report Generator (Report Editor)', 'Opened Chart Date Editor', Ext.encode(trackingConfig));
this.setTitle('Edit Chart Timeframe');
this.activeChartID = config.chart_id;
chart_config = config;
}
if (chart_config.type.toLowerCase() == 'user defined') {
rdoGrpTimeframeMode.items.get(0).setValue(true);
this.start_date_field.setValue(chart_config.start);
this.end_date_field.setValue(chart_config.end);
}
else {
rdoGrpTimeframeMode.items.get(1).setValue(true);
this.mnuPeriodicTimeframe.setText(chart_config.window);
}
};//present
// ---------------------------
self.mnuPeriodicTimeframe = new Ext.Button({
scope: this,
width: 90,
text: 'Month To Date',
tooltip: 'Set the periodic window',
cls: 'no-icon-menu',
menu: new Ext.menu.Menu({
plain: true,
showSeparator: false,
cls: 'no-icon-menu',
items: [
{text: 'Yesterday'},
{text: '7 Day'},
{text: '30 Day'},
{text: '90 Day'},
{text: 'Month To Date <b style="color: #00f">(' + date_utils.displayTimeframeDates('Month To Date') + ')</b>'},
{text: 'Quarter To Date <b style="color: #00f">(' + date_utils.displayTimeframeDates('Quarter To Date') + ')</b>'},
{text: 'Year To Date <b style="color: #00f">(' + date_utils.displayTimeframeDates('Year To Date') + ')</b>'},
{text: 'Previous Month <b style="color: #00f">(' + date_utils.getPreviousMonthName() + ')</b>'},
{text: 'Previous Quarter <b style="color: #00f">(' + date_utils.displayTimeframeDates('Previous Quarter') + ')</b>'},
{text: 'Previous Year <b style="color: #00f">(' + (today.getFullYear() - 1) + ')</b>'},
{text: '1 Year'},
{text: '2 Year'},
{text: '3 Year'},
{text: '5 Year'},
{text: '10 Year'},
{text: today.getFullYear()},
{text: today.getFullYear() - 1},
{text: today.getFullYear() - 2},
{text: today.getFullYear() - 3},
{text: today.getFullYear() - 4},
{text: today.getFullYear() - 5},
{text: today.getFullYear() - 6}
],
listeners: {
itemclick: {
fn: function(baseItem, e) {
var selectedItem = baseItem.text.toString().split(' <b')[0];
XDMoD.TrackEvent('Report Generator (Report Editor)', 'Chart Date Editor -> Selected Periodic Timeframe from drop-down menu', selectedItem);
self.mnuPeriodicTimeframe.setText(selectedItem);
}
}
}
})
});//mnuPeriodicTimeframe
this.start_date_field = new Ext.form.DateField({ height: 30, width: 90, format: 'Y-m-d', id: 'report_generator_edit_date_start_date_field' });
this.end_date_field = new Ext.form.DateField({ height: 30, width: 90, format: 'Y-m-d', id: 'report_generator_edit_date_end_date_field' });
this.start_date_field.on('select', function(dp, sel_date){
XDMoD.TrackEvent('Report Generator (Report Editor)', 'Chart Date Editor -> Selected start date from date picker', dp.getRawValue());
dp.startValue = sel_date;
});
this.end_date_field.on('select', function(dp, sel_date){
XDMoD.TrackEvent('Report Generator (Report Editor)', 'Chart Date Editor -> Selected end date from date picker', dp.getRawValue());
dp.startValue = sel_date;
});
this.start_date_field.on('change', function(dp, new_val, old_val){
XDMoD.TrackEvent('Report Generator (Report Editor)', 'Chart Date Editor -> Manually entered start date', dp.getRawValue());
});
this.end_date_field.on('change', function(dp, new_val, old_val){
XDMoD.TrackEvent('Report Generator (Report Editor)', 'Chart Date Editor -> Manually entered end date', dp.getRawValue());
});
var pnlTimeframeMode = new Ext.Panel({
region: 'center',
height: 30,
layout: 'card',
activeItem: 1,
border: false,
baseCls:'x-plain',
items: [
new Ext.Panel({
anchor:'100%',
baseCls:'x-plain',
layout:'hbox',
defaults: {
margins:'7 0 0 4'
},
items: [
self.mnuPeriodicTimeframe
]
}),
new Ext.Panel({
anchor:'100%',
baseCls:'x-plain',
layout:'hbox',
defaults: {
margins:'8 0 0 4'
},
items: [
self.start_date_field,
{xtype: 'tbtext', text: 'to', margins: '10 0 0 3' },
self.end_date_field
]
})
]
});
// -------------------------------------------------------------------
var presentOverlay = function(message, customdelay) {
var delay = customdelay ? customdelay : 2000;
btnCancel.setDisabled(true);
btnUpdate.setDisabled(true);
cPanel.getEl().mask('<div class="overlay_message" style="color: #f00">' + message + '</div>');
(function() {
btnCancel.setDisabled(false);
btnUpdate.setDisabled(false);
cPanel.getEl().unmask();
}).defer(delay);
};//presentOverlay
// -------------------------------------------------------------------
var btnCancel = new Ext.Button ({
iconCls: 'chart_date_editor_cancel_button',
text: 'Cancel',
handler: function(){ self.hide(); }
});//btnCancel
// -------------------------------------------------------------------
var btnUpdate = new Ext.Button({
iconCls: 'chart_date_editor_update_button',
text: 'Update',
handler: function(){
XDMoD.TrackEvent('Report Generator (Report Editor)', 'Chart Date Editor -> Clicked on Update button');
var new_start_date = '';
var new_end_date = '';
var new_timeframe_label = '';
// ====================================
if (self.getMode() == 'Specific') {
var response = dateRangeValidator(
self.start_date_field.getRawValue(),
self.end_date_field.getRawValue()
);
if (response.success == false) {
presentOverlay(response.message);
//alert(response.message);
return;
}
new_timeframe_label = 'User Defined';
new_start_date = self.start_date_field.getRawValue();
new_end_date = self.end_date_field.getRawValue();
}//if (Specific)
// ====================================
if (self.getMode() == 'Periodic') {
var endpoints = date_utils.getEndpoints(self.mnuPeriodicTimeframe.getText());
new_timeframe_label = self.mnuPeriodicTimeframe.getText();
new_start_date = endpoints.start_date;
new_end_date = endpoints.end_date;
}//if (Periodic)
// ====================================
XDMoD.TrackEvent('Report Generator (Report Editor)', 'Updated timeframe of selected chart(s)', new_start_date + ' to ' + new_end_date + ' (' + new_timeframe_label + ')');
if (self.batchMode == true) {
for (var c = 0; c < self.batchItems.length; c++) {
self.updateChartEntry({
chart_id: self.batchItems[c].chart_id,
timeframe_type: new_timeframe_label,
start_date: new_start_date,
end_date: new_end_date
});
}
}
else {
self.updateChartEntry({
chart_id: self.activeChartID,
timeframe_type: new_timeframe_label,
start_date: new_start_date,
end_date: new_end_date
});
}
self.hide();
self.reportCreatorPanel.dirtyConfig();
}//handler
});//btnUpdate
// -------------------------------------------------------------------
var rdoGrpTimeframeMode = new Ext.form.RadioGroup({
height: 200,
defaultType: 'radio',
columns: 1,
cls: 'custom_search_mode_group',
width: 70,
vertical: true,
region:'west',
items: [
{
boxLabel: 'Specific',
checked: true,
name: 'report_creator_chart_entry',
inputValue: 'Specific'
},
{
boxLabel: 'Periodic',
name: 'report_creator_chart_entry',
inputValue: 'Periodic'
}
],
listeners: {
change: function(rg, rc) {
XDMoD.TrackEvent('Report Generator (Report Editor)', 'Chart Date Editor -> Selected ' + rc.inputValue + ' option');
if (rc.inputValue == 'Specific') pnlTimeframeMode.getLayout().setActiveItem(1);
if (rc.inputValue == 'Periodic') pnlTimeframeMode.getLayout().setActiveItem(0);
}
}
});
var cPanel = new Ext.Panel({
layout: 'border',
border: false,
items: [
rdoGrpTimeframeMode,
pnlTimeframeMode
]//items
});//cPanel
self.on('hide', function() {
XDMoD.TrackEvent('Report Generator (Report Editor)', 'Closed Chart Date Editor');
});
// -------------------------------------------------------------------
Ext.apply(this, {
iconCls: 'custom_date',
cls: 'chart_date_editor',
items: [
cPanel
],
bbar: {
items: [
btnUpdate,
'->',
btnCancel
]//items
}//bbar
});
XDMoD.Reporting.ChartDateEditor.superclass.initComponent.call(this);
}//initComponent
});//XDMoD.Reporting.ChartDateEditor
|
lgpl-3.0
|
GuQiangJS/XPatchLib.Net
|
src/XPatchLib.UnitTest/ForXml/TestMulitPrimaryKeyClass.cs
|
1871
|
// Copyright © 2013-2017 - GuQiang
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using XPatchLib.UnitTest.TestClass;
#if NUNIT
using NUnit.Framework;
#elif XUNIT
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = XPatchLib.UnitTest.XUnitAssert;
#endif
namespace XPatchLib.UnitTest.ForXml
{
[TestFixture]
public class TestMulitPrimaryKeyClass:TestBase
{
[Test]
public void TestMulitPrimaryKeyClassListRemoveDivideAndCombine()
{
var oriList = new List<MulitPrimaryKeyClass>();
var revList = new List<MulitPrimaryKeyClass>();
oriList.Add(new MulitPrimaryKeyClass {Name = "Name1", Id = 1});
oriList.Add(new MulitPrimaryKeyClass {Name = "Name2", Id = 2});
oriList.Add(new MulitPrimaryKeyClass {Name = "Name3", Id = 3});
oriList.Add(new MulitPrimaryKeyClass {Name = "Name4", Id = 4});
revList.Add(new MulitPrimaryKeyClass {Name = "Name1", Id = 1});
revList.Add(new MulitPrimaryKeyClass {Name = "Name2", Id = 2});
revList.Add(new MulitPrimaryKeyClass {Name = "Name5", Id = 5});
var changedContext = @"<?xml version=""1.0"" encoding=""utf-8""?>
<List_MulitPrimaryKeyClass>
<MulitPrimaryKeyClass Action=""Remove"" Id=""3"" Name=""Name3"" />
<MulitPrimaryKeyClass Action=""Remove"" Id=""4"" Name=""Name4"" />
<MulitPrimaryKeyClass Action=""Add"">
<Id>5</Id>
<Name>Name5</Name>
</MulitPrimaryKeyClass>
</List_MulitPrimaryKeyClass>";
DoAssert(typeof(List<MulitPrimaryKeyClass>), changedContext, oriList, revList, true);
DoAssert(typeof(List<MulitPrimaryKeyClass>), changedContext, oriList, revList, false);
}
}
}
|
lgpl-3.0
|
Sebazzz/EntityProfiler
|
src/UI/EntityProfiler.Viewer/AppBootstrapper.cs
|
9324
|
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.ReflectionModel;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Windows;
using Anotar.Serilog;
using Caliburn.Micro;
using EntityProfiler.Common.Events;
using EntityProfiler.Interceptor.Reader;
using EntityProfiler.Interceptor.Reader.Protocol;
using EntityProfiler.TinyIoC;
using EntityProfiler.Viewer.Services;
using Gemini.Framework.Services;
using Serilog;
namespace EntityProfiler.Viewer
{
public class AppBootstrapper : BootstrapperBase, IDisposable
{
private TinyIoCContainer _tinyIoCContainer;
private bool _isDisposed;
private static readonly string[] _composableEmbeddedAssemblies =
{
"gemini"
};
protected CompositionContainer Container { get; set; }
public AppBootstrapper()
{
Initialize();
}
/// <summary>
/// By default, we are configured to use MEF
/// </summary>
[LogToErrorOnException]
protected override void Configure()
{
try
{
// Add all assemblies to AssemblySource (using a temporary DirectoryCatalog).
var directoryCatalog = new DirectoryCatalog(@"./");
AssemblySource.Instance.AddRange(
directoryCatalog.Parts
.Select(part => ReflectionModelServices.GetPartType(part).Value.Assembly)
.Where(assembly => !AssemblySource.Instance.Contains(assembly)));
// Prioritise the executable assembly. This allows the client project to override exports, including IShell.
// The client project can override SelectAssemblies to choose which assemblies are prioritised.
var priorityAssemblies = SelectAssemblies().ToList();
var priorityCatalog = new AggregateCatalog(priorityAssemblies.Select(x => new AssemblyCatalog(x)));
var priorityProvider = new CatalogExportProvider(priorityCatalog);
// Now get all other assemblies (excluding the priority assemblies).
var mainCatalog = new AggregateCatalog(
AssemblySource.Instance
.Where(assembly => !priorityAssemblies.Contains(assembly))
.Select(x => new AssemblyCatalog(x)));
var mainProvider = new CatalogExportProvider(mainCatalog);
Container = new CompositionContainer(priorityProvider, mainProvider);
priorityProvider.SourceProvider = Container;
mainProvider.SourceProvider = Container;
var batch = new CompositionBatch();
BindServices(batch);
batch.AddExportedValue(mainCatalog);
Container.Compose(batch);
}
catch (Exception e)
{
Log.Error(e, "Error on Bootstrapper Configure");
}
}
protected virtual void BindServices(CompositionBatch batch)
{
try
{
_tinyIoCContainer = new TinyIoCContainer();
var eventAggregator = new EventAggregator();
// Defaults
batch.AddExportedValue<IWindowManager>(new WindowManager());
batch.AddExportedValue<IEventAggregator>(eventAggregator);
// framework and infrastructure
_tinyIoCContainer.Register<IEventAggregator>(eventAggregator);
// _tinyIoCContainer.Register<IServiceLocator>(new TinyServiceLocator(_container));
_tinyIoCContainer.RegisterMultiple<IMessageEventSubscriber>(new[] {typeof (EventMessageListener)})
.AsSingleton();
// register other implementations
DependencyFactory.Configure(_tinyIoCContainer);
// Export IoC registrations
batch.AddExportedValue(_tinyIoCContainer.Resolve<IRestartableMessageListener>());
batch.AddExportedValue(Container);
}
catch (Exception e)
{
Log.Error(e, "Error on Bootstrapper BindServices: {CompositionBatch}", batch);
}
}
protected override object GetInstance(Type serviceType, string key)
{
string contract = string.IsNullOrEmpty(key) ? AttributedModelServices.GetContractName(serviceType) : key;
var exports = Container.GetExports<object>(contract);
if (exports.Any())
return exports.First().Value;
throw new Exception(string.Format("Could not locate any instances of contract {0}.", contract));
}
protected override IEnumerable<object> GetAllInstances(Type serviceType)
{
return Container.GetExportedValues<object>(AttributedModelServices.GetContractName(serviceType));
}
protected override void BuildUp(object instance)
{
Container.SatisfyImportsOnce(instance);
}
protected override void OnStartup(object sender, StartupEventArgs e)
{
base.OnStartup(sender, e);
DisplayRootViewFor<IMainWindow>();
}
protected override IEnumerable<Assembly> SelectAssemblies()
{
return new[] { Assembly.GetEntryAssembly() };
}
protected virtual Dictionary<string, Assembly> RegisterAssemblyAndEmbeddedDependencies()
{
var currentDomain = AppDomain.CurrentDomain;
var assemblies = currentDomain.GetAssemblies();
var references = new Dictionary<string, Assembly>();
var executingAssembly = Assembly.GetExecutingAssembly();
var embeddedAssemblies = _composableEmbeddedAssemblies.Select(p => string.Format("costura.{0}.dll.zip", p));
var manifestResourceNames = executingAssembly.GetManifestResourceNames()
.Where(p => embeddedAssemblies.Contains(p.ToLower()));
foreach (var resourceName in manifestResourceNames)
{
var solved = false;
foreach (var assembly in assemblies)
{
var refName = string.Format("costura.{0}.dll.zip", GetDllName(assembly, true));
if (resourceName.Equals(refName, StringComparison.OrdinalIgnoreCase))
{
references[assembly.FullName] = assembly;
solved = true;
break;
}
}
if (solved)
continue;
using (var resourceStream = executingAssembly.GetManifestResourceStream(resourceName))
{
if (resourceStream == null) continue;
if (resourceName.EndsWith(".zip"))
{
using (var compressStream = new DeflateStream(resourceStream, CompressionMode.Decompress))
{
var memStream = new MemoryStream();
CopyTo(compressStream, memStream);
memStream.Position = 0;
var rawAssembly = new byte[memStream.Length];
memStream.Read(rawAssembly, 0, rawAssembly.Length);
var reference = Assembly.Load(rawAssembly);
references[reference.FullName] = reference;
}
}
else
{
var rawAssembly = new byte[resourceStream.Length];
resourceStream.Read(rawAssembly, 0, rawAssembly.Length);
var reference = Assembly.Load(rawAssembly);
references[reference.FullName] = reference;
}
}
}
return references;
}
private static string GetDllName(Assembly assembly, bool withoutExtension = false)
{
var assemblyPath = assembly.CodeBase;
return withoutExtension ? Path.GetFileNameWithoutExtension(assemblyPath) : Path.GetFileName(assemblyPath);
}
private static void CopyTo(Stream source, Stream destination)
{
var array = new byte[81920];
int count;
while ((count = source.Read(array, 0, array.Length)) != 0)
{
destination.Write(array, 0, count);
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
if (!_isDisposed)
{
if (_tinyIoCContainer != null)
{
_tinyIoCContainer.Dispose();
}
_tinyIoCContainer = null;
_isDisposed = true;
}
}
}
}
|
lgpl-3.0
|
kidaa/Awakening-Core3
|
bin/scripts/object/draft_schematic/clothing/clothing_robe_formal_12.lua
|
3738
|
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_draft_schematic_clothing_clothing_robe_formal_12 = object_draft_schematic_clothing_shared_clothing_robe_formal_12:new {
templateType = DRAFTSCHEMATIC,
customObjectName = "Grand Mayoral Robe",
craftingToolTab = 8, -- (See DraftSchemticImplementation.h)
complexity = 23,
size = 4,
xpType = "crafting_clothing_general",
xp = 220,
assemblySkill = "clothing_assembly",
experimentingSkill = "clothing_experimentation",
customizationSkill = "clothing_customization",
customizationOptions = {34, 2, 1},
customizationStringNames = {"/private/index_color_0", "/private/index_color_1", "/private/index_color_2"},
customizationDefaults = {0, 142, 10},
ingredientTemplateNames = {"craft_clothing_ingredients_n", "craft_clothing_ingredients_n", "craft_clothing_ingredients_n", "craft_clothing_ingredients_n", "craft_clothing_ingredients_n", "craft_clothing_ingredients_n"},
ingredientTitleNames = {"trim_and_binding", "extra_trim", "jewelry_setting", "hardware", "inner_gown", "outer_gown"},
ingredientSlotType = {1, 1, 1, 0, 1, 0},
resourceTypes = {"object/tangible/component/clothing/shared_fiberplast_panel.iff", "object/tangible/component/clothing/shared_trim.iff", "object/tangible/component/clothing/shared_jewelry_setting.iff", "metal", "object/tangible/component/clothing/shared_synthetic_cloth.iff", "hide"},
resourceQuantities = {4, 4, 2, 160, 2, 120},
contribution = {100, 100, 100, 100, 100, 100},
targetTemplate = "object/tangible/wearables/robe/robe_s12.iff",
additionalTemplates = {
}
}
ObjectTemplates:addTemplate(object_draft_schematic_clothing_clothing_robe_formal_12, "object/draft_schematic/clothing/clothing_robe_formal_12.iff")
|
lgpl-3.0
|
MM2CSYNDIC/syndic
|
syndic-client-web/src/main/java/org/syndic/client/web/validator/UserValidator.java
|
2532
|
package org.syndic.client.web.validator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import org.syndic.client.web.command.UserCommand;
/**
*
* @author LYES KHERBICHE
*
*/
public class UserValidator implements Validator {
@SuppressWarnings("rawtypes")
@Override
public boolean supports(Class clazz) {
return UserCommand.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object obj, Errors error) {
ValidationUtils.rejectIfEmptyOrWhitespace(error, "userName", "required.userName", "Field userName is required");
ValidationUtils.rejectIfEmptyOrWhitespace(error, "passWord", "required.passWord", "Field passWord is required");
ValidationUtils.rejectIfEmptyOrWhitespace(error, "confirmation", "required.confirmation", "Field confirmation is required");
ValidationUtils.rejectIfEmptyOrWhitespace(error, "typeUser", "required.typeUser", "Field typeUser is required");
ValidationUtils.rejectIfEmptyOrWhitespace(error, "firstName", "required.firstName", "Field firstName is required");
ValidationUtils.rejectIfEmptyOrWhitespace(error, "lastName", "required.lastName", "Field lastName is required");
ValidationUtils.rejectIfEmptyOrWhitespace(error, "phone", "required.phone", "Field phone is required");
ValidationUtils.rejectIfEmptyOrWhitespace(error, "mobile", "required.mobile", "Field mobile is required");
ValidationUtils.rejectIfEmptyOrWhitespace(error, "email", "required.email", "Field email is required");
ValidationUtils.rejectIfEmptyOrWhitespace(error, "numAddress", "required.numAddress", "Field numAddress is required");
ValidationUtils.rejectIfEmptyOrWhitespace(error, "typeAddress", "required.typeAddress", "Field typeAddress is required");
ValidationUtils.rejectIfEmptyOrWhitespace(error, "street", "required.street", "Field street is required");
ValidationUtils.rejectIfEmptyOrWhitespace(error, "city", "required.city", "Field city is required");
ValidationUtils.rejectIfEmptyOrWhitespace(error, "zipCode", "required.zipCode", "Field zipCode is required");
ValidationUtils.rejectIfEmptyOrWhitespace(error, "country", "required.country", "Field country is required");
ValidationUtils.rejectIfEmptyOrWhitespace(error, "placeName", "required.placeName", "Field placeName is required");
if(!((UserCommand)obj).getPassWord().equals(((UserCommand)obj).getConfirmation())) {
error.reject("required.confirmation", "Confirmation is invalid ");
}
}
}
|
lgpl-3.0
|
edwinspire/VSharp
|
class/System.Web/System.Web.Configuration_2.0/EventMappingSettings.cs
|
4338
|
//
// System.Web.Configuration.EventMappingSettings
//
// Authors:
// Chris Toshok (toshok@ximian.com)
//
// (C) 2005 Novell, Inc (http://www.novell.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.ComponentModel;
using System.Configuration;
#if NET_2_0
namespace System.Web.Configuration {
public sealed class EventMappingSettings : ConfigurationElement
{
static ConfigurationProperty endEventCodeProp;
static ConfigurationProperty nameProp;
static ConfigurationProperty startEventCodeProp;
static ConfigurationProperty typeProp;
static ConfigurationPropertyCollection properties;
static EventMappingSettings ()
{
endEventCodeProp = new ConfigurationProperty ("endEventCode", typeof (int), Int32.MaxValue,
TypeDescriptor.GetConverter (typeof (int)),
PropertyHelper.IntFromZeroToMaxValidator,
ConfigurationPropertyOptions.None);
nameProp = new ConfigurationProperty ("name", typeof (string), "",
TypeDescriptor.GetConverter (typeof (string)),
PropertyHelper.NonEmptyStringValidator,
ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey);
startEventCodeProp = new ConfigurationProperty ("startEventCode", typeof (int), 0,
TypeDescriptor.GetConverter (typeof (int)),
PropertyHelper.IntFromZeroToMaxValidator,
ConfigurationPropertyOptions.None);
typeProp = new ConfigurationProperty ("type", typeof (string), "", ConfigurationPropertyOptions.IsRequired);
properties = new ConfigurationPropertyCollection ();
properties.Add (endEventCodeProp);
properties.Add (nameProp);
properties.Add (startEventCodeProp);
properties.Add (typeProp);
}
internal EventMappingSettings ()
{
}
public EventMappingSettings (string name, string type)
{
this.Name = name;
this.Type = type;
}
public EventMappingSettings (string name, string type, int startEventCode, int endEventCode)
{
this.Name = name;
this.Type = type;
this.StartEventCode = startEventCode;
this.EndEventCode = endEventCode;
}
[IntegerValidator (MinValue = 0, MaxValue = Int32.MaxValue)]
[ConfigurationProperty ("endEventCode", DefaultValue = "2147483647")]
public int EndEventCode {
get { return (int) base [endEventCodeProp];}
set { base[endEventCodeProp] = value; }
}
[ConfigurationProperty ("name", DefaultValue = "", Options = ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey)]
// LAMESPEC: MS lists no validator here but provides one in Properties.
public string Name {
get { return (string) base [nameProp];}
set { base[nameProp] = value; }
}
[IntegerValidator (MinValue = 0, MaxValue = Int32.MaxValue)]
[ConfigurationProperty ("startEventCode", DefaultValue = "0")]
public int StartEventCode {
get { return (int) base [startEventCodeProp];}
set { base[startEventCodeProp] = value; }
}
[ConfigurationProperty ("type", DefaultValue = "", Options = ConfigurationPropertyOptions.IsRequired)]
public string Type {
get { return (string) base [typeProp];}
set { base[typeProp] = value; }
}
protected internal override ConfigurationPropertyCollection Properties {
get { return properties; }
}
}
}
#endif
|
lgpl-3.0
|
kidaa/Awakening-Core3
|
bin/scripts/object/draft_schematic/structure/city/cityhall_tatooine.lua
|
3688
|
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_draft_schematic_structure_city_cityhall_tatooine = object_draft_schematic_structure_city_shared_cityhall_tatooine:new {
templateType = DRAFTSCHEMATIC,
customObjectName = "Deed for: Tatooine City Hall",
craftingToolTab = 1024, -- (See DraftSchemticImplementation.h)
complexity = 50,
size = 14,
xpType = "crafting_structure_general",
xp = 11800,
assemblySkill = "structure_assembly",
experimentingSkill = "structure_experimentation",
customizationSkill = "structure_customization",
customizationOptions = {},
customizationStringNames = {},
customizationDefaults = {},
ingredientTemplateNames = {"craft_structure_ingredients_n", "craft_structure_ingredients_n", "craft_structure_ingredients_n", "craft_structure_ingredients_n", "craft_structure_ingredients_n", "craft_structure_ingredients_n"},
ingredientTitleNames = {"load_bearing_structure_and_shell", "insulation_and_covering", "foundation", "wall_sections", "power_supply_unit", "storage_space"},
ingredientSlotType = {0, 0, 0, 2, 1, 1},
resourceTypes = {"metal", "ore", "ore", "object/tangible/component/structure/shared_wall_module.iff", "object/tangible/component/structure/shared_power_core_unit.iff", "object/tangible/component/structure/shared_structure_storage_section.iff"},
resourceQuantities = {1800, 4000, 400, 20, 6, 6},
contribution = {100, 100, 100, 100, 100, 100},
targetTemplate = "object/tangible/deed/city_deed/cityhall_tatooine_deed.iff",
additionalTemplates = {
}
}
ObjectTemplates:addTemplate(object_draft_schematic_structure_city_cityhall_tatooine, "object/draft_schematic/structure/city/cityhall_tatooine.iff")
|
lgpl-3.0
|
thelia/thelia
|
local/modules/Tinymce/I18n/it_IT.php
|
556
|
<?php
/*
* This file is part of the Thelia package.
* http://www.thelia.net
*
* (c) OpenStudio <info@thelia.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
return [
'Enter CSS or LESS code. You may also customize the editor.less file in the plugin template directory.' => 'Inserire il codice CSS o LESS. Si può anche personalizzare il file editor.less nella directory plugin del template.',
'Tinymce configuration' => 'Configurazione di TinyMCE',
];
|
lgpl-3.0
|
arcuri82/testing_security_development_enterprise_systems
|
intro/exercise-solutions/quiz-game/part-08/src/main/java/org/tsdes/intro/exercises/quizgame/entity/Category.java
|
1067
|
package org.tsdes.intro.exercises.quizgame.entity;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.List;
/**
* Created by arcuri82 on 30-Nov-16.
*/
@Entity
public class Category {
@Id
@GeneratedValue
private Long id;
@NotBlank
@Size(max=128)
@Column(unique=true)
private String name;
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
private List<SubCategory> subCategories;
public Category() {
subCategories = new ArrayList<>();
}
public List<SubCategory> getSubCategories() {
return subCategories;
}
public void setSubCategories(List<SubCategory> subCategories) {
this.subCategories = subCategories;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
lgpl-3.0
|
marikaris/molgenis
|
molgenis-data-security/src/main/java/org/molgenis/data/security/permission/model/LabelledObject.java
|
542
|
package org.molgenis.data.security.permission.model;
import com.google.auto.value.AutoValue;
import org.molgenis.util.AutoGson;
@AutoValue
@AutoGson(autoValueClass = AutoValue_LabelledObject.class)
@SuppressWarnings(
"squid:S1610") // Abstract classes without fields should be converted to interfaces
public abstract class LabelledObject {
public abstract String getId();
public abstract String getLabel();
public static LabelledObject create(String id, String label) {
return new AutoValue_LabelledObject(id, label);
}
}
|
lgpl-3.0
|
tethysplatform/TethysCluster
|
tethyscluster/plugins/pkginstaller.py
|
2221
|
# Copyright 2009-2014 Justin Riley
#
# This file is part of TethysCluster.
#
# TethysCluster is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# TethysCluster is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with TethysCluster. If not, see <http://www.gnu.org/licenses/>.
from tethyscluster import clustersetup
from tethyscluster.logger import log
class PackageInstaller(clustersetup.DefaultClusterSetup):
"""
This plugin installs Ubuntu packages on all nodes in the cluster. The
packages are specified in the plugin's config:
[plugin pkginstaller]
setup_class = tethyscluster.plugins.pkginstaller.PackageInstaller
packages = mongodb, python-mongodb
"""
def __init__(self, packages=None):
super(PackageInstaller, self).__init__()
self.packages = packages
if packages:
self.packages = [pkg.strip() for pkg in packages.split(',')]
def run(self, nodes, master, user, user_shell, volumes):
if not self.packages:
log.info("No packages specified!")
return
log.info('Installing the following packages on all nodes:')
log.info(', '.join(self.packages), extra=dict(__raw__=True))
pkgs = ' '.join(self.packages)
for node in nodes:
self.pool.simple_job(node.apt_install, (pkgs), jobid=node.alias)
self.pool.wait(len(nodes))
def on_add_node(self, new_node, nodes, master, user, user_shell, volumes):
log.info('Installing the following packages on %s:' % new_node.alias)
pkgs = ' '.join(self.packages)
new_node.apt_install(pkgs)
def on_remove_node(self, node, nodes, master, user, user_shell, volumes):
raise NotImplementedError("on_remove_node method not implemented")
|
lgpl-3.0
|
ruijieguo/firtex2
|
src/search/ResultCollectorImpl.cpp
|
3459
|
#include "firtex/search/ResultCollectorImpl.h"
#include "firtex/utility/NumberFormatter.h"
using namespace std;
FX_NS_USE(index);
FX_NS_USE(utility);
FX_NS_DEF(search);
SETUP_LOGGER(search, ResultCollectorImpl);
ResultCollectorImpl::ResultCollectorImpl(size_t nCapacity,
CompareField comp, const std::string& sField)
: m_pResultQueue(NULL)
, m_nCapacity(nCapacity)
{
switch (comp)
{
case COMP_SCORE:
m_pResultQueue = new ResultDocQueue(nCapacity, false,
NULL, new ScoreComparator);
break;
case COMP_DOCID:
m_pResultQueue = new ResultDocQueue(nCapacity, false,
NULL, new DocIdComparator);
break;
case COMP_FIELD_INT32:
m_pResultQueue = new ResultDocQueue(nCapacity, false,
NULL, new Int32FieldComparator(sField));
break;
case COMP_FIELD_UINT32:
m_pResultQueue = new ResultDocQueue(nCapacity, false,
NULL, new UInt32FieldComparator(sField));
break;
case COMP_FIELD_INT64:
m_pResultQueue = new ResultDocQueue(nCapacity, false,
NULL, new Int64FieldComparator(sField));
break;
case COMP_FIELD_UINT64:
m_pResultQueue = new ResultDocQueue(nCapacity, false,
NULL, new UInt64FieldComparator(sField));
break;
case COMP_FIELD_FLOAT:
m_pResultQueue = new ResultDocQueue(nCapacity, false,
NULL, new FloatFieldComparator(sField));
break;
case COMP_FIELD_DOUBLE:
m_pResultQueue = new ResultDocQueue(nCapacity, false,
NULL, new DoubleFieldComparator(sField));
break;
}
}
ResultCollectorImpl::~ResultCollectorImpl()
{
delete m_pResultQueue;
m_pResultQueue = NULL;
}
void ResultCollectorImpl::collect(const QueryResult& queryResults)
{
if (queryResults.hasError())
{
m_result.setError(m_result.getErrorMsg() + queryResults.getErrorMsg());
}
else
{
m_result.setTotalHits(m_result.getTotalHits() + queryResults.getTotalHits());
if (queryResults.getTimeCost() > m_result.getTimeCost())
{
m_result.setTimeCost(queryResults.getTimeCost());
}
shardid_t shardId = -1;
QueryResult::Iterator it = queryResults.iterator();
while (it.hasNext())
{
const ResultDocPtr& pDoc = it.next();
m_pResultQueue->insert(pDoc);
shardId = pDoc->getShardId();
}
const QueryTracerPtr& pTracer = queryResults.getTracer();
if (pTracer)
{
if (!m_result.getTracer())
{
QueryTracerPtr pTmp(new QueryTracer("proxy", pTracer->getLevel()));
m_result.setTracer(pTmp);
}
QueryTracerPtr& pResTracer = m_result.getTracer();
string str;
NumberFormatter::append(str, shardId);
pResTracer->addChildTracer(pTracer)->prependPath(str);
}
}
}
const QueryResult& ResultCollectorImpl::getResult()
{
while (m_pResultQueue->size() > 0)
{
ResultDocPtr pDoc = m_pResultQueue->pop();
m_result.addDoc(pDoc);
}
return m_result;
}
size_t ResultCollectorImpl::capacity() const
{
return m_nCapacity;
}
void ResultCollectorImpl::clear()
{
if (m_pResultQueue)
{
m_pResultQueue->clear();
}
m_result.clear();
}
FX_NS_END
|
lgpl-3.0
|
sfriesel/suds
|
suds/xsd/sxbasic.py
|
23899
|
# This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library Lesser General Public License for more details at
# ( http://www.gnu.org/licenses/lgpl.html ).
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# written by: Jeff Ortel ( jortel@redhat.com )
"""
The I{sxbasic} module provides classes that represent
I{basic} schema objects.
"""
from logging import getLogger
from suds import *
from suds.xsd import *
from suds.xsd.sxbase import *
from suds.xsd.query import *
from suds.sax import Namespace
from suds.transport import TransportError
from suds.reader import DocumentReader
from urlparse import urljoin
log = getLogger(__name__)
class RestrictionMatcher:
"""
For use with L{NodeFinder} to match restriction.
"""
def match(self, n):
return isinstance(n, Restriction)
class TypedContent(Content):
"""
Represents any I{typed} content.
"""
def __init__(self, *args, **kwargs):
Content.__init__(self, *args, **kwargs)
self.resolved_cache = {}
def resolve(self, nobuiltin=False):
"""
Resolve the node's type reference and return the referenced type node.
Returns self if the type is defined locally, e.g. as a <complexType>
subnode. Otherwise returns the referenced external node.
@param nobuiltin: Flag indicating whether resolving to XSD builtin
types should not be allowed.
@return: The resolved (true) type.
@rtype: L{SchemaObject}
"""
cached = self.resolved_cache.get(nobuiltin)
if cached is not None:
return cached
resolved = self.__resolve_type(nobuiltin)
self.resolved_cache[nobuiltin] = resolved
return resolved
def __resolve_type(self, nobuiltin=False):
"""
Private resolve() worker without any result caching.
@param nobuiltin: Flag indicating whether resolving to XSD builtin
types should not be allowed.
@return: The resolved (true) type.
@rtype: L{SchemaObject}
Implementation note:
Note that there is no need for a recursive implementation here since
a node can reference an external type node but there is no way using
WSDL to then make that type node actually be a reference to a different
type node.
"""
qref = self.qref()
if qref is None:
return self
query = TypeQuery(qref)
query.history = [self]
log.debug('%s, resolving: %s\n using:%s', self.id, qref, query)
resolved = query.execute(self.schema)
if resolved is None:
log.debug(self.schema)
raise TypeNotFound(qref)
if resolved.builtin() and nobuiltin:
return self
return resolved
def qref(self):
"""
Get the I{type} qualified reference to the referenced XSD type.
This method takes into account simple types defined through
restriction which are detected by determining that self is simple
(len=0) and by finding a restriction child.
@return: The I{type} qualified reference.
@rtype: qref
"""
qref = self.type
if qref is None and len(self) == 0:
ls = []
m = RestrictionMatcher()
finder = NodeFinder(m, 1)
finder.find(self, ls)
if len(ls):
return ls[0].ref
return qref
class Complex(SchemaObject):
"""
Represents an (XSD) schema <xs:complexType/> node.
@cvar childtags: A list of valid child node names.
@type childtags: (I{str},...)
"""
def childtags(self):
return 'attribute', 'attributeGroup', 'sequence', 'all', 'choice', \
'complexContent', 'simpleContent', 'any', 'group'
def description(self):
return ('name',)
def extension(self):
for c in self.rawchildren:
if c.extension():
return True
return False
def mixed(self):
for c in self.rawchildren:
if isinstance(c, SimpleContent) and c.mixed():
return True
return False
class Group(SchemaObject):
"""
Represents an (XSD) schema <xs:group/> node.
@cvar childtags: A list of valid child node names.
@type childtags: (I{str},...)
"""
def childtags(self):
return 'sequence', 'all', 'choice'
def dependencies(self):
deps = []
midx = None
if self.ref is not None:
query = GroupQuery(self.ref)
g = query.execute(self.schema)
if g is None:
log.debug(self.schema)
raise TypeNotFound(self.ref)
deps.append(g)
midx = 0
return midx, deps
def merge(self, other):
SchemaObject.merge(self, other)
self.rawchildren = other.rawchildren
def description(self):
return 'name', 'ref'
class AttributeGroup(SchemaObject):
"""
Represents an (XSD) schema <xs:attributeGroup/> node.
@cvar childtags: A list of valid child node names.
@type childtags: (I{str},...)
"""
def childtags(self):
return 'attribute', 'attributeGroup'
def dependencies(self):
deps = []
midx = None
if self.ref is not None:
query = AttrGroupQuery(self.ref)
ag = query.execute(self.schema)
if ag is None:
log.debug(self.schema)
raise TypeNotFound(self.ref)
deps.append(ag)
midx = 0
return midx, deps
def merge(self, other):
SchemaObject.merge(self, other)
self.rawchildren = other.rawchildren
def description(self):
return 'name', 'ref'
class Simple(SchemaObject):
"""
Represents an (XSD) schema <xs:simpleType/> node.
"""
def childtags(self):
return 'restriction', 'any', 'list'
def enum(self):
for child, ancestry in self.children():
if isinstance(child, Enumeration):
return True
return False
def mixed(self):
return len(self)
def description(self):
return ('name',)
def extension(self):
for c in self.rawchildren:
if c.extension():
return True
return False
def restriction(self):
for c in self.rawchildren:
if c.restriction():
return True
return False
class List(SchemaObject):
"""
Represents an (XSD) schema <xs:list/> node.
"""
def childtags(self):
return ()
def description(self):
return ('name',)
def xslist(self):
return True
class Restriction(SchemaObject):
"""
Represents an (XSD) schema <xs:restriction/> node.
"""
def __init__(self, schema, root):
SchemaObject.__init__(self, schema, root)
self.ref = root.get('base')
def childtags(self):
return 'enumeration', 'attribute', 'attributeGroup'
def dependencies(self):
deps = []
midx = None
if self.ref is not None:
query = TypeQuery(self.ref)
super = query.execute(self.schema)
if super is None:
log.debug(self.schema)
raise TypeNotFound(self.ref)
if not super.builtin():
deps.append(super)
midx = 0
return midx, deps
def restriction(self):
return True
def merge(self, other):
SchemaObject.merge(self, other)
filter = Filter(False, self.rawchildren)
self.prepend(self.rawchildren, other.rawchildren, filter)
def description(self):
return ('ref',)
class Collection(SchemaObject):
"""
Represents an (XSD) schema collection node:
- sequence
- choice
- all
"""
def childtags(self):
return 'element', 'sequence', 'all', 'choice', 'any', 'group'
class Sequence(Collection):
"""
Represents an (XSD) schema <xs:sequence/> node.
"""
def sequence(self):
return True
class All(Collection):
"""
Represents an (XSD) schema <xs:all/> node.
"""
def all(self):
return True
class Choice(Collection):
"""
Represents an (XSD) schema <xs:choice/> node.
"""
def choice(self):
return True
class ComplexContent(SchemaObject):
"""
Represents an (XSD) schema <xs:complexContent/> node.
"""
def childtags(self):
return 'attribute', 'attributeGroup', 'extension', 'restriction'
def extension(self):
for c in self.rawchildren:
if c.extension():
return True
return False
def restriction(self):
for c in self.rawchildren:
if c.restriction():
return True
return False
class SimpleContent(SchemaObject):
"""
Represents an (XSD) schema <xs:simpleContent/> node.
"""
def childtags(self):
return 'extension', 'restriction'
def extension(self):
for c in self.rawchildren:
if c.extension():
return True
return False
def restriction(self):
for c in self.rawchildren:
if c.restriction():
return True
return False
def mixed(self):
return len(self)
class Enumeration(Content):
"""
Represents an (XSD) schema <xs:enumeration/> node.
"""
def __init__(self, schema, root):
Content.__init__(self, schema, root)
self.name = root.get('value')
def description(self):
return ('name',)
def enum(self):
return True
class Element(TypedContent):
"""
Represents an (XSD) schema <xs:element/> node.
"""
def __init__(self, schema, root):
TypedContent.__init__(self, schema, root)
a = root.get('form')
if a is not None:
self.form_qualified = ( a == 'qualified' )
a = self.root.get('nillable')
if a is not None:
self.nillable = ( a in ('1', 'true') )
self.implany()
def implany(self):
"""
Set the type as any when implicit.
An implicit <xs:any/> is when an element has not
body and no type defined.
@return: self
@rtype: L{Element}
"""
if self.type is None and \
self.ref is None and \
self.root.isempty():
self.type = self.anytype()
return self
def childtags(self):
return 'attribute', 'simpleType', 'complexType', 'any'
def extension(self):
for c in self.rawchildren:
if c.extension():
return True
return False
def restriction(self):
for c in self.rawchildren:
if c.restriction():
return True
return False
def dependencies(self):
deps = []
midx = None
e = self.__deref()
if e is not None:
deps.append(e)
midx = 0
return midx, deps
def merge(self, other):
SchemaObject.merge(self, other)
self.rawchildren = other.rawchildren
def description(self):
return 'name', 'ref', 'type'
def anytype(self):
""" create an xsd:anyType reference """
p, u = Namespace.xsdns
mp = self.root.findPrefix(u)
if mp is None:
mp = p
self.root.addPrefix(p, u)
return ':'.join((mp, 'anyType'))
def namespace(self, prefix=None):
"""
Get this schema element's target namespace.
In case of reference elements, the target namespace is defined by the
referenced and not the referencing element node.
@param prefix: The default prefix.
@type prefix: str
@return: The schema element's target namespace
@rtype: (I{prefix},I{URI})
"""
e = self.__deref()
if e is not None:
return e.namespace(prefix)
return super(Element, self).namespace()
def __deref(self):
if self.ref is None:
return
query = ElementQuery(self.ref)
e = query.execute(self.schema)
if e is None:
log.debug(self.schema)
raise TypeNotFound(self.ref)
return e
class Extension(SchemaObject):
"""
Represents an (XSD) schema <xs:extension/> node.
"""
def __init__(self, schema, root):
SchemaObject.__init__(self, schema, root)
self.ref = root.get('base')
def childtags(self):
return 'attribute', 'attributeGroup', 'sequence', 'all', 'choice', \
'group'
def dependencies(self):
deps = []
midx = None
if self.ref is not None:
query = TypeQuery(self.ref)
super = query.execute(self.schema)
if super is None:
log.debug(self.schema)
raise TypeNotFound(self.ref)
if not super.builtin():
deps.append(super)
midx = 0
return midx, deps
def merge(self, other):
SchemaObject.merge(self, other)
filter = Filter(False, self.rawchildren)
self.prepend(self.rawchildren, other.rawchildren, filter)
def extension(self):
return self.ref is not None
def description(self):
return ('ref',)
class Import(SchemaObject):
"""
Represents an (XSD) schema <xs:import/> node.
@cvar locations: A dictionary of namespace locations.
@type locations: dict
@ivar ns: The imported namespace.
@type ns: str
@ivar location: The (optional) location.
@type location: namespace-uri
@ivar opened: Opened and I{imported} flag.
@type opened: boolean
"""
locations = {}
@classmethod
def bind(cls, ns, location=None):
"""
Bind a namespace to a schema location (URI).
This is used for imports that don't specify a schemaLocation.
@param ns: A namespace-uri.
@type ns: str
@param location: The (optional) schema location for the
namespace. (default=ns).
@type location: str
"""
if location is None:
location = ns
cls.locations[ns] = location
def __init__(self, schema, root):
SchemaObject.__init__(self, schema, root)
self.ns = (None, root.get('namespace'))
self.location = root.get('schemaLocation')
if self.location is None:
self.location = self.locations.get(self.ns[1])
self.opened = False
def open(self, options):
"""
Open and import the refrenced schema.
@param options: An options dictionary.
@type options: L{options.Options}
@return: The referenced schema.
@rtype: L{Schema}
"""
if self.opened:
return
self.opened = True
log.debug('%s, importing ns="%s", location="%s"', self.id, self.ns[1], self.location)
result = self.locate()
if result is None:
if self.location is None:
log.debug('imported schema (%s) not-found', self.ns[1])
else:
result = self.download(options)
log.debug('imported:\n%s', result)
return result
def locate(self):
""" find the schema locally """
if self.ns[1] != self.schema.tns[1]:
return self.schema.locate(self.ns)
def download(self, options):
""" download the schema """
url = self.location
try:
if '://' not in url:
url = urljoin(self.schema.baseurl, url)
reader = DocumentReader(options)
d = reader.open(url)
root = d.root()
root.set('url', url)
return self.schema.instance(root, url, options)
except TransportError:
msg = 'imported schema (%s) at (%s), failed' % (self.ns[1], url)
log.error('%s, %s', self.id, msg, exc_info=True)
raise Exception(msg)
def description(self):
return 'ns', 'location'
class Include(SchemaObject):
"""
Represents an (XSD) schema <xs:include/> node.
@ivar location: The (optional) location.
@type location: namespace-uri
@ivar opened: Opened and I{imported} flag.
@type opened: boolean
"""
locations = {}
def __init__(self, schema, root):
SchemaObject.__init__(self, schema, root)
self.location = root.get('schemaLocation')
if self.location is None:
self.location = self.locations.get(self.ns[1])
self.opened = False
def open(self, options):
"""
Open and include the refrenced schema.
@param options: An options dictionary.
@type options: L{options.Options}
@return: The referenced schema.
@rtype: L{Schema}
"""
if self.opened:
return
self.opened = True
log.debug('%s, including location="%s"', self.id, self.location)
result = self.download(options)
log.debug('included:\n%s', result)
return result
def download(self, options):
""" download the schema """
url = self.location
try:
if '://' not in url:
url = urljoin(self.schema.baseurl, url)
reader = DocumentReader(options)
d = reader.open(url)
root = d.root()
root.set('url', url)
self.__applytns(root)
return self.schema.instance(root, url, options)
except TransportError:
msg = 'include schema at (%s), failed' % url
log.error('%s, %s', self.id, msg, exc_info=True)
raise Exception(msg)
def __applytns(self, root):
""" make sure included schema has same tns. """
TNS = 'targetNamespace'
tns = root.get(TNS)
if tns is None:
tns = self.schema.tns[1]
root.set(TNS, tns)
else:
if self.schema.tns[1] != tns:
raise Exception, '%s mismatch' % TNS
def description(self):
return 'location'
class Attribute(TypedContent):
"""
Represents an (XSD) <attribute/> node.
"""
def __init__(self, schema, root):
TypedContent.__init__(self, schema, root)
self.use = root.get('use', default='')
def childtags(self):
return ('restriction',)
def isattr(self):
return True
def get_default(self):
"""
Gets the <xs:attribute default=""/> attribute value.
@return: The default value for the attribute
@rtype: str
"""
return self.root.get('default', default='')
def optional(self):
return self.use != 'required'
def dependencies(self):
deps = []
midx = None
if self.ref is not None:
query = AttrQuery(self.ref)
a = query.execute(self.schema)
if a is None:
log.debug(self.schema)
raise TypeNotFound(self.ref)
deps.append(a)
midx = 0
return midx, deps
def description(self):
return 'name', 'ref', 'type'
class Any(Content):
"""
Represents an (XSD) <any/> node.
"""
def get_child(self, name):
root = self.root.clone()
root.set('note', 'synthesized (any) child')
child = Any(self.schema, root)
return child, []
def get_attribute(self, name):
root = self.root.clone()
root.set('note', 'synthesized (any) attribute')
attribute = Any(self.schema, root)
return attribute, []
def any(self):
return True
class Factory:
"""
@cvar tags: A factory to create object objects based on tag.
@type tags: {tag:fn,}
"""
tags = {
'import' : Import,
'include' : Include,
'complexType' : Complex,
'group' : Group,
'attributeGroup' : AttributeGroup,
'simpleType' : Simple,
'list' : List,
'element' : Element,
'attribute' : Attribute,
'sequence' : Sequence,
'all' : All,
'choice' : Choice,
'complexContent' : ComplexContent,
'simpleContent' : SimpleContent,
'restriction' : Restriction,
'enumeration' : Enumeration,
'extension' : Extension,
'any' : Any,
}
@classmethod
def maptag(cls, tag, fn):
"""
Map (override) tag => I{class} mapping.
@param tag: An XSD tag name.
@type tag: str
@param fn: A function or class.
@type fn: fn|class.
"""
cls.tags[tag] = fn
@classmethod
def create(cls, root, schema):
"""
Create an object based on the root tag name.
@param root: An XML root element.
@type root: L{Element}
@param schema: A schema object.
@type schema: L{schema.Schema}
@return: The created object.
@rtype: L{SchemaObject}
"""
fn = cls.tags.get(root.name)
if fn is not None:
return fn(schema, root)
@classmethod
def build(cls, root, schema, filter=('*',)):
"""
Build an xsobject representation.
@param root: An schema XML root.
@type root: L{sax.element.Element}
@param filter: A tag filter.
@type filter: [str,...]
@return: A schema object graph.
@rtype: L{sxbase.SchemaObject}
"""
children = []
for node in root.getChildren(ns=Namespace.xsdns):
if '*' in filter or node.name in filter:
child = cls.create(node, schema)
if child is None:
continue
children.append(child)
c = cls.build(node, schema, child.childtags())
child.rawchildren = c
return children
@classmethod
def collate(cls, children):
imports = []
elements = {}
attributes = {}
types = {}
groups = {}
agrps = {}
for c in children:
if isinstance(c, (Import, Include)):
imports.append(c)
continue
if isinstance(c, Attribute):
attributes[c.qname] = c
continue
if isinstance(c, Element):
elements[c.qname] = c
continue
if isinstance(c, Group):
groups[c.qname] = c
continue
if isinstance(c, AttributeGroup):
agrps[c.qname] = c
continue
types[c.qname] = c
for i in imports:
children.remove(i)
return children, imports, attributes, elements, types, groups, agrps
#######################################################
# Static Import Bindings :-(
#######################################################
Import.bind(
'http://schemas.xmlsoap.org/soap/encoding/',
'suds://schemas.xmlsoap.org/soap/encoding/')
Import.bind(
'http://www.w3.org/XML/1998/namespace',
'http://www.w3.org/2001/xml.xsd')
Import.bind(
'http://www.w3.org/2001/XMLSchema',
'http://www.w3.org/2001/XMLSchema.xsd')
|
lgpl-3.0
|
exoplatform/answers
|
webapp/src/main/java/org/exoplatform/answer/webui/popup/UIQuestionForm.java
|
31601
|
/***************************************************************************
* Copyright (C) 2003-2007 eXo Platform SAS.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see<http://www.gnu.org/licenses/>.
***************************************************************************/
package org.exoplatform.answer.webui.popup;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.exoplatform.answer.webui.BaseUIFAQForm;
import org.exoplatform.answer.webui.FAQUtils;
import org.exoplatform.answer.webui.UIAnswersContainer;
import org.exoplatform.answer.webui.UIAnswersPortlet;
import org.exoplatform.answer.webui.UIQuestions;
import org.exoplatform.answer.webui.ValidatorDataInput;
import org.exoplatform.commons.utils.HTMLSanitizer;
import org.exoplatform.commons.utils.StringCommonUtils;
import org.exoplatform.container.PortalContainer;
import org.exoplatform.faq.service.FAQSetting;
import org.exoplatform.faq.service.FileAttachment;
import org.exoplatform.faq.service.Question;
import org.exoplatform.faq.service.QuestionLanguage;
import org.exoplatform.forum.common.CommonUtils;
import org.exoplatform.forum.common.UserHelper;
import org.exoplatform.forum.common.webui.BaseEventListener;
import org.exoplatform.forum.common.webui.UIPopupAction;
import org.exoplatform.forum.common.webui.UIPopupContainer;
import org.exoplatform.forum.service.ForumService;
import org.exoplatform.forum.service.MessageBuilder;
import org.exoplatform.forum.service.Topic;
import org.exoplatform.forum.service.Utils;
import org.exoplatform.portal.webui.util.Util;
import org.exoplatform.services.resources.LocaleConfig;
import org.exoplatform.services.resources.LocaleConfigService;
import org.exoplatform.webui.config.annotation.ComponentConfig;
import org.exoplatform.webui.config.annotation.EventConfig;
import org.exoplatform.webui.core.UIPopupComponent;
import org.exoplatform.webui.core.lifecycle.UIFormLifecycle;
import org.exoplatform.webui.core.model.SelectItemOption;
import org.exoplatform.webui.event.Event;
import org.exoplatform.webui.event.EventListener;
import org.exoplatform.webui.form.UIForm;
import org.exoplatform.webui.form.UIFormInputInfo;
import org.exoplatform.webui.form.UIFormInputWithActions;
import org.exoplatform.webui.form.UIFormInputWithActions.ActionData;
import org.exoplatform.webui.form.UIFormRichtextInput;
import org.exoplatform.webui.form.UIFormSelectBox;
import org.exoplatform.webui.form.UIFormStringInput;
import org.exoplatform.webui.form.input.UICheckBoxInput;
@ComponentConfig(lifecycle = UIFormLifecycle.class,
template = "app:/templates/answer/webui/popup/UIQuestionForm.gtmpl",
events = {
@EventConfig(listeners = UIQuestionForm.SelectLanguageActionListener.class),
@EventConfig(listeners = UIQuestionForm.DeleteLanguageActionListener.class, confirm = "UIQuestionForm.msg.DeleteQuestionInLanguage"),
@EventConfig(listeners = UIQuestionForm.AttachmentActionListener.class),
@EventConfig(listeners = UIQuestionForm.SaveActionListener.class),
@EventConfig(listeners = UIQuestionForm.CancelActionListener.class),
@EventConfig(listeners = UIQuestionForm.RemoveAttachmentActionListener.class)
})
public class UIQuestionForm extends BaseUIFAQForm implements UIPopupComponent {
public static final String AUTHOR = "Author";
public static final String EMAIL_ADDRESS = "EmailAddress";
public static final String QUESTION_CONTENT = "QuestionTitle";
public static final String ALL_LANGUAGES = "AllLanguages";
public static final String QUESTION_DETAIL = "Question";
public static final String ATTACHMENTS = "Attachment";
public static final String FILE_ATTACHMENTS = "FileAttach";
public static final String REMOVE_FILE_ATTACH = "RemoveFile";
public static final String IS_APPROVED = "IsApproved";
public static final String IS_ACTIVATED = "IsActivated";
public static final String DELETE_LANGUAGE_ACTION = "DeleteLanguage";
private UIFormStringInput inputAuthor = null;
private UIFormStringInput inputEmailAddress = null;
private UIFormStringInput inputQuestionContent = null;
private UIFormRichtextInput inputQuestionDetail = null;
private UIFormSelectBox selectLanguage = null;
private UICheckBoxInput inputIsApproved = null;
private UICheckBoxInput inputIsActivated = null;
private UIFormInputWithActions inputAttachcment = null;
private Question question_ = null;
private Map<String, List<ActionData>> actionField_;
private List<SelectItemOption<String>> listSystemLanguages = new ArrayList<SelectItemOption<String>>();
private List<FileAttachment> listFileAttach_ = new ArrayList<FileAttachment>();
private Map<String, QuestionLanguage> mapLanguage = new HashMap<String, QuestionLanguage>();
private String categoryId_ = "";
private String questionId_ = null;
private String defaultLanguage_ = "";
private String lastLanguage_ = "";
private String author_ = "";
private String email_ = "";
private List<String> questionContents_ = new ArrayList<String>();
private boolean isApproved_ = true;
private boolean isActivated_ = true;
private boolean isMode = false;
private boolean isChildOfManager = false;
private boolean isModerate = false;
private boolean isAddCheckBox = false;
private Locale currentLocale = null;
private String editLanguage = null;
protected boolean isRenderSelectLang = false;
private boolean isReadOnlyAuthor = true;
private FAQSetting faqSetting_;
public void activate() {
}
public void deActivate() {
}
public void setFAQSetting(FAQSetting faqSetting) {
this.faqSetting_ = faqSetting;
}
public String getEditLanguage() {
return editLanguage;
}
public void setEditLanguage(String editLanguage) {
this.editLanguage = editLanguage;
}
public UIQuestionForm() throws Exception {
isChildOfManager = false;
listFileAttach_.clear();
mapLanguage.clear();
questionContents_.clear();
listFileAttach_ = new ArrayList<FileAttachment>();
actionField_ = new HashMap<String, List<ActionData>>();
questionId_ = "";
question_ = null;
setActions(new String[] { "Save", "Cancel" });
}
public void refresh() throws Exception {
listFileAttach_.clear();
}
private String capitalizeFirstLetter(String word) {
if (word == null) {
return null;
}
if (word.length() == 0) {
return word;
}
StringBuilder result = new StringBuilder(word);
result.replace(0, 1, result.substring(0, 1).toUpperCase());
return result.toString();
}
public void setLanguages() throws Exception {
Locale currentLocale = Util.getPortalRequestContext().getLocale();
if (this.currentLocale == null || !this.currentLocale.getLanguage().equals(currentLocale.getLanguage())) {
this.currentLocale = currentLocale;
setListSystemLanguages();
}
}
private void setListSystemLanguages() {
listSystemLanguages.clear();
List<String> languages = FAQUtils.getAllLanguages(this);
if (languages.size() <= 1)
isRenderSelectLang = false;
else
isRenderSelectLang = true;
LocaleConfigService localeConfigService = getApplicationComponent(LocaleConfigService.class);
String displyByLocal, lang;
for (LocaleConfig localeConfig : localeConfigService.getLocalConfigs()) {
lang = localeConfig.getLocale().getDisplayLanguage();
displyByLocal = capitalizeFirstLetter(localeConfig.getLocale().getDisplayLanguage(currentLocale));
if (lang.equals(defaultLanguage_))
listSystemLanguages.add(new SelectItemOption<String>(displyByLocal + " (" + getLabel("default") + ") ", lang));
else
listSystemLanguages.add(new SelectItemOption<String>(displyByLocal, lang));
}
}
public void initPage() throws Exception {
setLanguages();
//
isReadOnlyAuthor = isReadOnlyAuthor();
//
inputAuthor = new UIFormStringInput(AUTHOR, AUTHOR, author_);
inputAuthor.setDisabled(isReadOnlyAuthor);
//
inputEmailAddress = new UIFormStringInput(EMAIL_ADDRESS, EMAIL_ADDRESS, email_);
inputEmailAddress.setDisabled(isReadOnlyAuthor);
//
inputQuestionContent = new UIFormStringInput(QUESTION_CONTENT, QUESTION_CONTENT, null);
selectLanguage = new UIFormSelectBox(ALL_LANGUAGES, ALL_LANGUAGES, listSystemLanguages);
if (!FAQUtils.isFieldEmpty(getEditLanguage())) {
selectLanguage.setValue(getEditLanguage());
selectLanguage.setSelectedValues(new String[] { getEditLanguage() });
} else if (!FAQUtils.isFieldEmpty(defaultLanguage_)) {
selectLanguage.setValue(defaultLanguage_);
selectLanguage.setSelectedValues(new String[] { defaultLanguage_ });
}
selectLanguage.setOnChange("SelectLanguage");
inputIsApproved = new UICheckBoxInput(IS_APPROVED, IS_APPROVED, false);
inputIsActivated = new UICheckBoxInput(IS_ACTIVATED, IS_ACTIVATED, false);
inputAttachcment = new UIFormInputWithActions(ATTACHMENTS);
inputAttachcment.addUIFormInput(new UIFormInputInfo(FILE_ATTACHMENTS, FILE_ATTACHMENTS, null));
try {
inputAttachcment.setActionField(FILE_ATTACHMENTS, getActionList());
} catch (Exception e) {
log.error("Set Attachcments in to InputActachcment is fall, exception: " + e.getMessage());
}
inputQuestionDetail = new UIFormRichtextInput(QUESTION_DETAIL, QUESTION_DETAIL, "");
inputQuestionDetail.setIgnoreParserHTML(true).setIsPasteAsPlainText(true)
.setToolbar(UIFormRichtextInput.FAQ_TOOLBAR);
if (!questionContents_.isEmpty()) {
String input = questionContents_.get(0);
if (input != null && input.indexOf("<p>") >= 0 && input.indexOf("</p>") >= 0) {
input = input.replace("<p>", "");
input = input.substring(0, input.lastIndexOf("</p>") - 1);
}
inputQuestionDetail.setValue(StringCommonUtils.decodeSpecialCharToHTMLnumberIgnore(input));
}
addChild(inputQuestionContent);
addChild(inputQuestionDetail);
addChild(selectLanguage);
addChild(inputAuthor);
addChild(inputEmailAddress);
isModerate = getFAQService().isModerateQuestion(getCategoryId());
isAddCheckBox = false;
if (getIsModerator()) {
if (questionId_ != null && questionId_.trim().length() > 0) {
addChild(inputIsApproved.setChecked(isApproved_));
addChild(inputIsActivated.setChecked(isActivated_));
isAddCheckBox = true;
} else {
if (isModerate) {
addChild(inputIsApproved.setChecked(false));
addChild(inputIsActivated.setChecked(true));
isAddCheckBox = true;
}
}
}
addUIFormInput(inputAttachcment);
if (question_ != null) {
this.setListFileAttach(question_.getAttachMent());
try {
refreshUploadFileList();
} catch (Exception e) {
log.error("Refresh upload InputActachcment is fall, exception: " + e.getMessage());
}
}
}
private boolean isReadOnlyAuthor() {
try {
return !CommonUtils.isEmpty(getAuthor()) && UserHelper.getUserByUserId(getAuthor()) != null;
} catch (Exception e) {
return false;
}
}
private boolean getIsModerator() throws Exception {
try {
if (faqSetting_.isAdmin() || isMode) {
isMode = true;
} else
isMode = getFAQService().isCategoryModerator(categoryId_, null);
} catch (Exception e) {
log.debug("Failed to get isModerator.", e);
}
return isMode;
}
public void setIsChildOfManager(boolean isChild) {
isChildOfManager = isChild;
this.removeChildById(AUTHOR);
this.removeChildById(EMAIL_ADDRESS);
this.removeChildById(QUESTION_CONTENT);
this.removeChildById(QUESTION_DETAIL);
this.removeChildById(ATTACHMENTS);
this.removeChildById(IS_APPROVED);
this.removeChildById(IS_ACTIVATED);
this.removeChildById(ALL_LANGUAGES);
listFileAttach_.clear();
mapLanguage.clear();
}
public void setQuestion(Question question) throws Exception {
questionId_ = question.getPath();
categoryId_ = question.getCategoryId();
try {
question_ = question;
defaultLanguage_ = question_.getLanguage();
lastLanguage_ = defaultLanguage_;
List<QuestionLanguage> questionLanguages = getFAQService().getQuestionLanguages(questionId_);
for (QuestionLanguage questionLanguage : questionLanguages) {
mapLanguage.put(questionLanguage.getLanguage(), questionLanguage);
}
isApproved_ = question_.isApproved();
isActivated_ = question_.isActivated();
setEmail(question_.getEmail());
setAuthor(question_.getAuthor());
//
initPage();
if(mapLanguage.containsKey(this.editLanguage)){
inputQuestionDetail.setValue(StringCommonUtils.decodeSpecialCharToHTMLnumberIgnore(mapLanguage.get(editLanguage).getDetail()));
inputQuestionContent.setValue(StringCommonUtils.decodeSpecialCharToHTMLnumber(mapLanguage.get(editLanguage).getQuestion()));
}else{
inputQuestionDetail.setValue(StringCommonUtils.decodeSpecialCharToHTMLnumberIgnore(question_.getDetail()));
inputQuestionContent.setValue(StringCommonUtils.decodeSpecialCharToHTMLnumber(question_.getQuestion()));
}
} catch (Exception e) {
log.error("Set question is fall, exception: " + e.getMessage());
initPage();
}
}
public boolean isMode() {
return isMode;
}
public void setIsMode(boolean isMode) {
this.isMode = isMode;
}
public String getQuestionId() {
return questionId_;
}
public void setDefaultLanguage(String defaultLanguage) {
this.defaultLanguage_ = defaultLanguage;
}
public String getDefaultLanguage() {
return this.defaultLanguage_;
}
protected String getAuthor() {
return this.author_;
}
public void setAuthor(String author) {
this.author_ = author;
}
protected String getEmail() {
return this.email_;
}
public void setEmail(String email) {
this.email_ = email;
}
private String getCategoryId() {
return this.categoryId_;
}
public void setCategoryId(String categoryId) throws Exception {
this.categoryId_ = categoryId;
questionId_ = null;
defaultLanguage_ = FAQUtils.getDefaultLanguage();
lastLanguage_ = defaultLanguage_;
initPage();
}
protected UIForm getParentForm() {
return (UIForm) this.getParent();
}
public List<ActionData> getActionList() {
List<ActionData> uploadedFiles = new ArrayList<ActionData>();
for (FileAttachment attachdata : listFileAttach_) {
ActionData uploadAction = new ActionData();
uploadAction.setActionListener("Download");
uploadAction.setActionParameter(attachdata.getPath());
uploadAction.setActionType(ActionData.TYPE_ICON);
uploadAction.setCssIconClass("AttachmentIcon"); // "AttachmentIcon ZipFileIcon"
uploadAction.setActionName(attachdata.getName() + " (" + attachdata.getSize() + " B)");
uploadAction.setShowLabel(true);
uploadedFiles.add(uploadAction);
ActionData removeAction = new ActionData();
removeAction.setActionListener("RemoveAttachment");
removeAction.setActionName(REMOVE_FILE_ATTACH);
removeAction.setActionParameter(attachdata.getPath());
removeAction.setCssIconClass("LabelLink");
removeAction.setActionType(ActionData.TYPE_LINK);
uploadedFiles.add(removeAction);
}
return uploadedFiles;
}
public void setListFileAttach(List<FileAttachment> listFileAttachment) {
listFileAttach_.addAll(listFileAttachment);
}
public void setListFileAttach(FileAttachment fileAttachment) {
listFileAttach_.add(fileAttachment);
}
protected List<FileAttachment> getListFile() {
return listFileAttach_;
}
public void refreshUploadFileList() throws Exception {
((UIFormInputWithActions) this.getChildById(ATTACHMENTS)).setActionField(FILE_ATTACHMENTS, getActionList());
}
public void setActionField(String fieldName, List<ActionData> actions) throws Exception {
actionField_.put(fieldName, actions);
}
public List<ActionData> getActionField(String fieldName) {
return actionField_.get(fieldName);
}
static public class SelectLanguageActionListener extends BaseEventListener<UIQuestionForm> {
public void onEvent(Event<UIQuestionForm> event, UIQuestionForm questionForm, String objectId) throws Exception {
String language = questionForm.selectLanguage.getValue();
String detail = questionForm.inputQuestionDetail.getValue();
String question = questionForm.inputQuestionContent.getValue();
if (!ValidatorDataInput.fckContentIsNotEmpty(detail)){
detail = " ";
}
if (!ValidatorDataInput.fckContentIsNotEmpty(question)) {
if (questionForm.mapLanguage.containsKey(questionForm.lastLanguage_)) {
questionForm.mapLanguage.get(questionForm.lastLanguage_).setState(QuestionLanguage.DELETE);
}
} else {
QuestionLanguage langObj = new QuestionLanguage();
if (questionForm.mapLanguage.containsKey(questionForm.lastLanguage_)) {
langObj = questionForm.mapLanguage.get(questionForm.lastLanguage_);
langObj.setState(QuestionLanguage.EDIT);
}
langObj.setQuestion(question);
langObj.setDetail(detail);
langObj.setLanguage(questionForm.lastLanguage_);
questionForm.mapLanguage.put(langObj.getLanguage(), langObj);
}
questionForm.lastLanguage_ = language;
if (questionForm.mapLanguage.containsKey(language)) {
questionForm.inputQuestionDetail.setValue(questionForm.mapLanguage.get(language).getDetail());
questionForm.inputQuestionContent.setValue(questionForm.mapLanguage.get(language).getQuestion());
} else {
questionForm.inputQuestionDetail.setValue("");
questionForm.inputQuestionContent.setValue("");
}
event.getRequestContext().addUIComponentToUpdateByAjax(questionForm);
}
}
static public class DeleteLanguageActionListener extends EventListener<UIQuestionForm> {
public void execute(Event<UIQuestionForm> event) throws Exception {
UIQuestionForm questionForm = event.getSource();
questionForm.inputQuestionDetail.setValue("");
questionForm.inputQuestionContent.setValue("");
event.getRequestContext().addUIComponentToUpdateByAjax(questionForm);
}
}
static public class SaveActionListener extends BaseEventListener<UIQuestionForm> {
public void onEvent(Event<UIQuestionForm> event, UIQuestionForm questionForm, String objectId) throws Exception {
try {
boolean isNew = true;
String author = questionForm.inputAuthor.getValue();
String emailAddress = questionForm.inputEmailAddress.getValue();
if (!questionForm.isReadOnlyAuthor) {
if (CommonUtils.isEmpty(author)) {
warning("UIQuestionForm.msg.author-is-null");
return;
}
if (CommonUtils.isEmpty(emailAddress) || !FAQUtils.isValidEmailAddresses(emailAddress)) {
warning("UIQuestionForm.msg.email-address-invalid");
return;
}
}
String questionContent = questionForm.inputQuestionContent.getValue();
String language = questionForm.selectLanguage.getValue();
language = FAQUtils.isFieldEmpty(language) ? questionForm.defaultLanguage_ : language;
// Duy Tu: Check require question content not empty.
if (FAQUtils.isFieldEmpty(questionContent)) {
if (language.equals(questionForm.defaultLanguage_)) {
warning("UIQuestionForm.msg.default-question-null");
} else {
warning("UIQuestionForm.msg.mutil-language-question-null", new String[] { language });
}
return;
}
if (!language.equals(questionForm.defaultLanguage_)) {
if (questionForm.mapLanguage.isEmpty() || questionForm.mapLanguage.get(questionForm.getDefaultLanguage()) == null) {
warning("UIQuestionForm.msg.default-question-null");
return;
}
}
String questionDetail = questionForm.inputQuestionDetail.getValue();
if (!ValidatorDataInput.fckContentIsNotEmpty(questionDetail))
questionDetail = " ";
if (!ValidatorDataInput.fckContentIsNotEmpty(questionContent)) {
if (questionForm.mapLanguage.containsKey(language)) {
questionForm.mapLanguage.get(language).setState(QuestionLanguage.DELETE);
}
}
//--- Sanitize HTML content to avoid XSS injection
questionDetail = HTMLSanitizer.sanitize(questionDetail);
questionContent = StringCommonUtils.encodeSpecialCharForSimpleInput(questionContent);
Question question = questionForm.getQuestion();
if(questionForm.questionId_ == null || questionForm.questionId_.trim().length() < 1) { //Add new question
question = new Question() ;
String catId = questionForm.getCategoryId();
question.setCategoryId((catId.indexOf("/") > 0) ? catId.substring(catId.lastIndexOf("/") + 1) : catId);
question.setCategoryPath(catId);
question.setRelations(new String[] {""});
questionForm.isModerate = questionForm.getFAQService().isModerateQuestion(catId);
} else { // Edit question
isNew = false ;
String questionPath = question.getPath();
String categorySubPath = questionPath.substring(0, questionPath.indexOf("/" + org.exoplatform.faq.service.Utils.QUESTION_HOME));
questionForm.isModerate = questionForm.getFAQService().isModerateQuestion(categorySubPath);
}
question.setApproved(!questionForm.isModerate || (questionForm.isMode && isNew)) ;
if(questionForm.isAddCheckBox){
question.setApproved(questionForm.getUICheckBoxInput(IS_APPROVED).isChecked()) ;
question.setActivated(questionForm.getUICheckBoxInput(IS_ACTIVATED).isChecked()) ;
}
question.setLanguage(questionForm.getDefaultLanguage());
question.setAuthor(author);
question.setEmail(emailAddress);
if (language.equals(questionForm.defaultLanguage_)) {
question.setQuestion(questionContent);
question.setDetail(questionDetail);
} else {
question.setQuestion(questionForm.mapLanguage.get(questionForm.getDefaultLanguage()).getQuestion());
question.setDetail(questionForm.mapLanguage.get(questionForm.getDefaultLanguage()).getDetail());
QuestionLanguage otherLang = new QuestionLanguage();
if (questionForm.mapLanguage.containsKey(language)) {
otherLang = questionForm.mapLanguage.get(language);
otherLang.setState(QuestionLanguage.EDIT);
}
otherLang.setQuestion(questionContent);
otherLang.setDetail(questionDetail);
otherLang.setLanguage(language);
questionForm.mapLanguage.put(language, otherLang);
}
questionForm.mapLanguage.remove(question.getLanguage());
question.setMultiLanguages(questionForm.mapLanguage.values().toArray(new QuestionLanguage[] {}));
question.setAttachMent(questionForm.listFileAttach_);
UIAnswersPortlet portlet = questionForm.getAncestorOfType(UIAnswersPortlet.class);
UIQuestions questions = portlet.getChild(UIAnswersContainer.class).getChild(UIQuestions.class);
//
question.setLink(FAQUtils.getQuestionURL(question.getId(), false));
// For discuss in forum
try {
FAQUtils.getEmailSetting(questionForm.faqSetting_, isNew, !isNew);
FAQSetting faqSetting = new FAQSetting();
FAQUtils.getPorletPreference(faqSetting);
if (faqSetting.getIsDiscussForum()) {
String topicId = question.getTopicIdDiscuss();
if (topicId != null && topicId.length() > 0) {
try {
ForumService forumService = (ForumService) PortalContainer.getInstance().getComponentInstanceOfType(ForumService.class);
Topic topic = (Topic) forumService.getObjectNameById(topicId, Utils.TOPIC);
if (topic != null) {
String[] ids = topic.getPath().split("/");
int t = ids.length;
topic.setModifiedBy(FAQUtils.getCurrentUser());
topic.setTopicName(question.getQuestion());
topic.setDescription(question.getDetail());
topic.setIsApproved(!forumService.getForum(ids[t - 3], ids[t - 2]).getIsModerateTopic());
forumService.saveTopic(ids[t - 3], ids[t - 2], topic, false, false, new MessageBuilder());
}
} catch (Exception e) {
questionForm.log.debug("Failed to get topic discussion.", e);
}
}
}
// end discuss
if (questionForm.getFAQService().saveQuestion(question, isNew, questionForm.faqSetting_) == null) {
warning("UIQuestions.msg.question-deleted", false);
portlet.cancelAction();
return;
}
} catch (Exception e) {
questionForm.log.error("Can not run discuss question in to forum portlet", false);
}
if(question.isApproved()) {
if(isNew) info("UIQuestionForm.msg.add-new-question-successful", false) ;
} else {
info("UIQuestionForm.msg.question-not-is-approved", false) ;
}
if (!questionForm.isChildOfManager) {
portlet.cancelAction();
} else {
UIQuestionManagerForm questionManagerForm = questionForm.getParent();
UIResponseForm responseForm = questionManagerForm.getChild(UIResponseForm.class);
if (questionManagerForm.isResponseQuestion && questionForm.getQuestionId().equals(responseForm.questionId_)) {
responseForm.updateChildOfQuestionManager(true);
responseForm.setModertator(true);
responseForm.setQuestionId(question, "", !questionForm.getFAQService().isModerateAnswer(question.getPath()));
}
questionManagerForm.isEditQuestion = false;
UIPopupContainer popupContainer = questionManagerForm.getParent();
event.getRequestContext().addUIComponentToUpdateByAjax(popupContainer);
}
// update question list in question container.
questions.setDefaultLanguage();
questions.updateCurrentQuestionList();
if (!isNew && question.getPath().equals(questions.viewingQuestionId_)) {
questions.updateLanguageMap();
}
event.getRequestContext().addUIComponentToUpdateByAjax(questions.getAncestorOfType(UIAnswersPortlet.class));
} catch (Exception e) {
questionForm.log.debug("Failed to save action creating question.", e);
}
}
}
static public class AttachmentActionListener extends EventListener<UIQuestionForm> {
public void execute(Event<UIQuestionForm> event) throws Exception {
UIQuestionForm questionForm = event.getSource();
UIPopupContainer popupContainer = questionForm.getAncestorOfType(UIPopupContainer.class);
UIAttachmentForm attachMentForm = questionForm.openPopup(popupContainer, UIAttachmentForm.class, 550, 0);
attachMentForm.setIsChangeAvatar(false);
attachMentForm.setNumberUpload(5);
}
}
static public class RemoveAttachmentActionListener extends BaseEventListener<UIQuestionForm> {
public void onEvent(Event<UIQuestionForm> event, UIQuestionForm questionForm, String attFileId) throws Exception {
for (FileAttachment att : questionForm.listFileAttach_) {
if (att.getId() != null) {
if (att.getId().equals(attFileId)) {
questionForm.listFileAttach_.remove(att);
break;
}
} else {
if (att.getPath().equals(attFileId)) {
questionForm.listFileAttach_.remove(att);
break;
}
}
}
questionForm.refreshUploadFileList();
event.getRequestContext().addUIComponentToUpdateByAjax(questionForm);
}
}
static public class CancelActionListener extends EventListener<UIQuestionForm> {
public void execute(Event<UIQuestionForm> event) throws Exception {
UIQuestionForm questionForm = event.getSource();
if (!questionForm.isChildOfManager) {
UIAnswersPortlet portlet = questionForm.getAncestorOfType(UIAnswersPortlet.class);
UIPopupAction popupAction = portlet.getChild(UIPopupAction.class);
popupAction.deActivate();
event.getRequestContext().addUIComponentToUpdateByAjax(popupAction);
} else {
UIQuestionManagerForm questionManagerForm = questionForm.getParent();
questionManagerForm.isEditQuestion = false;
UIPopupContainer popupContainer = questionManagerForm.getAncestorOfType(UIPopupContainer.class);
UIPopupAction popupAction = popupContainer.getChild(UIPopupAction.class);
if (popupAction != null) {
popupAction.deActivate();
}
event.getRequestContext().addUIComponentToUpdateByAjax(questionManagerForm);
}
}
}
public Question getQuestion() {
return question_;
}
}
|
lgpl-3.0
|
Toilal/bitlet
|
src/main/java/org/bitlet/wetorrent/peer/task/StartConnection.java
|
2730
|
/*
* bitlet - Simple bittorrent library
*
* Copyright (C) 2008 Alessandro Bahgat Shehata, Daniele Castagna
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Alessandro Bahgat Shehata - ale dot bahgat at gmail dot com
* Daniele Castagna - daniele dot castagna at gmail dot com
*
*/
package org.bitlet.wetorrent.peer.task;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.logging.Level;
import org.bitlet.wetorrent.Event;
import org.bitlet.wetorrent.Torrent;
import org.bitlet.wetorrent.peer.TorrentPeer;
import org.bitlet.wetorrent.util.thread.ThreadTask;
public class StartConnection implements ThreadTask {
boolean interrupted = false;
private TorrentPeer peer;
public StartConnection(TorrentPeer peer) {
this.peer = peer;
}
public boolean execute() throws Exception {
Socket socket = connect(peer.getIp(), peer.getPort());
peer.setSocket(socket);
if (socket != null) {
if (Torrent.verbose) {
peer.getPeersManager().getTorrent().addEvent(new Event(this, "Connected to " + peer.getIp(), Level.FINE));
}
} else {
throw new Exception("Problem connecting to " + peer.getIp());
}
return false;
}
public void interrupt() {
interrupted = true;
}
public synchronized boolean isInterrupted() {
return interrupted;
}
public synchronized Socket connect(InetAddress address, int port) throws Exception {
if (!interrupted) {
return new Socket(address, port);
} else {
throw new Exception("Interrupted before connecting");
}
}
public void exceptionCought(Exception e) {
if (e instanceof ConnectException) {
if (Torrent.verbose) {
peer.getPeersManager().getTorrent().addEvent(new Event(this, "Connection refused: " + peer.getIp(), Level.FINE));
}
}
peer.interrupt();
}
}
|
lgpl-3.0
|
simeshev/parabuild-ci
|
3rdparty/hibernate218/src/net/sf/hibernate/mapping/Bag.java
|
557
|
//$Id: Bag.java,v 1.10 2004/06/04 01:27:42 steveebersole Exp $
package net.sf.hibernate.mapping;
import net.sf.hibernate.type.PersistentCollectionType;
import net.sf.hibernate.type.TypeFactory;
/**
* A bag permits duplicates, so it has no primary key
* @author Gavin King
*/
public class Bag extends Collection {
public Bag(PersistentClass owner) {
super(owner);
}
public PersistentCollectionType getCollectionType() {
return TypeFactory.bag( getRole() );
}
void createPrimaryKey() {
//create an index on the key columns??
}
}
|
lgpl-3.0
|
Bjorn-Nilsson/SqlObject
|
lib/sql_object/template_file_dir.rb
|
1725
|
module SqlObject
class TemplateFileDir
attr_reader :path, :search_path
class << self
def all_in_path(*paths)
paths.map{| path | new(path) }
end
def all_template_files(*paths)
all_in_path(paths).map {| template_file_dir | template_file_dir.template_files }.flatten
end
def all_sql_objects(*paths)
all_template_files(paths).map do |template_file|
#Template.new(template_file.object_name_from_path, template_file.read)
""
end
end
end
def initialize(path)
@path = path
@search_path = base_path.join(*path)
raise "Missing directory: #{@search_path.dirname}" unless @search_path.dirname.exist?
end
def template_file_paths
Pathname.glob(@search_path.join("*" + TemplateFile::EXTENSION))
end
def template_files
template_file_paths.map do |path|
TemplateFile.new(path)
end
end
def find_best_match(base_path, file_candidates)
# file_candidates = ["default"] + file_candidates
file_candidates.reverse_each do | file_name |
file_name << TemplateFile::EXTENSION
rel_path = Pathname.new(base_path).join(file_name)
full_file_path = @search_path.join(rel_path)
#puts "path: #{full_file_path}"
return rel_path if File.exists? full_file_path
end
puts "found none"
nil
end
def template_file(sql_object_name)
TemplateFile.new(@search_path.join(sql_object_name))
end
def template_partial_file(sql_object_name)
TemplateFile.new(@search_path.join('partials/',('_' + sql_object_name)))
end
def base_path
SqlObject.templates_path
end
end
end
|
lgpl-3.0
|
AznStyle/lwb2
|
core/lib/Thelia/Core/Security/Token/TokenProvider.php
|
1519
|
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Core\Security\Token;
use Thelia\Core\Security\User\UserInterface;
class TokenProvider
{
public function encodeKey(UserInterface $user)
{
// Always set a new token in the user environment
$user->setToken(uniqid());
return base64_encode(serialize(
array($user->getUsername(), $user->getToken(), $user->getSerial())));
}
public function decodeKey($key)
{
$data = unserialize(base64_decode($key));
return array(
'username' => $data[0],
'token' => $data[1],
'serial' => $data[2]
);
}
}
|
lgpl-3.0
|
CFDEMproject/ParScale-PUBLIC
|
thirdParty/chemkinReader/src/transportParser.cpp
|
2347
|
/*
* transportParser.cpp
*
* Created on: Jun 23, 2011
* Author: gigadot
* License: Apache 2.0
*/
#include "transportParser.h"
#include "stringFunctions.h"
#include "species.h"
using namespace std;
using namespace boost;
const string IO::TransportParser::transportRegex
(
"\\s+([0-2]+?)\\s+"
"((?:[0-9]|\\.)+(?:\\.[0-9]*)?)\\s+"
"((?:[0-9]|\\.)+(?:\\.[0-9]*)?)\\s+"
"((?:[0-9]|\\.)+(?:\\.[0-9]*)?)\\s+"
"((?:[0-9]|\\.)+(?:\\.[0-9]*)?)\\s+"
"((?:[0-9]|\\.)+(?:\\.[0-9]*)?)"
);
// Empty default constructor, can be removed but leave it there just in case.
IO::TransportParser::TransportParser
(
const string tranfile
)
:
tranfile_(tranfile),
transportfilestring_(convertToCaps(fileToString(tranfile)))
{}
void IO::TransportParser::parse(vector<Species>& species)
{
cout << "Parsing Transport file: " << tranfile_ << endl;
for (size_t i = 0; i != species.size(); ++i)
{
smatch specieTransportData = findSpecies(species[i]);
setSpecieData(species[i], specieTransportData);
}
cout << "End of Transport file: " << tranfile_ << endl;
cout << " " << endl;
}
const smatch IO::TransportParser::findSpecies(const IO::Species& specie)
{
smatch what;
regex reg("\\b"+IO::regex_escape(specie.name())+transportRegex);
string::const_iterator start = transportfilestring_.begin();
string::const_iterator end = transportfilestring_.end();
if(!regex_search(start, end, what, reg))
{
throw regex_error
(
"Species " + specie.name() + " not found in tran.dat. using "
"\\b"+IO::regex_escape(specie.name())+transportRegex
);
}
return what;
}
void IO::TransportParser::setSpecieData
(
IO::Species& specie,
const smatch& specieTransportData
)
{
specie.transport().setMoleculeIndex(from_string<int>(specieTransportData[1]));
specie.transport().setPotentialWellDepth(from_string<double>(specieTransportData[2]));
specie.transport().setCollisionDiameter(from_string<double>(specieTransportData[3]));
specie.transport().setDipoleMoment(from_string<double>(specieTransportData[4]));
specie.transport().setPolarizability(from_string<double>(specieTransportData[5]));
specie.transport().setRotRelaxationNumber(from_string<double>(specieTransportData[6]));
}
|
lgpl-3.0
|
EIP-SAM/SAM-Solution-Node-js
|
libs/sequelizeSession.js
|
392
|
const sequelize = require('./sequelize');
const session = require('express-session');
const Store = require('connect-session-sequelize')(session.Store);
module.exports = function initSequelizeSession(app, conf) {
const store = new Store({ db: sequelize });
app.use(session({
secret: conf.secret,
store,
resave: false,
saveUninitialized: true,
}));
store.sync();
};
|
lgpl-3.0
|
rpau/walkmod-javalang-plugin
|
src/test/java/org/walkmod/javalang/walkers/DefaultJavaWalkerTest.java
|
9828
|
package org.walkmod.javalang.walkers;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.junit.Assert;
import org.junit.Test;
import org.walkmod.conf.entities.TransformationConfig;
import org.walkmod.conf.entities.impl.ChainConfigImpl;
import org.walkmod.conf.entities.impl.TransformationConfigImpl;
import org.walkmod.conf.entities.impl.WalkerConfigImpl;
import org.walkmod.javalang.ast.CompilationUnit;
import org.walkmod.javalang.compiler.symbols.RequiresSemanticAnalysis;
import org.walkmod.javalang.visitors.VoidVisitorAdapter;
import org.walkmod.walkers.VisitorContext;
public class DefaultJavaWalkerTest {
@Test
public void when_compilationunit_is_under_a_reader_path_then_subfolder_can_be_resolved() throws Exception {
DefaultJavaWalker walker = new DefaultJavaWalker(){
@Override
protected String getReaderPath() {
return "src/test/resources/test1";
}
};
File sampleDir = initFolder("src/test/resources/test1/subfolder");
File fooClass = createJavaFile("Foo", sampleDir);
walker.resolveSourceSubdirs(fooClass, new DefaultJavaParser().parse(fooClass));
Assert.assertEquals("subfolder"+File.separator, walker.getSourceSubdirectories());
}
@Test(expected = InvalidSourceDirectoryException.class)
public void when_compilationunit_contains_invalid_package_then_exception_is_thrown() throws Exception {
DefaultJavaWalker walker = new DefaultJavaWalker(){
@Override
protected String getReaderPath() {
return ".";
}
};
File sampleDir = new File(".");
File fooClass = createInvalidJavaFile("Foo", sampleDir);
walker.resolveSourceSubdirs(fooClass, new DefaultJavaParser().parse(fooClass));
fooClass.delete();
walker.getSourceSubdirectories();
}
@Test
public void when_compilationunit_is_in_root_dir_then_subfolder_is_empty() throws Exception {
DefaultJavaWalker walker = new DefaultJavaWalker(){
@Override
protected String getReaderPath() {
return ".";
}
};
File sampleDir = new File(".");
File fooClass = createJavaFile("Foo", sampleDir);
walker.resolveSourceSubdirs(fooClass, new DefaultJavaParser().parse(fooClass));
fooClass.delete();
Assert.assertEquals("", walker.getSourceSubdirectories());
}
@Test
public void when_compilationunit_is_under_a_subfolder_of_root_dir_then_subfolder_is_empty() throws Exception {
DefaultJavaWalker walker = new DefaultJavaWalker(){
@Override
protected String getReaderPath() {
return ".";
}
};
File sampleDir = initFolder("./src/test/resources/test1/subfolder");
File fooClass = createJavaFile("Foo", sampleDir);
walker.resolveSourceSubdirs(fooClass, new DefaultJavaParser().parse(fooClass));
fooClass.delete();
Assert.assertEquals("src/test/resources/test1/subfolder"+File.separator, walker.getSourceSubdirectories());
}
@Test
public void when_there_are_subfolders_then_outputfile_with_same_reader_path_contains_them() throws Exception{
DefaultJavaWalker walker = new DefaultJavaWalker(){
@Override
protected String getReaderPath() {
return "src/test/resources/test1";
}
@Override
protected String getWriterPath() {
return "src/test/resources/test1";
}
};
File sampleDir = initFolder("src/test/resources/test1/subfolder");
File fooClass = createJavaFile("Foo", sampleDir);
CompilationUnit cu = new DefaultJavaParser().parse(fooClass);
walker.resolveSourceSubdirs(fooClass, cu);
File file = walker.resolveFile(cu);
Assert.assertEquals(fooClass.getCanonicalPath(), file.getPath());
}
@Test
public void when_there_are_subfolders_then_outputfile_with_different_reader_path_contains_them() throws Exception{
DefaultJavaWalker walker = new DefaultJavaWalker(){
@Override
protected String getReaderPath() {
return "src/test/resources/test1";
}
@Override
protected String getWriterPath() {
return "src/test/resources/test2";
}
};
File sampleDir = initFolder("src/test/resources/test1/subfolder");
File sampleDir2 = initFolder("src/test/resources/test2");
File fooClass = createJavaFile("Foo", sampleDir);
CompilationUnit cu = new DefaultJavaParser().parse(fooClass);
walker.resolveSourceSubdirs(fooClass, cu);
File file = walker.resolveFile(cu);
Assert.assertEquals(new File(new File(sampleDir2, "subfolder"), "Foo.java").getCanonicalPath(), file.getPath());
}
private File initFolder(String folder) throws IOException {
File sampleDir = new File(folder);
if (sampleDir.exists()) {
FileUtils.deleteDirectory(sampleDir);
}
sampleDir.mkdirs();
return sampleDir;
}
private File createJavaFile(String name, File sampleDir) throws IOException {
File fooClass = new File(sampleDir, name + ".java");
fooClass.createNewFile();
FileUtils.write(fooClass, "public class " + name + " {}");
return fooClass;
}
private File createInvalidJavaFile(String name, File sampleDir) throws IOException {
File fooClass = new File(sampleDir, name + ".java");
fooClass.createNewFile();
FileUtils.write(fooClass, "package B; public class " + name + " {}");
return fooClass;
}
@Test
public void testExceptionsMustDefineTheAffectedSourceFile() throws Exception {
DefaultJavaWalker walker = new DefaultJavaWalker(){
@Override
protected String getReaderPath() {
return "src/test/resources/test1";
}
@Override
protected String getWriterPath() {
return "src/test/resources/test2";
}
};
File sampleDir = initFolder("src/test/resources/test1");
File fooClass= createJavaFile("Foo", sampleDir);
List<Object> visitors = new LinkedList<Object>();
VisitorWithException instance = new VisitorWithException();
visitors.add(instance);
walker.setVisitors(visitors);
walker.setParser(new DefaultJavaParser());
ChainConfigImpl cfg = new ChainConfigImpl();
WalkerConfigImpl walkerCfg = new WalkerConfigImpl();
List<TransformationConfig> transformations = new LinkedList<TransformationConfig>();
TransformationConfigImpl tcfg = new TransformationConfigImpl();
tcfg.setVisitorInstance(instance);
transformations.add(tcfg);
walkerCfg.setTransformations(transformations);
cfg.setWalkerConfig(walkerCfg);
walker.setChainConfig(cfg);
try {
walker.accept(fooClass);
} catch (Exception e) {
String message = e.getMessage();
Assert.assertTrue(message.contains("Error processing [" + fooClass.getCanonicalPath() + "]"));
} finally {
fooClass.delete();
FileUtils.deleteDirectory(sampleDir);
}
}
@Test
public void testExceptionsOnAnalysisSemantic() throws Exception {
DefaultJavaWalker walker = new DefaultJavaWalker(){
@Override
protected String getReaderPath() {
return "src/test/resources/test1";
}
@Override
protected String getWriterPath() {
return "src/test/resources/test2";
}
};
File sampleDir = initFolder("src/test/resources/test1");
File fooClass = createJavaFile("Foo", sampleDir);
FileUtils.write(fooClass, "import bar.InvalidClass; public class Foo {}");
List<Object> visitors = new LinkedList<Object>();
EmptySemanticVisitor instance = new EmptySemanticVisitor();
visitors.add(instance);
walker.setVisitors(visitors);
walker.setParser(new DefaultJavaParser());
walker.setClassLoader(this.getClass().getClassLoader());
ChainConfigImpl cfg = new ChainConfigImpl();
WalkerConfigImpl walkerCfg = new WalkerConfigImpl();
List<TransformationConfig> transformations = new LinkedList<TransformationConfig>();
TransformationConfigImpl tcfg = new TransformationConfigImpl();
tcfg.setVisitorInstance(instance);
transformations.add(tcfg);
walkerCfg.setTransformations(transformations);
cfg.setWalkerConfig(walkerCfg);
walker.setChainConfig(cfg);
try {
walker.accept(fooClass);
} catch (Exception e) {
String message = e.getMessage();
Assert.assertTrue(message.contains("Error processing the analysis of [Foo]"));
} finally {
fooClass.delete();
FileUtils.deleteDirectory(sampleDir);
}
}
public class VisitorWithException extends VoidVisitorAdapter<VisitorContext> {
@Override
public void visit(CompilationUnit cu, VisitorContext vc) {
throw new RuntimeException("Hello");
}
}
@RequiresSemanticAnalysis
public class EmptySemanticVisitor extends VoidVisitorAdapter<VisitorContext> {
}
}
|
lgpl-3.0
|
ProjectMi5/CloudLink
|
Gruntfile.js
|
826
|
/**
* Created by Thomas on 01.06.2015.
*/
// Gruntfile.js
module.exports = function(grunt) {
// Add the grunt-mocha-test tasks.
grunt.loadNpmTasks('grunt-mocha-test');
grunt.initConfig({
// Configure a mochaTest task
mochaTest: {
test: {
options: {
reporter: 'spec',
//captureFile: 'grunt-tests-results.txt', // Optionally capture the reporter output to a file
quiet: false, // Optionally suppress output to standard out (defaults to false)
clearRequireCache: false // Optionally clear the require cache before running tests (defaults to false)
},
src: ['test/**/*.js']
}
}
});
grunt.registerTask('default', 'mochaTest');
};
|
lgpl-3.0
|
OpenCorrelate/red5load
|
mess/red5/src/org/red5/server/adapter/StatefulScopeWrappingAdapter.java
|
6577
|
package org.red5.server.adapter;
/*
* RED5 Open Source Flash Server - http://www.osflash.org/red5
*
* Copyright (c) 2006-2009 by respective authors (see below). 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.
*
* You should have received a copy of the GNU Lesser General Public License along
* with this library; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.red5.server.api.IAttributeStore;
import org.red5.server.api.IClient;
import org.red5.server.api.IConnection;
import org.red5.server.api.IContext;
import org.red5.server.api.IScope;
import org.red5.server.api.IScopeAware;
import org.red5.server.plugin.PluginDescriptor;
import org.springframework.core.io.Resource;
/**
* StatefulScopeWrappingAdapter class wraps stateful IScope functionality. That
* is, it has attributes that you can work with, subscopes, associated resources
* and connections.
*
*/
public class StatefulScopeWrappingAdapter extends AbstractScopeAdapter implements IScopeAware, IAttributeStore {
/**
* Wrapped scope
*/
protected IScope scope;
/**
* List of plug-in descriptors
*/
protected List<PluginDescriptor> plugins;
/** {@inheritDoc} */
public void setScope(IScope scope) {
this.scope = scope;
}
/**
* Getter for wrapped scope
*
* @return Wrapped scope
*/
public IScope getScope() {
return scope;
}
/**
* Returns any plug-ins descriptors added
*
* @return plug-in descriptor list
*/
public List<PluginDescriptor> getPlugins() {
return plugins;
}
/**
* Adds a list of plug-in descriptors
*
* @param plugins
*/
public void setPlugins(List<PluginDescriptor> plugins) {
this.plugins = plugins;
}
/** {@inheritDoc} */
public Object getAttribute(String name) {
return scope.getAttribute(name);
}
/** {@inheritDoc} */
public Object getAttribute(String name, Object defaultValue) {
return scope.getAttribute(name, defaultValue);
}
/** {@inheritDoc} */
public Set<String> getAttributeNames() {
return scope.getAttributeNames();
}
/**
* Wrapper for Scope#getAttributes
* @return Scope attributes map
*/
public Map<String, Object> getAttributes() {
return scope.getAttributes();
}
/** {@inheritDoc} */
public boolean hasAttribute(String name) {
return scope.hasAttribute(name);
}
/** {@inheritDoc} */
public boolean removeAttribute(String name) {
return scope.removeAttribute(name);
}
/** {@inheritDoc} */
public void removeAttributes() {
scope.removeAttributes();
}
/** {@inheritDoc} */
public boolean setAttribute(String name, Object value) {
return scope.setAttribute(name, value);
}
/** {@inheritDoc} */
public void setAttributes(IAttributeStore values) {
scope.setAttributes(values);
}
/** {@inheritDoc} */
public void setAttributes(Map<String, Object> values) {
scope.setAttributes(values);
}
/**
* Creates child scope
* @param name Child scope name
* @return <code>true</code> on success, <code>false</code> otherwise
*/
public boolean createChildScope(String name) {
return scope.createChildScope(name);
}
/**
* Return child scope
* @param name Child scope name
* @return Child scope with given name
*/
public IScope getChildScope(String name) {
return scope.getScope(name);
}
/**
* Iterator for child scope names
*
* @return Iterator for child scope names
*/
public Iterator<String> getChildScopeNames() {
return scope.getScopeNames();
}
/**
* Getter for set of clients
*
* @return Set of clients
*/
public Set<IClient> getClients() {
return scope.getClients();
}
/**
* Returns all connections in the scope
*
* @return Connections
*/
public Collection<Set<IConnection>> getConnections() {
return scope.getConnections();
}
/**
* Getter for context
*
* @return Value for context
*/
public IContext getContext() {
return scope.getContext();
}
/**
* Getter for depth
*
* @return Value for depth
*/
public int getDepth() {
return scope.getDepth();
}
/**
* Getter for name
*
* @return Value for name
*/
public String getName() {
return scope.getName();
}
/**
* Return parent scope
*
* @return Parent scope
*/
public IScope getParent() {
return scope.getParent();
}
/**
* Getter for stateful scope path
*
* @return Value for path
*/
public String getPath() {
return scope.getPath();
}
/**
* Whether this scope has a child scope with given name
* @param name Child scope name
* @return <code>true</code> if it does have it, <code>false</code> otherwise
*/
public boolean hasChildScope(String name) {
return scope.hasChildScope(name);
}
/**
* If this scope has a parent
* @return <code>true</code> if this scope has a parent scope, <code>false</code> otherwise
*/
public boolean hasParent() {
return scope.hasParent();
}
public Set<IConnection> lookupConnections(IClient client) {
return scope.lookupConnections(client);
}
/**
* Returns array of resources (as Spring core Resource class instances)
*
* @param pattern Resource pattern
* @return Returns array of resources
* @throws IOException I/O exception
*/
public Resource[] getResources(String pattern) throws IOException {
return scope.getResources(pattern);
}
/**
* Return resource by name
* @param path Resource name
* @return Resource with given name
*/
public Resource getResource(String path) {
return scope.getResource(path);
}
}
|
lgpl-3.0
|
NeoRazorX/facturascripts
|
Dinamic/Lib/SupplierRiskTools.php
|
230
|
<?php namespace FacturaScripts\Dinamic\Lib;
/**
* Class created by Core/Base/PluginManager
* @author FacturaScripts <carlos@facturascripts.com>
*/
class SupplierRiskTools extends \FacturaScripts\Core\Lib\SupplierRiskTools
{
}
|
lgpl-3.0
|
mdaus/nitro
|
modules/c++/nitf/include/nitf/exports.hpp
|
3293
|
#ifndef NITRO_nitf_exports_hpp_INCLUDED_
#define NITRO_nitf_exports_hpp_INCLUDED_
#pragma once
// Use Windows naming conventions (DLL, LIB) because this really only matters
// for _MSC_VER, see below.
#if !defined(NITRO_NITFCPP_LIB) && !defined(NITRO_NITFCPP_DLL)
// Building a static library (not a DLL) is the default.
#define NITRO_NITFCPP_LIB 1
#endif
#if !defined(NITRO_NITFCPP_DLL)
#if defined(NITRO_NITFCPP_EXPORTS) && defined(NITRO_NITFCPP_LIB)
#error "Can't export from a LIB'"
#endif
#if !defined(NITRO_NITFCPP_LIB)
#define NITRO_NITFCPP_DLL 1
#endif
#endif
// The following ifdef block is the standard way of creating macros which make exporting
// from a DLL simpler. All files within this DLL are compiled with the NITRO_NITFCPP_EXPORTS
// symbol defined on the command line. This symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see
// NITRO_NITFCPP_API functions as being imported from a DLL, whereas this DLL sees symbols
// defined with this macro as being exported.
// https://www.gnu.org/software/gnulib/manual/html_node/Exported-Symbols-of-Shared-Libraries.html
#if NITRO_NITFCPP_EXPORTS
#if defined(__GNUC__) // && HAVE_VISIBILITY
#define NITRO_NITFCPP_API __attribute__((visibility("default")))
#elif defined(_MSC_VER) // && (defined(_WINDLL) && !defined(_LIB))
// Visual Studio projects define _WINDLL or _LIB, but not the compiler
#define NITRO_NITFCPP_API __declspec(dllexport)
#else
// https://stackoverflow.com/a/2164853/8877
#define NITRO_NITFCPP_API /* do nothing and hope for the best? */
#pragma warning Unknown dynamic link export semantics.
#endif
#else
// Either building a static library (no NITRO_NITFCPP_EXPORTS) or
// importing (not building) a shared library.
#if defined(_MSC_VER)
// We need to know whether we're consuming (importing) a DLL or static LIB
// The default is a static LIB as that's what existing code/builds expect.
#ifdef NITRO_NITFCPP_DLL
// Actually, it seems that the linker is able to figure this out from the .LIB, so
// there doesn't seem to be a need for __declspec(dllimport). Clients don't
// need to #define NITRO_NITFCPP_DLL ... ? Well, almost ... it looks
// like __declspec(dllimport) is needed to get virtual "inline"s (e.g.,
// destructors) correct.
#define NITRO_NITFCPP_API __declspec(dllimport)
#else
#define NITRO_NITFCPP_API /* "importing" a static LIB */
#endif
#elif defined(__GNUC__)
// For GCC, there's no difference in consuming ("importing") an .a or .so
#define NITRO_NITFCPP_API /* no __declspec(dllimport) for GCC */
#else
// https://stackoverflow.com/a/2164853/8877
#define NITRO_NITFCPP_API /* do nothing and hope for the best? */
#pragma warning Unknown dynamic link import semantics.
#endif
#endif
#if defined(_MSC_VER) && defined(NITRO_NITFCPP_DLL)
#pragma warning(disable: 4251) // '...' : class '...' needs to have dll-interface to be used by clients of struct '...'
#endif
#endif // NITRO_nitf_exports_hpp_INCLUDED_
|
lgpl-3.0
|
rmarting/java-samples
|
webservice-sample/src/main/java/com/redhat/samples/ws/request/SimpleType.java
|
1330
|
package com.redhat.samples.ws.request;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>
* Java class for PlaceOrderType complex type.
*
* <p>
* The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="SimpleType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="in" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SimpleType", propOrder = { "in" })
public class SimpleType {
@XmlElement(required = true)
protected String in;
/**
* Gets the value of the in property.
*
* @return possible object is {@link String }
*
*/
public String getIn() {
return this.in;
}
/**
* Sets the value of the in property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setIn(String value) {
this.in = value;
}
}
|
unlicense
|
r-lyeh/scriptorium
|
angelscript/sdk/docs/manual/functions_func.js
|
724
|
var functions_func =
[
[ "a", "functions_func.html", null ],
[ "b", "functions_func_0x62.html", null ],
[ "c", "functions_func_0x63.html", null ],
[ "d", "functions_func_0x64.html", null ],
[ "e", "functions_func_0x65.html", null ],
[ "f", "functions_func_0x66.html", null ],
[ "g", "functions_func_0x67.html", null ],
[ "i", "functions_func_0x69.html", null ],
[ "l", "functions_func_0x6c.html", null ],
[ "n", "functions_func_0x6e.html", null ],
[ "p", "functions_func_0x70.html", null ],
[ "r", "functions_func_0x72.html", null ],
[ "s", "functions_func_0x73.html", null ],
[ "u", "functions_func_0x75.html", null ],
[ "w", "functions_func_0x77.html", null ]
];
|
unlicense
|
TheDenys/.NET
|
Lucene.Net/test/core/Support/TestLRUCache.cs
|
1645
|
/*
*
* 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.
*
*/
using NUnit.Framework;
namespace Lucene.Net.Support
{
[TestFixture]
public class TestLRUCache
{
[Test]
public void Test()
{
Lucene.Net.Util.Cache.SimpleLRUCache<string, string> cache = new Lucene.Net.Util.Cache.SimpleLRUCache<string, string>(3);
cache.Put("a", "a");
cache.Put("b", "b");
cache.Put("c", "c");
Assert.IsNotNull(cache.Get("a"));
Assert.IsNotNull(cache.Get("b"));
Assert.IsNotNull(cache.Get("c"));
cache.Put("d", "d");
Assert.IsNull(cache.Get("a"));
Assert.IsNotNull(cache.Get("c"));
cache.Put("e", "e");
cache.Put("f", "f");
Assert.IsNotNull(cache.Get("c"));
}
}
}
|
unlicense
|
tlgs/dailyprogrammer
|
JavaScript/easy/e036.js
|
401
|
/* 12/04/2016 */
var numLockers = 1000;
var lockers = [];
for(var i=0; i <= numLockers; i++)
lockers.push(false);
for(i=1; i <= numLockers; i++)
for(var j=1; j <= numLockers; j++)
if(!(j%i))
lockers[j] = !lockers[j];
console.log("Number of open lockers: " + lockers.reduce((total, a) => a ? total + a : total, 0));
for(i=1; i <= numLockers; i++)
if(lockers[i])
console.log(i);
|
unlicense
|
fathi-hindi/oneplace
|
vendor/magento/module-sales-rule/Model/Plugin/ResourceModel/Rule.php
|
1306
|
<?php
/**
* Copyright © 2013-2017 Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\SalesRule\Model\Plugin\ResourceModel;
/**
* Class Rule
* @package Magento\SalesRule\Model\Plugin\ResourceModel
* @deprecated
*/
class Rule
{
/**
* @param \Magento\SalesRule\Model\ResourceModel\Rule $subject
* @param \Closure $proceed
* @param \Magento\Framework\Model\AbstractModel $object
* @return \Magento\Framework\Model\AbstractModel
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function aroundLoadCustomerGroupIds(
\Magento\SalesRule\Model\ResourceModel\Rule $subject,
\Closure $proceed,
\Magento\Framework\Model\AbstractModel $object
) {
return $subject;
}
/**
* @param \Magento\SalesRule\Model\ResourceModel\Rule $subject
* @param \Closure $proceed
* @param \Magento\Framework\Model\AbstractModel $object
* @return \Magento\Framework\Model\AbstractModel
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function aroundLoadWebsiteIds(
\Magento\SalesRule\Model\ResourceModel\Rule $subject,
\Closure $proceed,
\Magento\Framework\Model\AbstractModel $object
) {
return $subject;
}
}
|
unlicense
|
naconner/lamassu-server
|
lib/new-admin/services/funding.js
|
2882
|
const _ = require('lodash/fp')
const BN = require('../../bn')
const settingsLoader = require('../../new-settings-loader')
const configManager = require('../../new-config-manager')
const wallet = require('../../wallet')
const ticker = require('../../ticker')
const { utils: coinUtils } = require('lamassu-coins')
function computeCrypto (cryptoCode, _balance) {
const cryptoRec = coinUtils.getCryptoCurrency(cryptoCode)
const unitScale = cryptoRec.unitScale
return new BN(_balance).shiftedBy(-unitScale).decimalPlaces(5)
}
function computeFiat (rate, cryptoCode, _balance) {
const cryptoRec = coinUtils.getCryptoCurrency(cryptoCode)
const unitScale = cryptoRec.unitScale
return new BN(_balance).shiftedBy(-unitScale).times(rate).decimalPlaces(5)
}
function getSingleCoinFunding (settings, fiatCode, cryptoCode) {
const promises = [
wallet.newFunding(settings, cryptoCode),
ticker.getRates(settings, fiatCode, cryptoCode)
]
return Promise.all(promises)
.then(([fundingRec, ratesRec]) => {
const rates = ratesRec.rates
const rate = (rates.ask.plus(rates.bid)).div(2)
const fundingConfirmedBalance = fundingRec.fundingConfirmedBalance
const fiatConfirmedBalance = computeFiat(rate, cryptoCode, fundingConfirmedBalance)
const pending = fundingRec.fundingPendingBalance
const fiatPending = computeFiat(rate, cryptoCode, pending)
const fundingAddress = fundingRec.fundingAddress
const fundingAddressUrl = coinUtils.buildUrl(cryptoCode, fundingAddress)
return {
cryptoCode,
fundingAddress,
fundingAddressUrl,
confirmedBalance: computeCrypto(cryptoCode, fundingConfirmedBalance).toFormat(5),
pending: computeCrypto(cryptoCode, pending).toFormat(5),
fiatConfirmedBalance: fiatConfirmedBalance,
fiatPending: fiatPending,
fiatCode
}
})
}
// Promise.allSettled not running on current version of node
const reflect = p => p.then(value => ({ value, status: 'fulfilled' }), error => ({ error: error.toString(), status: 'rejected' }))
function getFunding () {
return settingsLoader.loadLatest().then(settings => {
const cryptoCodes = configManager.getAllCryptoCurrencies(settings.config)
const fiatCode = configManager.getGlobalLocale(settings.config).fiatCurrency
const pareCoins = c => _.includes(c.cryptoCode, cryptoCodes)
const cryptoCurrencies = coinUtils.cryptoCurrencies()
const cryptoDisplays = _.filter(pareCoins, cryptoCurrencies)
const promises = cryptoDisplays.map(it => getSingleCoinFunding(settings, fiatCode, it.cryptoCode))
return Promise.all(promises.map(reflect))
.then((response) => {
const mapped = response.map(it => _.merge({ errorMsg: it.error }, it.value))
return _.toArray(_.merge(mapped, cryptoDisplays))
})
})
}
module.exports = { getFunding }
|
unlicense
|
fathi-hindi/oneplace
|
vendor/magento/module-require-js/registration.php
|
276
|
<?php
/**
* Copyright © 2013-2017 Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Magento_RequireJs',
__DIR__
);
|
unlicense
|
botja/tarabica-wp75
|
Tarabica.Model/Domain/Twitter/Tweet.cs
|
622
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Tarabica.Model.Domain.Twitter
{
public class Tweet
{
public Int64 Id { get; set; }
public User User { get; set; }
public string Text { get; set; }
public DateTime Time { get; set; }
public string Since { get; set; }
public List<string> Urls { get; set; }
public override string ToString()
{
return String.Format("[{0}] @{1}: {2} ", LocalizedDateHelper.GetDateTimeForCulture(Time, "sr-Latn-CS"), User.ScreenName, Text);
}
}
}
|
unlicense
|
codeApeFromChina/resource
|
frame_packages/java_libs/hibernate-distribution-3.6.10.Final/project/hibernate-jbosscache/src/main/java/org/hibernate/cache/jbc2/JndiMultiplexedJBossCacheRegionFactory.java
|
1929
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2009, Red Hat, Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat, Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.cache.jbc2;
import java.util.Properties;
/**
* Deprecated version of superclass maintained solely for forwards
* compatibility.
*
* @deprecated use {@link org.hibernate.cache.jbc.JndiMultiplexedJBossCacheRegionFactory}
*
* @author Brian Stansberry
* @version $Revision$
*/
@Deprecated
public class JndiMultiplexedJBossCacheRegionFactory extends org.hibernate.cache.jbc.JndiMultiplexedJBossCacheRegionFactory {
/**
* FIXME Per the RegionFactory class Javadoc, this constructor version
* should not be necessary.
*
* @param props The configuration properties
*/
public JndiMultiplexedJBossCacheRegionFactory(Properties props) {
super(props);
}
/**
* Create a new MultiplexedJBossCacheRegionFactory.
*
*/
public JndiMultiplexedJBossCacheRegionFactory() {
super();
}
}
|
unlicense
|
geotrellis/geotrellis-osm-elevation
|
viewer/components/DiffLayers.js
|
5704
|
"use strict";
import React from 'react';
import _ from 'lodash';
import { PanelGroup, Panel, Input, Button, ButtonGroup } from 'react-bootstrap';
import ifAllDefined from '../utils/utils.js';
function updateInterLayerDiffMap (showLayerWithBreaks, showMaxState, hideMaxState, showMaxAverageState, hideMaxAverageState, root, layer1, layer2, t1, t2, showingMaxState, showingMaxAverageState) {
let time1 = layer1.times[t1];
let time2 = layer2.times[t2];
// Showing second layer as a stand-in for now
showLayerWithBreaks(
`${root}/layerdiff/${layer1.name}/${layer2.name}/{z}/{x}/{y}?time1=${time1}&time2=${time2}`,
`${root}/layerdiff/breaks/${layer1.name}/${layer2.name}?time1=${time1}&time2=${time2}`
);
if(showingMaxState) {
showMaxState(`${root}/maxstate/${layer1.name}/${layer2.name}?time1=${time1}&time2=${time2}`);
} else {
hideMaxState();
}
if(showingMaxAverageState) {
showMaxAverageState(`${root}/maxaveragestate/${layer1.name}/${layer2.name}?time1=${time1}&time2=${time2}`);
} else {
hideMaxState();
}
// showLayerWithBreaks(
// `${root}/layer-diff/${layer1.name}/{z}/{x}/{y}?layer2={$layer2.name}&time1=${time1}&time2=${time2}`,
// `${root}/layer-diff/breaks/${layer1.name}?layer2={$layer2.name}&time1=${time1}&time2=${time2}`
// );
};
var MapViews = React.createClass({
getInitialState: function () {
return {
layerId1: 1,
layerId1time: 0,
layerId2: 0,
layerId2time: 0,
showingMaxState: false,
showingMaxAverageState: false,
times: {}
};
},
handleLayerSelect: function(ev, target) {
let layerId = +ev.target.value;
let newState = _.merge({}, this.state, {
[target]: layerId,
[target + "time"]: _.get(this.state.times[layerId], target + "time", undefined),
"times": { // Saves time selection when switching layer
[this.state.layerId]: {
[target + "time"]: this.state[target + "time"]
}
}
});
this.setState(newState);
this.updateMap(newState);
this.props.showExtent(this.props.layers[layerId].extent);
},
handleShowMaxStateChecked: function(e) {
let v = e.target.checked || false;
let newState = _.merge({}, this.state, {showingMaxState: v});
this.setState(newState);
this.updateMap(newState);
},
handleShowMaxAverageStateChecked: function(e) {
let v = e.target.checked || false;
let newState = _.merge({}, this.state, {showingMaxAverageState: v});
this.setState(newState);
this.updateMap(newState);
},
updateState: function(target, value) {
let newState = _.merge({}, this.state, {[target]: value});
this.setState(newState);
this.updateMap(newState);
},
updateMap: function (state) {
if (! state) { state = this.state; }
ifAllDefined(
this.props.showLayerWithBreaks,
this.props.showMaxState,
this.props.hideMaxState,
this.props.showMaxAverageState,
this.props.hideMaxAverageState,
this.props.rootUrl,
this.props.layers[state.layerId1],
this.props.layers[state.layerId2],
state.layerId1time,
state.layerId2time)(function(showLayerWithBreaks, showMaxState, hideMaxState, showMaxAverageState, hideMaxAverageState, rootUrl, layer1, layer2, t1, t2) {
updateInterLayerDiffMap(showLayerWithBreaks, showMaxState, hideMaxState, showMaxAverageState, hideMaxAverageState, rootUrl, layer1, layer2, t1, t2,
state.showingMaxState,
state.showingMaxAverageState);
});
this.props.showExtent(this.props.layers[state.layerId1].extent);
},
render: function() {
let layer1 = this.props.layers[this.state.layerId1];
let layer2 = this.props.layers[this.state.layerId2];
let layerOptions =
_.map(this.props.layers, (layer, index) => {
return <option value={index} key={index}>{layer.name}</option>;
});
let layer1Times =
_.map(_.get(layer1, "times", []), (time, index) => {
return <option value={index} key={index}>{time}</option>;
});
let layer2Times =
_.map(_.get(layer2, "times", []), (time, index) => {
return <option value={index} key={index}>{time}</option>;
});
let showMaxState = false;
let showMaxAverageState = true;
return (
<div>
<Input type="select" label="Layer A" placeholder="select" value={this.state.layerId1}
onChange={e => this.handleLayerSelect(e, "layerId1")}>
{layerOptions}
</Input>
<Input type="select" label="Time A" placeholder="select" value={this.state.layerId1time}
onChange={e => this.updateState("layerId1time", +e.target.value)}>
{layer1Times}
</Input>
<Input type="select" label="Layer B" placeholder="select" value={this.state.layerId2}
onChange={e => this.handleLayerSelect(e, "layerId2")}>
{layerOptions}
</Input>
<Input type="select" label="Time B" placeholder="select" value={this.state.layerId2time}
onChange={e => this.updateState("layerId2time", +e.target.value)}>
{layer2Times}
</Input>
{ showMaxState ?
<Input type="checkbox" label="Show state with max difference" checked={this.state.showingMaxState} onChange={this.handleShowMaxStateChecked} visibility="hidden"/>
: null
}
{ showMaxAverageState ?
<Input type="checkbox" label="Show state with max average difference" checked={this.state.showingMaxAverageState} onChange={this.handleShowMaxAverageStateChecked} />
: null
}
</div>
)
}
});
module.exports = MapViews;
|
apache-2.0
|
siilobv/retrofit
|
retrofit/src/main/java/retrofit2/Retrofit.java
|
23591
|
/*
* Copyright (C) 2012 Square, Inc.
*
* 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 retrofit2;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import javax.annotation.Nullable;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.http.GET;
import retrofit2.http.HTTP;
import retrofit2.http.Header;
import retrofit2.http.Url;
import static java.util.Collections.unmodifiableList;
import static retrofit2.Utils.checkNotNull;
/**
* Retrofit adapts a Java interface to HTTP calls by using annotations on the declared methods to
* define how requests are made. Create instances using {@linkplain Builder
* the builder} and pass your interface to {@link #create} to generate an implementation.
* <p>
* For example,
* <pre><code>
* Retrofit retrofit = new Retrofit.Builder()
* .baseUrl("https://api.example.com/")
* .addConverterFactory(GsonConverterFactory.create())
* .build();
*
* MyApi api = retrofit.create(MyApi.class);
* Response<User> user = api.getUser().execute();
* </code></pre>
*
* @author Bob Lee (bob@squareup.com)
* @author Jake Wharton (jw@squareup.com)
*/
public final class Retrofit {
private final Map<Method, ServiceMethod<?, ?>> serviceMethodCache = new ConcurrentHashMap<>();
final okhttp3.Call.Factory callFactory;
final HttpUrl baseUrl;
final List<Converter.Factory> converterFactories;
final List<CallAdapter.Factory> callAdapterFactories;
final @Nullable Executor callbackExecutor;
final boolean validateEagerly;
Retrofit(okhttp3.Call.Factory callFactory, HttpUrl baseUrl,
List<Converter.Factory> converterFactories, List<CallAdapter.Factory> callAdapterFactories,
@Nullable Executor callbackExecutor, boolean validateEagerly) {
this.callFactory = callFactory;
this.baseUrl = baseUrl;
this.converterFactories = converterFactories; // Copy+unmodifiable at call site.
this.callAdapterFactories = callAdapterFactories; // Copy+unmodifiable at call site.
this.callbackExecutor = callbackExecutor;
this.validateEagerly = validateEagerly;
}
/**
* Create an implementation of the API endpoints defined by the {@code service} interface.
* <p>
* The relative path for a given method is obtained from an annotation on the method describing
* the request type. The built-in methods are {@link retrofit2.http.GET GET},
* {@link retrofit2.http.PUT PUT}, {@link retrofit2.http.POST POST}, {@link retrofit2.http.PATCH
* PATCH}, {@link retrofit2.http.HEAD HEAD}, {@link retrofit2.http.DELETE DELETE} and
* {@link retrofit2.http.OPTIONS OPTIONS}. You can use a custom HTTP method with
* {@link HTTP @HTTP}. For a dynamic URL, omit the path on the annotation and annotate the first
* parameter with {@link Url @Url}.
* <p>
* Method parameters can be used to replace parts of the URL by annotating them with
* {@link retrofit2.http.Path @Path}. Replacement sections are denoted by an identifier
* surrounded by curly braces (e.g., "{foo}"). To add items to the query string of a URL use
* {@link retrofit2.http.Query @Query}.
* <p>
* The body of a request is denoted by the {@link retrofit2.http.Body @Body} annotation. The
* object will be converted to request representation by one of the {@link Converter.Factory}
* instances. A {@link RequestBody} can also be used for a raw representation.
* <p>
* Alternative request body formats are supported by method annotations and corresponding
* parameter annotations:
* <ul>
* <li>{@link retrofit2.http.FormUrlEncoded @FormUrlEncoded} - Form-encoded data with key-value
* pairs specified by the {@link retrofit2.http.Field @Field} parameter annotation.
* <li>{@link retrofit2.http.Multipart @Multipart} - RFC 2388-compliant multipart data with
* parts specified by the {@link retrofit2.http.Part @Part} parameter annotation.
* </ul>
* <p>
* Additional static headers can be added for an endpoint using the
* {@link retrofit2.http.Headers @Headers} method annotation. For per-request control over a
* header annotate a parameter with {@link Header @Header}.
* <p>
* By default, methods return a {@link Call} which represents the HTTP request. The generic
* parameter of the call is the response body type and will be converted by one of the
* {@link Converter.Factory} instances. {@link ResponseBody} can also be used for a raw
* representation. {@link Void} can be used if you do not care about the body contents.
* <p>
* For example:
* <pre>
* public interface CategoryService {
* @POST("category/{cat}/")
* Call<List<Item>> categoryList(@Path("cat") String a, @Query("page") int b);
* }
* </pre>
*/
@SuppressWarnings("unchecked") // Single-interface proxy creation guarded by parameter safety.
public <T> T create(final Class<T> service) {
Utils.validateServiceInterface(service);
if (validateEagerly) {
eagerlyValidateMethods(service);
}
return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
new InvocationHandler() {
private final Platform platform = Platform.get();
@Override public Object invoke(Object proxy, Method method, @Nullable Object[] args)
throws Throwable {
// If the method is a method from Object then defer to normal invocation.
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
if (platform.isDefaultMethod(method)) {
return platform.invokeDefaultMethod(method, service, proxy, args);
}
ServiceMethod<Object, Object> serviceMethod =
(ServiceMethod<Object, Object>) loadServiceMethod(method);
OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
return serviceMethod.adapt(okHttpCall);
}
});
}
private void eagerlyValidateMethods(Class<?> service) {
Platform platform = Platform.get();
for (Method method : service.getDeclaredMethods()) {
if (!platform.isDefaultMethod(method)) {
loadServiceMethod(method);
}
}
}
ServiceMethod<?, ?> loadServiceMethod(Method method) {
ServiceMethod<?, ?> result = serviceMethodCache.get(method);
if (result != null) return result;
synchronized (serviceMethodCache) {
result = serviceMethodCache.get(method);
if (result == null) {
result = new ServiceMethod.Builder<>(this, method).build();
serviceMethodCache.put(method, result);
}
}
return result;
}
/**
* The factory used to create {@linkplain okhttp3.Call OkHttp calls} for sending a HTTP requests.
* Typically an instance of {@link OkHttpClient}.
*/
public okhttp3.Call.Factory callFactory() {
return callFactory;
}
/** The API base URL. */
public HttpUrl baseUrl() {
return baseUrl;
}
/**
* Returns a list of the factories tried when creating a
* {@linkplain #callAdapter(Type, Annotation[])} call adapter}.
*/
public List<CallAdapter.Factory> callAdapterFactories() {
return callAdapterFactories;
}
/**
* Returns the {@link CallAdapter} for {@code returnType} from the available {@linkplain
* #callAdapterFactories() factories}.
*
* @throws IllegalArgumentException if no call adapter available for {@code type}.
*/
public CallAdapter<?, ?> callAdapter(Type returnType, Annotation[] annotations) {
return nextCallAdapter(null, returnType, annotations);
}
/**
* Returns the {@link CallAdapter} for {@code returnType} from the available {@linkplain
* #callAdapterFactories() factories} except {@code skipPast}.
*
* @throws IllegalArgumentException if no call adapter available for {@code type}.
*/
public CallAdapter<?, ?> nextCallAdapter(@Nullable CallAdapter.Factory skipPast, Type returnType,
Annotation[] annotations) {
checkNotNull(returnType, "returnType == null");
checkNotNull(annotations, "annotations == null");
int start = callAdapterFactories.indexOf(skipPast) + 1;
for (int i = start, count = callAdapterFactories.size(); i < count; i++) {
CallAdapter<?, ?> adapter = callAdapterFactories.get(i).get(returnType, annotations, this);
if (adapter != null) {
return adapter;
}
}
StringBuilder builder = new StringBuilder("Could not locate call adapter for ")
.append(returnType)
.append(".\n");
if (skipPast != null) {
builder.append(" Skipped:");
for (int i = 0; i < start; i++) {
builder.append("\n * ").append(callAdapterFactories.get(i).getClass().getName());
}
builder.append('\n');
}
builder.append(" Tried:");
for (int i = start, count = callAdapterFactories.size(); i < count; i++) {
builder.append("\n * ").append(callAdapterFactories.get(i).getClass().getName());
}
throw new IllegalArgumentException(builder.toString());
}
/**
* Returns an unmodifiable list of the factories tried when creating a
* {@linkplain #requestBodyConverter(Type, Annotation[], Annotation[]) request body converter}, a
* {@linkplain #responseBodyConverter(Type, Annotation[]) response body converter}, or a
* {@linkplain #stringConverter(Type, Annotation[]) string converter}.
*/
public List<Converter.Factory> converterFactories() {
return converterFactories;
}
/**
* Returns a {@link Converter} for {@code type} to {@link RequestBody} from the available
* {@linkplain #converterFactories() factories}.
*
* @throws IllegalArgumentException if no converter available for {@code type}.
*/
public <T> Converter<T, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations) {
return nextRequestBodyConverter(null, type, parameterAnnotations, methodAnnotations);
}
/**
* Returns a {@link Converter} for {@code type} to {@link RequestBody} from the available
* {@linkplain #converterFactories() factories} except {@code skipPast}.
*
* @throws IllegalArgumentException if no converter available for {@code type}.
*/
public <T> Converter<T, RequestBody> nextRequestBodyConverter(
@Nullable Converter.Factory skipPast, Type type, Annotation[] parameterAnnotations,
Annotation[] methodAnnotations) {
checkNotNull(type, "type == null");
checkNotNull(parameterAnnotations, "parameterAnnotations == null");
checkNotNull(methodAnnotations, "methodAnnotations == null");
int start = converterFactories.indexOf(skipPast) + 1;
for (int i = start, count = converterFactories.size(); i < count; i++) {
Converter.Factory factory = converterFactories.get(i);
Converter<?, RequestBody> converter =
factory.requestBodyConverter(type, parameterAnnotations, methodAnnotations, this);
if (converter != null) {
//noinspection unchecked
return (Converter<T, RequestBody>) converter;
}
}
StringBuilder builder = new StringBuilder("Could not locate RequestBody converter for ")
.append(type)
.append(".\n");
if (skipPast != null) {
builder.append(" Skipped:");
for (int i = 0; i < start; i++) {
builder.append("\n * ").append(converterFactories.get(i).getClass().getName());
}
builder.append('\n');
}
builder.append(" Tried:");
for (int i = start, count = converterFactories.size(); i < count; i++) {
builder.append("\n * ").append(converterFactories.get(i).getClass().getName());
}
throw new IllegalArgumentException(builder.toString());
}
/**
* Returns a {@link Converter} for {@link ResponseBody} to {@code type} from the available
* {@linkplain #converterFactories() factories}.
*
* @throws IllegalArgumentException if no converter available for {@code type}.
*/
public <T> Converter<ResponseBody, T> responseBodyConverter(Type type, Annotation[] annotations) {
return nextResponseBodyConverter(null, type, annotations);
}
/**
* Returns a {@link Converter} for {@link ResponseBody} to {@code type} from the available
* {@linkplain #converterFactories() factories} except {@code skipPast}.
*
* @throws IllegalArgumentException if no converter available for {@code type}.
*/
public <T> Converter<ResponseBody, T> nextResponseBodyConverter(
@Nullable Converter.Factory skipPast, Type type, Annotation[] annotations) {
checkNotNull(type, "type == null");
checkNotNull(annotations, "annotations == null");
int start = converterFactories.indexOf(skipPast) + 1;
for (int i = start, count = converterFactories.size(); i < count; i++) {
Converter<ResponseBody, ?> converter =
converterFactories.get(i).responseBodyConverter(type, annotations, this);
if (converter != null) {
//noinspection unchecked
return (Converter<ResponseBody, T>) converter;
}
}
StringBuilder builder = new StringBuilder("Could not locate ResponseBody converter for ")
.append(type)
.append(".\n");
if (skipPast != null) {
builder.append(" Skipped:");
for (int i = 0; i < start; i++) {
builder.append("\n * ").append(converterFactories.get(i).getClass().getName());
}
builder.append('\n');
}
builder.append(" Tried:");
for (int i = start, count = converterFactories.size(); i < count; i++) {
builder.append("\n * ").append(converterFactories.get(i).getClass().getName());
}
throw new IllegalArgumentException(builder.toString());
}
/**
* Returns a {@link Converter} for {@code type} to {@link String} from the available
* {@linkplain #converterFactories() factories}.
*/
public <T> Converter<T, String> stringConverter(Type type, Annotation[] annotations) {
checkNotNull(type, "type == null");
checkNotNull(annotations, "annotations == null");
for (int i = 0, count = converterFactories.size(); i < count; i++) {
Converter<?, String> converter =
converterFactories.get(i).stringConverter(type, annotations, this);
if (converter != null) {
//noinspection unchecked
return (Converter<T, String>) converter;
}
}
// Nothing matched. Resort to default converter which just calls toString().
//noinspection unchecked
return (Converter<T, String>) BuiltInConverters.ToStringConverter.INSTANCE;
}
/**
* The executor used for {@link Callback} methods on a {@link Call}. This may be {@code null},
* in which case callbacks should be made synchronously on the background thread.
*/
public @Nullable Executor callbackExecutor() {
return callbackExecutor;
}
public Builder newBuilder() {
return new Builder(this);
}
/**
* Build a new {@link Retrofit}.
* <p>
* Calling {@link #baseUrl} is required before calling {@link #build()}. All other methods
* are optional.
*/
public static final class Builder {
private final Platform platform;
private @Nullable okhttp3.Call.Factory callFactory;
private HttpUrl baseUrl;
private final List<Converter.Factory> converterFactories = new ArrayList<>();
private final List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>();
private @Nullable Executor callbackExecutor;
private boolean validateEagerly;
Builder(Platform platform) {
this.platform = platform;
}
public Builder() {
this(Platform.get());
}
Builder(Retrofit retrofit) {
platform = Platform.get();
callFactory = retrofit.callFactory;
baseUrl = retrofit.baseUrl;
converterFactories.addAll(retrofit.converterFactories);
// Remove the default BuiltInConverters instance added by build().
converterFactories.remove(0);
callAdapterFactories.addAll(retrofit.callAdapterFactories);
// Remove the default, platform-aware call adapter added by build().
callAdapterFactories.remove(callAdapterFactories.size() - 1);
callbackExecutor = retrofit.callbackExecutor;
validateEagerly = retrofit.validateEagerly;
}
/**
* The HTTP client used for requests.
* <p>
* This is a convenience method for calling {@link #callFactory}.
*/
public Builder client(OkHttpClient client) {
return callFactory(checkNotNull(client, "client == null"));
}
/**
* Specify a custom call factory for creating {@link Call} instances.
* <p>
* Note: Calling {@link #client} automatically sets this value.
*/
public Builder callFactory(okhttp3.Call.Factory factory) {
this.callFactory = checkNotNull(factory, "factory == null");
return this;
}
/**
* Set the API base URL.
*
* @see #baseUrl(HttpUrl)
*/
public Builder baseUrl(String baseUrl) {
checkNotNull(baseUrl, "baseUrl == null");
HttpUrl httpUrl = HttpUrl.parse(baseUrl);
if (httpUrl == null) {
throw new IllegalArgumentException("Illegal URL: " + baseUrl);
}
return baseUrl(httpUrl);
}
/**
* Set the API base URL.
* <p>
* The specified endpoint values (such as with {@link GET @GET}) are resolved against this
* value using {@link HttpUrl#resolve(String)}. The behavior of this matches that of an
* {@code <a href="">} link on a website resolving on the current URL.
* <p>
* <b>Base URLs should always end in {@code /}.</b>
* <p>
* A trailing {@code /} ensures that endpoints values which are relative paths will correctly
* append themselves to a base which has path components.
* <p>
* <b>Correct:</b><br>
* Base URL: http://example.com/api/<br>
* Endpoint: foo/bar/<br>
* Result: http://example.com/api/foo/bar/
* <p>
* <b>Incorrect:</b><br>
* Base URL: http://example.com/api<br>
* Endpoint: foo/bar/<br>
* Result: http://example.com/foo/bar/
* <p>
* This method enforces that {@code baseUrl} has a trailing {@code /}.
* <p>
* <b>Endpoint values which contain a leading {@code /} are absolute.</b>
* <p>
* Absolute values retain only the host from {@code baseUrl} and ignore any specified path
* components.
* <p>
* Base URL: http://example.com/api/<br>
* Endpoint: /foo/bar/<br>
* Result: http://example.com/foo/bar/
* <p>
* Base URL: http://example.com/<br>
* Endpoint: /foo/bar/<br>
* Result: http://example.com/foo/bar/
* <p>
* <b>Endpoint values may be a full URL.</b>
* <p>
* Values which have a host replace the host of {@code baseUrl} and values also with a scheme
* replace the scheme of {@code baseUrl}.
* <p>
* Base URL: http://example.com/<br>
* Endpoint: https://github.com/square/retrofit/<br>
* Result: https://github.com/square/retrofit/
* <p>
* Base URL: http://example.com<br>
* Endpoint: //github.com/square/retrofit/<br>
* Result: http://github.com/square/retrofit/ (note the scheme stays 'http')
*/
public Builder baseUrl(HttpUrl baseUrl) {
checkNotNull(baseUrl, "baseUrl == null");
List<String> pathSegments = baseUrl.pathSegments();
if (!"".equals(pathSegments.get(pathSegments.size() - 1))) {
throw new IllegalArgumentException("baseUrl must end in /: " + baseUrl);
}
this.baseUrl = baseUrl;
return this;
}
/** Add converter factory for serialization and deserialization of objects. */
public Builder addConverterFactory(Converter.Factory factory) {
converterFactories.add(checkNotNull(factory, "factory == null"));
return this;
}
/**
* Add a call adapter factory for supporting service method return types other than {@link
* Call}.
*/
public Builder addCallAdapterFactory(CallAdapter.Factory factory) {
callAdapterFactories.add(checkNotNull(factory, "factory == null"));
return this;
}
/**
* The executor on which {@link Callback} methods are invoked when returning {@link Call} from
* your service method.
* <p>
* Note: {@code executor} is not used for {@linkplain #addCallAdapterFactory custom method
* return types}.
*/
public Builder callbackExecutor(Executor executor) {
this.callbackExecutor = checkNotNull(executor, "executor == null");
return this;
}
/** Returns a modifiable list of call adapter factories. */
public List<CallAdapter.Factory> callAdapterFactories() {
return this.callAdapterFactories;
}
/** Returns a modifiable list of converter factories. */
public List<Converter.Factory> converterFactories() {
return this.converterFactories;
}
/**
* When calling {@link #create} on the resulting {@link Retrofit} instance, eagerly validate
* the configuration of all methods in the supplied interface.
*/
public Builder validateEagerly(boolean validateEagerly) {
this.validateEagerly = validateEagerly;
return this;
}
/**
* Create the {@link Retrofit} instance using the configured values.
* <p>
* Note: If neither {@link #client} nor {@link #callFactory} is called a default {@link
* OkHttpClient} will be created and used.
*/
public Retrofit build() {
if (baseUrl == null) {
throw new IllegalStateException("Base URL required.");
}
okhttp3.Call.Factory callFactory = this.callFactory;
if (callFactory == null) {
callFactory = new OkHttpClient();
}
Executor callbackExecutor = this.callbackExecutor;
if (callbackExecutor == null) {
callbackExecutor = platform.defaultCallbackExecutor();
}
// Make a defensive copy of the adapters and add the default Call adapter.
List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(this.callAdapterFactories);
callAdapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));
// Make a defensive copy of the converters.
List<Converter.Factory> converterFactories =
new ArrayList<>(1 + this.converterFactories.size());
// Add the built-in converter factory first. This prevents overriding its behavior but also
// ensures correct behavior when using converters that consume all types.
converterFactories.add(new BuiltInConverters());
converterFactories.addAll(this.converterFactories);
return new Retrofit(callFactory, baseUrl, unmodifiableList(converterFactories),
unmodifiableList(callAdapterFactories), callbackExecutor, validateEagerly);
}
}
}
|
apache-2.0
|
StnetixDevTeam/ariADDna
|
rest-api-server/src/main/java/com/stnetix/ariaddna/restapiserver/model/PartLocation.java
|
2664
|
/*
* Copyright (c) 2018 stnetix.com. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.stnetix.ariaddna.restapiserver.model;
import java.util.Objects;
import java.util.UUID;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* Describes sequence number of file part and its location.
*/
@ApiModel(description = "Describes sequence number of file part and its location.")
@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2017-07-24T10:27:06.657+03:00")
public class PartLocation {
@JsonProperty("uuid")
private UUID uuid = null;
public PartLocation uuid(UUID uuid) {
this.uuid = uuid;
return this;
}
/**
* Object UUID.
* @return uuid
**/
@ApiModelProperty(required = true, value = "Object UUID.")
@NotNull
@Valid
public UUID getUuid() {
return uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PartLocation partLocation = (PartLocation) o;
return Objects.equals(this.uuid, partLocation.uuid);
}
@Override
public int hashCode() {
return Objects.hash(uuid);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PartLocation {\n");
sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
apache-2.0
|
vcpe-io/vcpe-hub
|
nat/pkt_utils/arp_pkt_gen.py
|
1577
|
from ryu.lib.packet import packet
from ryu.lib.packet import ethernet
from ryu.ofproto.ether import ETH_TYPE_ARP
from ryu.lib.packet import arp
from ryu.ofproto import ether
BROADCAST = 'ff:ff:ff:ff:ff:ff'
TARGET_MAC_ADDRESS = '00:00:00:00:00:00'
def arp_reply(src_mac, src_ip, target_mac, target_ip):
# Creat an empty Packet instance
pkt = packet.Packet()
pkt.add_protocol(ethernet.ethernet(ethertype=ETH_TYPE_ARP,
dst=target_mac,
src=src_mac))
pkt.add_protocol(arp.arp(opcode=arp.ARP_REPLY,
src_mac=src_mac,
src_ip=src_ip,
dst_mac=target_mac,
dst_ip=target_ip))
# Packet serializing
pkt.serialize()
data = pkt.data
# print 'Built up a arp reply packet:', data
return data
def broadcast_arp_request(src_mac, src_ip, target_ip):
pkt = packet.Packet()
pkt.add_protocol(ethernet.ethernet(ethertype=ETH_TYPE_ARP,
dst=BROADCAST,
src=src_mac))
pkt.add_protocol(arp.arp(opcode=arp.ARP_REQUEST,
src_mac=src_mac,
src_ip=src_ip,
dst_mac=TARGET_MAC_ADDRESS,
dst_ip=target_ip))
pkt.serialize()
data = pkt.data
# print 'Built up a broadcast arp request packet:', data
return data
if __name__ == '__main__':
print arp_reply()
|
apache-2.0
|
harnesscloud/nova-docker
|
novadocker/virt/docker/client.py
|
8632
|
# Copyright (c) 2013 dotCloud, Inc.
# All Rights Reserved.
#
# 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.
import functools
import socket
import urllib
from eventlet.green import httplib
from oslo.serialization import jsonutils
import six
from nova.openstack.common import log as logging
LOG = logging.getLogger(__name__)
def filter_data(f):
"""Decorator that post-processes data returned by Docker.
This will avoid any surprises with different versions of Docker.
"""
@functools.wraps(f)
def wrapper(*args, **kwds):
out = f(*args, **kwds)
def _filter(obj):
if isinstance(obj, list):
new_list = []
for o in obj:
new_list.append(_filter(o))
obj = new_list
if isinstance(obj, dict):
for k, v in obj.items():
if isinstance(k, six.string_types):
obj[k.lower()] = _filter(v)
return obj
return _filter(out)
return wrapper
class Response(object):
def __init__(self, http_response, url=None):
self.url = url
self._response = http_response
self.code = int(http_response.status)
self._json = None
def read(self, size=None):
return self._response.read(size)
def to_json(self, default=None):
if not self._json:
self._json = self._decode_json(self._response.read(), default)
return self._json
def _validate_content_type(self):
# Docker does not return always the correct Content-Type.
# Lets try to parse the response anyway since json is requested.
if self._response.getheader('Content-Type') != 'application/json':
LOG.debug("Content-Type of response is not application/json"
" (Docker bug?). Requested URL %s" % self.url)
@filter_data
def _decode_json(self, data, default=None):
if not data:
return default
self._validate_content_type()
# Do not catch ValueError or SyntaxError since that
# just hides the root cause of errors.
return jsonutils.loads(data)
class UnixHTTPConnection(httplib.HTTPConnection):
def __init__(self):
httplib.HTTPConnection.__init__(self, 'localhost')
self.unix_socket = '/var/run/docker.sock'
def connect(self):
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(self.unix_socket)
self.sock = sock
class DockerHTTPClient(object):
VERSION = 'v1.13'
def __init__(self, connection=None):
self._connection = connection
@property
def connection(self):
if self._connection:
return self._connection
else:
return UnixHTTPConnection()
def make_request(self, *args, **kwargs):
headers = {}
if 'headers' in kwargs and kwargs['headers']:
headers = kwargs['headers']
if 'Content-Type' not in headers:
headers['Content-Type'] = 'application/json'
kwargs['headers'] = headers
conn = self.connection
# args[1] == path, args[2:] == query represented as tuples
url = "/%s/%s" % (self.VERSION, urllib.quote(args[1]))
if len(args) > 2:
url += "?" + urllib.urlencode(args[2:])
encoded_args = args[0], url
conn.request(*encoded_args, **kwargs)
return Response(conn.getresponse(), url=encoded_args[1])
def list_containers(self, _all=True):
resp = self.make_request(
'GET',
'containers/ps',
('all', int(_all)))
if resp.code == 404:
return []
return resp.to_json(default=[])
def create_container(self, args, name):
data = {
'Hostname': '',
'User': '',
'Memory': 0,
'MemorySwap': 0,
'AttachStdin': False,
'AttachStdout': False,
'AttachStderr': False,
'PortSpecs': [],
'Tty': True,
'OpenStdin': True,
'StdinOnce': False,
'Env': None,
'Cmd': [],
'Dns': None,
'Image': None,
'Volumes': {},
'VolumesFrom': '',
}
data.update(args)
resp = self.make_request(
'POST',
'containers/create',
('name', unicode(name).encode('utf-8')),
body=jsonutils.dumps(data))
if resp.code != 201:
return
obj = resp.to_json()
for k, v in obj.iteritems():
if k.lower() == 'id':
return v
def start_container(self, container_id):
resp = self.make_request(
'POST',
'containers/{0}/start'.format(container_id),
body='{}')
return (resp.code == 200 or resp.code == 204)
def pause_container(self, container_id):
resp = self.make_request(
'POST',
'containers/{0}/pause'.format(container_id),
body='{}')
return (resp.code == 204)
def unpause_container(self, container_id):
resp = self.make_request(
'POST',
'containers/{0}/unpause'.format(container_id),
body='{}')
return (resp.code == 204)
def inspect_image(self, image_name):
resp = self.make_request(
'GET',
'images/{0}/json'.format(
unicode(image_name).encode('utf-8')))
if resp.code != 200:
return
return resp.to_json()
def inspect_container(self, container_id):
resp = self.make_request(
'GET',
'containers/{0}/json'.format(container_id))
if resp.code != 200:
return {}
return resp.to_json()
def stop_container(self, container_id, timeout=5):
resp = self.make_request(
'POST',
'containers/{0}/stop'.format(container_id),
('t', timeout))
return (resp.code == 204)
def kill_container(self, container_id):
resp = self.make_request(
'POST',
'containers/{0}/kill'.format(container_id))
return (resp.code == 204)
def destroy_container(self, container_id):
resp = self.make_request(
'DELETE',
'containers/{0}'.format(container_id))
return (resp.code == 204)
def get_image(self, name, size=4096):
parts = unicode(name).encode('utf-8').rsplit(':', 1)
url = 'images/{0}/get'.format(parts[0])
resp = self.make_request('GET', url)
while True:
buf = resp.read(size)
if not buf:
break
yield buf
return
def get_image_resp(self, name):
parts = unicode(name).encode('utf-8').rsplit(':', 1)
url = 'images/{0}/get'.format(parts[0])
resp = self.make_request('GET', url)
return resp
def load_repository(self, name, data):
url = 'images/load'
self.make_request('POST', url, body=data)
def load_repository_file(self, name, path):
with open(path) as fh:
self.load_repository(unicode(name).encode('utf-8'), fh)
def commit_container(self, container_id, name):
parts = unicode(name).encode('utf-8').rsplit(':', 1)
url = 'commit'
query = [('container', container_id),
('repo', parts[0])]
if len(parts) > 1:
query += (('tag', parts[1]),)
resp = self.make_request('POST', url, *query)
return (resp.code == 201)
def get_container_logs(self, container_id):
resp = self.make_request(
'POST',
'containers/{0}/attach'.format(container_id),
('logs', '1'),
('stream', '0'),
('stdout', '1'),
('stderr', '1'))
if resp.code != 200:
return
return resp.read()
def ping(self):
resp = self.make_request('GET', '_ping')
return (resp.code == 200)
|
apache-2.0
|
cloudera/hue
|
desktop/core/ext-py/pyasn1-modules-0.2.6/pyasn1_modules/rfc6019.py
|
994
|
# This file is being contributed to pyasn1-modules software.
#
# Created by Russ Housley.
# Modified by Russ Housley to add a map for use with opentypes.
#
# Copyright (c) 2019, Vigil Security, LLC
# License: http://snmplabs.com/pyasn1/license.html
#
# BinaryTime: An Alternate Format for Representing Date and Time
#
# ASN.1 source from:
# https://www.rfc-editor.org/rfc/rfc6019.txt
from pyasn1.type import constraint
from pyasn1.type import univ
MAX = float('inf')
# BinaryTime: Represent date and time as an integer
class BinaryTime(univ.Integer):
pass
BinaryTime.subtypeSpec = constraint.ValueRangeConstraint(0, MAX)
# CMS Attribute for representing signing time in BinaryTime
id_aa_binarySigningTime = univ.ObjectIdentifier('1.2.840.113549.1.9.16.2.46')
class BinarySigningTime(BinaryTime):
pass
# Map of Attribute Type OIDs to Attributes
# To be added to the ones that are in rfc5652.py
cmsAttributesMapUpdate = {
id_aa_binarySigningTime: BinarySigningTime(),
}
|
apache-2.0
|
cheld/dashboard
|
src/app/frontend/common/components/actionbar/module.js
|
2104
|
// Copyright 2017 The Kubernetes Dashboard Authors.
//
// 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.
import resourceModule from 'common/resource/module';
import {breadcrumbsComponent} from './../breadcrumbs/component';
import {BreadcrumbsService} from './../breadcrumbs/service';
import {actionbarDeleteItemComponent} from './actionbardeleteitem_component';
import {actionbarDetailButtonsComponent} from './actionbardetailbuttons_component';
import {actionbarEditItemComponent} from './actionbaredititem_component';
import {actionbarListButtonsComponent} from './actionbarlistbuttons_component';
import {actionbarLogsComponent} from './actionbarlogs_component';
import {actionbarComponent} from './component';
import {actionbarShellButtonComponent} from './shell_component';
/**
* Module containing common actionbar.
*/
export default angular
.module(
'kubernetesDashboard.common.components.actionbar',
[
'ngMaterial',
'ui.router',
resourceModule.name,
])
.component('kdActionbar', actionbarComponent)
.component('kdBreadcrumbs', breadcrumbsComponent)
.component('kdActionbarLogs', actionbarLogsComponent)
.component('kdActionbarDeleteItem', actionbarDeleteItemComponent)
.component('kdActionbarEditItem', actionbarEditItemComponent)
.component('kdActionbarDetailButtons', actionbarDetailButtonsComponent)
.component('kdActionbarListButtons', actionbarListButtonsComponent)
.component('kdActionbarShellButton', actionbarShellButtonComponent)
.service('kdBreadcrumbsService', BreadcrumbsService);
|
apache-2.0
|
justasabc/opensim76
|
OpenSim/Region/Framework/Interfaces/IEstateModule.cs
|
2640
|
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using OpenMetaverse;
namespace OpenSim.Region.Framework.Interfaces
{
public delegate void ChangeDelegate(UUID regionID);
public delegate void MessageDelegate(UUID regionID, UUID fromID, string fromName, string message);
public interface IEstateModule
{
event ChangeDelegate OnRegionInfoChange;
event ChangeDelegate OnEstateInfoChange;
event MessageDelegate OnEstateMessage;
uint GetRegionFlags();
bool IsManager(UUID avatarID);
/// <summary>
/// Tell all clients about the current state of the region (terrain textures, water height, etc.).
/// </summary>
void sendRegionHandshakeToAll();
void TriggerEstateInfoChange();
/// <summary>
/// Fires the OnRegionInfoChange event.
/// </summary>
void TriggerRegionInfoChange();
void setEstateTerrainBaseTexture(int level, UUID texture);
void setEstateTerrainTextureHeights(int corner, float lowValue, float highValue);
}
}
|
apache-2.0
|
ArsenShnurkov/poderosa
|
Plugin/StructuredText.cs
|
10803
|
/*
* Copyright 2004,2006 The Poderosa Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* $Id: StructuredText.cs,v 1.3 2012/05/20 09:10:30 kzmi Exp $
*/
using System;
using System.IO;
using System.Collections;
/*
[SPEC] 設定の基本原則
全体はツリーを構成し、デリミタは . 。
極力デフォルト値を使う。そうすればファイルのパース時間を短縮できる。
name-valueは同一名の存在許さず。これはXML形式との整合性のため
まあニセXMLですよこれは。パースが早いだけで。
*/
using Poderosa.Util.Collections;
namespace Poderosa {
/// <summary>
/// </summary>
/// <exclude/>
public class StructuredText : ICloneable {
private StructuredText _parent; //null in case of root
private string _name;
private ArrayList _children;
//外部からセットできる他、状態変更があったら立つフラグ
private bool _dirtyFlag;
/// <summary>
///
/// </summary>
/// <exclude/>
public class Entry : ICloneable {
public string name;
public string value;
public Entry(string n, string v) {
name = n;
value = v;
}
public object Clone() {
return new Entry(name, value);
}
}
public string Name {
get {
return _name;
}
}
public StructuredText Parent {
get {
return _parent;
}
}
public string FullName {
get {
return _parent == null ? _name : _parent.FullName + "." + _name;
}
}
public int ChildCount {
get {
return _children.Count;
}
}
public bool IsDirty {
get {
return _dirtyFlag;
}
set {
_dirtyFlag = value;
}
}
//values
public string Get(string name) {
return Get(name, null);
}
public string Get(string name, string defval) {
Entry e = FindEntry(name);
return e == null ? defval : e.value;
}
public void Set(string name, string value) {
_dirtyFlag = true;
_children.Add(new Entry(name, value));
}
public void SetOrReplace(string name, string value) {
_dirtyFlag = true;
Entry e = FindEntry(name);
if (e == null)
_children.Add(new Entry(name, value));
else
e.value = value;
}
public void SetByIndex(int index, string value) {
Entry e = GetEntryOrNull(index);
if (e == null)
throw new ArgumentException("the entry is not found");
e.value = value;
}
public void ClearValue(string name) {
_dirtyFlag = true;
for (int i = 0; i < _children.Count; i++) {
Entry e = _children[i] as Entry;
if (e != null && e.name == name) {
_children.RemoveAt(i);
return;
}
}
}
public void Clear() {
_dirtyFlag = true;
_children.Clear();
}
public Entry FindEntry(string name) {
foreach (object o in _children) {
Entry e = o as Entry;
if (e != null && e.name == name)
return e;
}
return null;
}
public Entry GetEntryOrNull(int index) {
return index < _children.Count ? _children[index] as Entry : null;
}
public StructuredText GetChildOrNull(int index) {
return index < _children.Count ? _children[index] as StructuredText : null;
}
//Entry or child nodes
public IEnumerable Children {
get {
return _children;
}
}
// child nodes
//子孫まで一気に作成もOK
public StructuredText GetOrCreateChild(string name) {
_dirtyFlag = true;
int comma = name.IndexOf('.');
string local = comma == -1 ? name : name.Substring(0, comma);
StructuredText n = FindChild(local);
if (n == null) {
n = new StructuredText(this, local);
_children.Add(n);
}
return comma == -1 ? n : n.GetOrCreateChild(name.Substring(comma + 1));
}
public StructuredText AddChild(string name) {
_dirtyFlag = true;
StructuredText n = new StructuredText(this, name);
_children.Add(n);
return n;
}
public StructuredText AddChild(StructuredText child) {
_dirtyFlag = true;
child._parent = this;
_children.Add(child);
return this;
}
public void RemoveChild(StructuredText child) {
_dirtyFlag = true;
_children.Remove(child);
}
public StructuredText FindChild(string name) {
foreach (object o in _children) {
StructuredText n = o as StructuredText;
if (n != null && n.Name == name)
return n;
}
return null;
}
//TODO 実はこの戻りをまたコレクションにコピーすることがよくある。むだだ
public IList FindMultipleNote(string name) {
ArrayList r = new ArrayList();
foreach (object o in _children) {
StructuredText n = o as StructuredText;
if (n != null && n.Name == name)
r.Add(n);
}
return r;
}
public IList FindMultipleEntries(string name) {
ArrayList r = new ArrayList();
foreach (object o in _children) {
Entry e = o as Entry;
if (e != null && e.name == name)
r.Add(e.value); //string collection返しだよ
}
return r;
}
/// <summary>
/// ディープコピーするが、親からは切り離される
/// </summary>
public object Clone() {
StructuredText np = new StructuredText(null, _name);
np._children = CollectionUtil.DeepCopyArrayList(_children);
return np;
}
//note that assembly private
internal StructuredText(StructuredText parent, string name) {
_name = name;
_parent = parent;
_children = new ArrayList();
}
//constructor with empty content
public StructuredText(string name) {
_name = name;
_children = new ArrayList();
}
}
//Reader, Writer
/// <summary>
///
/// </summary>
/// <exclude/>
public abstract class StructuredTextReader {
public abstract StructuredText Read();
}
/// <summary>
///
/// </summary>
/// <exclude/>
public abstract class StructuredTextWriter {
public abstract void Write(StructuredText node);
}
/// <summary>
///
/// </summary>
/// <exclude/>
public class TextStructuredTextReader : StructuredTextReader {
private TextReader _reader;
private StructuredText _current;
private StructuredText _root;
public TextStructuredTextReader(TextReader reader) {
_reader = reader;
}
public override StructuredText Read() {
_current = null;
_root = null;
string line = _reader.ReadLine();
while (line != null) {
ProcessLine(CutPrecedingSpace(line));
line = _reader.ReadLine();
}
return _root;
}
private void ProcessLine(string line) {
if (line.Length == 0 || line[0] == '#')
return; //comment line
int e = line.IndexOf('=');
if (e != -1 && _current != null) {
string name0 = CutPrecedingSpace(line.Substring(0, e));
string value = e == line.Length - 1 ? "" : CutPrecedingSpace(line.Substring(e + 1));
_current.Set(name0, value);
}
else if (line[line.Length - 1] == '{') {
string name = line.Substring(0, line.IndexOf(' '));
_current = _current == null ? new StructuredText(null, name) : _current.AddChild(name);
if (_root == null)
_root = _current; //最初のNodeをルートとする
}
else if (line[line.Length - 1] == '}') {
_current = _current.Parent;
}
}
private static string CutPrecedingSpace(string s) {
int i = 0;
do {
if (i == s.Length)
return "";
char ch = s[i++];
if (ch != ' ' && ch != '\t')
return s.Substring(i - 1);
} while (true);
}
}
/// <summary>
///
/// </summary>
/// <exclude/>
public class TextStructuredTextWriter : StructuredTextWriter {
private TextWriter _writer;
private int _indent;
public const int INDENT_UNIT = 2;
public TextStructuredTextWriter(TextWriter writer) {
_writer = writer;
}
public override void Write(StructuredText node) {
_indent = 0;
WriteNode(node);
}
private void WriteNode(StructuredText node) {
WriteIndent();
_writer.Write(node.Name);
_writer.WriteLine(" {");
_indent += INDENT_UNIT;
foreach (object ch in node.Children) {
StructuredText.Entry e = ch as StructuredText.Entry;
if (e != null) { //entry
WriteIndent();
_writer.Write(e.name);
_writer.Write('=');
_writer.WriteLine(e.value);
}
else { //child node
WriteNode((StructuredText)ch);
}
}
_indent -= INDENT_UNIT;
WriteIndent();
_writer.WriteLine("}");
}
private void WriteIndent() {
for (int i = 0; i < _indent; i++)
_writer.Write(' ');
}
}
}
|
apache-2.0
|
spasam/spring-ldap
|
test/integration-tests-openldap/src/test/java/org/springframework/ldap/control/LdapTemplatePagedSearchITest.java
|
6738
|
/*
* Copyright 2005-2010 the original author or authors.
*
* 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.springframework.ldap.control;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import java.util.List;
import javax.naming.Name;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.CollectingNameClassPairCallbackHandler;
import org.springframework.ldap.core.ContextMapper;
import org.springframework.ldap.core.ContextMapperCallbackHandler;
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.DistinguishedName;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.SearchExecutor;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
/**
* Tests the paged search result capability of LdapTemplate.
* <p>
* Note: Currently, ApacheDS does not support paged results controls, so this
* test must be run under another directory server, for example OpenLdap. This
* test will not run under ApacheDS, and the other integration tests assume
* ApacheDS and will probably not run under OpenLdap.
*
* @author Ulrik Sandberg
*/
@ContextConfiguration(locations = { "/conf/ldapTemplateTestContext.xml" })
public class LdapTemplatePagedSearchITest extends AbstractJUnit4SpringContextTests {
private static final Name BASE = DistinguishedName.EMPTY_PATH;
private static final String FILTER_STRING = "(&(objectclass=person))";
@Autowired
private LdapTemplate tested;
private CollectingNameClassPairCallbackHandler callbackHandler;
private SearchControls searchControls;
@Before
public void onSetUp() throws Exception {
PersonContextMapper mapper = new PersonContextMapper();
callbackHandler = new ContextMapperCallbackHandler(mapper);
searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchControls.setReturningObjFlag(true);
}
@After
public void onTearDown() throws Exception {
callbackHandler = null;
tested = null;
searchControls = null;
}
@Test
public void testSearch_PagedResult() {
SearchExecutor searchExecutor = new SearchExecutor() {
public NamingEnumeration executeSearch(DirContext ctx) throws NamingException {
return ctx.search(BASE, FILTER_STRING, searchControls);
}
};
Person person;
List list;
PagedResultsCookie cookie;
PagedResultsRequestControl requestControl;
// Prepare for first search
requestControl = new PagedResultsRequestControl(3);
tested.search(searchExecutor, callbackHandler, requestControl);
cookie = requestControl.getCookie();
assertNotNull("Cookie should not be null yet", cookie.getCookie());
list = callbackHandler.getList();
assertEquals(3, list.size());
person = (Person) list.get(0);
assertEquals("Some Person", person.getFullName());
assertEquals("+46 555-123456", person.getPhone());
person = (Person) list.get(1);
assertEquals("Some Person2", person.getFullName());
assertEquals("+46 555-654321", person.getPhone());
person = (Person) list.get(2);
assertEquals("Some Person3", person.getFullName());
assertEquals("+46 555-123654", person.getPhone());
// Prepare for second and last search
requestControl = new PagedResultsRequestControl(3, cookie);
tested.search(searchExecutor, callbackHandler, requestControl);
cookie = requestControl.getCookie();
assertNull("Cookie should be null now", cookie.getCookie());
assertEquals(5, list.size());
person = (Person) list.get(3);
assertEquals("Some Person", person.getFullName());
assertEquals("+46 555-456321", person.getPhone());
person = (Person) list.get(4);
assertEquals("Some Person", person.getFullName());
assertEquals("+45 555-654123", person.getPhone());
}
@Test
public void testSearch_PagedResult_ConvenienceMethod() {
Person person;
List list;
PagedResultsCookie cookie;
PagedResultsRequestControl requestControl;
// Prepare for first search
requestControl = new PagedResultsRequestControl(3);
tested.search(BASE, FILTER_STRING, searchControls, callbackHandler, requestControl);
cookie = requestControl.getCookie();
assertNotNull("Cookie should not be null yet", cookie.getCookie());
list = callbackHandler.getList();
assertEquals(3, list.size());
person = (Person) list.get(0);
assertEquals("Some Person", person.getFullName());
person = (Person) list.get(1);
assertEquals("Some Person2", person.getFullName());
person = (Person) list.get(2);
assertEquals("Some Person3", person.getFullName());
// Prepare for second and last search
requestControl = new PagedResultsRequestControl(3, cookie);
tested.search(BASE, FILTER_STRING, searchControls, callbackHandler, requestControl);
cookie = requestControl.getCookie();
assertNull("Cookie should be null now", cookie.getCookie());
assertEquals(5, list.size());
person = (Person) list.get(3);
assertEquals("Some Person", person.getFullName());
person = (Person) list.get(4);
assertEquals("Some Person", person.getFullName());
}
private static class PersonContextMapper implements ContextMapper {
public Object mapFromContext(Object ctx) {
DirContextAdapter context = (DirContextAdapter) ctx;
DistinguishedName dn = new DistinguishedName(context.getDn());
Person person = new Person();
person.setCountry(dn.getLdapRdn(0).getComponent().getValue());
person.setCompany(dn.getLdapRdn(1).getComponent().getValue());
person.setFullName(context.getStringAttribute("cn"));
person.setLastName(context.getStringAttribute("sn"));
person.setDescription(context.getStringAttribute("description"));
person.setPhone(context.getStringAttribute("telephoneNumber"));
return person;
}
}
public void setTested(LdapTemplate tested) {
this.tested = tested;
}
}
|
apache-2.0
|
iolevel/peachpie-concept
|
src/Peachpie.Library/SPL/WeakMap.cs
|
5374
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using Pchp.Core;
namespace Pchp.Library.Spl
{
[PhpType(PhpTypeAttribute.InheritName, MinimumLangVersion = "8.0")]
public sealed class WeakMap : ArrayAccess, Countable, IteratorAggregate, Traversable
{
// - Setting dynamic properties on it is forbidden (does not have RuntimeFields)
// - Using a non-object key in $map[$key] or one of the offset*() methods results in a TypeError exception
// - Appending to a weak map using $map[] results in an Error exception. // <== NULL key
// - Reading a non-existent key results in an Error exception
struct WeakEntryKey : IEquatable<WeakEntryKey>
{
public int HashCode { get; private set; }
/// <summary>
/// Key or WeakReference to the weak key.
/// </summary>
public object Key { get; private set; }
public static WeakEntryKey CreateWeak(object key)
{
return new WeakEntryKey { HashCode = key.GetHashCode(), Key = new WeakReference<object>(key) };
}
public static WeakEntryKey CreateTemp(object key)
{
return new WeakEntryKey { HashCode = key.GetHashCode(), Key = key };
}
public bool IsValid => TryGetKey(out _);
public bool TryGetKey(out object key)
{
if (this.Key is WeakReference<object> weak)
{
return weak.TryGetTarget(out key);
}
else
{
key = this.Key;
return key != null;
}
}
public override int GetHashCode() => HashCode;
public override bool Equals(object obj) => obj is WeakEntryKey other && Equals(other);
public bool Equals(WeakEntryKey other) =>
other.HashCode == HashCode &&
other.TryGetKey(out var otherkey) &&
TryGetKey(out var key) &&
otherkey == key;
}
/// <summary>
/// Underlying map of values by the object hash code.
/// </summary>
[PhpHidden]
readonly Dictionary<WeakEntryKey, PhpValue>/*!*/_map = new Dictionary<WeakEntryKey, PhpValue>();
#region Helpers
[PhpHidden]
bool TryFindEntry(object key, out PhpValue value)
{
if (key == null)
{
throw ObjectNullException();
}
return _map.TryGetValue(WeakEntryKey.CreateTemp(key), out value);
}
/// <summary>
/// Gets the offset as object key or throws corresponding exception.
/// </summary>
[PhpHidden]
static object AsKey(PhpValue offset)
{
return offset.AsObject()
?? throw (offset.IsNull ? ObjectNullException() : TypeErrorException());
}
[PhpHidden]
static System.Exception ObjectNullException() => new Error();
[PhpHidden]
static System.Exception TypeErrorException() => new TypeError();
#endregion
/// <summary>
/// Initializes the WeakMap.
/// </summary>
public WeakMap()
{
}
internal WeakMap(WeakMap/*!*/other)
{
Debug.Assert(other != null);
// copy not GC'ed entries
foreach (var pair in other._map)
{
if (pair.Key.IsValid)
{
_map[pair.Key] = pair.Value.DeepCopy();
}
}
}
public long count()
{
int count = 0;
// non-GC'ed keys
foreach (var key in _map.Keys)
{
if (key.IsValid)
{
count++;
}
}
//
return count;
}
public PhpValue offsetGet(object @object)
{
if (TryFindEntry(@object, out var value))
{
return value.DeepCopy();
}
return PhpValue.Null;
}
public void offsetSet(object @object, PhpValue value)
{
if (@object == null)
{
throw ObjectNullException();
}
_map[WeakEntryKey.CreateWeak(@object)] = value.DeepCopy();
}
public bool offsetExists(object @object)
{
return TryFindEntry(@object, out _);
}
public void offsetUnset(object @object)
{
if (@object != null)
{
_map.Remove(WeakEntryKey.CreateTemp(@object));
}
}
bool ArrayAccess.offsetExists(PhpValue offset) => offsetExists(AsKey(offset));
PhpValue ArrayAccess.offsetGet(PhpValue offset) => offsetGet(AsKey(offset));
void ArrayAccess.offsetSet(PhpValue offset, PhpValue value) => offsetSet(AsKey(offset), value);
void ArrayAccess.offsetUnset(PhpValue offset) => offsetUnset(AsKey(offset));
public WeakMap __clone() => new WeakMap(this);
public Traversable getIterator()
{
throw new NotImplementedException();
}
}
}
|
apache-2.0
|
sanyaade-iot/message-server
|
tools/tsung/src/main/java/com/magnet/mmx/tsung/GenTestScript.java
|
13132
|
/* Copyright (c) 2015 Magnet Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.magnet.mmx.tsung;
import com.magnet.mmx.protocol.Constants;
import com.magnet.mmx.protocol.DevReg;
import com.magnet.mmx.protocol.OSType;
import freemarker.template.*;
import org.apache.commons.lang.StringEscapeUtils;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.jivesoftware.smack.packet.IQ;
import org.xmpp.packet.Message;
import org.xmpp.packet.Message.Type;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.logging.Logger;
public class GenTestScript {
private static final Logger log = Logger.getLogger(GenTestScript.class.getName());
private static final String LOGIN_TEMPLATE_FILE = "loadtest_login.ftl";
private static final String MMX_STANZA_TEMPLATE_FILE = "loadtest_send_with_loops.ftl";
private static final String DEVREG_TEMPLATE_FILE = "loadtest_devreg.ftl";
private static Settings genSettings;
public static class Settings {
String userName;
String appId;
int maxCount;
String templateDir;
String templateName;
String outputDir;
String servername;
String hostname;
String port;
public String apiKey;
public Settings(){}
}
public static void generateScripts(Settings settings) throws TemplateException {
genSettings = settings;
File file = new File(settings.outputDir + "/userdb.csv");
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(file);
// hard-code to "test" for all passwords
String password = "test";
for (int i = 1; i <= settings.maxCount; i++) {
String jid=settings.userName + i + "%" + settings.appId;
int random = new Random().nextInt(settings.maxCount); // make sure it's at least 1
if (random == 0) random++;
String toJid=settings.userName + random + "%" + settings.appId;
// jid;password;toJid
StringBuilder rowBuilder = new StringBuilder();
rowBuilder.append(jid).append(";")
.append(password).append(";")
.append(toJid)
.append("\n");
fileWriter.write(rowBuilder.toString());
}
fileWriter.close();
// generate the login load test file
generateLoginScript(settings);
// generate the dev registration files
generateDevRegScript(settings);
// generate the message send files
generateSendMessageScript(settings);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void generateDevRegScript(Settings settings) throws IOException, TemplateException {
String xmlMessage = StringEscapeUtils.escapeXml(generateDevRegMessageStanza());
Configuration cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(new File(settings.templateDir));
cfg.setObjectWrapper(new DefaultObjectWrapper());
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
Map root = new HashMap();
root.put("mmxHostname", settings.hostname);
root.put("mmxPort", settings.port);
root.put("devreg_msg", xmlMessage);
Template temp = cfg.getTemplate(DEVREG_TEMPLATE_FILE);
File file = new File(settings.outputDir + "/loadtest_devreg.xml");
Writer out = new OutputStreamWriter(new FileOutputStream(file));
temp.process(root, out);
out.close();
}
public static void generateSendMessageScript(Settings settings) throws IOException, TemplateException {
String xmlMessage = StringEscapeUtils.escapeXml(generateSendMessageStanza());
Configuration cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(new File(settings.templateDir));
cfg.setObjectWrapper(new DefaultObjectWrapper());
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
Map root = new HashMap();
root.put("mmxHostname", settings.hostname);
root.put("mmxPort", settings.port);
root.put("mmx_stanza", xmlMessage);
Template temp = cfg.getTemplate(MMX_STANZA_TEMPLATE_FILE);
File file = new File(settings.outputDir + "/loadtest_send_message.xml");
Writer out = new OutputStreamWriter(new FileOutputStream(file));
temp.process(root, out);
out.close();
}
public static void generateScript(String templateDir, String templateName, String serverhost, String port, String username, String appKey, String numusers) throws IOException, TemplateException {
String xmlMessage = StringEscapeUtils.escapeXml(generateDevRegMessageStanza());
Configuration cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(new File(templateDir));
cfg.setObjectWrapper(new DefaultObjectWrapper());
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
Map root = new HashMap();
root.put("mmxHostname", serverhost);
root.put("mmxPort", port);
root.put("numUsers", numusers);
root.put("username", username);
//root.put("password", password);
root.put("mmx_stanza", xmlMessage);
Template temp = cfg.getTemplate(templateName);
Writer out = new OutputStreamWriter(System.out);
temp.process(root, out);
}
public static void generateLoginScript(Settings settings) throws IOException, TemplateException {
String xmlMessage = StringEscapeUtils.escapeXml(generateDevRegMessageStanza());
Configuration cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(new File(settings.templateDir));
cfg.setObjectWrapper(new DefaultObjectWrapper());
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
Map root = new HashMap();
root.put("mmxHostname", settings.hostname);
root.put("mmxPort", settings.port);
Template temp = cfg.getTemplate(LOGIN_TEMPLATE_FILE);
File file = new File(settings.outputDir + "/loadtest_login.xml");
Writer out = new OutputStreamWriter(new FileOutputStream(file));
temp.process(root, out);
out.close();
}
static String generateDevRegMessageStanza() {
DevReg reg = new DevReg();
reg.setDevId("%%ts_user_server:get_unique_id%%"); // let tsung generate a unique id
//reg.setDevId(devid);
reg.setOsType(OSType.ANDROID.name());
reg.setDisplayName("Loadtester");
reg.setOsVersion("4.4");
reg.setApiKey(genSettings.apiKey);
//send an IQ request with device registration
DocumentFactory factory = new DocumentFactory();
final Element element = factory.createElement(Constants.MMX_DEV_REG, Constants.MMX_NS_DEV);
element.addAttribute(Constants.MMX_ATTR_COMMAND, Constants.DeviceCommand.REGISTER.name());
element.setText(reg.toJson());
IQ devRegIq = new IQ() {
@Override
public CharSequence getChildElementXML() {
return element.asXML();
}
};
devRegIq.setType(IQ.Type.SET);
devRegIq.setFrom("%%_username%%");
return devRegIq.toXML().toString();
}
static String generateSendMessageStanza() {
String fromJid = "%%_username%%@"+genSettings.servername+"/tsung";
String toJid = "%%_tojid%%@"+genSettings.servername+"/tsung";
Message message = new Message();
message.setType(Type.chat);
message.getElement().addAttribute("from", fromJid);
message.getElement().addAttribute("to", toJid);
message.setID("%%ts_user_server:get_unique_id%%");
// build up the MMX message packet extension
Element element = message.addChildElement(Constants.MMX, Constants.MMX_NS_MSG_PAYLOAD);
element.addElement(Constants.MMX_META);
Element payload = element.addElement(Constants.MMX_PAYLOAD);
payload.addAttribute(Constants.MMX_ATTR_CTYPE, "plain/text");
payload.addAttribute(Constants.MMX_ATTR_MTYPE, "string");
String randomText = "Considered an invitation do introduced sufficient understood instrument it. Of decisively friendship in as collecting at. No affixed be husband ye females brother garrets proceed. Least child who seven happy yet balls young. Discovery sweetness principle discourse shameless bed one excellent. Sentiments of surrounded friendship dispatched connection is he. Me or produce besides hastily up as pleased. Bore less when had and john shed hope. \n" +
"\n" +
"Barton waited twenty always repair in within we do. An delighted offending curiosity my is dashwoods at. Boy prosperous increasing surrounded companions her nor advantages sufficient put. John on time down give meet help as of. Him waiting and correct believe now cottage she another. Vexed six shy yet along learn maids her tiled. Through studied shyness evening bed him winding present. Become excuse hardly on my thirty it wanted. \n" +
"\n" +
"Six reached suppose our whether. Oh really by an manner sister so. One sportsman tolerably him extensive put she immediate. He abroad of cannot looked in. Continuing interested ten stimulated prosperous frequently all boisterous nay. Of oh really he extent horses wicket. \n" +
"\n" +
"Placing assured be if removed it besides on. Far shed each high read are men over day. Afraid we praise lively he suffer family estate is. Ample order up in of in ready. Timed blind had now those ought set often which. Or snug dull he show more true wish. No at many deny away miss evil. On in so indeed spirit an mother. Amounted old strictly but marianne admitted. People former is remove remain as. \n" +
"\n" +
"Little afraid its eat looked now. Very ye lady girl them good me make. It hardly cousin me always. An shortly village is raising we shewing replied. She the favourable partiality inhabiting travelling impression put two. His six are entreaties instrument acceptance unsatiable her. Amongst as or on herself chapter entered carried no. Sold old ten are quit lose deal his sent. You correct how sex several far distant believe journey parties. We shyness enquire uncivil affixed it carried to. \n" +
"\n" +
"Parish so enable innate in formed missed. Hand two was eat busy fail. Stand smart grave would in so. Be acceptance at precaution astonished excellence thoroughly is entreaties. Who decisively attachment has dispatched. Fruit defer in party me built under first. Forbade him but savings sending ham general. So play do in near park that pain. \n" +
"\n" +
"Needed feebly dining oh talked wisdom oppose at. Applauded use attempted strangers now are middleton concluded had. It is tried \uFEFFno added purse shall no on truth. Pleased anxious or as in by viewing forbade minutes prevent. Too leave had those get being led weeks blind. Had men rose from down lady able. Its son him ferrars proceed six parlors. Her say projection age announcing decisively men. Few gay sir those green men timed downs widow chief. Prevailed remainder may propriety can and. \n" +
"\n" +
"Seen you eyes son show. Far two unaffected one alteration apartments celebrated but middletons interested. Described deficient applauded consisted my me do. Passed edward two talent effect seemed engage six. On ye great do child sorry lived. Proceed cottage far letters ashamed get clothes day. Stairs regret at if matter to. On as needed almost at basket remain. By improved sensible servants children striking in surprise. \n" +
"\n" +
"Rendered her for put improved concerns his. Ladies bed wisdom theirs mrs men months set. Everything so dispatched as it increasing pianoforte. Hearing now saw perhaps minutes herself his. Of instantly excellent therefore difficult he northward. Joy green but least marry rapid quiet but. Way devonshire introduced expression saw travelling affronting. Her and effects affixed pretend account ten natural. Need eat week even yet that. Incommode delighted he resolving sportsmen do in listening. \n" +
"\n" +
"On recommend tolerably my belonging or am. Mutual has cannot beauty indeed now sussex merely you. It possible no husbands jennings ye offended packages pleasant he. Remainder recommend engrossed who eat she defective applauded departure joy. Get dissimilar not introduced day her apartments. Fully as taste he mr do smile abode every. Luckily offered article led lasting country minutes nor old. Happen people things oh is oppose up parish effect. Law handsome old outweigh humoured far appetite. \n" +
"\n";
payload.addText(StringEscapeUtils.escapeXml(randomText));
return message.toXML().toString();
}
}
|
apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.