code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php /** * The template for displaying all pages * * This is the template that displays all pages by default. * Please note that this is the WordPress construct of pages * and that other 'pages' on your WordPress site will use a * different template. * * @package WordPress * @subpackage demo * @since demo 1.0 */ // download file when client request do_action('download_file'); do_action('wp_ajax_load'); get_header(); ?> <div class="about-report-page"> <?php while ( have_posts() ) : the_post() ?> <?php do_action('wp_load_sub_menu')?> <?php the_content() ?> <?php endwhile; ?> </div> <?php get_footer(); ?>
trungkienpvt/wordpress
wp-content/themes/ecommerce/page-report.php
PHP
gpl-2.0
664
import { expect } from 'chai'; import isRequestingSiteConnectionStatus from 'calypso/state/selectors/is-requesting-site-connection-status'; describe( 'isRequestingSiteConnectionStatus()', () => { const siteId = 2916284; test( 'should return true if connection status is currently being requested for that site', () => { const state = { sites: { connection: { requesting: { [ siteId ]: true, }, }, }, }; const output = isRequestingSiteConnectionStatus( state, siteId ); expect( output ).to.be.true; } ); test( 'should return false if connection status is currently not being requested for that site', () => { const state = { sites: { connection: { requesting: { [ siteId ]: false, }, }, }, }; const output = isRequestingSiteConnectionStatus( state, siteId ); expect( output ).to.be.false; } ); test( 'should return false if connection status has never been requested for that site', () => { const state = { sites: { connection: { requesting: { 77203074: true, }, }, }, }; const output = isRequestingSiteConnectionStatus( state, siteId ); expect( output ).to.be.false; } ); } );
Automattic/wp-calypso
client/state/selectors/test/is-requesting-site-connection-status.js
JavaScript
gpl-2.0
1,202
#include "mainview.h" #include "scrollarea.h" #include <QSplitter> #include <QHBoxLayout> #include <QTextEdit> #include <QPushButton> MainView::MainView(QWidget *parent) : QWidget(parent), i(0) { QHBoxLayout *lay = new QHBoxLayout; QSplitter *splitter = new QSplitter; scrollArea = new ScrollArea; splitter->addWidget(scrollArea); QWidget *w = new QWidget; QVBoxLayout *vbox = new QVBoxLayout; QPushButton *addListWidget = new QPushButton("add list widget"); connect(addListWidget, SIGNAL(clicked(bool)), SLOT(slotAddListWidget())); vbox->addWidget(addListWidget); vbox->addWidget(new QTextEdit); w->setLayout(vbox); splitter->addWidget(w); lay->addWidget(splitter); setLayout(lay); resize(800,600); } void MainView::slotAddListWidget() { scrollArea->createItemList(QString::number(i)); i++; }
neurosuite/libneurosuite
test/mainview.cpp
C++
gpl-2.0
873
/** * DOCLink 1.5.x * @version $Id: hu.js 362 2007-09-26 19:19:03Z mjaz $ * @package DOCLink_1.5 * @copyright (C) 2003-2007 The DOCman Development Team * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * @link http://www.joomlatools.org/ Official website **/ /** * TRANSLATORS: * PLEASE CHANGE THE INFO BELOW * * Hungarian (formal) language file * * Creator: Jozsef Tamas Herczeg * Website: http://www.joomlandia.eu/ * E-mail: info@joomlandia.eu * Revision: 1.5 * Date: February 2007 **/ DOCLink.I18N = { "enterurl": "Be kell írnia az URL-t", "entercaption": "Írja be a felirat szövegét", "loading": "Fájlok betöltése", "OK": "OK", "Cancel": "Mégse", "Refresh": "Frissítés" };
thinkcollege/tc-code
plugins/editors-xtd/doclink/lang/hu.js
JavaScript
gpl-2.0
763
define(['datetime', 'focusManager'], function (datetime, focusManager) { return function (options) { var self = this; var lastFocus = 0; self.refresh = function () { reloadPage(options.element); }; // 30 mins var cellCurationMinutes = 30; var cellDurationMs = cellCurationMinutes * 60 * 1000; var msPerDay = 86400000; var currentDate; var defaultChannels = 50; var channelLimit = 1000; var channelQuery = { StartIndex: 0, Limit: defaultChannels, EnableFavoriteSorting: true }; var channelsPromise; function normalizeDateToTimeslot(date) { var minutesOffset = date.getMinutes() - cellCurationMinutes; if (minutesOffset >= 0) { date.setHours(date.getHours(), cellCurationMinutes, 0, 0); } else { date.setHours(date.getHours(), 0, 0, 0); } return date; } function reloadChannels(page) { channelsPromise = null; reloadGuide(page); } function showLoading() { } function hideLoading() { } function reloadGuide(page, newStartDate) { showLoading(); require(['connectionManager'], function (connectionManager) { var apiClient = connectionManager.currentApiClient(); channelQuery.UserId = apiClient.getCurrentUserId(); channelQuery.Limit = Math.min(channelQuery.Limit || defaultChannels, channelLimit); channelQuery.AddCurrentProgram = false; channelsPromise = channelsPromise || apiClient.getLiveTvChannels(channelQuery); var date = newStartDate; // Add one second to avoid getting programs that are just ending date = new Date(date.getTime() + 1000); // Subtract to avoid getting programs that are starting when the grid ends var nextDay = new Date(date.getTime() + msPerDay - 2000); console.log(nextDay); channelsPromise.done(function (channelsResult) { apiClient.getLiveTvPrograms({ UserId: apiClient.getCurrentUserId(), MaxStartDate: nextDay.toISOString(), MinEndDate: date.toISOString(), channelIds: channelsResult.Items.map(function (c) { return c.Id; }).join(','), ImageTypeLimit: 1, EnableImageTypes: "Primary", SortBy: "StartDate" }).done(function (programsResult) { renderGuide(page, date, channelsResult.Items, programsResult.Items, apiClient); hideLoading(); }); }); }); } function getDisplayTime(date) { if ((typeof date).toString().toLowerCase() === 'string') { try { date = datetime.parseISO8601Date(date, { toLocal: true }); } catch (err) { return date; } } var lower = date.toLocaleTimeString().toLowerCase(); var hours = date.getHours(); var minutes = date.getMinutes(); var text; if (lower.indexOf('am') != -1 || lower.indexOf('pm') != -1) { var suffix = hours > 11 ? 'pm' : 'am'; hours = (hours % 12) || 12; text = hours; if (minutes) { text += ':'; if (minutes < 10) { text += '0'; } text += minutes; } text += suffix; } else { text = hours + ':'; if (minutes < 10) { text += '0'; } text += minutes; } return text; } function getTimeslotHeadersHtml(startDate, endDateTime) { var html = ''; // clone startDate = new Date(startDate.getTime()); html += '<div class="timeslotHeadersInner">'; while (startDate.getTime() < endDateTime) { html += '<div class="timeslotHeader">'; html += getDisplayTime(startDate); html += '</div>'; // Add 30 mins startDate.setTime(startDate.getTime() + cellDurationMs); } html += '</div>'; return html; } function parseDates(program) { if (!program.StartDateLocal) { try { program.StartDateLocal = datetime.parseISO8601Date(program.StartDate, { toLocal: true }); } catch (err) { } } if (!program.EndDateLocal) { try { program.EndDateLocal = datetime.parseISO8601Date(program.EndDate, { toLocal: true }); } catch (err) { } } return null; } function getChannelProgramsHtml(page, date, channel, programs) { var html = ''; var startMs = date.getTime(); var endMs = startMs + msPerDay - 1; programs = programs.filter(function (curr) { return curr.ChannelId == channel.Id; }); html += '<div class="channelPrograms">'; for (var i = 0, length = programs.length; i < length; i++) { var program = programs[i]; if (program.ChannelId != channel.Id) { continue; } parseDates(program); if (program.EndDateLocal.getTime() < startMs) { continue; } if (program.StartDateLocal.getTime() > endMs) { break; } var renderStartMs = Math.max(program.StartDateLocal.getTime(), startMs); var startPercent = (program.StartDateLocal.getTime() - startMs) / msPerDay; startPercent *= 100; startPercent = Math.max(startPercent, 0); var renderEndMs = Math.min(program.EndDateLocal.getTime(), endMs); var endPercent = (renderEndMs - renderStartMs) / msPerDay; endPercent *= 100; var cssClass = "programCell clearButton itemAction"; var addAccent = true; if (program.IsKids) { cssClass += " childProgramInfo"; } else if (program.IsSports) { cssClass += " sportsProgramInfo"; } else if (program.IsNews) { cssClass += " newsProgramInfo"; } else if (program.IsMovie) { cssClass += " movieProgramInfo"; } else { cssClass += " plainProgramInfo"; addAccent = false; } html += '<button data-action="link" data-isfolder="' + program.IsFolder + '" data-id="' + program.Id + '" data-type="' + program.Type + '" class="' + cssClass + '" style="left:' + startPercent + '%;width:' + endPercent + '%;">'; var guideProgramNameClass = "guideProgramName"; html += '<div class="' + guideProgramNameClass + '">'; html += program.Name; html += '</div>'; if (program.IsHD) { html += '<iron-icon icon="hd"></iron-icon>'; } //html += '<div class="guideProgramTime">'; //if (program.IsLive) { // html += '<span class="liveTvProgram">' + Globalize.translate('LabelLiveProgram') + '&nbsp;&nbsp;</span>'; //} //else if (program.IsPremiere) { // html += '<span class="premiereTvProgram">' + Globalize.translate('LabelPremiereProgram') + '&nbsp;&nbsp;</span>'; //} //else if (program.IsSeries && !program.IsRepeat) { // html += '<span class="newTvProgram">' + Globalize.translate('LabelNewProgram') + '&nbsp;&nbsp;</span>'; //} //html += getDisplayTime(program.StartDateLocal); //html += ' - '; //html += getDisplayTime(program.EndDateLocal); //if (program.SeriesTimerId) { // html += '<div class="timerCircle seriesTimerCircle"></div>'; // html += '<div class="timerCircle seriesTimerCircle"></div>'; // html += '<div class="timerCircle seriesTimerCircle"></div>'; //} //else if (program.TimerId) { // html += '<div class="timerCircle"></div>'; //} //html += '</div>'; if (addAccent) { html += '<div class="programAccent"></div>'; } html += '</button>'; } html += '</div>'; return html; } function renderPrograms(page, date, channels, programs) { var html = []; for (var i = 0, length = channels.length; i < length; i++) { html.push(getChannelProgramsHtml(page, date, channels[i], programs)); } var programGrid = page.querySelector('.programGrid'); programGrid.innerHTML = html.join(''); programGrid.scrollTop = 0; programGrid.scrollLeft = 0; } function renderChannelHeaders(page, channels, apiClient) { var html = ''; for (var i = 0, length = channels.length; i < length; i++) { var channel = channels[i]; html += '<button type="button" class="channelHeaderCell clearButton itemAction" data-action="link" data-isfolder="' + channel.IsFolder + '" data-id="' + channel.Id + '" data-type="' + channel.Type + '">'; var hasChannelImage = channel.ImageTags.Primary; var cssClass = hasChannelImage ? 'guideChannelInfo guideChannelInfoWithImage' : 'guideChannelInfo'; html += '<div class="' + cssClass + '">' + channel.Number + '</div>'; if (hasChannelImage) { var url = apiClient.getScaledImageUrl(channel.Id, { maxHeight: 40, maxWidth: 80, tag: channel.ImageTags.Primary, type: "Primary" }); html += '<div class="guideChannelImage lazy" data-src="' + url + '"></div>'; } html += '</button>'; } var channelList = page.querySelector('.channelList'); channelList.innerHTML = html; Emby.ImageLoader.lazyChildren(channelList); } function renderGuide(page, date, channels, programs, apiClient) { renderChannelHeaders(page, channels, apiClient); var startDate = date; var endDate = new Date(startDate.getTime() + msPerDay); page.querySelector('.timeslotHeaders').innerHTML = getTimeslotHeadersHtml(startDate, endDate); renderPrograms(page, date, channels, programs); focusManager.autoFocus(page.querySelector('.programGrid'), true); } var gridScrolling = false; var headersScrolling = false; function onProgramGridScroll(page, elem) { if (!headersScrolling) { gridScrolling = true; $(page.querySelector('.timeslotHeaders')).scrollLeft($(elem).scrollLeft()); gridScrolling = false; } } function onTimeslotHeadersScroll(page, elem) { if (!gridScrolling) { headersScrolling = true; $(page.querySelector('.programGrid')).scrollLeft($(elem).scrollLeft()); headersScrolling = false; } } function getFutureDateText(date) { var weekday = []; weekday[0] = Globalize.translate('OptionSundayShort'); weekday[1] = Globalize.translate('OptionMondayShort'); weekday[2] = Globalize.translate('OptionTuesdayShort'); weekday[3] = Globalize.translate('OptionWednesdayShort'); weekday[4] = Globalize.translate('OptionThursdayShort'); weekday[5] = Globalize.translate('OptionFridayShort'); weekday[6] = Globalize.translate('OptionSaturdayShort'); var day = weekday[date.getDay()]; date = date.toLocaleDateString(); if (date.toLowerCase().indexOf(day.toLowerCase()) == -1) { return day + " " + date; } return date; } function changeDate(page, date) { var newStartDate = normalizeDateToTimeslot(date); currentDate = newStartDate; reloadGuide(page, newStartDate); var text = getFutureDateText(date); text = '<span class="currentDay">' + text.replace(' ', ' </span>'); page.querySelector('.btnSelectDate').innerHTML = text; } var dateOptions = []; function setDateRange(page, guideInfo) { var today = new Date(); today.setHours(today.getHours(), 0, 0, 0); var start = datetime.parseISO8601Date(guideInfo.StartDate, { toLocal: true }); var end = datetime.parseISO8601Date(guideInfo.EndDate, { toLocal: true }); start.setHours(0, 0, 0, 0); end.setHours(0, 0, 0, 0); if (start.getTime() >= end.getTime()) { end.setDate(start.getDate() + 1); } start = new Date(Math.max(today, start)); dateOptions = []; while (start <= end) { dateOptions.push({ name: getFutureDateText(start), id: start.getTime() }); start.setDate(start.getDate() + 1); start.setHours(0, 0, 0, 0); } var date = new Date(); if (currentDate) { date.setTime(currentDate.getTime()); } changeDate(page, date); } function reloadPageAfterValidation(page, limit) { channelLimit = limit; require(['connectionManager'], function (connectionManager) { var apiClient = connectionManager.currentApiClient(); apiClient.getLiveTvGuideInfo().done(function (guideInfo) { setDateRange(page, guideInfo); }); }); } function reloadPage(page) { showLoading(); reloadPageAfterValidation(page, 1000); } function selectDate(page) { require(['actionsheet'], function (actionsheet) { actionsheet.show({ items: dateOptions, title: Globalize.translate('HeaderSelectDate'), callback: function (id) { var date = new Date(); date.setTime(parseInt(id)); changeDate(page, date); } }); }); } function createVerticalScroller(view, pageInstance) { require(["slyScroller", 'loading'], function (slyScroller, loading) { var scrollFrame = view.querySelector('.scrollFrameY'); var scrollSlider = view.querySelector('.scrollSliderY'); var options = { horizontal: 0, itemNav: 0, mouseDragging: 1, touchDragging: 1, slidee: scrollSlider, itemSelector: '.card', smart: true, easing: 'swing', releaseSwing: true, scrollBar: view.querySelector('.scrollbarY'), scrollBy: 200, speed: 300, dragHandle: 1, dynamicHandle: 1, clickBar: 1 }; slyScroller.create(scrollFrame, options).then(function (slyFrame) { pageInstance.verticalSlyFrame = slyFrame; slyFrame.init(); initFocusHandler(view, scrollSlider, slyFrame); createHorizontalScroller(view, pageInstance); }); }); } function initFocusHandler(view, scrollSlider, slyFrame) { scrollSlider.addEventListener('focus', function (e) { var focused = focusManager.focusableParent(e.target); if (focused) { var now = new Date().getTime(); var threshold = 50; var animate = (now - lastFocus) > threshold; slyFrame.toCenter(focused, !animate); lastFocus = now; } }, true); } function createHorizontalScroller(view, pageInstance) { require(["slyScroller", 'loading'], function (slyScroller, loading) { var scrollFrame = view.querySelector('.scrollFrameX'); var scrollSlider = view.querySelector('.scrollSliderX'); var options = { horizontal: 1, itemNav: 0, mouseDragging: 0, touchDragging: 0, slidee: scrollSlider, itemSelector: '.card', smart: true, easing: 'swing', releaseSwing: true, scrollBy: 200, speed: 300, dragHandle: 0, dynamicHandle: 0, clickBar: 0 }; slyScroller.create(scrollFrame, options).then(function (slyFrame) { pageInstance.horizontallyFrame = slyFrame; slyFrame.init(); initFocusHandler(view, scrollSlider, slyFrame); }); }); } fetch(Emby.Page.baseUrl() + '/components/tvguide/tvguide.template.html', { mode: 'no-cors' }).then(function (response) { return response.text(); }).then(function (template) { var tabContent = options.element; tabContent.innerHTML = template; var programGrid = tabContent.querySelector('.programGrid'); programGrid.addEventListener('scroll', function () { onProgramGridScroll(tabContent, this); }); var isMobile = false; if (isMobile) { //tabContent.querySelector('.tvGuide').classList.add('mobileGuide'); } else { //tabContent.querySelector('.tvGuide').classList.remove('mobileGuide'); tabContent.querySelector('.timeslotHeaders').addEventListener('scroll', function () { onTimeslotHeadersScroll(tabContent, this); }); } tabContent.querySelector('.btnSelectDate').addEventListener('click', function () { selectDate(tabContent); }); createVerticalScroller(tabContent, self); self.refresh(); }); }; });
JfelixStudio/Polflix
components/tvguide/guide.js
JavaScript
gpl-2.0
20,046
<?php /* ** Zabbix ** Copyright (C) 2001-2018 Zabbix SIA ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **/ /** * A helper class for generating HTML snippets. */ class CViewHelper { /** * Generates </a>&nbsp;<sup>num</sup>" to be used in tables. Null is returned if equal to zero. * * @static * * @param integer $num * * @return mixed */ public static function showNum($num) { if ($num == 0) { return null; } return [SPACE, new CSup($num)]; } }
zyongqing/okp
frontends/php/include/classes/helpers/CViewHelper.php
PHP
gpl-2.0
1,153
/* Jquery Validation using jqBootstrapValidation example is taken from jqBootstrapValidation docs */ $(function() { $("input,textarea").jqBootstrapValidation({ preventSubmit: true, submitError: function($form, event, errors) { // something to have when submit produces an error ? // Not decided if I need it yet }, submitSuccess: function($form, event) { event.preventDefault(); // prevent default submit behaviour // get values from FORM var name = $("input#name").val(); var phone = $("input#phone").val(); var email = $("input#email").val(); var message = $("textarea#message").val(); var firstName = name; // For Success/Failure Message // Check for white space in name for Success/Fail message if (firstName.indexOf(' ') >= 0) { firstName = name.split(' ').slice(0, -1).join(' '); } $.ajax({ url: "./bin/contact_me.php", type: "POST", data: { name: name, phone: phone, email: email, message: message }, cache: false, success: function() { // Success message $('#success').php("<div class='alert alert-success'>"); $('#success > .alert-success').php("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;") .append("</button>"); $('#success > .alert-success') .append("<strong>Your message has been sent. </strong>"); $('#success > .alert-success') .append('</div>'); //clear all fields $('#contactForm').trigger("reset"); }, error: function() { // Fail message $('#success').php("<div class='alert alert-danger'>"); $('#success > .alert-danger').php("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;") .append("</button>"); $('#success > .alert-danger').append("<strong>Sorry " + firstName + " it seems that my mail server is not responding...</strong> Could you please email me directly to <a href='mailto:me@example.com?Subject=Message_Me from myprogrammingblog.com;>me@example.com</a> ? Sorry for the inconvenience!"); $('#success > .alert-danger').append('</div>'); //clear all fields $('#contactForm').trigger("reset"); }, }) }, filter: function() { return $(this).is(":visible"); }, }); $("a[data-toggle=\"tab\"]").click(function(e) { e.preventDefault(); $(this).tab("show"); }); }); /*When clicking on Full hide fail/success boxes */ $('#name').focus(function() { $('#success').php(''); });
tejdeeps/tejcs.com
l4sure/js/contact_me.js
JavaScript
gpl-2.0
3,169
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Util; import dto.PermisoDTO; import dto.UsuarioDTO; import java.io.IOException; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import org.primefaces.context.RequestContext; @ManagedBean @SessionScoped public class Utils { public void logOut(){ FacesContext.getCurrentInstance().getExternalContext().invalidateSession(); FacesContext.getCurrentInstance().getExternalContext().invalidateSession(); try { FacesContext.getCurrentInstance().getExternalContext().redirect("login.xhtml"); } catch (IOException ex) { } } public void mostrarNotificacion(RequestContext req, String mensaje, int tiempo){ req.execute("Materialize.toast('"+mensaje+"', "+tiempo+")"); } }
jorgeevj/SICOTEC
sicotec-war/src/java/Util/Utils.java
Java
gpl-2.0
1,048
// Note that this configuration is used by Webpack (babel-loader) and Jest module.exports = { presets: [ "@babel/preset-react", "@babel/preset-env" ] };
php-coder/mystamps
src/main/frontend/babel.config.js
JavaScript
gpl-2.0
154
package com.gravityrd.receng.web.webshop.jsondto; import com.gravityrd.receng.web.webshop.jsondto.facet.FacetResponse; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import java.util.Arrays; import java.util.Map; /** * The list of items recommended to a user. */ @SuppressWarnings({ "WeakerAccess", "unused" }) @JsonIgnoreProperties(ignoreUnknown = true) public class GravityItemRecommendation { /** * The recommendationId is generated by the recommendation engine. See {@link GravityEvent#recommendationId }. */ public String recommendationId; /** * The list of items. This is populated only if the scenario specifies to do so, otherwise this is null. * The items in this list only have the NameValues specified by the scenario. * The list of NameValues specified by the scenario can be overridden by the {@link GravityRecommendationContext#resultNameValues } on a per request basis. */ public GravityItem[] items; /** * The identifiers of the recommended items. */ public String[] itemIds; /** * The prediction values of the recommended items. */ public double[] predictionValues; /** * Requested meta information for the recommended items. */ public GravityNameValue[] outputNameValues; /** * Facet information for the recommendation request. */ @JsonInclude(JsonInclude.Include.NON_EMPTY) public Map<String, FacetResponse> facets; /** * How many recommendations were in the facet set. */ @JsonInclude(JsonInclude.Include.NON_EMPTY) public Long totalResults; /** * Gravity server side recommendation time. */ @JsonInclude(JsonInclude.Include.NON_EMPTY) public Long took; @Override public String toString() { final StringBuilder sb = new StringBuilder("GravityItemRecommendation{"); sb.append("recommendationId='").append(recommendationId).append('\''); if (items != null && items.length > 0) sb.append(", items=").append(Arrays.toString(items)); if (itemIds != null && itemIds.length > 0) sb.append(", itemIds=").append(Arrays.toString(itemIds)); if (predictionValues != null && predictionValues.length > 0) sb.append(", predictionValues=").append(Arrays.toString(predictionValues)); if (outputNameValues != null && outputNameValues.length > 0) sb.append(", outputNameValues=").append(Arrays.toString(outputNameValues)); if (facets != null && !facets.isEmpty()) sb.append(", facets=").append(facets); if (totalResults != null) sb.append(", totalResults=").append(totalResults); if (took != null) sb.append(", took=").append(took); sb.append('}'); return sb.toString(); } @JsonIgnore @SuppressWarnings("unchecked") public <F extends FacetResponse> F getFacet(String name) { return (F) facets.get(name); } }
gravityrd/jsondto
src/main/java/com/gravityrd/receng/web/webshop/jsondto/GravityItemRecommendation.java
Java
gpl-2.0
2,832
package com.ryanprintup.sample; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
RyanPrintup/EasyNavDrawer
sample/src/androidTest/java/com/ryanprintup/sample/ApplicationTest.java
Java
gpl-2.0
342
/* Copyright 2013 Brett Story and Kyle Falconer 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. */ #include "display.h" display::display() { initRenders(); } void display::initRenders() { cout << "loading scenes..."<<endl; sceneObjects[0][0].Load("scenes/0home/couch"); sceneObjects[0][1].Load("scenes/0home/floor"); sceneObjects[0][2].Load("scenes/0home/walls"); sceneObjects[0][3].Load("scenes/0home/ceiling"); sceneObjects[0][4].Load("scenes/0home/trim"); sceneObjects[0][5].Load("scenes/0home/tv01"); sceneObjects[0][6].Load("scenes/0home/tv02"); sceneObjects[0][7].Load("scenes/0home/tv03"); sceneObjects[0][8].Load("scenes/0home/tvstand"); sceneObjects[1][0].Load("scenes/4window/leaves"); sceneObjects[1][1].Load("scenes/4window/exterior"); sceneObjects[1][2].Load("scenes/4window/trees"); sceneObjects[1][3].Load("scenes/4window/windows"); sceneObjects[1][4].Load("scenes/4window/lamppost"); sceneObjects[1][5].Load("scenes/4window/ground"); sceneObjects[2][0].Load("scenes/2secretary/brown"); sceneObjects[2][1].Load("scenes/2secretary/black"); sceneObjects[2][2].Load("scenes/2secretary/grey"); sceneObjects[2][3].Load("scenes/2secretary/floor"); sceneObjects[2][4].Load("scenes/2secretary/walls"); sceneObjects[3][0].Load("scenes/3humanresources/blue"); sceneObjects[3][1].Load("scenes/3humanresources/black"); sceneObjects[3][2].Load("scenes/3humanresources/grey"); sceneObjects[3][3].Load("scenes/3humanresources/walls"); sceneObjects[5][0].Load("scenes/5secondfloor/brown"); sceneObjects[5][1].Load("scenes/5secondfloor/green"); sceneObjects[5][2].Load("scenes/5secondfloor/grey"); sceneObjects[5][3].Load("scenes/5secondfloor/yellow"); sceneObjects[6][0].Load("scenes/6foodcourt/brown"); sceneObjects[6][1].Load("scenes/6foodcourt/black"); sceneObjects[6][2].Load("scenes/6foodcourt/grey"); sceneObjects[6][3].Load("scenes/6foodcourt/red"); sceneObjects[6][4].Load("scenes/6foodcourt/white"); sceneObjects[7][0].Load("scenes/7stairs/stairs"); sceneObjects[7][1].Load("scenes/7stairs/floors"); sceneObjects[7][2].Load("scenes/7stairs/railings"); sceneObjects[7][3].Load("scenes/7stairs/walls"); sceneObjects[8][0].Load("scenes/8thirdfloor/black"); sceneObjects[8][1].Load("scenes/8thirdfloor/brown"); sceneObjects[8][2].Load("scenes/8thirdfloor/floor"); sceneObjects[8][3].Load("scenes/8thirdfloor/white"); sceneObjects[9][0].Load("scenes/9desk/black"); sceneObjects[9][1].Load("scenes/9desk/blue"); sceneObjects[9][2].Load("scenes/9desk/brown"); sceneObjects[9][3].Load("scenes/9desk/grey"); sceneObjects[9][4].Load("scenes/9desk/white"); } //Desk void display::render9() { gluLookAt(2.5,2,-2, 0,1.5,0, 0,1,0); glPushMatrix(); glTranslatef(0,0,0); glScalef(0.25, 0.25, 0.25); sceneObjects[9][0].Draw(); sceneObjects[9][1].Draw(); sceneObjects[9][2].Draw(); sceneObjects[9][3].Draw(); sceneObjects[9][4].Draw(); } //Third floor void display::render8() { gluLookAt(2.3,1.0,-0.2, 0,0,0, 0,1,0); glPushMatrix(); glTranslatef(0,0,0); glScalef(0.25, 0.25, 0.25); sceneObjects[8][0].Draw(); sceneObjects[8][1].Draw(); sceneObjects[8][2].Draw(); sceneObjects[8][3].Draw(); } // Stairs void display::render7() { gluLookAt(1,3,0.5, -3,0,0, 0,1,0); glPushMatrix(); glTranslatef(0,0,0); glScalef(0.25, 0.25, 0.25); sceneObjects[7][0].Draw(); sceneObjects[7][1].Draw(); sceneObjects[7][2].Draw(); sceneObjects[7][3].Draw(); } // Food Court void display::render6() { gluLookAt(3,1,-1, 0,.5,-0.5, 0,1,0); glPushMatrix(); glTranslatef(0,0,0); glScalef(0.25, 0.25, 0.25); sceneObjects[6][0].Draw(); sceneObjects[6][1].Draw(); sceneObjects[6][2].Draw(); sceneObjects[6][3].Draw(); sceneObjects[6][4].Draw(); } // Second floor void display::render5() { gluLookAt(4,5,-2, 0,4,-1, 0,1,0); glPushMatrix(); glTranslatef(0,0,0); glScalef(0.25, 0.25, 0.25); sceneObjects[5][0].Draw(); sceneObjects[5][1].Draw(); sceneObjects[5][2].Draw(); sceneObjects[5][3].Draw(); } // Window void display::render4() { glClearColor(0.2, 0.4, 0.8, 1); gluLookAt(2,1,0, 1,1.5,2, 0,1,0); glPushMatrix(); glTranslatef(0,0,0); glScalef(0.25, 0.25, 0.25); sceneObjects[1][0].Draw(); sceneObjects[1][1].Draw(); sceneObjects[1][2].Draw(); sceneObjects[1][3].Draw(); sceneObjects[1][4].Draw(); sceneObjects[1][5].Draw(); } // Human resources void display::render3() { gluLookAt(1,1.25,1, 0,1.1,.5, 0,1,0); glPushMatrix(); glTranslatef(0,0,0); glScalef(0.25, 0.25, 0.25); sceneObjects[3][0].Draw(); sceneObjects[3][1].Draw(); sceneObjects[3][2].Draw(); sceneObjects[3][3].Draw(); } // Secretary void display::render2() { gluLookAt(-1.5,1.1,-1, -1,.5,1, 0,1,0); glPushMatrix(); glTranslatef(0,0,0); glScalef(0.25, 0.25, 0.25); sceneObjects[2][0].Draw(); sceneObjects[2][1].Draw(); sceneObjects[2][2].Draw(); sceneObjects[2][3].Draw(); sceneObjects[2][4].Draw(); } // Doors void display::render1() { glClearColor(0.2, 0.4, 0.8, 1); gluLookAt(.5,0.25,1.5, 2,0,1, 0,1,0); glPushMatrix(); glTranslatef(0,0,0); glScalef(0.25, 0.25, 0.25); sceneObjects[1][0].Draw(); sceneObjects[1][1].Draw(); sceneObjects[1][2].Draw(); sceneObjects[1][3].Draw(); sceneObjects[1][4].Draw(); sceneObjects[1][5].Draw(); } // Home void display::render0() { gluLookAt(4,3,0, 0,2,0, 0,1,0); glPushMatrix(); glTranslatef(0,0,0); glScalef(0.25, 0.25, 0.25); sceneObjects[0][0].Draw(); sceneObjects[0][1].Draw(); sceneObjects[0][2].Draw(); sceneObjects[0][3].Draw(); sceneObjects[0][4].Draw(); sceneObjects[0][5].Draw(); sceneObjects[0][6].Draw(); sceneObjects[0][7].Draw(); sceneObjects[0][8].Draw(); }
netinept/CSC-525-Computer-Graphics
project/Project/Project/display.cpp
C++
gpl-2.0
6,258
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2007-2008 Brian G. Matherly # Copyright (C) 2009 Gary Burton # Contribution 2009 by Reinhard Mueller <reinhard.mueller@bytewise.at> # Copyright (C) 2010 Jakim Friant # Copyright (C) 2013-2014 Paul Franklin # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # """Reports/Text Reports/Kinship Report""" #------------------------------------------------------------------------ # # python modules # #------------------------------------------------------------------------ #------------------------------------------------------------------------ # # gramps modules # #------------------------------------------------------------------------ from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext from gramps.gen.errors import ReportError from gramps.gen.relationship import get_relationship_calculator from gramps.gen.plug.docgen import (IndexMark, FontStyle, ParagraphStyle, FONT_SANS_SERIF, INDEX_TYPE_TOC, PARA_ALIGN_CENTER) from gramps.gen.plug.menu import NumberOption, BooleanOption, PersonOption from gramps.gen.plug.report import Report from gramps.gen.plug.report import utils as ReportUtils from gramps.gen.plug.report import MenuReportOptions from gramps.gen.plug.report import stdoptions from gramps.gen.utils.db import get_birth_or_fallback, get_death_or_fallback #------------------------------------------------------------------------ # # KinshipReport # #------------------------------------------------------------------------ class KinshipReport(Report): def __init__(self, database, options, user): """ Create the KinshipReport object that produces the report. The arguments are: database - the GRAMPS database instance options - instance of the Options class for this report user - a gen.user.User() instance This report needs the following parameters (class variables) that come in the options class. maxdescend - Maximum generations of descendants to include. maxascend - Maximum generations of ancestors to include. incspouses - Whether to include spouses. inccousins - Whether to include cousins. incaunts - Whether to include aunts/uncles/nephews/nieces. pid - The Gramps ID of the center person for the report. name_format - Preferred format to display names incl_private - Whether to include private data """ Report.__init__(self, database, options, user) menu = options.menu stdoptions.run_private_data_option(self, menu) self.__db = self.database self.max_descend = menu.get_option_by_name('maxdescend').get_value() self.max_ascend = menu.get_option_by_name('maxascend').get_value() self.inc_spouses = menu.get_option_by_name('incspouses').get_value() self.inc_cousins = menu.get_option_by_name('inccousins').get_value() self.inc_aunts = menu.get_option_by_name('incaunts').get_value() pid = menu.get_option_by_name('pid').get_value() self.person = self.database.get_person_from_gramps_id(pid) if (self.person == None) : raise ReportError(_("Person %s is not in the Database") % pid ) rlocale = self.set_locale(menu.get_option_by_name('trans').get_value()) stdoptions.run_name_format_option(self, menu) self.rel_calc = get_relationship_calculator(reinit=True, clocale=rlocale) self.kinship_map = {} self.spouse_map = {} def write_report(self): """ The routine the actually creates the report. At this point, the document is opened and ready for writing. """ pname = self._name_display.display(self.person) self.doc.start_paragraph("KIN-Title") # feature request 2356: avoid genitive form title = self._("Kinship Report for %s") % pname mark = IndexMark(title, INDEX_TYPE_TOC, 1) self.doc.write_text(title, mark) self.doc.end_paragraph() if self.inc_spouses: spouse_handles = self.get_spouse_handles(self.person.get_handle()) if spouse_handles: self.write_people(self._("Spouses"), spouse_handles) # Collect all descendants of the person self.traverse_down(self.person.get_handle(), 0, 1) # Collect all ancestors/aunts/uncles/nephews/cousins of the person self.traverse_up(self.person.get_handle(), 1, 0) # Write Kin for Ga, Gbs in self.kinship_map.items(): for Gb in Gbs: # To understand these calculations, see: # http://en.wikipedia.org/wiki/Cousin#Mathematical_definitions x = min (Ga, Gb) y = abs(Ga-Gb) # Skip unrequested people if x == 1 and y > 0 and not self.inc_aunts: continue elif x > 1 and not self.inc_cousins: continue get_rel_str = self.rel_calc.get_plural_relationship_string title = get_rel_str(Ga, Gb, in_law_b=False) self.write_people(self._(title), self.kinship_map[Ga][Gb]) if (self.inc_spouses and Ga in self.spouse_map and Gb in self.spouse_map[Ga]): title = get_rel_str(Ga, Gb, in_law_b=True) self.write_people(self._(title), self.spouse_map[Ga][Gb]) def traverse_down(self, person_handle, Ga, Gb, skip_handle=None): """ Populate a map of arrays containing person handles for the descendants of the passed person. This function calls itself recursively until it reaches max_descend. Parameters: person_handle: the handle of the person to go to next Ga: The number of generations from the main person to the common ancestor. This should be incremented when going up generations, and left alone when going down generations. Gb: The number of generations from this person (person_handle) to the common ancestor. This should be incremented when going down generations and set back to zero when going up generations. skip_handle: an optional handle to skip when going down. This is useful to skip the descendant that brought you this generation in the first place. """ for child_handle in self.get_children_handles(person_handle): if child_handle != skip_handle: self.add_kin(child_handle, Ga, Gb) if self.inc_spouses: for spouse_handle in self.get_spouse_handles(child_handle): self.add_spouse(spouse_handle, Ga, Gb) if Gb < self.max_descend: self.traverse_down(child_handle, Ga, Gb+1) def traverse_up(self, person_handle, Ga, Gb): """ Populate a map of arrays containing person handles for the ancestors of the passed person. This function calls itself recursively until it reaches max_ascend. Parameters: person_handle: the handle of the person to go to next Ga: The number of generations from the main person to the common ancestor. This should be incremented when going up generations, and left alone when going down generations. Gb: The number of generations from this person (person_handle) to the common ancestor. This should be incremented when going down generations and set back to zero when going up generations. """ parent_handles = self.get_parent_handles(person_handle) for parent_handle in parent_handles: self.add_kin(parent_handle, Ga, Gb) self.traverse_down(parent_handle, Ga, Gb+1, person_handle) if Ga < self.max_ascend: self.traverse_up(parent_handle, Ga+1, 0) def add_kin(self, person_handle, Ga, Gb): """ Add a person handle to the kin map. """ if Ga not in self.kinship_map: self.kinship_map[Ga] = {} if Gb not in self.kinship_map[Ga]: self.kinship_map[Ga][Gb] = [] if person_handle not in self.kinship_map[Ga][Gb]: self.kinship_map[Ga][Gb].append(person_handle) def add_spouse(self, spouse_handle, Ga, Gb): """ Add a person handle to the spouse map. """ if Ga not in self.spouse_map: self.spouse_map[Ga] = {} if Gb not in self.spouse_map[Ga]: self.spouse_map[Ga][Gb] = [] if spouse_handle not in self.spouse_map[Ga][Gb]: self.spouse_map[Ga][Gb].append(spouse_handle) def get_parent_handles(self, person_handle): """ Return an array of handles for all the parents of the given person handle. """ parent_handles = [] person = self.__db.get_person_from_handle(person_handle) family_handle = person.get_main_parents_family_handle() if family_handle: family = self.__db.get_family_from_handle(family_handle) father_handle = family.get_father_handle() if father_handle: parent_handles.append(father_handle) mother_handle = family.get_mother_handle() if mother_handle: parent_handles.append(mother_handle) return parent_handles def get_spouse_handles(self, person_handle): """ Return an array of handles for all the spouses of the given person handle. """ spouses = [] person = self.__db.get_person_from_handle(person_handle) for family_handle in person.get_family_handle_list(): family = self.__db.get_family_from_handle(family_handle) father_handle = family.get_father_handle() mother_handle = family.get_mother_handle() spouse_handle = None if mother_handle and father_handle == person_handle: spouse_handle = mother_handle elif father_handle and mother_handle == person_handle: spouse_handle = father_handle if spouse_handle and spouse_handle not in spouses: spouses.append(spouse_handle) return spouses def get_children_handles(self, person_handle): """ Return an array of handles for all the children of the given person handle. """ children = [] person = self.__db.get_person_from_handle(person_handle) for family_handle in person.get_family_handle_list(): family = self.__db.get_family_from_handle(family_handle) for child_ref in family.get_child_ref_list(): children.append(child_ref.get_reference_handle()) return children def write_people(self, title, people_handles): """ Write information about a group of people - including the title. """ cap_title = title[0].upper() + title[1:] subtitle = "%s (%d)" % (cap_title, len(people_handles)) self.doc.start_paragraph("KIN-Subtitle") mark = IndexMark(cap_title, INDEX_TYPE_TOC, 2) self.doc.write_text(subtitle, mark) self.doc.end_paragraph() list(map(self.write_person, people_handles)) def write_person(self, person_handle): """ Write information about the given person. """ person = self.database.get_person_from_handle(person_handle) name = self._name_display.display(person) mark = ReportUtils.get_person_mark(self.database, person) birth_date = "" birth = get_birth_or_fallback(self.database, person) if birth: birth_date = self._get_date(birth.get_date_object()) death_date = "" death = get_death_or_fallback(self.database, person) if death: death_date = self._get_date(death.get_date_object()) dates = self._(" (%(birth_date)s - %(death_date)s)") % { 'birth_date' : birth_date, 'death_date' : death_date } self.doc.start_paragraph('KIN-Normal') self.doc.write_text(name, mark) self.doc.write_text(dates) self.doc.end_paragraph() #------------------------------------------------------------------------ # # KinshipOptions # #------------------------------------------------------------------------ class KinshipOptions(MenuReportOptions): """ Defines options and provides handling interface. """ def __init__(self, name, dbase): MenuReportOptions.__init__(self, name, dbase) def add_menu_options(self, menu): """ Add options to the menu for the kinship report. """ category_name = _("Report Options") pid = PersonOption(_("Center Person")) pid.set_help(_("The center person for the report")) menu.add_option(category_name, "pid", pid) stdoptions.add_name_format_option(menu, category_name) maxdescend = NumberOption(_("Max Descendant Generations"), 2, 1, 20) maxdescend.set_help(_("The maximum number of descendant generations")) menu.add_option(category_name, "maxdescend", maxdescend) maxascend = NumberOption(_("Max Ancestor Generations"), 2, 1, 20) maxascend.set_help(_("The maximum number of ancestor generations")) menu.add_option(category_name, "maxascend", maxascend) incspouses = BooleanOption(_("Include spouses"), True) incspouses.set_help(_("Whether to include spouses")) menu.add_option(category_name, "incspouses", incspouses) inccousins = BooleanOption(_("Include cousins"), True) inccousins.set_help(_("Whether to include cousins")) menu.add_option(category_name, "inccousins", inccousins) incaunts = BooleanOption(_("Include aunts/uncles/nephews/nieces"), True) incaunts.set_help(_("Whether to include aunts/uncles/nephews/nieces")) menu.add_option(category_name, "incaunts", incaunts) stdoptions.add_private_data_option(menu, category_name) stdoptions.add_localization_option(menu, category_name) def make_default_style(self, default_style): """Make the default output style for the Kinship Report.""" f = FontStyle() f.set_size(16) f.set_type_face(FONT_SANS_SERIF) f.set_bold(1) p = ParagraphStyle() p.set_header_level(1) p.set_bottom_border(1) p.set_bottom_margin(ReportUtils.pt2cm(8)) p.set_font(f) p.set_alignment(PARA_ALIGN_CENTER) p.set_description(_("The style used for the title of the page.")) default_style.add_paragraph_style("KIN-Title", p) font = FontStyle() font.set_size(12) font.set_bold(True) p = ParagraphStyle() p.set_header_level(3) p.set_font(font) p.set_top_margin(ReportUtils.pt2cm(6)) p.set_description(_('The basic style used for sub-headings.')) default_style.add_paragraph_style("KIN-Subtitle", p) font = FontStyle() font.set_size(10) p = ParagraphStyle() p.set_font(font) p.set_left_margin(0.5) p.set_description(_('The basic style used for the text display.')) default_style.add_paragraph_style("KIN-Normal", p)
pmghalvorsen/gramps_branch
gramps/plugins/textreport/kinshipreport.py
Python
gpl-2.0
16,756
<?php /** Jkreativ Admin Page */ if( defined('JEG_PLUGIN_JKREATIV') ) { locate_template(array('admin/import/import-content.php'), true, true); locate_template(array('admin/init-dashboard.php'), true, true); locate_template(array('admin/init-widget.php'), true, true); locate_template(array('admin/additional-widget.php'), true, true); locate_template(array('admin/admin-functionality.php'), true, true); locate_template(array('admin/post-type.php'), true, true); locate_template(array('admin/plugin-metabox.php'), true, true); locate_template(array('admin/shortcode.php'), true, true); locate_template(array('admin/additional-shortcode.php'), true, true); locate_template(array('admin/google-authorship.php'), true, true); locate_template(array('admin/vc-integration.php'), true, true); locate_template(array('admin/revslider-integration.php'), true, true); }
OpenDoorBrewCo/odbc-wp-prod
wp-content/themes/jkreativ-themes/lib/admin.php
PHP
gpl-2.0
925
/* * Copyright (C) eZ Systems AS. All rights reserved. * For full copyright and license information view LICENSE file distributed with this source code. */ YUI.add('ez-asynchronoussubitemview', function (Y) { "use strict"; /** * Provides the base class for the asynchronous subitem views * * @module ez-subitemlistmoreview */ Y.namespace('eZ'); /** * It's an abstract view for the asynchronous subitem views. It avoids * duplicating the same method in every asynchronous subitem views. * * @namespace eZ * @class AsynchronousSubitemView * @constructor * @extends eZ.SubitemBaseView */ Y.eZ.AsynchronousSubitemView = Y.Base.create('asynchronousSubitemView', Y.eZ.SubitemBaseView, [Y.eZ.AsynchronousView, Y.eZ.LoadMorePagination], { initializer: function () { this._fireMethod = this._prepareInitialLoad; this._errorHandlingMethod = this._handleError; this._getExpectedItemsCount = this._getChildCount; this._set('loading', (this._getChildCount() > 0)); this.after('offsetChange', function (e) { if ( this.get('offset') >= 0 ) { this._fireLocationSearch(); } }); this.after('loadingErrorChange', function (e) { this._set('loading', false); }); this.get('location').after( ['sortOrderChange', 'sortFieldChange'], Y.bind(this._refresh, this) ); }, /** * Sets for the `offset` attribute to launch the initial loading of the * subitems. This method is supposed to be called when the view becomes * active. * * @method _prepareInitialLoad * @protected */ _prepareInitialLoad: function () { if ( this.get('offset') < 0 && this._getChildCount() ) { this.set('offset', 0); } }, /** * Refreshes the view if it's active. The subitems are reloaded and then * rerendered. * * @method _refresh * @protected */ _refresh: function () { if ( this._getChildCount() ) { if ( this.get('active') ) { this.set('items', [], {reset: true}); this._set('loading', true); this.once('loadingChange', function () { this._destroyItemViews(); }); this._fireLocationSearch(this.get('offset') + this.get('limit')); } else if ( this.get('offset') >= 0 ) { this._destroyItemViews(); this.set('items', [], {reset: true}); this.reset('offset'); } } }, /** * Handles the loading error. It fires a notification and makes sure the * state of the view is consistent with what is actually loaded. * * @method _handleError * @protected */ _handleError: function () { if ( this.get('loadingError') ) { this.fire('notify', { notification: { text: Y.eZ.trans('subitem.error.loading.list', {}, 'subitem'), identifier: 'subitem-load-error-' + this.get('location').get('id'), state: 'error', timeout: 0 } }); this._disableLoadMore(); } }, /** * Fires the `locationSearch` event to fetch the subitems of the * currently displayed Location. * * @method _fireLocationSearch * @param {Number} forceLimit indicates if we should force a limit value * (and offset to 0). This is used to reload the current list of * subitems. * @protected */ _fireLocationSearch: function (forceLimit) { var locationId = this.get('location').get('locationId'); this.set('loadingError', false); this.fire('locationSearch', { viewName: 'subitems-' + locationId, resultAttribute: 'items', loadContentType: true, loadContent: true, search: { filter: { "ParentLocationIdCriterion": this.get('location').get('locationId'), }, offset: forceLimit ? 0 : this.get('offset'), limit: forceLimit ? forceLimit : this.get('limit'), sortLocation: this.get('location'), }, }); }, }); });
intenseprogramming/PlatformUIBundle
Resources/public/js/views/subitem/ez-asynchronoussubitemview.js
JavaScript
gpl-2.0
4,849
/*************************************************************************** dpro.hpp - GDL procedure/function ------------------- begin : July 22 2002 copyright : (C) 2002 by Marc Schellens email : m_schellens@users.sf.net ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef DPRO_HPP_ #define DPRO_HPP_ // #include <deque> #include <string> #include <algorithm> #include <vector> //#include <stack> #include "basegdl.hpp" #include "dcommon.hpp" #include "dvar.hpp" #include "prognode.hpp" #include "str.hpp" #include <antlr/Token.hpp> template<typename T> class Is_eq: public std::unary_function<T,bool> { std::string name; public: explicit Is_eq(const std::string& n): name(n) {} bool operator() (const T* p) const { return (p->Name() == name);} }; // for jumps (goto, on_ioerror) struct LabelT { std::string label; ProgNodeP target; LabelT( const std::string& l, ProgNodeP t): label( l), target( t) {} }; class LabelListT { std::vector<LabelT> list; public: LabelListT(): list() {} ~LabelListT() {} void Add( const std::string& l, ProgNodeP t) { list.push_back( LabelT( l, t)); } SizeT Size() { return list.size();} int Find( const std::string& s) { SizeT nEl = list.size(); for( SizeT i=0; i<nEl; i++) if( list[ i].label == s) return static_cast<int>(i); return -1; } ProgNodeP Get( SizeT ix) { return list[ ix].target; } void SetLabelNode( ProgNodeP t) { int ix = Find( t->getText()); // already checked for presence list[ ix].target = t; } const std::string& GetLabel( SizeT ix) { return list[ ix].label; } void Clear() { list.clear(); } }; // Fun/Pro classes ***************************************************** // Base class ********************************************************** class DSub { public: enum ExtraType { NONE=0, EXTRA, REFEXTRA }; protected: std::string name; // name (of procedure/function) std::string object; // name of class for methods (might not be defined // when method is compiled) // keywords are pushed in front so they are first // followed by the parameters // (which are pushed back, // but due to the syntax are first, // so the layout is: // keyVar_N (ID in key[0]),..,keyVar_1 (key[n-1]), // par_1,..,par_nPar, var1,..,varK // N=size(key) // K=size(var)-nPar-N KeyVarListT key; // keyword names (IDList: typedefs.hpp) // (KEYWORD_NAME=keyword_value) int nPar; // number of parameters (-1 = infinite) int nParMin; // minimum number of parameters (-1 = infinite) ExtraType extra; int extraIx; // index of extra keyword IDList warnKey; // keyword names to accept but warn // (IDList: typedefs.hpp) public: DSub( const std::string& n, const std::string& o=""): name(n), object(o), key(), nPar(0), nParMin(0), extra(NONE), extraIx(-1), warnKey() {} virtual ~DSub(); // polymorphism const std::string& Name() const { return name;} const std::string& Object() const { return object;} std::string ObjectName() const { if( object == "") return name; return object+"::"+name; } std::string ObjectFileName() const { if( object == "") return name; return object+"__"+name; } ExtraType Extra() { return extra; } int ExtraIx() { return extraIx; } // returns the (abbreviated) keyword value index int FindKey(const std::string& s) { String_abbref_eq searchKey(s); int ix=0; for(KeyVarListT::iterator i=key.begin(); i != key.end(); ++i, ++ix) if( searchKey(*i)) { return ix; } return -1; } int NKey() const { return key.size();} int NPar() const { return nPar;} int NParMin() const { return nParMin;} // bool AKey() { return aKey;} // additional keywords allowed friend class EnvBaseT; friend class EnvT; friend class ExtraT; friend void SetupOverloadSubroutines(); // overload base class methods }; // Lib pro/fun ******************************************************** // moved to prognode.hpp // class EnvT; // // typedef void (*LibPro)(EnvT*); // typedef BaseGDL* (*LibFun)(EnvT*); // typedef BaseGDL* (*LibFunDirect)(BaseGDL* param,bool canGrab); // library procedure/function (in cases both are handled the same way) class DLib: public DSub { bool hideHelp; // if set HELP,/LIB will not list this subroutine public: DLib( const std::string& n, const std::string& o, const int nPar_, const std::string keyNames[], const std::string warnKeyNames[], const int nParMin_); virtual const std::string ToString() = 0; bool GetHideHelp() const { return hideHelp;} void SetHideHelp( bool v) { hideHelp = v;} // for sorting lists by name. Not used (lists too short to make a time gain. Long lists would, if existing, // benefit from sorting by hash number in a std::map instead of a std::list. struct CompLibFunName: public std::binary_function< DLib*, DLib*, bool> { bool operator() ( DLib* f1, DLib* f2) const { return f1->ObjectName() < f2->ObjectName();} }; }; // library procedure class DLibPro: public DLib { LibPro pro; public: // warnKeyNames are keywords wich are not supported, but which // should not make the compilation fail. // A warning will be issued. // use this for keywords which are truly optional and don't // change the results. // Note that due to their nature, there should never be keywords // on which a value is returned. DLibPro( LibPro p, const std::string& n, const int nPar_=0, const std::string keyNames[]=NULL, const std::string warnKeyNames[]=NULL, const int nParMin_=0); DLibPro( LibPro p, const std::string& n, const std::string& o, const int nPar_=0, const std::string keyNames[]=NULL, const std::string warnKeyNames[]=NULL, const int nParMin_=0); LibPro Pro() { return pro;} const std::string ToString(); }; // library function class DLibFun: public DLib { LibFun fun; public: DLibFun( LibFun f, const std::string& n, const int nPar_=0, const std::string keyNames[]=NULL, const std::string warnKeyNames[]=NULL, const int nParMin_=0); DLibFun( LibFun f, const std::string& n, const std::string& o, const int nPar_=0, const std::string keyNames[]=NULL, const std::string warnKeyNames[]=NULL, const int nParMin_=0); LibFun Fun() { return fun;} const std::string ToString(); virtual bool RetNew() { return false;} virtual bool DirectCall() { return false;} }; // library function which ALWAYS return a new value // (as opposite to returning an input value) class DLibFunRetNew: public DLibFun { bool retConstant; // means: can be pre-evaluated with constant input public: DLibFunRetNew( LibFun f, const std::string& n, const int nPar_=0, const std::string keyNames[]=NULL, const std::string warnKeyNames[]=NULL, bool rConstant=false, const int nParMin_=0); DLibFunRetNew( LibFun f, const std::string& n, const std::string& o, const int nPar_=0, const std::string keyNames[]=NULL, const std::string warnKeyNames[]=NULL, const int nParMin_=0); bool RetNew() { return true;} bool RetConstant() { return this->retConstant;} }; // direct call functions must have: // ony one parameter, no keywords // these functions are called "direct", no environment is created class DLibFunDirect: public DLibFunRetNew { LibFunDirect funDirect; public: DLibFunDirect( LibFunDirect f, const std::string& n, bool retConstant_=true); LibFunDirect FunDirect() { return funDirect;} // bool RetNew() { return true;} bool DirectCall() { return true;} }; // UD pro/fun ******************************************************** // function/procedure (differ because they are in different lists) // User Defined class DSubUD: public DSub { std::string file; // filename were procedure is defined in KeyVarListT var; // keyword values, parameters, local variables CommonBaseListT common; // common blocks or references ProgNodeP tree; // the 'code' unsigned int compileOpt; // e.g. hidden or obsolete LabelListT labelList; void ResolveLabel( ProgNodeP); protected: int nForLoops; public: DSubUD(const std::string&,const std::string& o="",const std::string& f=""); ~DSubUD(); void Reset(); void DelTree(); void SetTree( ProgNodeP t) { tree = t;} void AddCommon(DCommonBase* c) { common.push_back(c);} void DeleteLastAddedCommon() { delete common.back(); common.pop_back(); } void ResolveAllLabels(); LabelListT& LabelList() { return labelList;} ProgNodeP GotoTarget( int ix) { if( ix >= labelList.Size()) throw GDLException( "Undefined label."); return labelList.Get( ix); } // int LabelOrd( int ix) { return labelList.GetOrd( ix);} int NDefLabel() { return labelList.Size();} std::string GetFilename() { return file; } // add variables DSubUD* AddPar(const std::string&); // add paramter unsigned AddVar(const std::string&); // add local variable DSubUD* AddKey(const std::string&, const std::string&); // add keyword=value void DelVar(const int ix) {var.erase(var.begin() + ix);} SizeT Size() {return var.size();} SizeT CommonsSize() { SizeT commonsize=0; CommonBaseListT::iterator c = common.begin(); for(; c != common.end(); ++c) commonsize+=(*c)->NVar(); return commonsize; } int NForLoops() const { return nForLoops;} // search for variable returns true if its found in var or common blocks bool Find(const std::string& n) { KeyVarListT::iterator f=std::find(var.begin(),var.end(),n); if( f != var.end()) return true; CommonBaseListT::iterator c= std::find_if(common.begin(),common.end(),DCommon_contains_var(n)); return (c != common.end()); } // returns common block with name n DCommon* Common(const std::string& n) { CommonBaseListT::iterator c = common.begin(); for(; c != common.end(); ++c) if( dynamic_cast< DCommon*>( *c) != NULL && (*c)->Name() == n) return static_cast< DCommon*>( *c); return NULL; } // returns common block which holds variable n DCommonBase* FindCommon(const std::string& n) { CommonBaseListT::iterator c= std::find_if(common.begin(),common.end(),DCommon_contains_var(n)); return (c != common.end())? *c : NULL; } const std::string& GetVarName( SizeT ix) { return var[ix]; } const std::string& GetKWName( SizeT ix) { return key[ix]; } BaseGDL* GetCommonVarNameList(); bool GetCommonVarName(const BaseGDL* p, std::string& varName); bool GetCommonVarName4Help(const BaseGDL* p, std::string& varName); BaseGDL** GetCommonVarPtr(const BaseGDL* p) { for( CommonBaseListT::iterator c=common.begin(); c != common.end(); ++c) { int vIx = (*c)->Find( p); if( vIx >= 0) { DVar* var = (*c)->Var( vIx); return &(var->Data()); } } return NULL; } BaseGDL** GetCommonVarPtr(std::string& s) { for(CommonBaseListT::iterator c=common.begin(); c != common.end(); ++c) { DVar* v=(*c)->Find(s); if (v) return &(v->Data()); } return NULL; } bool ReplaceExistingCommonVar(std::string& s, BaseGDL* val) { for(CommonBaseListT::iterator c=common.begin(); c != common.end(); ++c) { DVar* v=(*c)->Find(s); if (v) { delete (v)->Data(); (v)->SetData(val); return true; } } return false; } // returns the variable index (-1 if not found) int FindVar(const std::string& s) { return FindInKeyVarListT(var,s); } // returns ptr to common variable (NULL if not found) DVar* FindCommonVar(const std::string& s) { for(CommonBaseListT::iterator c=common.begin(); c != common.end(); ++c) { DVar* v=(*c)->Find(s); if( v) return v; } return NULL; } // the final "compilation" takes part here void SetTree( RefDNode n); // { // // // // Converter Translation Transcription Rewrite RefDNode ProgNode ProgNodeP // // // // here the conversion RefDNode -> ProgNode is done // // // tree = ProgNode::NewProgNode( n); // } ProgNodeP GetTree() { return tree; } unsigned int GetCompileOpt() { return compileOpt; } void SetCompileOpt(const unsigned int n) { compileOpt = n; } bool isObsolete(); bool isHidden(); friend class EnvUDT; }; class DPro: public DSubUD { public: // for main function, not inserted into proList // should be fine (way too much): 32 NESTED loops in $MAIN$ (elswhere: unlimited) DPro(): DSubUD("$MAIN$","","") { this->nForLoops = 32;} DPro(const std::string& n,const std::string& o="",const std::string& f=""): DSubUD(n,o,f) {} const std::string ToString(); ~DPro() {}; }; class DFun: public DSubUD { public: DFun(const std::string& n,const std::string& o="",const std::string& f=""): DSubUD(n,o,f) {} const std::string ToString(); ~DFun() {}; }; typedef std::vector<DFun*> FunListT; typedef std::vector<DPro*> ProListT; typedef std::vector<DLibFun*> LibFunListT; typedef std::vector<DLibPro*> LibProListT; #endif
olebole/gnudatalanguage
src/dpro.hpp
C++
gpl-2.0
14,135
<?php if (session_id() == "") session_start(); // Initialize Session data ob_start(); // Turn on output buffering ?> <?php include_once "ewcfg10.php" ?> <?php include_once "adodb5/adodb.inc.php" ?> <?php include_once "phpfn10.php" ?> <?php include_once "periodopeiinfo.php" ?> <?php include_once "usuarioinfo.php" ?> <?php include_once "userfn10.php" ?> <?php // // Page class // $periodopei_add = NULL; // Initialize page object first class cperiodopei_add extends cperiodopei { // Page ID var $PageID = 'add'; // Project ID var $ProjectID = "{F59C7BF3-F287-4BE0-9F86-FCB94F808AF8}"; // Table name var $TableName = 'periodopei'; // Page object name var $PageObjName = 'periodopei_add'; // Page name function PageName() { return ew_CurrentPage(); } // Page URL function PageUrl() { $PageUrl = ew_CurrentPage() . "?"; if ($this->UseTokenInUrl) $PageUrl .= "t=" . $this->TableVar . "&"; // Add page token return $PageUrl; } // Message function getMessage() { return @$_SESSION[EW_SESSION_MESSAGE]; } function setMessage($v) { ew_AddMessage($_SESSION[EW_SESSION_MESSAGE], $v); } function getFailureMessage() { return @$_SESSION[EW_SESSION_FAILURE_MESSAGE]; } function setFailureMessage($v) { ew_AddMessage($_SESSION[EW_SESSION_FAILURE_MESSAGE], $v); } function getSuccessMessage() { return @$_SESSION[EW_SESSION_SUCCESS_MESSAGE]; } function setSuccessMessage($v) { ew_AddMessage($_SESSION[EW_SESSION_SUCCESS_MESSAGE], $v); } function getWarningMessage() { return @$_SESSION[EW_SESSION_WARNING_MESSAGE]; } function setWarningMessage($v) { ew_AddMessage($_SESSION[EW_SESSION_WARNING_MESSAGE], $v); } // Show message function ShowMessage() { $hidden = FALSE; $html = ""; // Message $sMessage = $this->getMessage(); $this->Message_Showing($sMessage, ""); if ($sMessage <> "") { // Message in Session, display if (!$hidden) $sMessage = "<button type=\"button\" class=\"close\" data-dismiss=\"alert\">&times;</button>" . $sMessage; $html .= "<div class=\"alert alert-success ewSuccess\">" . $sMessage . "</div>"; $_SESSION[EW_SESSION_MESSAGE] = ""; // Clear message in Session } // Warning message $sWarningMessage = $this->getWarningMessage(); $this->Message_Showing($sWarningMessage, "warning"); if ($sWarningMessage <> "") { // Message in Session, display if (!$hidden) $sWarningMessage = "<button type=\"button\" class=\"close\" data-dismiss=\"alert\">&times;</button>" . $sWarningMessage; $html .= "<div class=\"alert alert-warning ewWarning\">" . $sWarningMessage . "</div>"; $_SESSION[EW_SESSION_WARNING_MESSAGE] = ""; // Clear message in Session } // Success message $sSuccessMessage = $this->getSuccessMessage(); $this->Message_Showing($sSuccessMessage, "success"); if ($sSuccessMessage <> "") { // Message in Session, display if (!$hidden) $sSuccessMessage = "<button type=\"button\" class=\"close\" data-dismiss=\"alert\">&times;</button>" . $sSuccessMessage; $html .= "<div class=\"alert alert-success ewSuccess\">" . $sSuccessMessage . "</div>"; $_SESSION[EW_SESSION_SUCCESS_MESSAGE] = ""; // Clear message in Session } // Failure message $sErrorMessage = $this->getFailureMessage(); $this->Message_Showing($sErrorMessage, "failure"); if ($sErrorMessage <> "") { // Message in Session, display if (!$hidden) $sErrorMessage = "<button type=\"button\" class=\"close\" data-dismiss=\"alert\">&times;</button>" . $sErrorMessage; $html .= "<div class=\"alert alert-error ewError\">" . $sErrorMessage . "</div>"; $_SESSION[EW_SESSION_FAILURE_MESSAGE] = ""; // Clear message in Session } echo "<table class=\"ewStdTable\"><tr><td><div class=\"ewMessageDialog\"" . (($hidden) ? " style=\"display: none;\"" : "") . ">" . $html . "</div></td></tr></table>"; } var $PageHeader; var $PageFooter; // Show Page Header function ShowPageHeader() { $sHeader = $this->PageHeader; $this->Page_DataRendering($sHeader); if ($sHeader <> "") { // Header exists, display echo "<p>" . $sHeader . "</p>"; } } // Show Page Footer function ShowPageFooter() { $sFooter = $this->PageFooter; $this->Page_DataRendered($sFooter); if ($sFooter <> "") { // Footer exists, display echo "<p>" . $sFooter . "</p>"; } } // Validate page request function IsPageRequest() { global $objForm; if ($this->UseTokenInUrl) { if ($objForm) return ($this->TableVar == $objForm->GetValue("t")); if (@$_GET["t"] <> "") return ($this->TableVar == $_GET["t"]); } else { return TRUE; } } // // Page class constructor // function __construct() { global $conn, $Language, $UserAgent; // User agent $UserAgent = ew_UserAgent(); $GLOBALS["Page"] = &$this; // Language object if (!isset($Language)) $Language = new cLanguage(); // Parent constuctor parent::__construct(); // Table object (periodopei) if (!isset($GLOBALS["periodopei"])) { $GLOBALS["periodopei"] = &$this; $GLOBALS["Table"] = &$GLOBALS["periodopei"]; } // Table object (usuario) if (!isset($GLOBALS['usuario'])) $GLOBALS['usuario'] = new cusuario(); // Page ID if (!defined("EW_PAGE_ID")) define("EW_PAGE_ID", 'add', TRUE); // Table name (for backward compatibility) if (!defined("EW_TABLE_NAME")) define("EW_TABLE_NAME", 'periodopei', TRUE); // Start timer if (!isset($GLOBALS["gTimer"])) $GLOBALS["gTimer"] = new cTimer(); // Open connection if (!isset($conn)) $conn = ew_Connect(); } // // Page_Init // function Page_Init() { global $gsExport, $gsExportFile, $UserProfile, $Language, $Security, $objForm; // User profile $UserProfile = new cUserProfile(); $UserProfile->LoadProfile(@$_SESSION[EW_SESSION_USER_PROFILE]); // Security $Security = new cAdvancedSecurity(); if (IsPasswordExpired()) $this->Page_Terminate("changepwd.php"); if (!$Security->IsLoggedIn()) $Security->AutoLogin(); if (!$Security->IsLoggedIn()) { $Security->SaveLastUrl(); $this->Page_Terminate("login.php"); } $Security->TablePermission_Loading(); $Security->LoadCurrentUserLevel($this->ProjectID . $this->TableName); $Security->TablePermission_Loaded(); if (!$Security->IsLoggedIn()) { $Security->SaveLastUrl(); $this->Page_Terminate("login.php"); } if (!$Security->CanAdd()) { $Security->SaveLastUrl(); $this->setFailureMessage($Language->Phrase("NoPermission")); // Set no permission $this->Page_Terminate("periodopeilist.php"); } $Security->UserID_Loading(); if ($Security->IsLoggedIn()) $Security->LoadUserID(); $Security->UserID_Loaded(); // Create form object $objForm = new cFormObj(); $this->CurrentAction = (@$_GET["a"] <> "") ? $_GET["a"] : @$_POST["a_list"]; // Set up curent action // Global Page Loading event (in userfn*.php) Page_Loading(); // Page Load event $this->Page_Load(); } // // Page_Terminate // function Page_Terminate($url = "") { global $conn; // Page Unload event $this->Page_Unload(); // Global Page Unloaded event (in userfn*.php) Page_Unloaded(); $this->Page_Redirecting($url); // Close connection $conn->Close(); // Go to URL if specified if ($url <> "") { if (!EW_DEBUG_ENABLED && ob_get_length()) ob_end_clean(); header("Location: " . $url); } exit(); } var $DbMasterFilter = ""; var $DbDetailFilter = ""; var $Priv = 0; var $OldRecordset; var $CopyRecord; // // Page main // function Page_Main() { global $objForm, $Language, $gsFormError; // Process form if post back if (@$_POST["a_add"] <> "") { $this->CurrentAction = $_POST["a_add"]; // Get form action $this->CopyRecord = $this->LoadOldRecord(); // Load old recordset $this->LoadFormValues(); // Load form values } else { // Not post back // Load key values from QueryString $this->CopyRecord = TRUE; if (@$_GET["nu_periodoPei"] != "") { $this->nu_periodoPei->setQueryStringValue($_GET["nu_periodoPei"]); $this->setKey("nu_periodoPei", $this->nu_periodoPei->CurrentValue); // Set up key } else { $this->setKey("nu_periodoPei", ""); // Clear key $this->CopyRecord = FALSE; } if ($this->CopyRecord) { $this->CurrentAction = "C"; // Copy record } else { $this->CurrentAction = "I"; // Display blank record $this->LoadDefaultValues(); // Load default values } } // Set up Breadcrumb $this->SetupBreadcrumb(); // Validate form if post back if (@$_POST["a_add"] <> "") { if (!$this->ValidateForm()) { $this->CurrentAction = "I"; // Form error, reset action $this->EventCancelled = TRUE; // Event cancelled $this->RestoreFormValues(); // Restore form values $this->setFailureMessage($gsFormError); } } // Perform action based on action code switch ($this->CurrentAction) { case "I": // Blank record, no action required break; case "C": // Copy an existing record if (!$this->LoadRow()) { // Load record based on key if ($this->getFailureMessage() == "") $this->setFailureMessage($Language->Phrase("NoRecord")); // No record found $this->Page_Terminate("periodopeilist.php"); // No matching record, return to list } break; case "A": // Add new record $this->SendEmail = TRUE; // Send email on add success if ($this->AddRow($this->OldRecordset)) { // Add successful if ($this->getSuccessMessage() == "") $this->setSuccessMessage($Language->Phrase("AddSuccess")); // Set up success message $sReturnUrl = $this->getReturnUrl(); if (ew_GetPageName($sReturnUrl) == "periodopeiview.php") $sReturnUrl = $this->GetViewUrl(); // View paging, return to view page with keyurl directly $this->Page_Terminate($sReturnUrl); // Clean up and return } else { $this->EventCancelled = TRUE; // Event cancelled $this->RestoreFormValues(); // Add failed, restore form values } } // Render row based on row type $this->RowType = EW_ROWTYPE_ADD; // Render add type // Render row $this->ResetAttrs(); $this->RenderRow(); } // Get upload files function GetUploadFiles() { global $objForm; // Get upload data } // Load default values function LoadDefaultValues() { $this->nu_anoInicio->CurrentValue = NULL; $this->nu_anoInicio->OldValue = $this->nu_anoInicio->CurrentValue; $this->nu_anoFim->CurrentValue = NULL; $this->nu_anoFim->OldValue = $this->nu_anoFim->CurrentValue; $this->no_periodo->CurrentValue = NULL; $this->no_periodo->OldValue = $this->no_periodo->CurrentValue; $this->ic_situacao->CurrentValue = "D"; } // Load form values function LoadFormValues() { // Load from form global $objForm; if (!$this->nu_anoInicio->FldIsDetailKey) { $this->nu_anoInicio->setFormValue($objForm->GetValue("x_nu_anoInicio")); } if (!$this->nu_anoFim->FldIsDetailKey) { $this->nu_anoFim->setFormValue($objForm->GetValue("x_nu_anoFim")); } if (!$this->no_periodo->FldIsDetailKey) { $this->no_periodo->setFormValue($objForm->GetValue("x_no_periodo")); } if (!$this->ic_situacao->FldIsDetailKey) { $this->ic_situacao->setFormValue($objForm->GetValue("x_ic_situacao")); } } // Restore form values function RestoreFormValues() { global $objForm; $this->LoadOldRecord(); $this->nu_anoInicio->CurrentValue = $this->nu_anoInicio->FormValue; $this->nu_anoFim->CurrentValue = $this->nu_anoFim->FormValue; $this->no_periodo->CurrentValue = $this->no_periodo->FormValue; $this->ic_situacao->CurrentValue = $this->ic_situacao->FormValue; } // Load row based on key values function LoadRow() { global $conn, $Security, $Language; $sFilter = $this->KeyFilter(); // Call Row Selecting event $this->Row_Selecting($sFilter); // Load SQL based on filter $this->CurrentFilter = $sFilter; $sSql = $this->SQL(); $res = FALSE; $rs = ew_LoadRecordset($sSql); if ($rs && !$rs->EOF) { $res = TRUE; $this->LoadRowValues($rs); // Load row values $rs->Close(); } return $res; } // Load row values from recordset function LoadRowValues(&$rs) { global $conn; if (!$rs || $rs->EOF) return; // Call Row Selected event $row = &$rs->fields; $this->Row_Selected($row); $this->nu_periodoPei->setDbValue($rs->fields('nu_periodoPei')); $this->nu_anoInicio->setDbValue($rs->fields('nu_anoInicio')); $this->nu_anoFim->setDbValue($rs->fields('nu_anoFim')); $this->no_periodo->setDbValue($rs->fields('no_periodo')); $this->ic_situacao->setDbValue($rs->fields('ic_situacao')); } // Load DbValue from recordset function LoadDbValues(&$rs) { if (!$rs || !is_array($rs) && $rs->EOF) return; $row = is_array($rs) ? $rs : $rs->fields; $this->nu_periodoPei->DbValue = $row['nu_periodoPei']; $this->nu_anoInicio->DbValue = $row['nu_anoInicio']; $this->nu_anoFim->DbValue = $row['nu_anoFim']; $this->no_periodo->DbValue = $row['no_periodo']; $this->ic_situacao->DbValue = $row['ic_situacao']; } // Load old record function LoadOldRecord() { // Load key values from Session $bValidKey = TRUE; if (strval($this->getKey("nu_periodoPei")) <> "") $this->nu_periodoPei->CurrentValue = $this->getKey("nu_periodoPei"); // nu_periodoPei else $bValidKey = FALSE; // Load old recordset if ($bValidKey) { $this->CurrentFilter = $this->KeyFilter(); $sSql = $this->SQL(); $this->OldRecordset = ew_LoadRecordset($sSql); $this->LoadRowValues($this->OldRecordset); // Load row values } else { $this->OldRecordset = NULL; } return $bValidKey; } // Render row values based on field settings function RenderRow() { global $conn, $Security, $Language; global $gsLanguage; // Initialize URLs // Call Row_Rendering event $this->Row_Rendering(); // Common render codes for all row types // nu_periodoPei // nu_anoInicio // nu_anoFim // no_periodo // ic_situacao if ($this->RowType == EW_ROWTYPE_VIEW) { // View row // nu_periodoPei $this->nu_periodoPei->ViewValue = $this->nu_periodoPei->CurrentValue; $this->nu_periodoPei->ViewCustomAttributes = ""; // nu_anoInicio if (strval($this->nu_anoInicio->CurrentValue) <> "") { switch ($this->nu_anoInicio->CurrentValue) { case $this->nu_anoInicio->FldTagValue(1): $this->nu_anoInicio->ViewValue = $this->nu_anoInicio->FldTagCaption(1) <> "" ? $this->nu_anoInicio->FldTagCaption(1) : $this->nu_anoInicio->CurrentValue; break; case $this->nu_anoInicio->FldTagValue(2): $this->nu_anoInicio->ViewValue = $this->nu_anoInicio->FldTagCaption(2) <> "" ? $this->nu_anoInicio->FldTagCaption(2) : $this->nu_anoInicio->CurrentValue; break; case $this->nu_anoInicio->FldTagValue(3): $this->nu_anoInicio->ViewValue = $this->nu_anoInicio->FldTagCaption(3) <> "" ? $this->nu_anoInicio->FldTagCaption(3) : $this->nu_anoInicio->CurrentValue; break; case $this->nu_anoInicio->FldTagValue(4): $this->nu_anoInicio->ViewValue = $this->nu_anoInicio->FldTagCaption(4) <> "" ? $this->nu_anoInicio->FldTagCaption(4) : $this->nu_anoInicio->CurrentValue; break; case $this->nu_anoInicio->FldTagValue(5): $this->nu_anoInicio->ViewValue = $this->nu_anoInicio->FldTagCaption(5) <> "" ? $this->nu_anoInicio->FldTagCaption(5) : $this->nu_anoInicio->CurrentValue; break; case $this->nu_anoInicio->FldTagValue(6): $this->nu_anoInicio->ViewValue = $this->nu_anoInicio->FldTagCaption(6) <> "" ? $this->nu_anoInicio->FldTagCaption(6) : $this->nu_anoInicio->CurrentValue; break; case $this->nu_anoInicio->FldTagValue(7): $this->nu_anoInicio->ViewValue = $this->nu_anoInicio->FldTagCaption(7) <> "" ? $this->nu_anoInicio->FldTagCaption(7) : $this->nu_anoInicio->CurrentValue; break; case $this->nu_anoInicio->FldTagValue(8): $this->nu_anoInicio->ViewValue = $this->nu_anoInicio->FldTagCaption(8) <> "" ? $this->nu_anoInicio->FldTagCaption(8) : $this->nu_anoInicio->CurrentValue; break; case $this->nu_anoInicio->FldTagValue(9): $this->nu_anoInicio->ViewValue = $this->nu_anoInicio->FldTagCaption(9) <> "" ? $this->nu_anoInicio->FldTagCaption(9) : $this->nu_anoInicio->CurrentValue; break; case $this->nu_anoInicio->FldTagValue(10): $this->nu_anoInicio->ViewValue = $this->nu_anoInicio->FldTagCaption(10) <> "" ? $this->nu_anoInicio->FldTagCaption(10) : $this->nu_anoInicio->CurrentValue; break; case $this->nu_anoInicio->FldTagValue(11): $this->nu_anoInicio->ViewValue = $this->nu_anoInicio->FldTagCaption(11) <> "" ? $this->nu_anoInicio->FldTagCaption(11) : $this->nu_anoInicio->CurrentValue; break; case $this->nu_anoInicio->FldTagValue(12): $this->nu_anoInicio->ViewValue = $this->nu_anoInicio->FldTagCaption(12) <> "" ? $this->nu_anoInicio->FldTagCaption(12) : $this->nu_anoInicio->CurrentValue; break; case $this->nu_anoInicio->FldTagValue(13): $this->nu_anoInicio->ViewValue = $this->nu_anoInicio->FldTagCaption(13) <> "" ? $this->nu_anoInicio->FldTagCaption(13) : $this->nu_anoInicio->CurrentValue; break; case $this->nu_anoInicio->FldTagValue(14): $this->nu_anoInicio->ViewValue = $this->nu_anoInicio->FldTagCaption(14) <> "" ? $this->nu_anoInicio->FldTagCaption(14) : $this->nu_anoInicio->CurrentValue; break; case $this->nu_anoInicio->FldTagValue(15): $this->nu_anoInicio->ViewValue = $this->nu_anoInicio->FldTagCaption(15) <> "" ? $this->nu_anoInicio->FldTagCaption(15) : $this->nu_anoInicio->CurrentValue; break; case $this->nu_anoInicio->FldTagValue(16): $this->nu_anoInicio->ViewValue = $this->nu_anoInicio->FldTagCaption(16) <> "" ? $this->nu_anoInicio->FldTagCaption(16) : $this->nu_anoInicio->CurrentValue; break; case $this->nu_anoInicio->FldTagValue(17): $this->nu_anoInicio->ViewValue = $this->nu_anoInicio->FldTagCaption(17) <> "" ? $this->nu_anoInicio->FldTagCaption(17) : $this->nu_anoInicio->CurrentValue; break; default: $this->nu_anoInicio->ViewValue = $this->nu_anoInicio->CurrentValue; } } else { $this->nu_anoInicio->ViewValue = NULL; } $this->nu_anoInicio->ViewCustomAttributes = ""; // nu_anoFim if (strval($this->nu_anoFim->CurrentValue) <> "") { switch ($this->nu_anoFim->CurrentValue) { case $this->nu_anoFim->FldTagValue(1): $this->nu_anoFim->ViewValue = $this->nu_anoFim->FldTagCaption(1) <> "" ? $this->nu_anoFim->FldTagCaption(1) : $this->nu_anoFim->CurrentValue; break; case $this->nu_anoFim->FldTagValue(2): $this->nu_anoFim->ViewValue = $this->nu_anoFim->FldTagCaption(2) <> "" ? $this->nu_anoFim->FldTagCaption(2) : $this->nu_anoFim->CurrentValue; break; case $this->nu_anoFim->FldTagValue(3): $this->nu_anoFim->ViewValue = $this->nu_anoFim->FldTagCaption(3) <> "" ? $this->nu_anoFim->FldTagCaption(3) : $this->nu_anoFim->CurrentValue; break; case $this->nu_anoFim->FldTagValue(4): $this->nu_anoFim->ViewValue = $this->nu_anoFim->FldTagCaption(4) <> "" ? $this->nu_anoFim->FldTagCaption(4) : $this->nu_anoFim->CurrentValue; break; case $this->nu_anoFim->FldTagValue(5): $this->nu_anoFim->ViewValue = $this->nu_anoFim->FldTagCaption(5) <> "" ? $this->nu_anoFim->FldTagCaption(5) : $this->nu_anoFim->CurrentValue; break; case $this->nu_anoFim->FldTagValue(6): $this->nu_anoFim->ViewValue = $this->nu_anoFim->FldTagCaption(6) <> "" ? $this->nu_anoFim->FldTagCaption(6) : $this->nu_anoFim->CurrentValue; break; case $this->nu_anoFim->FldTagValue(7): $this->nu_anoFim->ViewValue = $this->nu_anoFim->FldTagCaption(7) <> "" ? $this->nu_anoFim->FldTagCaption(7) : $this->nu_anoFim->CurrentValue; break; case $this->nu_anoFim->FldTagValue(8): $this->nu_anoFim->ViewValue = $this->nu_anoFim->FldTagCaption(8) <> "" ? $this->nu_anoFim->FldTagCaption(8) : $this->nu_anoFim->CurrentValue; break; case $this->nu_anoFim->FldTagValue(9): $this->nu_anoFim->ViewValue = $this->nu_anoFim->FldTagCaption(9) <> "" ? $this->nu_anoFim->FldTagCaption(9) : $this->nu_anoFim->CurrentValue; break; case $this->nu_anoFim->FldTagValue(10): $this->nu_anoFim->ViewValue = $this->nu_anoFim->FldTagCaption(10) <> "" ? $this->nu_anoFim->FldTagCaption(10) : $this->nu_anoFim->CurrentValue; break; case $this->nu_anoFim->FldTagValue(11): $this->nu_anoFim->ViewValue = $this->nu_anoFim->FldTagCaption(11) <> "" ? $this->nu_anoFim->FldTagCaption(11) : $this->nu_anoFim->CurrentValue; break; case $this->nu_anoFim->FldTagValue(12): $this->nu_anoFim->ViewValue = $this->nu_anoFim->FldTagCaption(12) <> "" ? $this->nu_anoFim->FldTagCaption(12) : $this->nu_anoFim->CurrentValue; break; case $this->nu_anoFim->FldTagValue(13): $this->nu_anoFim->ViewValue = $this->nu_anoFim->FldTagCaption(13) <> "" ? $this->nu_anoFim->FldTagCaption(13) : $this->nu_anoFim->CurrentValue; break; case $this->nu_anoFim->FldTagValue(14): $this->nu_anoFim->ViewValue = $this->nu_anoFim->FldTagCaption(14) <> "" ? $this->nu_anoFim->FldTagCaption(14) : $this->nu_anoFim->CurrentValue; break; case $this->nu_anoFim->FldTagValue(15): $this->nu_anoFim->ViewValue = $this->nu_anoFim->FldTagCaption(15) <> "" ? $this->nu_anoFim->FldTagCaption(15) : $this->nu_anoFim->CurrentValue; break; case $this->nu_anoFim->FldTagValue(16): $this->nu_anoFim->ViewValue = $this->nu_anoFim->FldTagCaption(16) <> "" ? $this->nu_anoFim->FldTagCaption(16) : $this->nu_anoFim->CurrentValue; break; case $this->nu_anoFim->FldTagValue(17): $this->nu_anoFim->ViewValue = $this->nu_anoFim->FldTagCaption(17) <> "" ? $this->nu_anoFim->FldTagCaption(17) : $this->nu_anoFim->CurrentValue; break; default: $this->nu_anoFim->ViewValue = $this->nu_anoFim->CurrentValue; } } else { $this->nu_anoFim->ViewValue = NULL; } $this->nu_anoFim->ViewCustomAttributes = ""; // no_periodo $this->no_periodo->ViewValue = $this->no_periodo->CurrentValue; $this->no_periodo->ViewCustomAttributes = ""; // ic_situacao if (strval($this->ic_situacao->CurrentValue) <> "") { switch ($this->ic_situacao->CurrentValue) { case $this->ic_situacao->FldTagValue(1): $this->ic_situacao->ViewValue = $this->ic_situacao->FldTagCaption(1) <> "" ? $this->ic_situacao->FldTagCaption(1) : $this->ic_situacao->CurrentValue; break; case $this->ic_situacao->FldTagValue(2): $this->ic_situacao->ViewValue = $this->ic_situacao->FldTagCaption(2) <> "" ? $this->ic_situacao->FldTagCaption(2) : $this->ic_situacao->CurrentValue; break; case $this->ic_situacao->FldTagValue(3): $this->ic_situacao->ViewValue = $this->ic_situacao->FldTagCaption(3) <> "" ? $this->ic_situacao->FldTagCaption(3) : $this->ic_situacao->CurrentValue; break; case $this->ic_situacao->FldTagValue(4): $this->ic_situacao->ViewValue = $this->ic_situacao->FldTagCaption(4) <> "" ? $this->ic_situacao->FldTagCaption(4) : $this->ic_situacao->CurrentValue; break; default: $this->ic_situacao->ViewValue = $this->ic_situacao->CurrentValue; } } else { $this->ic_situacao->ViewValue = NULL; } $this->ic_situacao->ViewCustomAttributes = ""; // nu_anoInicio $this->nu_anoInicio->LinkCustomAttributes = ""; $this->nu_anoInicio->HrefValue = ""; $this->nu_anoInicio->TooltipValue = ""; // nu_anoFim $this->nu_anoFim->LinkCustomAttributes = ""; $this->nu_anoFim->HrefValue = ""; $this->nu_anoFim->TooltipValue = ""; // no_periodo $this->no_periodo->LinkCustomAttributes = ""; $this->no_periodo->HrefValue = ""; $this->no_periodo->TooltipValue = ""; // ic_situacao $this->ic_situacao->LinkCustomAttributes = ""; $this->ic_situacao->HrefValue = ""; $this->ic_situacao->TooltipValue = ""; } elseif ($this->RowType == EW_ROWTYPE_ADD) { // Add row // nu_anoInicio $this->nu_anoInicio->EditCustomAttributes = ""; $arwrk = array(); $arwrk[] = array($this->nu_anoInicio->FldTagValue(1), $this->nu_anoInicio->FldTagCaption(1) <> "" ? $this->nu_anoInicio->FldTagCaption(1) : $this->nu_anoInicio->FldTagValue(1)); $arwrk[] = array($this->nu_anoInicio->FldTagValue(2), $this->nu_anoInicio->FldTagCaption(2) <> "" ? $this->nu_anoInicio->FldTagCaption(2) : $this->nu_anoInicio->FldTagValue(2)); $arwrk[] = array($this->nu_anoInicio->FldTagValue(3), $this->nu_anoInicio->FldTagCaption(3) <> "" ? $this->nu_anoInicio->FldTagCaption(3) : $this->nu_anoInicio->FldTagValue(3)); $arwrk[] = array($this->nu_anoInicio->FldTagValue(4), $this->nu_anoInicio->FldTagCaption(4) <> "" ? $this->nu_anoInicio->FldTagCaption(4) : $this->nu_anoInicio->FldTagValue(4)); $arwrk[] = array($this->nu_anoInicio->FldTagValue(5), $this->nu_anoInicio->FldTagCaption(5) <> "" ? $this->nu_anoInicio->FldTagCaption(5) : $this->nu_anoInicio->FldTagValue(5)); $arwrk[] = array($this->nu_anoInicio->FldTagValue(6), $this->nu_anoInicio->FldTagCaption(6) <> "" ? $this->nu_anoInicio->FldTagCaption(6) : $this->nu_anoInicio->FldTagValue(6)); $arwrk[] = array($this->nu_anoInicio->FldTagValue(7), $this->nu_anoInicio->FldTagCaption(7) <> "" ? $this->nu_anoInicio->FldTagCaption(7) : $this->nu_anoInicio->FldTagValue(7)); $arwrk[] = array($this->nu_anoInicio->FldTagValue(8), $this->nu_anoInicio->FldTagCaption(8) <> "" ? $this->nu_anoInicio->FldTagCaption(8) : $this->nu_anoInicio->FldTagValue(8)); $arwrk[] = array($this->nu_anoInicio->FldTagValue(9), $this->nu_anoInicio->FldTagCaption(9) <> "" ? $this->nu_anoInicio->FldTagCaption(9) : $this->nu_anoInicio->FldTagValue(9)); $arwrk[] = array($this->nu_anoInicio->FldTagValue(10), $this->nu_anoInicio->FldTagCaption(10) <> "" ? $this->nu_anoInicio->FldTagCaption(10) : $this->nu_anoInicio->FldTagValue(10)); $arwrk[] = array($this->nu_anoInicio->FldTagValue(11), $this->nu_anoInicio->FldTagCaption(11) <> "" ? $this->nu_anoInicio->FldTagCaption(11) : $this->nu_anoInicio->FldTagValue(11)); $arwrk[] = array($this->nu_anoInicio->FldTagValue(12), $this->nu_anoInicio->FldTagCaption(12) <> "" ? $this->nu_anoInicio->FldTagCaption(12) : $this->nu_anoInicio->FldTagValue(12)); $arwrk[] = array($this->nu_anoInicio->FldTagValue(13), $this->nu_anoInicio->FldTagCaption(13) <> "" ? $this->nu_anoInicio->FldTagCaption(13) : $this->nu_anoInicio->FldTagValue(13)); $arwrk[] = array($this->nu_anoInicio->FldTagValue(14), $this->nu_anoInicio->FldTagCaption(14) <> "" ? $this->nu_anoInicio->FldTagCaption(14) : $this->nu_anoInicio->FldTagValue(14)); $arwrk[] = array($this->nu_anoInicio->FldTagValue(15), $this->nu_anoInicio->FldTagCaption(15) <> "" ? $this->nu_anoInicio->FldTagCaption(15) : $this->nu_anoInicio->FldTagValue(15)); $arwrk[] = array($this->nu_anoInicio->FldTagValue(16), $this->nu_anoInicio->FldTagCaption(16) <> "" ? $this->nu_anoInicio->FldTagCaption(16) : $this->nu_anoInicio->FldTagValue(16)); $arwrk[] = array($this->nu_anoInicio->FldTagValue(17), $this->nu_anoInicio->FldTagCaption(17) <> "" ? $this->nu_anoInicio->FldTagCaption(17) : $this->nu_anoInicio->FldTagValue(17)); array_unshift($arwrk, array("", $Language->Phrase("PleaseSelect"))); $this->nu_anoInicio->EditValue = $arwrk; // nu_anoFim $this->nu_anoFim->EditCustomAttributes = ""; $arwrk = array(); $arwrk[] = array($this->nu_anoFim->FldTagValue(1), $this->nu_anoFim->FldTagCaption(1) <> "" ? $this->nu_anoFim->FldTagCaption(1) : $this->nu_anoFim->FldTagValue(1)); $arwrk[] = array($this->nu_anoFim->FldTagValue(2), $this->nu_anoFim->FldTagCaption(2) <> "" ? $this->nu_anoFim->FldTagCaption(2) : $this->nu_anoFim->FldTagValue(2)); $arwrk[] = array($this->nu_anoFim->FldTagValue(3), $this->nu_anoFim->FldTagCaption(3) <> "" ? $this->nu_anoFim->FldTagCaption(3) : $this->nu_anoFim->FldTagValue(3)); $arwrk[] = array($this->nu_anoFim->FldTagValue(4), $this->nu_anoFim->FldTagCaption(4) <> "" ? $this->nu_anoFim->FldTagCaption(4) : $this->nu_anoFim->FldTagValue(4)); $arwrk[] = array($this->nu_anoFim->FldTagValue(5), $this->nu_anoFim->FldTagCaption(5) <> "" ? $this->nu_anoFim->FldTagCaption(5) : $this->nu_anoFim->FldTagValue(5)); $arwrk[] = array($this->nu_anoFim->FldTagValue(6), $this->nu_anoFim->FldTagCaption(6) <> "" ? $this->nu_anoFim->FldTagCaption(6) : $this->nu_anoFim->FldTagValue(6)); $arwrk[] = array($this->nu_anoFim->FldTagValue(7), $this->nu_anoFim->FldTagCaption(7) <> "" ? $this->nu_anoFim->FldTagCaption(7) : $this->nu_anoFim->FldTagValue(7)); $arwrk[] = array($this->nu_anoFim->FldTagValue(8), $this->nu_anoFim->FldTagCaption(8) <> "" ? $this->nu_anoFim->FldTagCaption(8) : $this->nu_anoFim->FldTagValue(8)); $arwrk[] = array($this->nu_anoFim->FldTagValue(9), $this->nu_anoFim->FldTagCaption(9) <> "" ? $this->nu_anoFim->FldTagCaption(9) : $this->nu_anoFim->FldTagValue(9)); $arwrk[] = array($this->nu_anoFim->FldTagValue(10), $this->nu_anoFim->FldTagCaption(10) <> "" ? $this->nu_anoFim->FldTagCaption(10) : $this->nu_anoFim->FldTagValue(10)); $arwrk[] = array($this->nu_anoFim->FldTagValue(11), $this->nu_anoFim->FldTagCaption(11) <> "" ? $this->nu_anoFim->FldTagCaption(11) : $this->nu_anoFim->FldTagValue(11)); $arwrk[] = array($this->nu_anoFim->FldTagValue(12), $this->nu_anoFim->FldTagCaption(12) <> "" ? $this->nu_anoFim->FldTagCaption(12) : $this->nu_anoFim->FldTagValue(12)); $arwrk[] = array($this->nu_anoFim->FldTagValue(13), $this->nu_anoFim->FldTagCaption(13) <> "" ? $this->nu_anoFim->FldTagCaption(13) : $this->nu_anoFim->FldTagValue(13)); $arwrk[] = array($this->nu_anoFim->FldTagValue(14), $this->nu_anoFim->FldTagCaption(14) <> "" ? $this->nu_anoFim->FldTagCaption(14) : $this->nu_anoFim->FldTagValue(14)); $arwrk[] = array($this->nu_anoFim->FldTagValue(15), $this->nu_anoFim->FldTagCaption(15) <> "" ? $this->nu_anoFim->FldTagCaption(15) : $this->nu_anoFim->FldTagValue(15)); $arwrk[] = array($this->nu_anoFim->FldTagValue(16), $this->nu_anoFim->FldTagCaption(16) <> "" ? $this->nu_anoFim->FldTagCaption(16) : $this->nu_anoFim->FldTagValue(16)); $arwrk[] = array($this->nu_anoFim->FldTagValue(17), $this->nu_anoFim->FldTagCaption(17) <> "" ? $this->nu_anoFim->FldTagCaption(17) : $this->nu_anoFim->FldTagValue(17)); array_unshift($arwrk, array("", $Language->Phrase("PleaseSelect"))); $this->nu_anoFim->EditValue = $arwrk; // no_periodo $this->no_periodo->EditCustomAttributes = ""; $this->no_periodo->EditValue = ew_HtmlEncode($this->no_periodo->CurrentValue); $this->no_periodo->PlaceHolder = ew_HtmlEncode(ew_RemoveHtml($this->no_periodo->FldCaption())); // ic_situacao $this->ic_situacao->EditCustomAttributes = ""; $arwrk = array(); $arwrk[] = array($this->ic_situacao->FldTagValue(1), $this->ic_situacao->FldTagCaption(1) <> "" ? $this->ic_situacao->FldTagCaption(1) : $this->ic_situacao->FldTagValue(1)); $arwrk[] = array($this->ic_situacao->FldTagValue(2), $this->ic_situacao->FldTagCaption(2) <> "" ? $this->ic_situacao->FldTagCaption(2) : $this->ic_situacao->FldTagValue(2)); $arwrk[] = array($this->ic_situacao->FldTagValue(3), $this->ic_situacao->FldTagCaption(3) <> "" ? $this->ic_situacao->FldTagCaption(3) : $this->ic_situacao->FldTagValue(3)); $arwrk[] = array($this->ic_situacao->FldTagValue(4), $this->ic_situacao->FldTagCaption(4) <> "" ? $this->ic_situacao->FldTagCaption(4) : $this->ic_situacao->FldTagValue(4)); array_unshift($arwrk, array("", $Language->Phrase("PleaseSelect"))); $this->ic_situacao->EditValue = $arwrk; // Edit refer script // nu_anoInicio $this->nu_anoInicio->HrefValue = ""; // nu_anoFim $this->nu_anoFim->HrefValue = ""; // no_periodo $this->no_periodo->HrefValue = ""; // ic_situacao $this->ic_situacao->HrefValue = ""; } if ($this->RowType == EW_ROWTYPE_ADD || $this->RowType == EW_ROWTYPE_EDIT || $this->RowType == EW_ROWTYPE_SEARCH) { // Add / Edit / Search row $this->SetupFieldTitles(); } // Call Row Rendered event if ($this->RowType <> EW_ROWTYPE_AGGREGATEINIT) $this->Row_Rendered(); } // Validate form function ValidateForm() { global $Language, $gsFormError; // Initialize form error message $gsFormError = ""; // Check if validation required if (!EW_SERVER_VALIDATE) return ($gsFormError == ""); if (!$this->nu_anoInicio->FldIsDetailKey && !is_null($this->nu_anoInicio->FormValue) && $this->nu_anoInicio->FormValue == "") { ew_AddMessage($gsFormError, $Language->Phrase("EnterRequiredField") . " - " . $this->nu_anoInicio->FldCaption()); } if (!$this->nu_anoFim->FldIsDetailKey && !is_null($this->nu_anoFim->FormValue) && $this->nu_anoFim->FormValue == "") { ew_AddMessage($gsFormError, $Language->Phrase("EnterRequiredField") . " - " . $this->nu_anoFim->FldCaption()); } if (!$this->ic_situacao->FldIsDetailKey && !is_null($this->ic_situacao->FormValue) && $this->ic_situacao->FormValue == "") { ew_AddMessage($gsFormError, $Language->Phrase("EnterRequiredField") . " - " . $this->ic_situacao->FldCaption()); } // Return validate result $ValidateForm = ($gsFormError == ""); // Call Form_CustomValidate event $sFormCustomError = ""; $ValidateForm = $ValidateForm && $this->Form_CustomValidate($sFormCustomError); if ($sFormCustomError <> "") { ew_AddMessage($gsFormError, $sFormCustomError); } return $ValidateForm; } // Add record function AddRow($rsold = NULL) { global $conn, $Language, $Security; // Load db values from rsold if ($rsold) { $this->LoadDbValues($rsold); } $rsnew = array(); // nu_anoInicio $this->nu_anoInicio->SetDbValueDef($rsnew, $this->nu_anoInicio->CurrentValue, NULL, FALSE); // nu_anoFim $this->nu_anoFim->SetDbValueDef($rsnew, $this->nu_anoFim->CurrentValue, NULL, FALSE); // no_periodo $this->no_periodo->SetDbValueDef($rsnew, $this->no_periodo->CurrentValue, NULL, FALSE); // ic_situacao $this->ic_situacao->SetDbValueDef($rsnew, $this->ic_situacao->CurrentValue, NULL, FALSE); // Call Row Inserting event $rs = ($rsold == NULL) ? NULL : $rsold->fields; $bInsertRow = $this->Row_Inserting($rs, $rsnew); if ($bInsertRow) { $conn->raiseErrorFn = 'ew_ErrorFn'; $AddRow = $this->Insert($rsnew); $conn->raiseErrorFn = ''; if ($AddRow) { } } else { if ($this->getSuccessMessage() <> "" || $this->getFailureMessage() <> "") { // Use the message, do nothing } elseif ($this->CancelMessage <> "") { $this->setFailureMessage($this->CancelMessage); $this->CancelMessage = ""; } else { $this->setFailureMessage($Language->Phrase("InsertCancelled")); } $AddRow = FALSE; } // Get insert id if necessary if ($AddRow) { $this->nu_periodoPei->setDbValue($conn->Insert_ID()); $rsnew['nu_periodoPei'] = $this->nu_periodoPei->DbValue; } if ($AddRow) { // Call Row Inserted event $rs = ($rsold == NULL) ? NULL : $rsold->fields; $this->Row_Inserted($rs, $rsnew); } return $AddRow; } // Set up Breadcrumb function SetupBreadcrumb() { global $Breadcrumb, $Language; $Breadcrumb = new cBreadcrumb(); $PageCaption = $this->TableCaption(); $Breadcrumb->Add("list", "<span id=\"ewPageCaption\">" . $PageCaption . "</span>", "periodopeilist.php", $this->TableVar); $PageCaption = ($this->CurrentAction == "C") ? $Language->Phrase("Copy") : $Language->Phrase("Add"); $Breadcrumb->Add("add", "<span id=\"ewPageCaption\">" . $PageCaption . "</span>", ew_CurrentUrl(), $this->TableVar); } // Page Load event function Page_Load() { //echo "Page Load"; } // Page Unload event function Page_Unload() { //echo "Page Unload"; } // Page Redirecting event function Page_Redirecting(&$url) { // Example: //$url = "your URL"; } // Message Showing event // $type = ''|'success'|'failure'|'warning' function Message_Showing(&$msg, $type) { if ($type == 'success') { //$msg = "your success message"; } elseif ($type == 'failure') { //$msg = "your failure message"; } elseif ($type == 'warning') { //$msg = "your warning message"; } else { //$msg = "your message"; } } // Page Render event function Page_Render() { //echo "Page Render"; } // Page Data Rendering event function Page_DataRendering(&$header) { // Example: //$header = "your header"; } // Page Data Rendered event function Page_DataRendered(&$footer) { // Example: //$footer = "your footer"; } // Form Custom Validate event function Form_CustomValidate(&$CustomError) { // Return error message in CustomError return TRUE; } } ?> <?php ew_Header(FALSE) ?> <?php // Create page object if (!isset($periodopei_add)) $periodopei_add = new cperiodopei_add(); // Page init $periodopei_add->Page_Init(); // Page main $periodopei_add->Page_Main(); // Global Page Rendering event (in userfn*.php) Page_Rendering(); // Page Rendering event $periodopei_add->Page_Render(); ?> <?php include_once "header.php" ?> <script type="text/javascript"> // Page object var periodopei_add = new ew_Page("periodopei_add"); periodopei_add.PageID = "add"; // Page ID var EW_PAGE_ID = periodopei_add.PageID; // For backward compatibility // Form object var fperiodopeiadd = new ew_Form("fperiodopeiadd"); // Validate form fperiodopeiadd.Validate = function() { if (!this.ValidateRequired) return true; // Ignore validation var $ = jQuery, fobj = this.GetForm(), $fobj = $(fobj); this.PostAutoSuggest(); if ($fobj.find("#a_confirm").val() == "F") return true; var elm, felm, uelm, addcnt = 0; var $k = $fobj.find("#" + this.FormKeyCountName); // Get key_count var rowcnt = ($k[0]) ? parseInt($k.val(), 10) : 1; var startcnt = (rowcnt == 0) ? 0 : 1; // Check rowcnt == 0 => Inline-Add var gridinsert = $fobj.find("#a_list").val() == "gridinsert"; for (var i = startcnt; i <= rowcnt; i++) { var infix = ($k[0]) ? String(i) : ""; $fobj.data("rowindex", infix); elm = this.GetElements("x" + infix + "_nu_anoInicio"); if (elm && !ew_HasValue(elm)) return this.OnError(elm, ewLanguage.Phrase("EnterRequiredField") + " - <?php echo ew_JsEncode2($periodopei->nu_anoInicio->FldCaption()) ?>"); elm = this.GetElements("x" + infix + "_nu_anoFim"); if (elm && !ew_HasValue(elm)) return this.OnError(elm, ewLanguage.Phrase("EnterRequiredField") + " - <?php echo ew_JsEncode2($periodopei->nu_anoFim->FldCaption()) ?>"); elm = this.GetElements("x" + infix + "_ic_situacao"); if (elm && !ew_HasValue(elm)) return this.OnError(elm, ewLanguage.Phrase("EnterRequiredField") + " - <?php echo ew_JsEncode2($periodopei->ic_situacao->FldCaption()) ?>"); // Set up row object ew_ElementsToRow(fobj); // Fire Form_CustomValidate event if (!this.Form_CustomValidate(fobj)) return false; } // Process detail forms var dfs = $fobj.find("input[name='detailpage']").get(); for (var i = 0; i < dfs.length; i++) { var df = dfs[i], val = df.value; if (val && ewForms[val]) if (!ewForms[val].Validate()) return false; } return true; } // Form_CustomValidate event fperiodopeiadd.Form_CustomValidate = function(fobj) { // DO NOT CHANGE THIS LINE! // Your custom validation code here, return false if invalid. return true; } // Use JavaScript validation or not <?php if (EW_CLIENT_VALIDATE) { ?> fperiodopeiadd.ValidateRequired = true; <?php } else { ?> fperiodopeiadd.ValidateRequired = false; <?php } ?> // Dynamic selection lists // Form object for search </script> <script type="text/javascript"> // Write your client script here, no need to add script tags. </script> <?php $Breadcrumb->Render(); ?> <?php $periodopei_add->ShowPageHeader(); ?> <?php $periodopei_add->ShowMessage(); ?> <form name="fperiodopeiadd" id="fperiodopeiadd" class="ewForm form-horizontal" action="<?php echo ew_CurrentPage() ?>" method="post"> <input type="hidden" name="t" value="periodopei"> <input type="hidden" name="a_add" id="a_add" value="A"> <table cellspacing="0" class="ewGrid"><tr><td> <table id="tbl_periodopeiadd" class="table table-bordered table-striped"> <?php if ($periodopei->nu_anoInicio->Visible) { // nu_anoInicio ?> <tr id="r_nu_anoInicio"> <td><span id="elh_periodopei_nu_anoInicio"><?php echo $periodopei->nu_anoInicio->FldCaption() ?><?php echo $Language->Phrase("FieldRequiredIndicator") ?></span></td> <td<?php echo $periodopei->nu_anoInicio->CellAttributes() ?>> <span id="el_periodopei_nu_anoInicio" class="control-group"> <select data-field="x_nu_anoInicio" id="x_nu_anoInicio" name="x_nu_anoInicio"<?php echo $periodopei->nu_anoInicio->EditAttributes() ?>> <?php if (is_array($periodopei->nu_anoInicio->EditValue)) { $arwrk = $periodopei->nu_anoInicio->EditValue; $rowswrk = count($arwrk); $emptywrk = TRUE; for ($rowcntwrk = 0; $rowcntwrk < $rowswrk; $rowcntwrk++) { $selwrk = (strval($periodopei->nu_anoInicio->CurrentValue) == strval($arwrk[$rowcntwrk][0])) ? " selected=\"selected\"" : ""; if ($selwrk <> "") $emptywrk = FALSE; ?> <option value="<?php echo ew_HtmlEncode($arwrk[$rowcntwrk][0]) ?>"<?php echo $selwrk ?>> <?php echo $arwrk[$rowcntwrk][1] ?> </option> <?php } } ?> </select> </span> <?php echo $periodopei->nu_anoInicio->CustomMsg ?></td> </tr> <?php } ?> <?php if ($periodopei->nu_anoFim->Visible) { // nu_anoFim ?> <tr id="r_nu_anoFim"> <td><span id="elh_periodopei_nu_anoFim"><?php echo $periodopei->nu_anoFim->FldCaption() ?><?php echo $Language->Phrase("FieldRequiredIndicator") ?></span></td> <td<?php echo $periodopei->nu_anoFim->CellAttributes() ?>> <span id="el_periodopei_nu_anoFim" class="control-group"> <select data-field="x_nu_anoFim" id="x_nu_anoFim" name="x_nu_anoFim"<?php echo $periodopei->nu_anoFim->EditAttributes() ?>> <?php if (is_array($periodopei->nu_anoFim->EditValue)) { $arwrk = $periodopei->nu_anoFim->EditValue; $rowswrk = count($arwrk); $emptywrk = TRUE; for ($rowcntwrk = 0; $rowcntwrk < $rowswrk; $rowcntwrk++) { $selwrk = (strval($periodopei->nu_anoFim->CurrentValue) == strval($arwrk[$rowcntwrk][0])) ? " selected=\"selected\"" : ""; if ($selwrk <> "") $emptywrk = FALSE; ?> <option value="<?php echo ew_HtmlEncode($arwrk[$rowcntwrk][0]) ?>"<?php echo $selwrk ?>> <?php echo $arwrk[$rowcntwrk][1] ?> </option> <?php } } ?> </select> </span> <?php echo $periodopei->nu_anoFim->CustomMsg ?></td> </tr> <?php } ?> <?php if ($periodopei->no_periodo->Visible) { // no_periodo ?> <tr id="r_no_periodo"> <td><span id="elh_periodopei_no_periodo"><?php echo $periodopei->no_periodo->FldCaption() ?></span></td> <td<?php echo $periodopei->no_periodo->CellAttributes() ?>> <span id="el_periodopei_no_periodo" class="control-group"> <input type="text" data-field="x_no_periodo" name="x_no_periodo" id="x_no_periodo" size="30" maxlength="15" placeholder="<?php echo $periodopei->no_periodo->PlaceHolder ?>" value="<?php echo $periodopei->no_periodo->EditValue ?>"<?php echo $periodopei->no_periodo->EditAttributes() ?>> </span> <?php echo $periodopei->no_periodo->CustomMsg ?></td> </tr> <?php } ?> <?php if ($periodopei->ic_situacao->Visible) { // ic_situacao ?> <tr id="r_ic_situacao"> <td><span id="elh_periodopei_ic_situacao"><?php echo $periodopei->ic_situacao->FldCaption() ?><?php echo $Language->Phrase("FieldRequiredIndicator") ?></span></td> <td<?php echo $periodopei->ic_situacao->CellAttributes() ?>> <span id="el_periodopei_ic_situacao" class="control-group"> <select data-field="x_ic_situacao" id="x_ic_situacao" name="x_ic_situacao"<?php echo $periodopei->ic_situacao->EditAttributes() ?>> <?php if (is_array($periodopei->ic_situacao->EditValue)) { $arwrk = $periodopei->ic_situacao->EditValue; $rowswrk = count($arwrk); $emptywrk = TRUE; for ($rowcntwrk = 0; $rowcntwrk < $rowswrk; $rowcntwrk++) { $selwrk = (strval($periodopei->ic_situacao->CurrentValue) == strval($arwrk[$rowcntwrk][0])) ? " selected=\"selected\"" : ""; if ($selwrk <> "") $emptywrk = FALSE; ?> <option value="<?php echo ew_HtmlEncode($arwrk[$rowcntwrk][0]) ?>"<?php echo $selwrk ?>> <?php echo $arwrk[$rowcntwrk][1] ?> </option> <?php } } ?> </select> </span> <?php echo $periodopei->ic_situacao->CustomMsg ?></td> </tr> <?php } ?> </table> </td></tr></table> <button class="btn btn-primary ewButton" name="btnAction" id="btnAction" type="submit"><?php echo $Language->Phrase("AddBtn") ?></button> </form> <script type="text/javascript"> fperiodopeiadd.Init(); <?php if (EW_MOBILE_REFLOW && ew_IsMobile()) { ?> ew_Reflow(); <?php } ?> </script> <?php $periodopei_add->ShowPageFooter(); if (EW_DEBUG_ENABLED) echo ew_DebugMsg(); ?> <script type="text/javascript"> // Write your table-specific startup script here // document.write("page loaded"); </script> <?php include_once "footer.php" ?> <?php $periodopei_add->Page_Terminate(); ?>
ismaelmelo/git-zapmetrics
02 - Prototipação/01 - Fontes/periodopeiadd.php
PHP
gpl-2.0
44,683
/* * Copyright (C) 2012 Glencoe Software, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <omero/fixture.h> #include <omero/callbacks.h> #include <omero/all.h> #include <string> #include <map> #include <IceUtil/RecMutex.h> #include <IceUtil/Config.h> #include <Ice/Handle.h> #include <omero/util/concurrency.h> using namespace std; using namespace omero; using namespace omero::api; using namespace omero::cmd; using namespace omero::callbacks; using namespace omero::model; using namespace omero::rtypes; using namespace omero::sys; class TestCB; typedef CallbackWrapper<TestCB> TestCBPtr; class TestCB: virtual public CmdCallbackI { private: // Preventing copy-construction and assigning by value. TestCB& operator=(const TestCB& rv); TestCB(TestCB&); IceUtil::RecMutex mutex; public: omero::util::concurrency::Event event; int steps; int finished; TestCB(const omero::client_ptr client, const HandlePrx& handle) : CmdCallbackI(client, handle), steps(0), finished(0) {} ~TestCB(){} virtual void step(int complete, int total, const Ice::Current& current = Ice::Current()) { IceUtil::RecMutex::Lock lock(mutex); steps++; } virtual void onFinished(const ResponsePtr& rsp, const StatusPtr& s, const Ice::Current& current = Ice::Current()) { IceUtil::RecMutex::Lock lock(mutex); finished++; event.set(); } void assertSteps() { IceUtil::RecMutex::Lock lock(mutex); // Not guranteed to get called for all steps, as the callback can // get added on the server after the operation has already started // if there is network latency ASSERT_GE(steps, 1); } void assertFinished(bool testSteps = true) { IceUtil::RecMutex::Lock lock(mutex); ASSERT_EQ(1, finished); ASSERT_FALSE(isCancelled()); ASSERT_FALSE(isFailure()); ResponsePtr rsp = getResponse(); if (!rsp) { FAIL() << "null response"; } ERRPtr err = ERRPtr::dynamicCast(rsp); if (err) { ostringstream ss; omero::cmd::StringMap::iterator it; for (it=err->parameters.begin(); it != err->parameters.end(); it++ ) { ss << (*it).first << " => " << (*it).second << endl; } FAIL() << "ERR!" << "cat:" << err->category << "\n" << "name:" << err->name << "\n" << "params:" << ss.str() << "\n"; } if (testSteps) { assertSteps(); } } void assertCancelled() { IceUtil::RecMutex::Lock lock(mutex); ASSERT_EQ(1, finished); ASSERT_TRUE(isCancelled()); } }; class CBFixture : virtual public Fixture { public: TestCBPtr run(const RequestPtr& req, int addCbDelay = 0) { ExperimenterPtr user = newUser(); login(user->getOmeName()->getValue()); HandlePrx handle = client->getSession()->submit(req); if (addCbDelay > 0) { omero::util::concurrency::Event event; event.wait(IceUtil::Time::milliSeconds(addCbDelay)); } return new TestCB(client, handle); } // Timing // ========================================================================= TestCBPtr timing(int millis, int steps, int addCbDelay = 0) { omero::cmd::TimingPtr t = new Timing(); t->millisPerStep = millis; t->steps = steps; return run(t, addCbDelay); } // DoAll // ========================================================================= TestCBPtr doAllOfNothing() { return run(new omero::cmd::DoAll()); } TestCBPtr doAllTiming(int count) { omero::cmd::RequestList timings; for (int i = 0; i < count; i++) { omero::cmd::TimingPtr t = new omero::cmd::Timing(); t->steps = 3; t->millisPerStep = 2; timings.push_back(t); } omero::cmd::DoAllPtr all = new omero::cmd::DoAll(); all->requests = timings; return run(all); } }; TEST(CmdCallbackTest, testTimingFinishesOnLatch) { CBFixture f; TestCBPtr cb = f.timing(25, 4 * 10); // Runs 1 second cb->event.wait(IceUtil::Time::milliSeconds(1500)); cb->assertFinished(); } TEST(CmdCallbackTest, testTimingFinishesOnBlock) { CBFixture f; TestCBPtr cb = f.timing(25, 4 * 10); // Runs 1 second cb->block(1500); cb->assertFinished(); } TEST(CmdCallbackTest, testTimingFinishesOnLoop) { CBFixture f; TestCBPtr cb = f.timing(25, 4 * 10); // Runs 1 second cb->loop(3, 500); cb->assertFinished(); } TEST(CmdCallbackTest, testDoNothingFinishesOnLatch) { CBFixture f; TestCBPtr cb = f.doAllOfNothing(); cb->event.wait(IceUtil::Time::milliSeconds(5000)); cb->assertCancelled(); } TEST(CmdCallbackTest, testDoNothingFinishesOnLoop) { CBFixture f; TestCBPtr cb = f.doAllOfNothing(); cb->loop(5, 1000); cb->assertCancelled(); } TEST(CmdCallbackTest, testDoAllTimingFinishesOnLoop) { CBFixture f; TestCBPtr cb = f.doAllTiming(5); cb->loop(5, 1000); cb->assertFinished(); // For some reason the number of steps is varying between 10 and 15 } TEST(CmdCallbackTest, testAddAfterFinish) { CBFixture f; TestCBPtr cb = f.timing(25, 4 * 10, 1200); // Runs 1 second cb->event.wait(IceUtil::Time::milliSeconds(1500)); cb->assertFinished(false); }
emilroz/openmicroscopy
components/tools/OmeroCpp/test/integration/cmdcallbacktest.cpp
C++
gpl-2.0
6,231
# # Copyright 2001 - 2011 Ludek Smid [http://www.ospace.net/] # # This file is part of IGE - Outer Space. # # IGE - Outer Space is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # IGE - Outer Space 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 IGE - Outer Space; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from ige import * from ige import log from ige.IObject import IObject from ige.IDataHolder import IDataHolder from Const import * import Rules, Utils, math, ShipUtils, time import re from ai_parser import AIList class IPlayer(IObject): typeID = T_PLAYER resignTo = T_AIPLAYER forums = {"INBOX": 56, "OUTBOX": 56, "EVENTS": 4} def init(self, obj): IObject.init(self, obj) # obj.login = u'' obj.fullName = u'' # obj.buoys = {} obj.alliedBuoys = {} obj.planets = [] obj.fleets = [] obj.techs = {} # techs and their sublevel obj.obsoleteTechs = set() obj.rsrchQueue = [] obj.sciPoints = 0 obj.effSciPoints = 0 obj.techLevel = 1 obj.shipDesigns = {} obj.race = "H" # race Bionic, Human, Cyborg # bonuses obj.prodEff = 1.0 obj.sciEff = 1.0 # obj.govPwr = 0 obj.govPwrCtrlRange = 1 # fleet support obj.fleetUpgradePool = 0.0 obj.fleetUpgradeInProgress = 0 # production obj.prodQueues = [[],[],[],[],[]] obj.prodIncreasePool = 0.0 # diplomacy obj.diplomacyRels = {} obj.defaultRelation = Rules.defaultRelation obj.voteFor = OID_NONE obj.governorOf = OID_NONE obj.governors = [] obj.alliance = OID_NONE obj.imperator = 0 # combat # anti-small, anti-medium, anti-large, shield generator obj.planetWeapons = [None, None, None, None, None] # obj.staticMap = {} obj.dynamicMap = {} obj.galaxies = [] obj.validSystems = [] # obj.stats = IDataHolder() obj.stats.type = T_STATS obj.timeEnabled = 0 obj.stratRes = {} obj.lastLogin = 0.0 # obj.shipRedirections = {} obj.buoys = {} # obj.clientStats = {} def update(self, tran, obj): # update all designs for designID in obj.shipDesigns: old = obj.shipDesigns[designID] new = ShipUtils.makeShipMinSpec(obj, old.name, old.hullID, old.eqIDs, old.improvements, raiseExs = False) new.built = old.built if hasattr(old, "upgradeTo"): new.upgradeTo = old.upgradeTo obj.shipDesigns[designID] = new # check all diplomacyRels for partyID in obj.diplomacyRels.keys(): party = tran.db.get(partyID, None) if not party or party.type not in PLAYER_TYPES: log.debug("Deleting party", obj.oid, partyID) del obj.diplomacyRels[partyID] # delete obj with low scan pwr # check type of the objects in the map for objID in obj.staticMap.keys(): obj.staticMap[objID] = min(obj.staticMap[objID], Rules.maxScanPwr) if obj.staticMap[objID] < Rules.level1InfoScanPwr: del obj.staticMap[objID] if not tran.db.has_key(objID) or tran.db[objID].type not in (T_SYSTEM, T_WORMHOLE): log.debug("Deleting non system %d from static map of player %d" % (objID, obj.oid)) del obj.staticMap[objID] for objID in obj.dynamicMap.keys(): if obj.dynamicMap[objID] < Rules.level1InfoScanPwr: del obj.dynamicMap[objID] if not tran.db.has_key(objID) or tran.db[objID].type not in (T_FLEET, T_ASTEROID): log.debug("Deleting obj %d from dynamic map of player %d" % (objID, objID)) del obj.dynamicMap[objID] # check if all planets are planets for objID in obj.planets[:]: try: if not tran.db.has_key(objID): log.debug("Planet does not exists - removing", obj.oid, objID) obj.planets.remove(objID) if tran.db[objID].type != T_PLANET: log.debug("Planet is not a planet - removing", obj.oid, objID) obj.planets.remove(objID) except: log.warning("There is a problem when processing planet - removing", obj.oid, objID) obj.planets.remove(objID) # check if systems in buoys are systems for objID in obj.buoys.keys(): try: if not tran.db.has_key(objID): log.debug("System for buoy does not exists - removing", obj.oid, objID) del obj.buoys[objID] if tran.db[objID].type not in (T_SYSTEM, T_WORMHOLE): log.debug("System for buoy is not a system - removing", obj.oid, objID) del obj.buoys[objID] except: log.warning("There is a problem when processing system for buoy - removing", obj.oid, objID) del obj.buoys[objID] # check if fleets are fleets for objID in obj.fleets[:]: try: if not tran.db.has_key(objID): log.debug("Fleet does not exists - removing", obj.oid, objID) obj.fleets.remove(objID) if tran.db[objID].type not in (T_FLEET, T_ASTEROID): log.debug("Fleet is not a fleet - removing", obj.oid, objID) obj.fleets.remove(objID) except: log.warning("There is a problem when processing planet - removing", obj.oid, objID) # check accessible technologies wip = 1 while wip: wip = 0 for techID in obj.techs.keys(): if techID not in Rules.techs: wip = 1 log.debug("Deleting nonexistent tech", techID, "player", obj.oid) del obj.techs[techID] continue tech = Rules.techs[techID] # check tech level if tech.level > obj.techLevel: wip = 1 log.debug("Deleting tech", techID, "player", obj.oid) if techID in obj.techs: del obj.techs[techID] # disabled? #for tmpTechID in obj.techs.keys(): # if techID in Rules.techs[tmpTechID].researchDisables: # wip = 1 # log.debug("Deleting tech", techID, "player", obj.oid) # if techID in obj.techs: del obj.techs[techID] # break # check requirements #for tmpTechID, improvement in tech.researchRequires: # if not obj.techs.has_key(tmpTechID) or obj.techs[tmpTechID] < improvement: # wip = 1 # log.debug("Deleting tech", techID, "player", obj.oid) # if techID in obj.techs: del obj.techs[techID] # break for rTask in obj.rsrchQueue[:]: if rTask.techID not in Rules.techs: log.debug("Deleting res task for nonexistent tech", rTask.techID, "player", obj.oid) obj.rsrchQueue.remove(rTask) continue tech = Rules.techs[rTask.techID] if tech.level == 99: log.debug("Deleting res task", rTask.techID, "player", obj.oid) obj.rsrchQueue.remove(rTask) # check if player is in the universe universe = tran.db[OID_UNIVERSE] if obj.oid not in universe.players and obj.oid not in (OID_NATURE, OID_ADMIN): log.debug(obj.oid, "Adding player to the universe") universe.players.append(obj.oid) # check nick (TODO remove in 0.5.33) if not hasattr(obj, "fullName"): obj.fullName = obj.name # TODO remove in 0.5.69 if not hasattr(obj, "prodQueues"): obj.prodQueues = [[],[],[],[],[]] # check if player is a leader if not obj.galaxies: log.debug(obj.oid, obj.name, "IS NOT IN ANY GALAXY") else: galaxy = tran.db[obj.galaxies[0]] if galaxy.imperator != obj.oid and obj.imperator > 0: log.debug(obj.oid, "Removing imperator/leader bonus") obj.imperator = 0 ## NON VALIDATING CODE (DERIVED ATTRS AND SO ON) # get best technologies for planet weapons bestScores = [0, 0, 0, 0] obj.planetWeapons = [None, None, None, None, None] for techID in obj.techs: tech = Rules.techs[techID] if tech.isShipEquip and tech.weaponDmgMin > 0 and not tech.buildSRes\ and tech.weaponGoodForFlak: # compute score weaponEff = Rules.techImprEff[obj.techs.get(techID, Rules.techBaseImprovement)] score = (tech.weaponDmgMin + tech.weaponDmgMax) / 2.0 * \ tech.weaponROF * (tech.weaponAtt + 10.0)/10 * weaponEff if score > bestScores[tech.weaponClass]: obj.planetWeapons[tech.weaponClass] = techID bestScores[tech.weaponClass] = score #@log.debug(obj.oid, "Planet weapons", obj.planetWeapons) # update all ship designs for designID in obj.shipDesigns: old = obj.shipDesigns[designID] new = ShipUtils.makeShipMinSpec(obj, old.name, old.hullID, old.eqIDs, old.improvements, raiseExs = False) new.built = old.built new.upgradeTo = old.upgradeTo obj.shipDesigns[designID] = new if not hasattr(obj, 'obsoleteTechs'): obj.obsoleteTechs = set() update.public = 0 def startGlobalConstruction(self, tran, player, techID, quantity, isShip, reportFinished, queue): if len(player.prodQueues) <= queue: raise GameException('Invalid queue.') if len(player.prodQueues[queue]) > Rules.maxProdQueueLen: raise GameException('Queue is full.') if quantity < 1: raise GameException("Quantity must be greater than 0") if not player.techs.has_key(techID) and isShip == 0: raise GameException('You do not own this kind of technology.') if not player.shipDesigns.has_key(techID) and isShip == 1: raise GameException('You do not own this ship design.') if isShip: tech = player.shipDesigns[techID] if tech.upgradeTo: raise GameException("You cannot build obsolete ship design.") else: tech = Rules.techs[techID] if tech.isStructure or not tech.isProject: raise GameException('You cannot construct this technology.') elif tech.globalDisabled: raise GameException('You cannot construct targeted project.') neededSR = {} for sr in tech.buildSRes: if player.stratRes.get(sr, 0) < neededSR.get(sr, 0) + quantity: raise GameException("You do not own required strategic resource(s)") neededSR[sr] = neededSR.get(sr, 0) + quantity # consume strategic resources for sr in neededSR: player.stratRes[sr] -= neededSR[sr] # start construction item = IDataHolder() item.techID = techID item.quantity = int(quantity) item.changePerc = 0 item.isShip = bool(isShip) item.reportFin = bool(reportFinished) item.type = T_TASK player.prodQueues[queue].append(item) return player.prodQueues[queue], player.stratRes startGlobalConstruction.public = 1 startGlobalConstruction.accLevel = AL_FULL def changeGlobalConstruction(self, tran, player, queue, index, quantity): if index < 0 or index >= len(player.prodQueues[queue]): raise GameException("No such item in the construction queue.") if quantity < 1: raise GameException("Quantity must be greater than 0") item = player.prodQueues[queue][index] if item.isShip: tech = player.shipDesigns[item.techID] else: tech = Rules.techs[item.techID] quantityChange = quantity - player.prodQueues[queue][index].quantity neededSR = {} for sr in tech.buildSRes: if player.stratRes.get(sr, 0) < neededSR.get(sr, 0) + quantityChange: raise GameException("You do not own required strategic resource(s)") neededSR[sr] = neededSR.get(sr, 0) + quantityChange # consume strategic resources for sr in neededSR: player.stratRes[sr] += (-1 * neededSR[sr]) player.prodQueues[queue][index].quantity = quantity player.prodQueues[queue][index].const = tech.buildProd * quantity return player.prodQueues[queue], player.stratRes changeGlobalConstruction.public = 1 changeGlobalConstruction.accLevel = AL_FULL def abortGlobalConstruction(self, tran, player, queue, index): if len(player.prodQueues) <= queue or queue < 0: raise GameException('Invalid queue.') if len(player.prodQueues[queue]) <= index or index < 0: raise GameException('Invalid task.') item = player.prodQueues[queue][index] # return strategic resources #is ship if item.techID < 1000: tech = player.shipDesigns[item.techID] else: tech = Rules.techs[item.techID] for sr in tech.buildSRes: player.stratRes[sr] += item.quantity player.prodQueues[queue].pop(index) return player.prodQueues[queue], player.stratRes abortGlobalConstruction.public = 1 abortGlobalConstruction.accLevel = AL_FULL def moveGlobalConstrItem(self, tran, player, queue, index, rel): if index >= len(player.prodQueues[queue]): raise GameException('No such item in the construction queue.') if index + rel < 0 or index + rel >= len(player.prodQueues[queue]): raise GameException('Cannot move.') item = player.prodQueues[queue][index] del player.prodQueues[queue][index] player.prodQueues[queue].insert(index + rel, item) return player.prodQueues[queue] moveGlobalConstrItem.public = 1 moveGlobalConstrItem.accLevel = AL_FULL def getReferences(self, tran, obj): return obj.fleets getReferences.public = 0 def loggedIn(self, tran, obj): obj.lastLogin = time.time() loggedIn.public = 0 def resign(self, tran, obj): """Remove player from the game. Give remaining planets, ... to the REBELS""" # cannot resign when time is stopped # TODO smarted conditions (like cannot resign twice a week or so) if not obj.timeEnabled: raise GameException('You cannot resign current game - time is stopped.') log.debug("Resigning player", obj.oid) # morph player to AI obj.type = self.resignTo self.cmd(obj).upgrade(tran, obj) self.cmd(obj).update(tran, obj) # reregister tran.gameMngr.removePlayer(obj.oid) self.cmd(obj).reregister(tran, obj) resign.public = 1 resign.accLevel = AL_OWNER def delete(self, tran, obj): # check whether it is AI or normal player if obj.type in AI_PLAYER_TYPES: # remove AI account from the game, and record in the AI list log.debug("Removing AI account from the AI list", obj.oid) tran.gameMngr.clientMngr.removeAiAccount(obj.login) aiList = AIList(tran.gameMngr.configDir) aiList.remove(obj.login) log.debug("Deleting player", obj.oid) # delete relations for playerID in tran.db[OID_UNIVERSE].players: player = tran.db[playerID] self.cmd(player).deleteDiplomacyWith(tran, player, obj.oid) # delete fleets for fleetID in obj.fleets: fleet = tran.db[fleetID] self.cmd(fleet).disbandFleet(tran, fleet) try: tran.gameMngr.removePlayer(obj.oid) except Exception: log.warning("Cannot remove player") delete.public = 1 delete.accLevel = AL_ADMIN def giveUp(self, tran, obj, playerID): """Remove player from the game. Give remaining planets, ... to the specified player""" # cannot resign when time is stopped # TODO smarted conditions (like cannot resign twice a week or so) if not obj.timeEnabled: raise GameException('You cannot resign current game - time is stopped.') player = tran.db[playerID] # give planets for planetID in obj.planets[:]: # needs a copy - changeOwner modifies this planet = tran.db[planetID] self.cmd(planet).changeOwner(tran, planet, playerID, force = 1) # give fleets for fleetID in obj.fleets[:]: fleet = tran.db[fleetID] fleet.owner = playerID player.fleets.append(fleetID) # remove player tran.gameMngr.removePlayer(obj.oid) try: tran.db[OID_UNIVERSE].players.remove(obj.oid) except ValueError: pass giveUp.public = 1 giveUp.accLevel = AL_ADMIN def addShipDesign(self, tran, obj, name, hullID, eqIDs): """Add ship design to the database of designs.""" # normalize design name = name.strip() # check technologies if hullID not in obj.techs: raise GameException("You do not posses this hull type.") for techID in eqIDs: if techID not in obj.techs: raise GameException("You do not posses technology(ies) to construct this ship.") # create spec (throws exception for invad ones) spec = ShipUtils.makeShipMinSpec(obj, name, hullID, eqIDs, []) # check number of designs if len(obj.shipDesigns) > Rules.shipMaxDesigns: raise GameException("No space to store design.") # check name of designs for designID in obj.shipDesigns: if obj.shipDesigns[designID].name == name: raise GameException("Design name is already used.") if re.match("^\s*$",name): raise GameException("Design name must not be entirely whitespace.") # find free design id index = 1 ids = obj.shipDesigns.keys() while 1: if index not in ids: break index += 1 # add design obj.shipDesigns[index] = spec return obj.shipDesigns, index addShipDesign.public = 1 addShipDesign.accLevel = AL_OWNER def addBuoy(self, tran, obj, systemID, text, type): """Add new buoy to player buoys.""" # delete buoy if not text: if systemID in obj.buoys: del obj.buoys[systemID] return obj.buoys else: raise GameException("Buoy at specified system does not exist.") if type not in (BUOY_PRIVATE, BUOY_TO_ALLY, BUOY_TO_SCANNERSHARE): raise GameException("Wrong bouy type.") # edit buoy if systemID in obj.buoys: obj.buoys[systemID] = (text, type) return obj.buoys if len(obj.buoys) >= 30: raise GameException("You cannot add more than 30 buoys.") if tran.db[systemID].type not in (T_SYSTEM, T_WORMHOLE): raise GameException("You can add buoy only to system.") # new buoy if len(text) > 0: obj.buoys[systemID] = (text, type) return obj.buoys addBuoy.public = 1 addBuoy.accLevel = AL_OWNER def scrapShipDesign(self, tran, obj, designID): """Remove ship design from the database of designs and remove all active ships using this design.""" # check design ID if designID not in obj.shipDesigns: raise GameException("No such design.") # delete ships for fleetID in obj.fleets[:]: # make copy, fleet can be deleted fleet = tran.db[fleetID] self.cmd(fleet).deleteDesign(tran, fleet, designID) # delete tasks for planetID in obj.planets: planet = tran.db[planetID] self.cmd(planet).deleteDesign(tran, planet, designID) # clear upgradeTo for tmpDesignID in obj.shipDesigns: spec = obj.shipDesigns[tmpDesignID] if spec.upgradeTo == designID: spec.upgradeTo = 0 # delete design del obj.shipDesigns[designID] return obj.shipDesigns, obj.fleets, obj.stratRes scrapShipDesign.public = 1 scrapShipDesign.accLevel = AL_OWNER def getShipDesign(self,tran,obj,designID): if designID not in obj.shipDesigns: raise GameException("No such design.") return obj.shipDesigns[designID] def upgradeShipDesign(self, tran, obj, oldDesignID, newDesignID): # check designs ID if oldDesignID not in obj.shipDesigns: raise GameException("No such design.") if newDesignID not in obj.shipDesigns: raise GameException("No such design.") if oldDesignID == newDesignID: raise GameException("Designs are the same.") oldSpec = obj.shipDesigns[oldDesignID] newSpec = obj.shipDesigns[newDesignID] if oldSpec.upgradeTo: raise GameException("Old design has already been made obsolete.") if newSpec.upgradeTo: raise GameException("New design has already been made obsolete.") if oldSpec.combatClass != newSpec.combatClass: raise GameException("Designs must be of the same combat class.") # set old design as upgradable oldSpec.upgradeTo = newDesignID # if something is upgraded to oldDesign change it to new design for desID in obj.shipDesigns: if obj.shipDesigns[desID].upgradeTo == oldDesignID: obj.shipDesigns[desID].upgradeTo = newDesignID # compute strat res difference stratRes = {} for sr in oldSpec.buildSRes: stratRes[sr] = stratRes.get(sr, 0) - 1 for sr in newSpec.buildSRes: stratRes[sr] = stratRes.get(sr, 0) + 1 if stratRes[sr] == 0: del stratRes[sr] log.debug("upgradeShipDesign", obj.oid, stratRes) # modify tasks tasksUpgraded = False if not stratRes: log.debug("upgradeShipDesign - upgrading tasks") for planetID in obj.planets: planet = tran.db[planetID] self.cmd(planet).changeShipDesign(tran, planet, oldDesignID, newDesignID) # upgrade global queue as well for queue in obj.prodQueues: for task in queue: if task.techID == oldDesignID: task.techID = newDesignID tasksUpgraded = True else: log.debug("upgradeShipDesing - NOT upgrading tasks") return obj.shipDesigns, obj.stratRes, tasksUpgraded, obj.prodQueues upgradeShipDesign.public = 1 upgradeShipDesign.accLevel = AL_OWNER def cancelUpgradeShipDesign(self, tran, obj, designID): # check designs ID if designID not in obj.shipDesigns: raise GameException("No such design.") obj.shipDesigns[designID].upgradeTo = OID_NONE return obj.shipDesigns cancelUpgradeShipDesign.public = 1 cancelUpgradeShipDesign.accLevel = AL_OWNER def startResearch(self, tran, obj, techID, improveToMax = 0): if len(obj.rsrchQueue) > Rules.maxRsrchQueueLen: GameException('Queue is full.') tech = Rules.techs[techID] # player has to be a right race if obj.race not in tech.researchRaces: raise GameException("Your race cannot research this technology.") # item cannot be researched twice for tmpTech in obj.rsrchQueue: if tmpTech.techID == techID: raise GameException('Technology is already sheduled for research.') # disabled? for tmpTechID in obj.techs: if techID in Rules.techs[tmpTechID].researchDisables: raise GameException("Previous research has disabled this technology.") # check requirements for tmpTechID, improvement in tech.researchRequires: if not obj.techs.has_key(tmpTechID) or obj.techs[tmpTechID] < improvement: raise GameException('You cannot research this technology yet.') improvement = obj.techs.get(techID, Rules.techBaseImprovement - 1) + 1 if improvement > Rules.techMaxImprovement or improvement > tech.maxImprovement: raise GameException('You cannot improve this technology further.') if tech.level > obj.techLevel: raise GameException("Your technological level is insufficient.") # check strategic resources if improvement == 1: for stratRes in tech.researchReqSRes: if obj.stratRes.get(stratRes, 0) < 1: raise GameException("Required strategy resource missing.") item = IDataHolder() item.techID = techID item.improvement = improvement item.currSci = 0 item.changeSci = 0 item.improveToMax = improveToMax item.type = T_RESTASK obj.rsrchQueue.append(item) return obj.rsrchQueue startResearch.public = 1 startResearch.accLevel = AL_FULL def abortResearch(self, tran, obj, index): if index >= len(obj.rsrchQueue) or index < 0: GameException('No such item in queue.') del obj.rsrchQueue[index] return obj.rsrchQueue abortResearch.public = 1 abortResearch.accLevel = AL_FULL def editResearch(self, tran, obj, index, improveToMax = 0): if index >= len(obj.rsrchQueue) or index < 0: GameException('No such item in queue.') obj.rsrchQueue[index].improveToMax = improveToMax return obj.rsrchQueue editResearch.public = 1 editResearch.accLevel = AL_FULL def moveResearch(self, tran, obj, index, rel): if index >= len(obj.rsrchQueue): raise GameException('No such item in the researcg queue.') if index + rel < 0 or index + rel >= len(obj.rsrchQueue): raise GameException('Cannot move.') item = obj.rsrchQueue[index] del obj.rsrchQueue[index] obj.rsrchQueue.insert(index + rel, item) return obj.rsrchQueue moveResearch.public = 1 moveResearch.accLevel = AL_FULL def redirectShips(self, tran, obj, sourceSystemID, targetSystemID): # check sourceSystemID ok = 0 if sourceSystemID == targetSystemID: targetSystemID = OID_NONE for planetID in tran.db[sourceSystemID].planets: if tran.db[planetID].owner == obj.oid: ok = 1 if not ok: raise GameException("You must own planet in the source system") # check targetSystemID if targetSystemID != OID_NONE and 0: # TODO: switch on ok = 0 for planetID in tran.db[targetSystemID].planets: if tran.db[planetID].owner == obj.oid: ok = 1 if not ok: raise GameException("You must own planet in the target system") # fine - record it log.debug(obj.oid, "Adding redirection", sourceSystemID, targetSystemID) if targetSystemID: obj.shipRedirections[sourceSystemID] = targetSystemID else: try: del obj.shipRedirections[sourceSystemID] except KeyError: pass return obj.shipRedirections redirectShips.public = 1 redirectShips.accLevel = AL_FULL def getPublicInfo(self, tran, obj): result = IObject.getPublicInfo(self, tran, obj) result.type = obj.type result.name = obj.name return result getPublicInfo.public = 1 getPublicInfo.accLevel = AL_NONE def changePactCond(self, tran, obj, playerID, pactID, state, conditions): log.debug("changePactCond", obj.oid, playerID, pactID) # must have a contact if playerID not in obj.diplomacyRels: raise GameException('No contact with this player.') player = tran.db[playerID] # must be a player if player.type not in PLAYER_TYPES and player.type != T_ALLIANCE: raise GameException('Pacts can be offered to players and aliances only.') # check pactID pact = Rules.pactDescrs.get(pactID, None) if not pact: raise GameException('No such pact type.') # check state if state not in (PACT_OFF, PACT_INACTIVE, PACT_ACTIVE): raise GameException("Wrong pact state") # check conditions for tmpPactID in conditions: pact = Rules.pactDescrs.get(tmpPactID, None) if not pact: raise GameException('No such pact type.') # record pact dipl = self.cmd(obj).getDiplomacyWith(tran, obj, playerID) dipl.pacts[pactID] = [state] dipl.pacts[pactID].extend(conditions) # if state if PACT_OFF, disable state on partner's side if state == PACT_OFF: partner = tran.db[playerID] dipl = self.cmd(partner).getDiplomacyWith(tran, partner, obj.oid) if pactID in dipl.pacts: dipl.pacts[pactID][0] = PACT_OFF else: dipl.pacts[pactID] = [PACT_OFF] return obj.diplomacyRels changePactCond.public = 1 changePactCond.accLevel = AL_OWNER def getDiplomacyWith(self, tran, obj, playerID): if obj.governorOf: # player is a governor leader = tran.db[obj.governorOf] return self.cmd(leader).getDiplomacyWith(tran, leader, objID) # player is independent dipl = obj.diplomacyRels.get(playerID, None) if not dipl: # make default dipl = IDataHolder() dipl.type = T_DIPLREL dipl.pacts = { PACT_ALLOW_CIVILIAN_SHIPS: [PACT_ACTIVE, PACT_ALLOW_CIVILIAN_SHIPS] } dipl.relation = obj.defaultRelation dipl.relChng = 0 dipl.lastContact = tran.db[OID_UNIVERSE].turn dipl.contactType = CONTACT_NONE dipl.stats = None if playerID != obj.oid: obj.diplomacyRels[playerID] = dipl else: log.debug("getDiplomacyWith myself", obj.oid) return dipl def getPartyDiplomacyRels(self, tran, obj, partyID): if partyID not in obj.diplomacyRels: return None, None if obj.diplomacyRels[partyID].contactType == CONTACT_NONE: return obj.diplomacyRels[partyID], None party = tran.db[partyID] return obj.diplomacyRels[partyID], party.diplomacyRels.get(obj.oid, None) getPartyDiplomacyRels.public = 1 getPartyDiplomacyRels.accLevel = AL_OWNER def isPactActive(self, tran, obj, partnerID, pactID): #@log.debug("isPactActive", obj.oid, partnerID, pactID) if partnerID not in obj.diplomacyRels: return 0 partner = tran.db[partnerID] partnerDipl = partner.diplomacyRels.get(obj.oid, None) if not partnerDipl: return 0 return partnerDipl.pacts.get(pactID, [PACT_OFF])[0] == PACT_ACTIVE def deleteDiplomacyWith(self, tran, obj, playerID): if playerID in obj.diplomacyRels: del obj.diplomacyRels[playerID] def getRelationTo(self, tran, obj, objID): if objID == OID_NONE: return REL_UNDEF if obj.oid == objID: return REL_UNITY if obj.governorOf: leader = tran.db[obj.governorOf] return self.cmd(leader).getRelationTo(tran, leader, objID) dipl = obj.diplomacyRels.get(objID, None) if dipl: return dipl.relation else: return obj.defaultRelation getRelationTo.public = 1 getRelationTo.accLevel = AL_FULL def setVoteFor(self, tran, obj, playerID): if playerID not in obj.diplomacyRels and playerID != obj.oid and playerID != OID_NONE: raise GameException("No contact with this commander.") # check type if playerID != OID_NONE: player = tran.db[playerID] if player.type != T_PLAYER: raise GameException("You cannot vote for this player.") # set obj.voteFor = playerID return obj.voteFor setVoteFor.public = 1 setVoteFor.accLevel = AL_OWNER def processDIPLPhase(self, tran, obj, data): if not obj.timeEnabled: return turn = tran.db[OID_UNIVERSE].turn # record changes from valid pacts for partyID in obj.diplomacyRels: dipl = obj.diplomacyRels[partyID] # check contact if dipl.contactType == CONTACT_NONE: #@log.debug("Skipping contact", obj.oid, partyID) continue # base change of relation dipl.relChng += Rules.baseRelationChange # process pacts for pactID in dipl.pacts: #@log.debug("Processing pact", obj.oid, partyID, pactID, dipl.pacts[pactID]) if dipl.pacts[pactID][0] != PACT_ACTIVE: continue pactSpec = Rules.pactDescrs[pactID] if dipl.relation < pactSpec.validityInterval[0] or \ dipl.relation > pactSpec.validityInterval[1] or \ dipl.relChng < Rules.relLostWhenAttacked / 2: # skip this non active pact, mark it as off # mark all pact off when attacked dipl.pacts[pactID][0] = PACT_OFF # TODO report it continue # pact is valid if dipl.relation < pactSpec.targetRel: #@log.debug("Affecting relation", pactSpec.relChng) dipl.relChng += min(pactSpec.targetRel - dipl.relation, pactSpec.relChng) # apply relation changes for partyID in obj.diplomacyRels: dipl = obj.diplomacyRels[partyID] dipl.relation += dipl.relChng dipl.relation = min(dipl.relation, REL_ALLY_HI) dipl.relation = max(dipl.relation, REL_ENEMY_LO) #@log.debug('IPlayer', 'Final relation', obj.oid, partyID, dipl.relation, dipl.relChng) processDIPLPhase.public = 1 processDIPLPhase.accLevel = AL_ADMIN def getScannerMap(self, tran, obj): scanLevels = {} # full map for the admin if obj.oid == OID_ADMIN: universe = tran.db[OID_UNIVERSE] for galaxyID in universe.galaxies: galaxy = tran.db[galaxyID] for systemID in galaxy.systems: system = tran.db[systemID] obj.staticMap[systemID] = 111111 for planetID in system.planets: obj.staticMap[planetID] = 111111 # adding systems with buoys for objID in obj.buoys: scanLevels[objID] = Rules.level1InfoScanPwr # fixing system scan level for mine fields systems = {} for planetID in obj.planets: systems[tran.db[planetID].compOf] = None for systemID in systems.keys(): scanLevels[systemID] = Rules.partnerScanPwr # player's map for objID in obj.staticMap: scanLevels[objID] = max(scanLevels.get(objID, 0), obj.staticMap[objID]) for objID in obj.dynamicMap: scanLevels[objID] = max(scanLevels.get(objID, 0), obj.dynamicMap[objID]) # parties' map for partnerID in obj.diplomacyRels: if self.cmd(obj).isPactActive(tran, obj, partnerID, PACT_SHARE_SCANNER): # load partner's map partner = tran.db[partnerID] for objID in partner.staticMap: scanLevels[objID] = max(scanLevels.get(objID, 0), partner.staticMap[objID]) for objID in partner.dynamicMap: scanLevels[objID] = max(scanLevels.get(objID, 0), partner.dynamicMap[objID]) # partner's fleets and planets for objID in partner.fleets: scanLevels[objID] = Rules.partnerScanPwr for objID in partner.planets: scanLevels[objID] = Rules.partnerScanPwr # create map map = dict() for objID, level in scanLevels.iteritems(): tmpObj = tran.db.get(objID, None) if not tmpObj: continue # add movement validation data if tmpObj.type in (T_SYSTEM,T_WORMHOLE) and objID not in obj.validSystems: obj.validSystems.append(objID) for info in self.cmd(tmpObj).getScanInfos(tran, tmpObj, level, obj): if (info.oid not in map) or (info.scanPwr > map[info.oid].scanPwr): map[info.oid] = info return map getScannerMap.public = 1 getScannerMap.accLevel = AL_OWNER def mergeScannerMap(self, tran, obj, map): #@log.debug(obj.oid, "Merging scanner map") contacts = {} for object, level in map.iteritems(): objID = object.oid if object.type in (T_SYSTEM, T_WORMHOLE): obj.staticMap[objID] = max(obj.staticMap.get(objID, 0), level) contacts.update(object.scannerPwrs) elif object.type in (T_FLEET, T_ASTEROID): obj.dynamicMap[objID] = max(obj.dynamicMap.get(objID, 0), level) contacts[object.owner] = None else: raise GameException("Unsupported type %d" % object.type) if obj.oid in contacts: del contacts[obj.oid] if OID_NONE in contacts: del contacts[OID_NONE] for partyID in contacts: # add to player's contacts dipl = self.cmd(obj).getDiplomacyWith(tran, obj, partyID) dipl.contactType = max(dipl.contactType, CONTACT_DYNAMIC) dipl.lastContact = tran.db[OID_UNIVERSE].turn # add to detected owner's contacts owner = tran.db[partyID] assert owner.type in PLAYER_TYPES dipl = self.cmd(obj).getDiplomacyWith(tran, owner, obj.oid) dipl.contactType = max(dipl.contactType, CONTACT_DYNAMIC) dipl.lastContact = tran.db[OID_UNIVERSE].turn mergeScannerMap.public = 0 mergeScannerMap.accLevel = AL_OWNER def processRSRCHPhase(self, tran, obj, data): if not obj.timeEnabled: return # sci pts from allies pts = obj.sciPoints for partnerID in obj.diplomacyRels: if self.cmd(obj).isPactActive(tran, obj, partnerID, PACT_MINOR_SCI_COOP): partner = tran.db[partnerID] pactSpec = Rules.pactDescrs[PACT_MINOR_SCI_COOP] pts += min( int(partner.sciPoints * pactSpec.effectivity), int(obj.sciPoints * pactSpec.effectivity), ) if self.cmd(obj).isPactActive(tran, obj, partnerID, PACT_MAJOR_SCI_COOP): partner = tran.db[partnerID] pactSpec = Rules.pactDescrs[PACT_MAJOR_SCI_COOP] pts += min( int(partner.sciPoints * pactSpec.effectivity), int(obj.sciPoints * pactSpec.effectivity), ) # compute effective sci pts obj.effSciPoints = epts = pts - int(obj.stats.storPop * Rules.sciPtsPerCitizen[obj.techLevel]) index = 0 while epts > 0 and obj.rsrchQueue and index < len(obj.rsrchQueue): item = obj.rsrchQueue[index] tech = Rules.techs[item.techID] # check requirements canResearch = 1 # player has to be a right race if obj.race not in tech.researchRaces: canResearch = 0 for stratRes in tech.researchReqSRes: if obj.stratRes.get(stratRes, 0) < 1 and item.improvement == 1: Utils.sendMessage(tran, obj, MSG_MISSING_STRATRES, OID_NONE, stratRes) canResearch = 0 break for tmpTechID in obj.techs: if item.techID in Rules.techs[tmpTechID].researchDisables: canResearch = 0 Utils.sendMessage(tran, obj, MSG_DELETED_RESEARCH, OID_NONE, item.techID) del obj.rsrchQueue[index] index -= 1 break if tech.level > obj.techLevel: canResearch = 0 Utils.sendMessage(tran, obj, MSG_DELETED_RESEARCH, OID_NONE, item.techID) del obj.rsrchQueue[index] index -= 1 if not canResearch: index += 1 continue researchSci = Utils.getTechRCost(obj, item.techID) wantSci = min(epts, researchSci - item.currSci, researchSci / tech.researchTurns) item.currSci += wantSci item.changeSci = wantSci epts -= wantSci if item.currSci >= researchSci: del obj.rsrchQueue[index] obj.techs[item.techID] = item.improvement # call finish handler tech = Rules.techs[item.techID] tech.finishResearchHandler(tran, obj, tech) Utils.sendMessage(tran, obj, MSG_COMPLETED_RESEARCH, OID_NONE, item.techID) # update derived attributes of player self.cmd(obj).update(tran, obj) # repeat research if required by player if item.improveToMax == 1 and item.improvement < Rules.techMaxImprovement: # reinsert the item on the top of the queue self.cmd(obj).startResearch(tran, obj, item.techID, improveToMax = 1) idx = len(obj.rsrchQueue) - 1 self.cmd(obj).moveResearch(tran, obj, idx, - idx) if epts > 0 and 0: # TODO: remove me Utils.sendMessage(tran, obj, MSG_WASTED_SCIPTS, OID_NONE, epts) return # oops we have negative epts while epts < 0: log.debug("Not enought RP", epts, obj.oid) if obj.rsrchQueue: item = obj.rsrchQueue[0] if item.currSci > 0: wantSci = min(item.currSci, - epts) item.currSci -= wantSci item.changeSci = - wantSci epts += wantSci if item.currSci == 0: # remove item from the queue - TODO send message to player del obj.rsrchQueue[0] # at this point, epts can be zero if epts == 0: log.debug("RP deficit satisfied", obj.oid) break # try next project if obj.rsrchQueue: continue # oops we must find technology to degrade avail = obj.techs.keys() # do not degrade technologies, which enables others for techID in obj.techs: tech = Rules.techs[techID] for tmpTechID, impr in tech.researchRequires: if tmpTechID in avail: avail.remove(tmpTechID) log.debug("Techs avialable for degradation", avail) if not avail: # no technology... break # from hight to low IDs avail.sort() avail.reverse() degraded = 0 for level in range(obj.techLevel, 0, -1): for techID in avail: tech = Rules.techs[techID] # check level if tech.level != level: continue # do not touch starting technologies if tech.isStarting and obj.techs[techID] <= 3: continue # ok we have one to degrade item = IDataHolder() item.techID = techID item.improvement = obj.techs[techID] item.currSci = Utils.getTechRCost(obj, techID, obj.techs[techID]) item.changeSci = 0 item.improveToMax = 0 item.type = T_RESTASK obj.rsrchQueue.append(item) # degrade tech if obj.techs[techID] == 1: # TODO send message del obj.techs[techID] else: # TODO send message obj.techs[techID] -= 1 if tech.recheckWhenTechLost: # reset some attributes plLevel = obj.techLevel obj.techLevel = 1 # recheck remaining techs for level in range(1, plLevel + 1): for techID in obj.techs: tech = Rules.techs[techID] if tech.level != level: continue # call finish handler again tech.finishResearchHandler(tran, obj, tech) degraded = 1 break if degraded: break return processRSRCHPhase.public = 1 processRSRCHPhase.accLevel = AL_ADMIN def processACTIONPhase(self, tran, obj, data): return NotImplementedError() processACTIONPhase.public = 1 processACTIONPhase.accLevel = AL_ADMIN def processINITPhase(self, tran, obj, data): # reset stats obj.stats.storPop = 0 obj.stats.prodProd = 0 obj.stats.effProdProd = 0 obj.stats.prodSci = 0 obj.stats.effProdSci = 0 obj.stats.slots = 0 obj.stats.structs = 0 obj.stats.planets = 0 obj.stats.fleetPwr = 0 obj.stats.fleetSupportProd = 0 obj.govPwr = Rules.baseGovPwr # update galaxies obj.galaxies = [] # remove old messages self.cmd(obj).deleteOldMsgs(tran, obj) # clear fleet upgrade flag obj.fleetUpgradeInProgress = 0 # clear production pool obj.prodIncreasePool = 0 # clear map obj.dynamicMap.clear() # set empty population distribution obj.tmpPopDistr = {} # do not process other cmds if time disabled if not obj.timeEnabled: return # clear contacts and delete too old rels turn = tran.db[OID_UNIVERSE].turn for objID in obj.diplomacyRels.keys(): dipl = obj.diplomacyRels[objID] # reset contact type obj.diplomacyRels[objID].contactType = CONTACT_NONE # delete old contacts if dipl.lastContact + Rules.contactTimeout < turn: del obj.diplomacyRels[objID] continue # lower scan powers in static map for objID in obj.staticMap: level = obj.staticMap[objID] if level > Rules.level3InfoScanPwr: obj.staticMap[objID] = max( Rules.level3InfoScanPwr, int(level * Rules.mapForgetScanPwr), ) #@log.debug(obj.oid, "player static map fix", objID, level - obj.staticMap[objID]) # clear relations change indicator for partyID in obj.diplomacyRels: obj.diplomacyRels[partyID].relChng = 0 # reset science points obj.sciPoints = 0 processINITPhase.public = 1 processINITPhase.accLevel = AL_ADMIN def processFINALPhase(self, tran, obj, data): if obj.timeEnabled: #try/except so that entire final process doesn't break on error in sub-phase try: self.cmd(obj).processRSRCHPhase(tran, obj, data) except: log.warning('Cannot execute FINAL/RSRCH on %d' % (obj.oid)) try: self.cmd(obj).processDIPLPhase(tran, obj, data) except: log.warning('Cannot execute FINAL/DIPL on %d' % (obj.oid)) # efficiency obj.prodEff = 1.0 obj.sciEff = 1.0 if obj.imperator == 1: log.debug(obj.oid, "Leader bonus") obj.prodEff += Rules.galLeaderBonus obj.sciEff += Rules.galLeaderBonus elif obj.imperator >= 2: log.debug(obj.oid, "Imperator bonus") obj.prodEff += Rules.galImperatorBonus obj.sciEff += Rules.galImperatorBonus #@log.debug("Fleet upgrade pool", obj.oid, obj.fleetUpgradePool, obj.fleetUpgradeInProgress) # compute some stats # TODO remove, RAW SCI PTS represented now obj.stats.prodSci = obj.effSciPoints obj.stats.planets = len(obj.planets) # fleet support #@log.debug("Fleet support", obj.oid, obj.stats.fleetSupportProd, obj.stats.prodProd) if obj.stats.fleetSupportProd > 0 and obj.stats.prodProd > 0: # TODO 0.1 shall be dependend on the race / government type obj.prodEff += min(0.1 - float(obj.stats.fleetSupportProd + obj.fleetUpgradePool * Rules.operProdRatio) / obj.stats.prodProd, 0.0) # delete non active player if obj.lastLogin + Rules.playerTimeout < time.time(): log.message("Resigning inactive player", obj.name, obj.oid) # TODO send a message? self.cmd(obj).resign(tran, obj) # delete nonactive newbie player if obj.lastLogin + Rules.novicePlayerTimeout < time.time() \ and len(obj.planets) < 4: log.message("Resigning inactive novice player", obj.name, obj.oid) # TODO send a message? self.cmd(obj).resign(tran, obj) # acquire government power if obj.planets: planet = tran.db[obj.planets[0]] for slot in planet.slots: tech = Rules.techs[slot[STRUCT_IDX_TECHID]] if tech.govPwr > 0 and slot[STRUCT_IDX_STATUS] & STRUCT_STATUS_ON: eff = Utils.getTechEff(tran, slot[STRUCT_IDX_TECHID], obj.oid) obj.govPwr = max(int(tech.govPwr * eff * (slot[STRUCT_IDX_OPSTATUS] / 100.0)), obj.govPwr) # compute government controll range if not hasattr(obj,"tmpPopDistr"): #when player is force-resigned, tmpPopDistr is unset. This is easiest fix. obj.tmpPopDistr = {} ranges = obj.tmpPopDistr.keys() ranges.sort() sum = 0 range = 1 for range in ranges: sum += obj.tmpPopDistr[range] if sum > obj.govPwr: break obj.govPwrCtrlRange = max(1, range) if sum < obj.govPwr and sum > 0: #@log.debug(obj.oid, "GovPwr compensation", obj.govPwrCtrlRange, obj.govPwr, sum) obj.govPwrCtrlRange = int(obj.govPwrCtrlRange * obj.govPwr / float(sum)) #@log.debug(obj.oid, "GovPwr control range", obj.govPwrCtrlRange) # compute prodBonus and sciBonus sum = 0 for range in ranges: sum += obj.tmpPopDistr[range] if sum < obj.govPwr and sum > 0: ratio = float(obj.govPwr - sum) / obj.govPwr #@log.debug(obj.oid, "SMALL EMPIRE BONUS", ratio, "govPwr", obj.govPwr, "sum", sum) # TODO let user to define how much to invest into prod and to sci obj.prodEff += ratio / 2 obj.sciEff += ratio / 2 del obj.tmpPopDistr # delete temporary attribute # increase prod eff from pacts # CPs from allies sum = 0 for partnerID in obj.diplomacyRels: if self.cmd(obj).isPactActive(tran, obj, partnerID, PACT_MINOR_CP_COOP): partner = tran.db[partnerID] pactSpec = Rules.pactDescrs[PACT_MINOR_CP_COOP] sum += min( partner.stats.prodProd * pactSpec.effectivity, obj.stats.prodProd * pactSpec.effectivity, ) if self.cmd(obj).isPactActive(tran, obj, partnerID, PACT_MAJOR_CP_COOP): partner = tran.db[partnerID] pactSpec = Rules.pactDescrs[PACT_MAJOR_CP_COOP] sum += min( partner.stats.prodProd * pactSpec.effectivity, obj.stats.prodProd * pactSpec.effectivity, ) # apply production increase pool obj.prodIncreasePool += sum if obj.stats.prodProd > 0: ratio = (Rules.unusedProdMod * obj.prodIncreasePool) / obj.stats.prodProd real = min(ratio, math.sqrt(ratio)) #@log.debug(obj.oid, "Increase production by", ratio, "real", real) obj.prodEff += real # clean up prodEff if prodEff < 0 (prevent abuse) if obj.prodEff < 0: obj.prodEff = 0.0 # clean up ship redirections systems = {} for planetID in obj.planets: systems[tran.db[planetID].compOf] = None for systemID in obj.shipRedirections.keys(): if systemID not in systems: del obj.shipRedirections[systemID] # delete allied bouys obj.alliedBuoys = {} # find all allies for partnerID in obj.diplomacyRels.keys(): dipl = obj.diplomacyRels[partnerID] getAllyBuoys = False getScannerBuoys = False if dipl.relation >= REL_ALLY_LO: getAllyBuoys = True if self.isPactActive(tran, obj, partnerID, PACT_SHARE_SCANNER): getScannerBuoys = True if (getAllyBuoys or getScannerBuoys): partner = tran.db[partnerID] if hasattr(partner, "buoys"): for systemID in partner.buoys.keys(): toAllyBuoy = BUOY_NONE if getAllyBuoys and partner.buoys[systemID][1] == BUOY_TO_ALLY: toAllyBuoy = (partner.buoys[systemID][0], BUOY_FROM_ALLY, partner.name) elif getScannerBuoys and partner.buoys[systemID][1] == BUOY_TO_SCANNERSHARE: toAllyBuoy = (partner.buoys[systemID][0], BUOY_FROM_ALLY, partner.name) if toAllyBuoy != BUOY_NONE: if systemID in obj.alliedBuoys: obj.alliedBuoys[systemID].append(toAllyBuoy) else: obj.alliedBuoys[systemID] = [toAllyBuoy] return None processFINALPhase.public = 1 processFINALPhase.accLevel = AL_ADMIN ## messaging def canSendMsg(self, tran, obj, oid, forum): if forum == "INBOX": sender = tran.db[oid] return oid == OID_ADMIN or (oid in obj.diplomacyRels) or \ (obj.oid in sender.diplomacyRels) if forum == "OUTBOX": return obj.oid == oid return 0 canSendMsg.public = 0 def cleanUpMsgs(self, tran, obj): # get messages msgs = self.cmd(obj).getMsgs(tran, obj) # build list of events delete = [] for msg in msgs: if msg["forum"] == "EVENTS": delete.append(msg["id"]) # delete self.cmd(obj).deleteMsgs(tran, obj, delete) return 1 cleanUpMsgs.public = 1 cleanUpMsgs.accLevel = AL_OWNER def setResolution(self, tran, obj, x, y): if not hasattr(obj,'clientStats'): obj.clientStats = {} obj.clientStats['x'] = x; obj.clientStats['y'] = y; setResolution.public = 1 setResolution.accLevel = AL_OWNER def getResolution(self, obj): if not hasattr(obj,'clientStats'): obj.clientStats = {} if obj.clientStats.has_key('x') and obj.clientStats.has_key('y'): return ("%s,%s" % (obj.clientStats['x'],obj.clientStats['y'])) else: return "0,0" getResolution.public = 0 def addObsoleteTechs(self, tran, player, techID): # add tech temp = set([techID]) player.obsoleteTechs = player.obsoleteTechs | temp return player.obsoleteTechs addObsoleteTechs.public = 1 addObsoleteTechs.accLevel = AL_FULL def delObsoleteTechs(self, tran, player, techID): # del tech temp = set([techID]) player.obsoleteTechs = player.obsoleteTechs - temp return player.obsoleteTechs delObsoleteTechs.public = 1 delObsoleteTechs.accLevel = AL_FULL
Lukc/ospace-lukc
server/lib/ige/ospace/IPlayer.py
Python
gpl-2.0
47,542
<?php /** * @covers FormatJson */ class FormatJsonTest extends MediaWikiUnitTestCase { /** * Test data for testParseTryFixing. * * Some PHP interpreters use json-c rather than the JSON.org canonical * parser to avoid being encumbered by the "shall be used for Good, not * Evil" clause of the JSON.org parser's license. By default, json-c * parses in a non-strict mode which allows trailing commas for array and * object delarations among other things, so our JSON_ERROR_SYNTAX rescue * block is not always triggered. It however isn't lenient in exactly the * same ways as our TRY_FIXING mode, so the assertions in this test are * a bit more complicated than they ideally would be: * * Optional third argument: true if json-c parses the value without * intervention, false otherwise. Defaults to true. * * Optional fourth argument: expected cannonical JSON serialization of * json-c parsed result. Defaults to the second argument's value. */ public static function provideParseTryFixing() { return [ [ "[,]", '[]', false ], [ "[ , ]", '[]', false ], [ "[ , }", false ], [ '[1],', false, true, '[1]' ], [ "[1,]", '[1]' ], [ "[1\n,]", '[1]' ], [ "[1,\n]", '[1]' ], [ "[1,]\n", '[1]' ], [ "[1\n,\n]\n", '[1]' ], [ '["a,",]', '["a,"]' ], [ "[[1,]\n,[2,\n],[3\n,]]", '[[1],[2],[3]]' ], // I wish we could parse this, but would need quote parsing [ '[[1,],[2,],[3,]]', false, true, '[[1],[2],[3]]' ], [ '[1,,]', false, false, '[1]' ], ]; } /** * @dataProvider provideParseTryFixing * @param string $value * @param string|bool $expected Expected result with strict parser * @param bool $jsoncParses Will json-c parse this value without TRY_FIXING? * @param string|bool $expectedJsonc Expected result with lenient parser * if different from the strict expectation */ public function testParseTryFixing( $value, $expected, $jsoncParses = true, $expectedJsonc = null ) { // PHP5 results are always expected to have isGood() === false $expectedGoodStatus = false; // Check to see if json parser allows trailing commas if ( json_decode( '[1,]' ) !== null ) { // Use json-c specific expected result if provided $expected = ( $expectedJsonc === null ) ? $expected : $expectedJsonc; // If json-c parses the value natively, expect isGood() === true $expectedGoodStatus = $jsoncParses; } $st = FormatJson::parse( $value, FormatJson::TRY_FIXING ); $this->assertInstanceOf( Status::class, $st ); if ( $expected === false ) { $this->assertFalse( $st->isOK(), 'Expected isOK() == false' ); } else { $this->assertSame( $expectedGoodStatus, $st->isGood(), 'Expected isGood() == ' . ( $expectedGoodStatus ? 'true' : 'false' ) ); $this->assertTrue( $st->isOK(), 'Expected isOK == true' ); $val = FormatJson::encode( $st->getValue(), false, FormatJson::ALL_OK ); $this->assertEquals( $expected, $val ); } } }
pierres/archlinux-mediawiki
tests/phpunit/unit/includes/json/FormatJsonTest.php
PHP
gpl-2.0
2,949
// showaffidavits.cpp // // Show an affiliates affidavit status. // // (C) Copyright 2010 Fred Gleason <fredg@paravelsystems.com> // // $Id: showaffidavits.cpp,v 1.8 2011/04/29 22:13:25 pcvs Exp $ // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. // #include <qdatetime.h> #include <qsqldatabase.h> #include <qmessagebox.h> #include <dvtconf.h> #include <showaffidavits.h> #include <globals.h> ShowAffidavits::ShowAffidavits(int id,QWidget *parent,const char *name) : QWidget(parent,name) { QDate now(QDate::currentDate().year(),QDate::currentDate().month(),1); QDate month=now.addMonths(-11); int col=0; bool ok=true; QListViewItem *item=NULL; show_id=id; // // Create Fonts // QFont label_font=QFont("Helvetica",12,QFont::Bold); label_font.setPixelSize(12); show_list=new QListView(this,"show_list"); show_list->setAllColumnsShowFocus(true); show_list->setItemMargin(5); while(month<now) { show_list->addColumn(month.toString("MMM")); show_list->setColumnAlignment(col++,AlignCenter); month=month.addMonths(1); } month=now.addMonths(-11); col=0; item=new QListViewItem(show_list); while(month<now) { if(DvtAffidavitNeeded(id,month)) { ok=false; } else { item->setText(col,"OK"); } col++; month=month.addMonths(1); } show_mail_button=new QPushButton(tr("Send Reminder\nE-Mail"),this); show_mail_button->setFont(label_font); show_mail_button->setDisabled(ok||(!email_enabled)); connect(show_mail_button,SIGNAL(clicked()),this,SLOT(mailClickedData())); } ShowAffidavits::~ShowAffidavits() { } QSize ShowAffidavits::sizeHint() const { return QSize(10,10); } QSizePolicy ShowAffidavits::sizePolicy() const { return QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); } void ShowAffidavits::setAffiliateStatus(bool state) { if(!state) { QListViewItem *item=show_list->firstChild(); for(int i=0;i<show_list->columns();i++) { item->setText(i,""); } } } void ShowAffidavits::mailClickedData() { QStringList to_addrs; QString sql; QSqlQuery *q; // // Load System Values // QString origin_email=global_dvtsystem->originEmail(); QString affidavit_email_subject=global_dvtsystem->affidavitEmailSubject(); QString affidavit_email_template=global_dvtsystem->affidavitEmailTemplate(); sql=QString().sprintf("select STATION_CALL,STATION_TYPE,USER_PASSWORD \ from AFFILIATES where ID=%d",show_id); q=new QSqlQuery(sql); if(q->first()) { affidavit_email_subject.replace("%S",q->value(0).toString()+"-"+ q->value(1).toString()+"M"); affidavit_email_template.replace("%S",q->value(0).toString()+"-"+ q->value(1).toString()+"M"); affidavit_email_subject.replace("%U",q->value(0).toString().lower()+"-"+ q->value(1).toString().lower()+"m"); affidavit_email_template.replace("%U",q->value(0).toString().lower()+"-"+ q->value(1).toString().lower()+"m"); affidavit_email_subject.replace("%P",q->value(2).toString()); affidavit_email_template.replace("%P",q->value(2).toString()); } delete q; sql=QString().sprintf("select NAME,EMAIL from CONTACTS \ where (AFFILIATE_ID=%d)&&(AFFIDAVIT=\"Y\")", show_id); q=new QSqlQuery(sql); while(q->next()) { to_addrs.push_back(DvtFormatEmailAddress(q->value(0).toString(), q->value(1).toString())); } delete q; if(mail_dialog->exec(to_addrs,QStringList(),QStringList(), origin_email,global_dvtuser->email(), affidavit_email_subject, affidavit_email_template)==0) { sql=QString(). sprintf("insert into AFFILIATE_REMARKS set \ EVENT_TYPE=%d, \ AFFILIATE_ID=%d,\ REMARK_DATETIME=now(),\ USER_NAME=\"%s\",\ REMARK=\"Sent an affidavit reminder e-mail.\"", Dvt::RemarkAffidavitReminder, show_id, (const char *)DvtEscapeString(global_dvtuser->name())); q=new QSqlQuery(sql); delete q; emit remarksUpdated(); } } void ShowAffidavits::resizeEvent(QResizeEvent *e) { show_list->setGeometry(0,0,size().width()-120,size().height()); show_mail_button->setGeometry(size().width()-110,5,110,size().height()-10); }
ElvishArtisan/davit
davit/showaffidavits.cpp
C++
gpl-2.0
4,893
<?php // (C) Copyright Bobbing Wide 2015 /** * Schunter options * * Contains the options data for Schunter * * This is used to control the scanning of the WordPress database for content which appears to contain shortcodes * * */ class Schunter_options { /** * Total number of posts to process in an invocation */ public $limit; /** * Posts to load per block */ public $posts_per_page; /** * Last date processed * * Reset this to 0 to restart the processing */ public $last_date; /** * Not sure we need this */ public $max_id; function __construct() { $this->limit = 1000; $this->posts_per_page = 100; $this->last_date = 0; $this->max_id = 0; } function fetch() { $options = get_option( "schunter" ); $this->limit = bw_array_get( $options, "limit", $this->limit ); $this->posts_per_page = bw_array_get( $options, "posts_per_page", $this->posts_per_page ); $this->last_date = bw_array_get( $options, "last_date", $this->last_date ); $this->max_id = bw_array_get( $options, "max_id", $this->max_id ); } function last_date( $last_date ) { $this->last_date = $last_date; } function update() { //$options = get_option( "schunter" ); $updated = array( "limit" => $this->limit , "post_per_page" => $this->posts_per_page , "last_date" => $this->last_date , "max_id" => $this->max_id ); update_option( "schunter", $updated ); } }
bobbingwide/schunter
admin/class-schunter-options.php
PHP
gpl-2.0
1,456
class PostPolicy < ApplicationPolicy class Scope < Scope def resolve if user && user.admin? scope.all else scope.where(published: true) end end end def create? user end def show? record.published? || (user && user.admin?) end def show_with_contest? user && (user.id == record.comments.first.user_id || user.admin? || record.contest.in_judger_group?) end def update? user && (user.admin? || record.user.id == user.id) end def destroy? user && user.admin? end def permitted_attributes [:title, :raw, :author, :published] end end
DHUers/rigidoj
app/policies/post_policy.rb
Ruby
gpl-2.0
627
<!-- PAGE table --> <div class="row"> <div class="col-md-12"> <!-- BOX --> <div class="box border blue"> <div class="box-title"> <h4><i class="fa fa-table"></i>Inbox</h4> </div> <div class="box-body"> <table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="data"> <thead> <tr> <th>Device</th> <th>ReceivingDateTime</th> <th>Number</th> <th>Messages</th> <th>Options</th> </tr> </thead> <tbody> <tr> <td colspan="5">Loading Data</td> </tr> </tbody> </table> </div> </div> </div> </div> <!-- /PAGE table --> <div class="separator"></div> <div class="footer-tools"> <span class="go-top"><i class="fa fa-chevron-up"></i> Top </span> </div> <script type="text/javascript"> var url = "<?php echo site_url();?>"; $(document).ready(function() { $('#data').dataTable({ 'sPaginationType': 'bs_full', "bProcessing": true, "bServerSide": true, "sAjaxSource": url+"smsgateway/messages/load_inbox", "sServerMethod": "POST", "aaSorting": [[1, "asc"]], "iDisplayLength": 10, "aoColumns" : [ {"mData": "RecipientID"}, {"mData": "ReceivingDateTime"}, {"mData": "SenderNumber"}, {"mData": "TextDecoded"}, {"mData": "show", "mRender" : function ( data, type, full ) { var link = '<a title="Balas"class="btn btn-warning btn-xs" href='+url+'smsgateway/messages/balas/'+full.ID+'>Balas</a> || '+ '<button title="Delete" class="btn btn-danger btn-xs" data-id='+full.ID+' onclick="del(this);">Hapus</button>'; return link; } }, ], }); $('#data').each(function(){ var datatable = $(this); var search_input = datatable.closest('.dataTables_wrapper').find('div[id$=_filter] input'); search_input.attr('placeholder', 'Search'); search_input.addClass('form-control input-sm'); var length_sel = datatable.closest('.dataTables_wrapper').find('div[id$=_length] select'); length_sel.addClass('form-control input-sm'); }); $('#data').delegate('.checkbox','change',function() { var i = $(this).attr('data-id'); var id = $(this).attr('data-id'); if(this.checked){ $.ajax({ url: url+'unit/unit/execute/active', type: 'post', data: 'active=0&id='+i, success: function(result) { $('span-'+id).removeClass('label-default ').addClass('label-info'); $('span-'+id).html('Active'); window.location.reload(); } }); }else { $.ajax({ url: url+'unit/unit/execute/active', type: 'post', data: 'active=1&id='+i, success: function(result) { $('span-'+id).removeClass('label-info ').addClass('label-default'); $('span-'+id).html('Inactive'); window.location.reload(); } }); } }); }); function del(btn) { var cek = confirm("Apakah anda yakin akan menghapus??"); if(cek==false) { return false; } else { var id = $(btn).attr('data-id'); $.ajax({ url: url+'smsgateway/messages/remove/'+id, type: "POST", data:{data_id:id}, crossDomain:true, beforeSend: function(){ $("#msg").html("loading"); }, complete : function(){ $("#msg").html("delete Sukses"); }, success: function(data) { $("#data").dataTable().fnClearTable(); }, }); return false; } } </script>
LawangSukmaSejati/RegisterPakan
application/modules/registrasi/views/messagess/inbox.php
PHP
gpl-2.0
4,027
<?php namespace App\Controller; use App\Entity\Member; use App\Repository\MemberRepository; use App\Service\Mailer; use App\Utilities\TranslatorTrait; use Exception; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Security\Core\Exception\AccessDeniedException; use Symfony\Component\Security\Core\Security; use Symfony\Component\Security\Http\Authentication\AuthenticationUtils; class SignupController extends AbstractController { use TranslatorTrait; /** * @Route("/signup/finish", name="signup_finish") * * @throws Exception * * @return Response */ public function finishSignup(Request $request, Mailer $mailer) { $signupVars = $request->getSession()->get('SignupBWVars'); if (!empty($signupVars)) { $email = $signupVars['email']; $username = strtolower($signupVars['username']); $key = hash('sha256', strtolower($email) . ' - ' . strtolower($username)); // Member isn't logged in at this time, so we need to find it in the database. $memberRepository = $this->getDoctrine()->getRepository(Member::class); /** @var Member $member */ $member = $memberRepository->findOneBy(['username' => $username]); if (!$member) { throw new Exception('No member found in database. Terminating.'); } $member->setRegistrationKey($key); $em = $this->getDoctrine()->getManager(); $em->persist($member); $em->flush(); $subject = $this->getTranslator()->trans('signup.confirm.email'); $parameters = [ 'subject' => $subject, 'username' => $username, 'email_address' => $email, 'key' => $key, ]; $mailer->sendSignupEmail( $member, 'signup', $parameters ); // Remove the session variable $request->getSession()->remove('SignupBWVars'); // show finish page return $this->render('signup/finish.html.twig', $parameters); } return $this->render('signup/error.html.twig'); } /** * @Route("/signup/resend/{username}", name="resend_confirmation_email") * * @param $username * * @throws AccessDeniedException * * @return Response */ public function resendConfirmationEmail(Member $member, AuthenticationUtils $helper, Mailer $mailer) { $username = $member->getUsername(); if ($helper->getLastUsername() !== $username) { throw $this->createAccessDeniedException(); } $memberRepository = $this->getDoctrine()->getRepository(Member::class); /** @var Member $member */ $member = $memberRepository->findOneBy(['username' => $username]); if (!$member) { throw $this->createAccessDeniedException(); } $subject = $this->getTranslator()->trans('signup.confirm.email'); $parameters = [ 'subject' => $subject, 'username' => $username, 'gender' => $member->getGender(), 'email_address' => $member->getEmail(), 'key' => $member->getRegistrationKey(), ]; $mailer->sendSignupEmail( $member, 'resent', $parameters ); return $this->render('signup/resent.html.twig', $parameters); } /** * @Route("/signup/confirm/{username}/{registrationKey}", name="signup_confirm") * * @param $username * @param $registrationKey * * @return Response */ public function confirmEmailAddress(Request $request, $username, $registrationKey) { $em = $this->getDoctrine()->getManager(); /** @var MemberRepository $memberRepository */ $memberRepository = $em->getRepository(Member::class); /** @var Member $member */ $member = $memberRepository->findOneBy(['username' => $username]); if (null === $member) { $this->addFlash('error', $this->getTranslator()->trans('flash.signup.username.invalid')); return $this->redirectToRoute('login'); } if ($registrationKey === $member->getRegistrationKey()) { // Yeah, successfully confirmed email address $member ->setStatus('Active') ->setRegistrationKey('') ; $em->persist($member); $em->flush(); $this->addFlash('notice', $this->getTranslator()->trans('flash.signup.activated')); $request->getSession()->set(Security::LAST_USERNAME, $username); return $this->redirect('/login'); } $this->addFlash('error', $this->getTranslator()->trans('flash.signup.key.invalid')); return $this->redirect('/login'); } }
BeWelcome/rox
src/Controller/SignupController.php
PHP
gpl-2.0
5,131
/** * @created on : 30-jul-2017, 11:41:59 * @see * @since * @version * @author Raul Vela Salas */ package java_ejemplo_Operaciones; public class CambiarSentidoNumeroMejorado2 { private static int resto; private static int cociente; private static double totalTemp; public static int getNumeroDividido(int numero) { // 1234 int dividendo = resto * 10; // 12340 cociente = dividendo / 10000; resto = dividendo % 10000; return cociente; } public static double getNumeroInvertidoWhile() { int temp; while (resto > 0) { temp = getNumeroDividido(resto); totalTemp = ((totalTemp + temp) / 10); } double numero = totalTemp * 10000; return numero; } public static void main(String[] args) { resto = 1122; System.out.println("Numero : " + resto); double resto1 = getNumeroInvertidoWhile(); System.out.println("Valor : " + Math.round(resto1)); System.out.println("-----------------------"); resto = 5643; System.out.println("Numero : " + resto); System.out.println("-----------------------"); resto = 7439; System.out.println("Numero : " + resto); } }
NoTengoNombre/Java_ActualizarConocimientos
Java_Ejemplos/src/java_ejemplo_Operaciones/CambiarSentidoNumeroMejorado2.java
Java
gpl-2.0
1,269
/******************************************************************************* * File ClassicYFComposer.java * * Authors: * Wolfgang Maier * * Copyright: * Wolfgang Maier, 2011 * * This file is part of rparse, see <www.wolfgang-maier.net/rparse>. * * rparse is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * rparse 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 de.tuebingen.rparse.parser; import java.util.BitSet; import de.tuebingen.rparse.misc.IntegerContainer; /** * Composes two range vectors. Linear in size of the vectors. Much slower than the other implementation. * * @author wmaier */ public class ClassicYFComposer extends YieldFunctionComposer { // can get serialized private static final long serialVersionUID = -829666387336377643L; @Override public BitSet doComposition(CYKItem lit, CYKItem rit, boolean[][] goalyf, IntegerContainer s, IntegerContainer e) { int arg = 0; int argc = 0; for (int i = 0; i < lit.length; ++i) { if (lit.rvec.get(i) && !rit.rvec.get(i)) { if (arg == goalyf.length || argc == goalyf[arg].length || goalyf[arg][argc]) return null; else if (i + 1 < lit.length && !lit.rvec.get(i + 1)) argc++; } else if (!lit.rvec.get(i) && rit.rvec.get(i)) { if (arg == goalyf.length || argc == goalyf[arg].length || !goalyf[arg][argc]) return null; else if (i + 1 < lit.length && !rit.rvec.get(i + 1)) argc++; } else if (lit.rvec.get(i) && rit.rvec.get(i)) { return null; } else if (!lit.rvec.get(i) && !rit.rvec.get(i)) { if (i > 0 && (lit.rvec.get(i - 1) ^ rit.rvec.get(i - 1))) { arg++; argc = 0; } } } BitSet yp = (BitSet) lit.rvec.clone(); yp.xor(rit.rvec); return yp; } }
wmaier/rparse
src/de/tuebingen/rparse/parser/ClassicYFComposer.java
Java
gpl-2.0
2,689
package com.aucguy.usefulthings.util; import java.util.Iterator; /** * goes over a series of numbers. This is like python's range (for 3) or xrange (for 2) function * * @author aucguy */ public class Range implements Iterable<Integer>, Iterator<Integer> { protected int start; protected int end; /** * the current state of the iterator */ protected int index; /** * creates a range iterator * * @param start - the first element in the sequence * @param end - one more than the last element in the sequence */ public Range(int start, int end) { this.start = start; this.end = end; this.index = start; } @Override public Iterator<Integer> iterator() { return this; } @Override public boolean hasNext() { return this.index != this.end; } @Override public Integer next() { return this.index++; } @Override public void remove() { throw(new UnsupportedOperationException("there is no underlying sequence object for a range")); } }
aucguy/Useful-Things-Mod
src/main/java/com/aucguy/usefulthings/util/Range.java
Java
gpl-2.0
987
/* * Copyright 1995-1997 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package java.lang; /** * Thrown if an application tries to access or modify a specified * field of an object, and that object no longer has that field. * <p> * Normally, this error is caught by the compiler; this error can * only occur at run time if the definition of a class has * incompatibly changed. * * @author unascribed * @since JDK1.0 */ public class NoSuchFieldError extends IncompatibleClassChangeError { /** * Constructs a <code>NoSuchFieldException</code> with no detail message. */ public NoSuchFieldError() { super(); } /** * Constructs a <code>NoSuchFieldException</code> with the specified * detail message. * * @param s the detail message. */ public NoSuchFieldError(String s) { super(s); } }
neelance/jre4ruby
jre4ruby/src/share/java/lang/NoSuchFieldError.java
Java
gpl-2.0
2,013
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest17593") public class BenchmarkTest17593 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { java.util.Map<String,String[]> map = request.getParameterMap(); String param = ""; if (!map.isEmpty()) { param = map.get("foo")[0]; } String bar = doSomething(param); boolean randNumber = new java.util.Random().nextBoolean(); response.getWriter().println("Weak Randomness Test java.util.Random.nextBoolean() executed"); } // end doPost private static String doSomething(String param) throws ServletException, IOException { String bar; // Simple if statement that assigns param to bar on true condition int i = 196; if ( (500/42) + i > 200 ) bar = param; else bar = "This should never happen"; return bar; } }
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest17593.java
Java
gpl-2.0
2,173
package de.ahaus.dennis.javautils.impl.helper; /** * This Assert class is a helper to to validate objects in just one line of code * <p> * This is mainly to avoid writing redundant code. Each validating method throws * a special Exception when the test fails or returns true if validation * succeeds. * <p> * Example: * * <pre> * <code> * String str = null * Assert.isNull(str); // returns true * Assert.notNull(str); // throws IllegalArgumentException * </code> * </pre> * * @author Dennis Ahaus * */ public class Assert { /** * Checks if given object is null. * * @param object * The object to test * @return Returns true if the object is null, else throws * {@link IllegalArgumentException} with default message * @see #isNull(String, Object) */ public static boolean isNull(Object object) { return isNull("Object is NOT null!", object); } /** * Checks if given object is null. * * @param object * The object to test * @param message * The exception message * @return Returns true if the object is null, else throws * {@link IllegalArgumentException} with given message */ public static boolean isNull(String message, Object object) { if (object == null) { return true; } throw new IllegalArgumentException(message); } /** * Checks if given object is NOT null. * * @param object * The object to test * @return Returns true if the object is NOT null, else throws * {@link IllegalArgumentException} with default message * @see #isNull(String, Object) */ static boolean notNull(Object object) { return notNull("Object is null!", object); } /** * Checks if given object is NOT null. * * @param object * The object to test * @param message * The exception message * @return Returns true if the object is NOT null, else throws * {@link IllegalArgumentException} with given message */ public static boolean notNull(String message, Object object) { if (object != null) { return true; } throw new IllegalArgumentException(message); } }
DennisAhaus/java-utils
java-utils-impl/src/main/java/de/ahaus/dennis/javautils/impl/helper/Assert.java
Java
gpl-2.0
2,163
# pygsear # Copyright (C) 2003 Lee Harr # # # This file is part of pygsear. # # pygsear is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # pygsear 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 pygsear; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import random import pygame from pygsear import Game, Drawable, Path, conf from pygsear.locals import * class Wing(Drawable.RotatedImage): def __init__(self, name): self.name = name Drawable.RotatedImage.__init__(self, filename='arrow/right.png', steps=36) p = Path.RandomAccelerationPathBounded(minSpeed=2) self.set_path(p) self.center() def move(self): self.set_rotation(self.path.get_direction()) Drawable.RotatedImage.move(self) class Ship(Drawable.RotatedImage): def __init__(self): Drawable.RotatedImage.__init__(self, filename='penguin2.png', steps=36) self.path.set_speed(100) self.set_position((50, 50)) def set_enemy(self, enemy): self.enemy = enemy def follow_enemy(self): self.path.turn_towards(self.enemy.get_position()) def move(self): self.follow_enemy() self.set_rotation(self.path.get_direction()) Drawable.RotatedImage.move(self) class AGame(Game.Game): def initialize(self): self.makeWings() self.makeShip() def makeWings(self): self.enemies = self.addGroup() for name in ['Kirk', 'Spock', 'McCoy', 'Scotty', 'Chekov']: i = Wing(name) self.sprites.add(i) self.enemies.add(i) def makeShip(self): self.ship = Ship() self.sprites.add(self.ship) self.chooseEnemy() def chooseEnemy(self): enemy = random.choice(self.enemies.sprites()) self.ship.set_enemy(enemy) if hasattr(self, 'message'): self.message.clear() message = Drawable.String(message='"I am for %s"' % enemy.name, fontSize=30) message.center() self.message = Drawable.Stationary(sprite=message) self.message.draw() def checkCollisions(self): if self.ship.collide(self.ship.enemy): self.ship.enemy.kill() if not len(self.enemies.sprites()): self.makeWings() self.chooseEnemy() if __name__ == '__main__': g = AGame() g.mainloop()
davesteele/pygsear-debian
examples/wings_chase.py
Python
gpl-2.0
2,919
<?php /** * @file * Zen theme's implementation for comments. * * Available variables: * - $author: Comment author. Can be link or plain text. * - $content: An array of comment items. Use render($content) to print them all, or * print a subset such as render($content['field_example']). Use * hide($content['field_example']) to temporarily suppress the printing of a * given element. * - $created: Formatted date and time for when the comment was created. * Preprocess functions can reformat it by calling format_date() with the * desired parameters on the $comment->created variable. * - $changed: Formatted date and time for when the comment was last changed. * Preprocess functions can reformat it by calling format_date() with the * desired parameters on the $comment->changed variable. * - $new: New comment marker. * - $permalink: Comment permalink. * - $submitted: Submission information created from $author and $created during * template_preprocess_comment(). * - $picture: Authors picture. * - $signature: Authors signature. * - $status: Comment status. Possible values are: * comment-unpublished, comment-published or comment-preview. * - $title: Linked title. * - $classes: String of classes that can be used to style contextually through * CSS. It can be manipulated through the variable $classes_array from * preprocess functions. The default values can be one or more of the following: * - comment: The current template type, i.e., "theming hook". * - comment-by-anonymous: Comment by an unregistered user. * - comment-by-node-author: Comment by the author of the parent node. * - comment-preview: When previewing a new or edited comment. * - first: The first comment in the list of displayed comments. * - last: The last comment in the list of displayed comments. * - odd: An odd-numbered comment in the list of displayed comments. * - even: An even-numbered comment in the list of displayed comments. * The following applies only to viewers who are registered users: * - comment-unpublished: An unpublished comment visible only to administrators. * - comment-by-viewer: Comment by the user currently viewing the page. * - comment-new: New comment since the last visit. * - $title_prefix (array): An array containing additional output populated by * modules, intended to be displayed in front of the main title tag that * appears in the template. * - $title_suffix (array): An array containing additional output populated by * modules, intended to be displayed after the main title tag that appears in * the template. * * These two variables are provided for context: * - $comment: Full comment object. * - $node: Node object the comments are attached to. * * Other variables: * - $classes_array: Array of html class attribute values. It is flattened * into a string within the variable $classes. * * @see template_preprocess() * @see template_preprocess_comment() * @see zen_preprocess_comment() * @see template_process() * @see theme_comment() */ ?> <div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>> <?php print $picture; ?> <?php print render($title_prefix); ?> <?php if ($title): ?> <h3<?php print $title_attributes; ?>> <?php print $title; ?> <?php if ($new): ?> <span class="new"><?php print $new; ?></span> <?php endif; ?> </h3> <?php elseif ($new): ?> <div class="new"><?php print $new; ?></div> <?php endif; ?> <?php print render($title_suffix); ?> <?php if ($status == 'comment-unpublished'): ?> <div class="unpublished"><?php print t('Unpublished'); ?></div> <?php endif; ?> <div class="submitted"> <?php print $permalink; ?> <?php print $created . ' '. $author; ?> </div> <div class="content"<?php print $content_attributes; ?>> <?php // We hide the comments and links now so that we can render them later. hide($content['links']); print render($content); ?> <?php if ($signature): ?> <div class="user-signature clearfix"> <?php print $signature; ?> </div> <?php endif; ?> </div> <?php print render($content['links']) ?> </div><!-- /.comment -->
Drupalbook/shopogoliki
sites/all/themes/sitemade/templates/comment.tpl.php
PHP
gpl-2.0
4,250
//----------------------------------------------------------------------------- // File: ObjectExportDialog.cpp //----------------------------------------------------------------------------- // Project: Kactus2 // Author: Mikko Teuho // Date: 04.07.2017 // // Description: // Dialog for selecting the exported items. //----------------------------------------------------------------------------- #include "ObjectExportDialog.h" #include <QLabel> #include <QFileDialog> //----------------------------------------------------------------------------- // Function: ObjectExportDialog::ObjectExportDialog() //----------------------------------------------------------------------------- ObjectExportDialog::ObjectExportDialog(QWidget* parent, Qt::WindowFlags f): ObjectSelectionDialog(tr("Export"), QStringLiteral(":icons/common/graphics/export.png"), QStringLiteral(":icons/common/graphics/arrowRight.png"), tr("Select items to be exported"), parent, f), folderPathEditor_(QString(), this), folderBrowseButton_(QIcon(":icons/common/graphics/folder-horizontal-open.png"), QString(), this), currentPath_(QString()) { setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); QString styleSheet("*[mandatoryField=\"true\"] { background-color: LemonChiffon; }"); setStyleSheet(styleSheet); disableOkButton(); setupLayout(); connectSignals(); } //----------------------------------------------------------------------------- // Function: ObjectExportDialog::~ObjectExportDialog() //----------------------------------------------------------------------------- ObjectExportDialog::~ObjectExportDialog() { } //----------------------------------------------------------------------------- // Function: ObjectExportDialog::connectSignals() //----------------------------------------------------------------------------- void ObjectExportDialog::connectSignals() { ObjectSelectionDialog::connectSignals(); connect(&folderBrowseButton_, SIGNAL(clicked()), this, SLOT(onBrowseTarget()), Qt::UniqueConnection); connect(&folderPathEditor_, SIGNAL(textChanged(const QString&)), this, SLOT(onDestinationFolderChanged(const QString&)), Qt::UniqueConnection); } //----------------------------------------------------------------------------- // Function: ObjectExportDialog::onBrowseTarget() //----------------------------------------------------------------------------- void ObjectExportDialog::onBrowseTarget() { QFileDialog browseDialog(this, tr("Select destination folder for export"), currentPath_); browseDialog.setFileMode(QFileDialog::Directory); if (browseDialog.exec() == QDialog::Accepted) { QStringList selectedFiles = browseDialog.selectedFiles(); if (!selectedFiles.isEmpty()) { QString selectedFolder = selectedFiles.first(); onDestinationFolderChanged(selectedFolder); } } } //----------------------------------------------------------------------------- // Function: ObjectExportDialog::onDestinationFolderChanged() //----------------------------------------------------------------------------- void ObjectExportDialog::onDestinationFolderChanged(const QString& newDestination) { folderPathEditor_.setText(newDestination); currentPath_ = newDestination; QPalette pathPalette = folderPathEditor_.palette(); if (QFileInfo(newDestination).isDir()) { pathPalette.setColor(QPalette::Text, Qt::black); enableOkButton(); } else { pathPalette.setColor(QPalette::Text, Qt::red); disableOkButton(); } folderPathEditor_.setPalette(pathPalette); } //----------------------------------------------------------------------------- // Function: ObjectExportDialog::getTargetDirectory() //----------------------------------------------------------------------------- QString ObjectExportDialog::getTargetDirectory() const { return currentPath_; } //----------------------------------------------------------------------------- // Function: ObjectExportDialog::setupLayout() //----------------------------------------------------------------------------- void ObjectExportDialog::setupLayout() { QString introLabel = tr("Export"); QString introText = tr("Export the selected items to the destination folder. ") + tr(" The original files will be retained in their containing folders.\n") + tr("Selected files are exported to the folder of their containing component.") + tr(" Unselected files are given paths to their original location."); QWidget* introWidget = setupIntroWidget(introLabel, introText); QString folderToolTip(tr("The destination folder for the export.")); QLabel* folderLabel = new QLabel(tr("Destination folder:"), this); folderLabel->setToolTip(folderToolTip); folderPathEditor_.setToolTip(folderToolTip); folderPathEditor_.setProperty("mandatoryField", true); folderBrowseButton_.setToolTip("Browse."); QHBoxLayout* folderBrowseLayout = new QHBoxLayout(); folderBrowseLayout->addWidget(folderLabel); folderBrowseLayout->addWidget(&folderPathEditor_); folderBrowseLayout->addWidget(&folderBrowseButton_); QHBoxLayout* buttonLayout = setupButtonLayout(); QVBoxLayout* overallLayout = new QVBoxLayout(this); overallLayout->addWidget(introWidget); overallLayout->addLayout(folderBrowseLayout, 0); overallLayout->addWidget(getItemList(), 1); overallLayout->addLayout(buttonLayout, 0); }
kactus2/kactus2dev
common/dialogs/ObjectExportDialog/ObjectExportDialog.cpp
C++
gpl-2.0
5,516
<?php use dokuwiki\test\mock\AuthPlugin; use dokuwiki\test\mock\AuthCaseInsensitivePlugin; class auth_admin_test extends DokuWikiTest { private $oldauth; function setUp() { parent::setUp(); global $auth; $this->oldauth = $auth; } function setSensitive() { global $auth; $auth = new AuthPlugin(); } function setInSensitive() { global $auth; $auth = new AuthCaseInsensitivePlugin(); } function teardown() { global $auth; global $AUTH_ACL; unset($AUTH_ACL); $auth = $this->oldauth; } function test_ismanager_insensitive(){ $this->setInSensitive(); global $conf; $conf['superuser'] = 'john,@admin,@Mötly Görls, Dörte'; $conf['manager'] = 'john,@managers,doe, @Mötly Böys, Dänny'; // anonymous user $this->assertEquals(auth_ismanager('jill', null,false), false); // admin or manager users $this->assertEquals(auth_ismanager('john', null,false), true); $this->assertEquals(auth_ismanager('doe', null,false), true); $this->assertEquals(auth_ismanager('dörte', null,false), true); $this->assertEquals(auth_ismanager('dänny', null,false), true); // admin or manager groups $this->assertEquals(auth_ismanager('jill', array('admin'),false), true); $this->assertEquals(auth_ismanager('jill', array('managers'),false), true); $this->assertEquals(auth_ismanager('jill', array('mötly görls'),false), true); $this->assertEquals(auth_ismanager('jill', array('mötly böys'),false), true); } function test_isadmin_insensitive(){ $this->setInSensitive(); global $conf; $conf['superuser'] = 'john,@admin,doe,@roots'; // anonymous user $this->assertEquals(auth_ismanager('jill', null,true), false); // admin user $this->assertEquals(auth_ismanager('john', null,true), true); $this->assertEquals(auth_ismanager('doe', null,true), true); // admin groups $this->assertEquals(auth_ismanager('jill', array('admin'),true), true); $this->assertEquals(auth_ismanager('jill', array('roots'),true), true); $this->assertEquals(auth_ismanager('john', array('admin'),true), true); $this->assertEquals(auth_ismanager('doe', array('admin'),true), true); } function test_ismanager_sensitive(){ $this->setSensitive(); global $conf; $conf['superuser'] = 'john,@admin,@Mötly Görls, Dörte'; $conf['manager'] = 'john,@managers,doe, @Mötly Böys, Dänny'; // anonymous user $this->assertEquals(auth_ismanager('jill', null,false), false); // admin or manager users $this->assertEquals(auth_ismanager('john', null,false), true); $this->assertEquals(auth_ismanager('doe', null,false), true); $this->assertEquals(auth_ismanager('dörte', null,false), false); $this->assertEquals(auth_ismanager('dänny', null,false), false); // admin or manager groups $this->assertEquals(auth_ismanager('jill', array('admin'),false), true); $this->assertEquals(auth_ismanager('jill', array('managers'),false), true); $this->assertEquals(auth_ismanager('jill', array('mötly görls'),false), false); $this->assertEquals(auth_ismanager('jill', array('mötly böys'),false), false); } function test_isadmin_sensitive(){ $this->setSensitive(); global $conf; $conf['superuser'] = 'john,@admin,doe,@roots'; // anonymous user $this->assertEquals(auth_ismanager('jill', null,true), false); // admin user $this->assertEquals(auth_ismanager('john', null,true), true); $this->assertEquals(auth_ismanager('Doe', null,true), false); // admin groups $this->assertEquals(auth_ismanager('jill', array('admin'),true), true); $this->assertEquals(auth_ismanager('jill', array('roots'),true), true); $this->assertEquals(auth_ismanager('john', array('admin'),true), true); $this->assertEquals(auth_ismanager('doe', array('admin'),true), true); $this->assertEquals(auth_ismanager('Doe', array('admin'),true), true); } } //Setup VIM: ex: et ts=4 :
lzs/dokuwiki
_test/tests/inc/auth_admincheck.test.php
PHP
gpl-2.0
4,340
<?php include __DIR__ . '/paths.php'; // Load Nette Framework or autoloader generated by Composer require __DIR__ . '/Parsedown.php'; require __DIR__ . '/../libs/autoload.php'; $configurator = new Nette\Config\Configurator; // Enable Nette Debugger for error visualisation & logging $configurator->setDebugMode(true); // Enable RobotLoader - this will load all classes automatically $configurator->setTempDirectory(__DIR__ . '/../temp'); $configurator->createRobotLoader() ->addDirectory(__DIR__) ->addDirectory(__DIR__ . '/../libs') ->register(); // Create Dependency Injection container from config.neon file $configurator->addConfig(__DIR__ . '/config/config.neon'); $configurator->addConfig(__DIR__ . '/config/config.local.neon', $configurator::NONE); $container = $configurator->createContainer(); error_reporting(E_ERROR | E_WARNING | E_PARSE); return $container;
hackcraft-sk/swarm
overmind/app/bootstrap.php
PHP
gpl-2.0
907
package org.bytedeco.javacpp.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.bytedeco.javacpp.Loader; import org.bytedeco.javacpp.tools.Builder; import org.bytedeco.javacpp.tools.Generator; import org.bytedeco.javacpp.tools.Parser; /** * Makes it possible to define more than one set of properties for each platform. * The effective set of properties are taken from all {@link Platform} values in * this annotation, but priority is given to values found later in the list, making * it possible to define a default set of properties as the first value of the array, * and specializing a smaller set of properties for each platform, subsequently. * <p> * A class with this annotation gets recognized as top-level enclosing class by * {@link Loader#getEnclosingClass(Class)}, with the same implications as with * the {@link Platform} annotation. * <p> * Additionally, it is possible to inherit properties from another class also * annotated with this annotation, and specialize further for the current class. * * @see Builder * @see Generator * @see Loader * @see Parser * * @author Samuel Audet */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface Properties { /** A list of classes from which to inherit properties. */ Class[] inherit() default {}; /** A list of properties for different platforms. */ Platform[] value() default {}; /** The target Java source code file of the {@link Parser}. */ String target() default ""; /** An optional helper class the {@link Parser} should use as base of the target. Defaults to the class where this annotation was found. */ String helper() default ""; }
xuse/javacpp
src/main/java/org/bytedeco/javacpp/annotation/Properties.java
Java
gpl-2.0
1,823
/******************************************************************************* * Copyright (c) 2017 Moritz Lang. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v2.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * * Contributors: * Moritz Lang - initial API and implementation ******************************************************************************/ package org.youscope.plugin.bdbiosciencemicroplates; import org.youscope.addon.microplate.MicroplateConfiguration; import org.youscope.common.configuration.YSConfigAlias; import org.youscope.common.configuration.YSConfigIcon; /** * 12 well microplate (BD Bioscience - Multiwell TC Plate). * @author Moritz Lang * */ @YSConfigAlias("12 well microplate (BD Bioscience - Multiwell TC Plate)") @YSConfigIcon("icons/map.png") public class BDBioscienceMultiwellTC12MicroplateConfiguration extends MicroplateConfiguration { /** * Serial Version UID. */ private static final long serialVersionUID = -8043869569063229857L; /** * Type identifier. */ public static final String TYPE_IDENTIFIER = "YouScope.microplate.DBioscienceMultiwellTC12Microplate"; @Override public String getTypeIdentifier() { return TYPE_IDENTIFIER; } }
langmo/youscope
plugins/bd-bioscience-multiwell-tc-microplates/src/main/java/org/youscope/plugin/bdbiosciencemicroplates/BDBioscienceMultiwellTC12MicroplateConfiguration.java
Java
gpl-2.0
1,371
using Autofac; using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using Trooper.Interface.DynamicServiceHost; namespace Trooper.DynamicServiceHost { public class HostInfoHelper { public static void BuildHostInfo(Func<object> supporter, IDynamicHostInfo hostInfo) { var supportType = supporter().GetType(); BuildHostInfo(supportType, hostInfo); } public static void BuildHostInfo(Type supportType, IDynamicHostInfo hostInfo) { var serviceTypeName = supportType.Name; var typeInterfaces = supportType.GetInterfaces(); var interfaceTypeName = typeInterfaces.Count() == 1 ? typeInterfaces.First().Name : null; var methods = GetMethods(supportType).ToList(); hostInfo.InterfaceName = hostInfo.InterfaceName ?? interfaceTypeName; hostInfo.ServiceName = hostInfo.ServiceName ?? serviceTypeName; if (hostInfo.Methods == null) { hostInfo.Methods = methods; } else { hostInfo.Methods.AddRange(methods); } } public static IDynamicHostInfo BuildHostInfo(Type serviceType) { var serviceTypeName = serviceType.Name; var typeInterfaces = serviceType.GetInterfaces(); var interfaceTypeName = typeInterfaces.Count() == 1 ? typeInterfaces.First().Name : null; var hostInfo = new HostInfo { InterfaceName = interfaceTypeName, ServiceName = serviceTypeName, Methods = new List<Method>() }; hostInfo.Methods = GetMethods(serviceType).ToList(); return hostInfo; } private static IEnumerable<Method> GetMethods(Type serviceType) { var typeInterfaces = serviceType.GetInterfaces(); foreach (var typeMethod in serviceType.GetMethods()) { var typeMethodParameters = typeMethod.GetParameters().Select(p => p.ParameterType).ToArray(); var interfaceMethod = (from ti in typeInterfaces let m = ti.GetMethod(typeMethod.Name, typeMethodParameters) where m != null select m).FirstOrDefault(); var hasOperationContract = interfaceMethod != null && interfaceMethod.GetCustomAttributes(typeof(OperationContractAttribute), true).Any(); if (!hasOperationContract) { continue; } var method = new Method { Name = typeMethod.Name, Parameters = typeMethod.GetParameters().Select(p => new Paramater(p.ParameterType, p.Name)).ToList(), Returns = typeMethod.ReturnType, Body = (MethodInput input) => { var targetMethod = input.Supporter.GetType().GetMethod(typeMethod.Name); var result = targetMethod.Invoke(input.Supporter, input.Inputs); return typeMethod.ReturnType.IsEquivalentTo(typeof(void)) ? null : result; } }; yield return method; } } public static string MakeClassName(Type classType, bool incInterfacePrefix = false) { var name = classType.Name; if (classType.GenericTypeArguments.Any()) { name += string.Format("Of{0}", classType.GenericTypeArguments.First().Name); } if (classType.GenericTypeArguments.Count() > 1) { name += string.Join("And", classType.GenericTypeArguments.Select(a => a.Name)); } if (incInterfacePrefix) { name = "I" + name; } return name; } } }
stevenharrap/Trooper
Trooper/DynamicServiceHost/HostInfoHelper.cs
C#
gpl-2.0
4,126
/* * serial.hpp * * Serial communications wrapper. This code compiles under Windows and * Linux. Handy for multiplatform projects that use seria lcommunications. * * Copyright (C) 2014 Raúl Hermoso Sánchez * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Created on: 18/04/2013 * Author: Raúl Hermoso Sánchez * e-mail: raul.hermoso@gmail.com */ //----------------------------------------------------------------------------- #ifndef __SERIAL_HPP__ #define __SERIAL_HPP__ //----------------------------------------------------------------------------- #ifdef __RPI__ #include <wiringSerial.h> // #include <termios.h> typedef short FILETIME; typedef int uav_fd; // typedef termios ser_dcb; #define USR_INVALID_HANDLE -1 #elif defined(ARDUINO) #elif defined(WIN32) #include <windows.h> typedef HANDLE uav_fd; typedef DCB ser_dcb; #define USR_INVALID_HANDLE NULL #endif //----------------------------------------------------------------------------- #include <string> //----------------------------------------------------------------------------- namespace nsSerial { //------------------------------------------------------------------------- enum TBaudRate { br110 = 110, br300 = 300, br600 = 600, br1200 = 1200, br2400 = 2400, br4800 = 4800, br9600 = 9600, br14400 = 14400, br19200 = 19200, br38400 = 38400, br56000 = 56000, br57600 = 57600, br115200 = 115200, br128000 = 128000, br256000 = 256000 }; enum TByteSize { bs4 = 4, bs5, bs6, bs7, bs8 }; enum TParity { pNone = 0, pOdd, pEven, pMark, pSpace }; enum TStopBits { sb1 = 0, sb3_2, sb2 }; enum TFlowControl { fcNone = 0, fcHardware, fcSoftware }; enum TControl { cNone = 0, cHalfDuplex, cFullDuplex }; //------------------------------------------------------------------------- #ifdef WIN32 struct SSerialConf { unsigned long BaudRate; TByteSize ByteSize; TParity Parity; TStopBits StopBits; TFlowControl FlowControl; TControl Control; SSerialConf(); virtual ~SSerialConf(); }; //------------------------------------------------------------------------- class TSerial; typedef void (*evntOnSerial)(void*, nsSerial::TSerial*, char*, unsigned long); typedef void (*evntOnError)(void*, nsSerial::TSerial*, char*, int); #endif //------------------------------------------------------------------------- class TSerial { private: void* m_vUser; uav_fd m_hSerial; std::string m_strPort; std::string m_strError; #ifdef WIN32 SSerialConf m_scSetts; ser_dcb m_dcbSetts; ULARGE_INTEGER m_liWriteTime; ULARGE_INTEGER m_liReadTime; void getTimeNow(ULARGE_INTEGER& liNow); void setError(unsigned long ulError, std::string strTitle = ""); bool setTimeouts(); void dcb2setts(); void setts2dcb(); bool getDCB(); bool setDCB(); #endif protected: public: TSerial(void* vUser); virtual ~TSerial(); inline void* user() { return m_vUser; } inline std::string port() { return m_strPort; } inline std::string lastError() { return m_strError; } inline bool isOpened() { return m_hSerial != USR_INVALID_HANDLE; } #ifdef WIN32 inline unsigned long& baudRate() { return m_scSetts.BaudRate; } inline TByteSize& byteSize() { return m_scSetts.ByteSize; } inline TParity& parity() { return m_scSetts.Parity; } inline TStopBits& stopBits() { return m_scSetts.StopBits; } inline TFlowControl& flowControl() { return m_scSetts.FlowControl; } inline TControl& control() { return m_scSetts.Control; } inline bool setSettings() { return getDCB(); } inline bool getSettings() { return setDCB(); } double waitTime(); bool setConfig(int iBauds, TByteSize bsSize, TParity pParity, TStopBits sbStop); #endif bool open(std::string strPort); bool open(std::string strPort, int iBauds, TByteSize bsSize, TParity pParity, TStopBits sbStop); bool close(); unsigned long write(char* cData, int iSize); int read(char* cData, int& iSize); unsigned long wrrd(char* cData, int iSize); #ifdef WIN32 bool read(); evntOnSerial onRead; evntOnSerial onWrite; evntOnSerial onDebug; evntOnError onError; #endif }; //------------------------------------------------------------------------- }; //----------------------------------------------------------------------------- #endif /* __SERIAL_HPP__ */ //-----------------------------------------------------------------------------
Di4l/fluav-rpi
ui_serial/serial.hpp
C++
gpl-2.0
5,272
module Spree module Betaout class Engine < Rails::Engine require 'spree/core' isolate_namespace Spree engine_name 'spree_betaout' config.autoload_paths += %W(#{config.root}/lib) # use rspec for tests config.generators do |g| g.test_framework :rspec end initializer "spree_betaout.environment", :before => :load_config_initializers do |app| Betaout::Config = Spree::Betaout::Configuration.new end def self.activate Dir.glob(File.join(File.dirname(__FILE__), '../../../app/**/*_decorator*.rb')) do |c| Rails.configuration.cache_classes ? require(c) : load(c) end end config.to_prepare &method(:activate).to_proc end end end
betaout/spree_betaout
lib/spree/betaout/engine.rb
Ruby
gpl-2.0
752
<?php /** * 2Moons * Copyright (C) 2012 Jan Kröpke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @package 2Moons * @author Jan Kröpke <info@2moons.cc> * @copyright 2012 Jan Kröpke <info@2moons.cc> * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License * @version 1.7.3 (2013-05-19) * @info $Id: openid.class.php 2749 2013-05-19 11:43:20Z slaver7 $ * @link http://2moons.cc/ */ require '/includes/libs/OpenID/openid.php'; class OpenIDAuth extends LightOpenID { function __construct() { parent::__construct(PROTOCOL.HTTP_HOST); if(!$this->mode) { if(isset($_REQUEST['openid_identifier'])) { $this->identity = $_REQUEST['openid_identifier']; $this->required = array('contact/email'); $this->optional = array('namePerson', 'namePerson/friendly'); header('Location: ' . $this->authUrl()); exit; } else { HTTP::redirectTo('index.php?code=4'); } } } function isVaild() { return $this->mode && $this->mode != 'cancel'; } function getAccount() { $user = $this->getAttributes(); if(!empty($user['contact/email'])) { return $user['contact/email']; } if(!empty($user['namePerson/friendly'])) { return $user['namePerson/friendly']; } if(!empty($user['namePerson'])) { return $user['namePerson']; } HTTP::redirectTo('index.php?code=4'); } function register() { $uid = getAccount(); $user = $this->getAttributes(); if(empty($user['contact/email'])) { $user['contact/email'] = ""; } if(!empty($user['namePerson/friendly'])) { $username = $user['namePerson/friendly']; } elseif(!empty($user['namePerson'])) { $username = $user['namePerson']; } $ValidReg = $GLOBALS['DATABASE']->getFirstCell("SELECT cle FROM ".USERS_VALID." WHERE universe = ".$UNI." AND email = '".$GLOBALS['DATABASE']->sql_escape($user['contact/email'])."';"); if(!empty($ValidReg)) HTTP::redirectTo("index.php?uni=".$UNI."&page=reg&action=valid&clef=".$ValidReg); $GLOBALS['DATABASE']->query("INSERT INTO ".USERS_AUTH." SET id = (SELECT id FROM ".USERS." WHERE email = '".$GLOBALS['DATABASE']->sql_escape($me['email'])."' OR email_2 = '".$GLOBALS['DATABASE']->sql_escape($user['contact/email'])."'), account = '".$uid."', mode = '".$GLOBALS['DATABASE']->sql_escape($_REQUEST['openid_identifier'])."';"); } function getLoginData() { global $UNI; try { $user = $this->getAttributes(); } catch (FacebookApiException $e) { HTTP::redirectTo('index.php?code=4'); } return $GLOBALS['DATABASE']->getFirstRow("SELECT user.id, user.username, user.dpath, user.authlevel, user.id_planet FROM ".USERS_AUTH." auth INNER JOIN ".USERS." user ON auth.id = user.id AND user.universe = ".$UNI." WHERE auth.account = '".$user['contact/email']."' AND mode = '".$GLOBALS['DATABASE']->sql_escape($_REQUEST['openid_identifier'])."';"); } }
joancefet/StellarWars
1.7.3/includes/extauth/openid.class.php
PHP
gpl-2.0
3,504
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Xamasoft.JsonClassGenerator.CodeWriters { public class JavaCodeWriter : ICodeWriter { public string FileExtension { get { return ".java"; } } public string DisplayName { get { return "Java"; } } public IList<string> Keywords { get {return _getKeywords();} } public string GetTypeName(JsonType type, IJsonClassGeneratorConfig config) { var arraysAsLists = !config.ExplicitDeserialization; switch (type.Type) { case JsonTypeEnum.Anything: return "Object"; case JsonTypeEnum.Array: return arraysAsLists ? "List<" + GetTypeName(type.InternalType, config) + ">" : GetTypeName(type.InternalType, config) + "[]"; case JsonTypeEnum.Dictionary: return "Dictionary<string, " + GetTypeName(type.InternalType, config) + ">"; case JsonTypeEnum.Boolean: return "boolean"; case JsonTypeEnum.Float: return "double"; case JsonTypeEnum.Integer: return "int"; case JsonTypeEnum.Long: return "long"; case JsonTypeEnum.Date: return "Date"; case JsonTypeEnum.NonConstrained: return "Object"; case JsonTypeEnum.NullableBoolean: return "bool?"; case JsonTypeEnum.NullableFloat: return "double?"; case JsonTypeEnum.NullableInteger: return "int?"; case JsonTypeEnum.NullableLong: return "long?"; case JsonTypeEnum.NullableDate: return "DateTime?"; case JsonTypeEnum.NullableSomething: return "object"; case JsonTypeEnum.Object: return type.AssignedName; case JsonTypeEnum.String: return "String"; default: throw new System.NotSupportedException("Unsupported json type"); } } public void WriteClass(IJsonClassGeneratorConfig config, TextWriter sw, JsonType type) { var visibility = config.InternalVisibility ? "" : "public"; //if (config.UseNestedClasses) //{ // if (!type.IsRoot) // { // if (config.PropertyAttribute == "DataMember") // { // sw.WriteLine(" [DataContract]"); // } // if (ShouldApplyNoRenamingAttribute(config)) sw.WriteLine(" " + NoRenameAttribute); // if (ShouldApplyNoPruneAttribute(config)) sw.WriteLine(" " + NoPruneAttribute); // sw.WriteLine(" {0} class {1}", visibility, type.AssignedName); // sw.WriteLine(" {"); // } //} //else //{ // if (config.PropertyAttribute == "DataMember") // { // sw.WriteLine(" [DataContract]"); // } // if (ShouldApplyNoRenamingAttribute(config)) sw.WriteLine(" " + NoRenameAttribute); // if (ShouldApplyNoPruneAttribute(config)) sw.WriteLine(" " + NoPruneAttribute); sw.WriteLine("{0} class {1}", visibility, type.AssignedName); sw.WriteLine("{"); //} var prefix = config.UseNestedClasses && !type.IsRoot ? "" : " "; var shouldSuppressWarning = config.InternalVisibility && !config.UseProperties && !config.ExplicitDeserialization; if (shouldSuppressWarning) { sw.WriteLine("#pragma warning disable 0649"); if (!config.UsePascalCase) sw.WriteLine(); } //if (type.IsRoot && config.ExplicitDeserialization) WriteStringConstructorExplicitDeserialization(config, sw, type, prefix); //if (config.ExplicitDeserialization) //{ // if (config.UseProperties) WriteClassWithPropertiesExplicitDeserialization(sw, type, prefix); // else WriteClassWithFieldsExplicitDeserialization(sw, type, prefix); //} //else //{ WriteClassMembers(config, sw, type, prefix); //} if (shouldSuppressWarning) { sw.WriteLine(); sw.WriteLine("#pragma warning restore 0649"); sw.WriteLine(); } if (config.UseNestedClasses && !type.IsRoot) sw.WriteLine(" }"); if (!config.UseNestedClasses) sw.WriteLine("}"); sw.WriteLine(); } public void WriteFileStart(IJsonClassGeneratorConfig config, TextWriter sw) { foreach (var line in JsonClassGenerator.FileHeader) { sw.WriteLine("// " + line); } } public void WriteFileEnd(IJsonClassGeneratorConfig config, TextWriter sw) { throw new NotImplementedException(); } public void WriteNamespaceStart(IJsonClassGeneratorConfig config, TextWriter sw, bool root) { sw.WriteLine(); sw.WriteLine("package {0};", root && !config.UseNestedClasses ? config.Namespace : (config.SecondaryNamespace ?? config.Namespace)); sw.WriteLine(); } public void WriteNamespaceEnd(IJsonClassGeneratorConfig config, TextWriter sw, bool root) { sw.WriteLine(); } private void WriteClassMembers(IJsonClassGeneratorConfig config, TextWriter sw, JsonType type, string prefix) { foreach (var field in type.Fields) { //if (config.UsePascalCase || config.ExamplesInDocumentation) sw.WriteLine(); //if (config.ExamplesInDocumentation) //{ // sw.WriteLine(prefix + "/// <summary>"); // sw.WriteLine(prefix + "/// Examples: " + field.GetExamplesText()); // sw.WriteLine(prefix + "/// </summary>"); //} //if (config.UsePascalCase || config.PropertyAttribute != "None") //{ // if (config.UsePascalCase && config.PropertyAttribute == "None") // sw.WriteLine(prefix + "@JsonProperty(\"{0}\")", field.JsonMemberName); // else // { // //if (config.PropertyAttribute == "DataMember") // // sw.WriteLine(prefix + "[" + config.PropertyAttribute + "(Name=\"{0}\")]", field.JsonMemberName); // if (config.PropertyAttribute == "JsonProperty") // sw.WriteLine(prefix + "@" + config.PropertyAttribute + "(\"{0}\")", field.JsonMemberName); // } //} if (config.UseProperties) { sw.WriteLine(prefix + "@JsonProperty" + "(\"{0}\")", field.JsonMemberName); sw.WriteLine(prefix + "public {0} get{1}() {{ \r\t\t return this.{2} \r\t}}", field.Type.GetTypeName(), ChangeFirstChar(field.MemberName), ChangeFirstChar(field.MemberName, false)); sw.WriteLine(prefix + "public {0} set{1}({0} {2}) {{ \r\t\t this.{2} = {2} \r\t}}", field.Type.GetTypeName(), ChangeFirstChar(field.MemberName), ChangeFirstChar(field.MemberName, false)); sw.WriteLine(prefix + "{0} {1};", field.Type.GetTypeName(), ChangeFirstChar(field.MemberName, false)); sw.WriteLine(); } else { string memberName = ChangeFirstChar(field.MemberName, false); if(field.JsonMemberName != memberName) sw.WriteLine(prefix + "@JsonProperty" + "(\"{0}\")", field.JsonMemberName); sw.WriteLine(prefix + "public {0} {1};", field.Type.GetTypeName(), memberName); } } } private static string ChangeFirstChar(string value, bool toCaptial = true) { if (value == null) throw new ArgumentNullException("value"); if (value.Length == 0) return value; StringBuilder sb = new StringBuilder(); sb.Append(toCaptial ? char.ToUpper(value[0]) : char.ToLower(value[0])); sb.Append(value.Substring(1)); return sb.ToString(); } private static List<string> _getKeywords() { return new List<string>() { "abstract", "assert" , "boolean", "break", "byte", "case", "catch", "char", "class", "const", "default", "do", "double", "else", "enum", "extends", "false", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "void", "volatile", "while", "continue" }; } } }
akovacevic/JsonUtils
JsonCSharpClassGeneratorLib/CodeWriters/JavaCodeWriter.cs
C#
gpl-2.0
10,149
<?php namespace Gjo\GjoSjrOffers\Domain\Model; use TYPO3\CMS\Extbase\DomainObject\AbstractEntity; /*************************************************************** * Copyright notice * * (c) 2009 Jochen Rau <jochen.rau@typoplanet.de> * All rights reserved * * This script is part of the TYPO3 project. The TYPO3 project is * free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * The GNU General Public License can be found at * http://www.gnu.org/copyleft/gpl.html. * * This script is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * This copyright notice MUST APPEAR in all copies of the script! ***************************************************************/ /** * An Contact * * @author gregory.jo * @version 1.0 * @updated 29-Apr-2014 16:17:00 */ class Contact extends AbstractEntity { /** * @var string The address of the contact **/ protected $address = ''; /** * @var string The email of the contact **/ protected $email = ''; /** * @var string The fax number of the contact **/ protected $fax = ''; /** * @var string The name of the contact * @validate StringLength(minimum = 2, maximum = 80) **/ protected $name; /** * @var string The telephone number of the contact **/ protected $phone = ''; /** * @var string The role of the contact **/ protected $role = ''; /** * @var string The url of the homepage of the contact **/ protected $url = ''; public function __construct($name = NULL) { $this->setName($name); } /** * @param string $address */ public function setAddress($address) { $this->address = $address; } /** * @return string */ public function getAddress() { return $this->address; } /** * @param string $email */ public function setEmail($email) { $this->email = $email; } /** * @return string */ public function getEmail() { return $this->email; } /** * @param string $fax */ public function setFax($fax) { $this->fax = $fax; } /** * @return string */ public function getFax() { return $this->fax; } /** * @param string $name */ public function setName($name) { $this->name = $name; } /** * @return string */ public function getName() { return $this->name; } /** * @param string $phone */ public function setPhone($phone) { $this->phone = $phone; } /** * @return string */ public function getPhone() { return $this->phone; } /** * @param string $role */ public function setRole($role) { $this->role = $role; } /** * @return string */ public function getRole() { return $this->role; } /** * @param string $url */ public function setUrl($url) { $this->url = $url; } /** * @return string */ public function getUrl() { return $this->url; } }
obsolete-gjo-se/2014_typo3_gjo_sjr_offers
Classes/Domain/Model/Contact.php
PHP
gpl-2.0
3,606
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "inputdialog.h" #include "buttonbox.h" #include "gmenu2x.h" #include "iconbutton.h" #include "surface.h" #include "utilities.h" using namespace std; #define KEY_WIDTH 20 #define KEY_HEIGHT 20 #define KB_TOP 90 static bool utf8Code(unsigned char c) { return (c>=194 && c<=198) || c==208 || c==209; } InputDialog::InputDialog(GMenu2X *gmenu2x, InputManager &inputMgr_, Touchscreen &ts_, const string &text, const string &startvalue, const string &title, const string &icon) : Dialog(gmenu2x) , inputMgr(inputMgr_) , ts(ts_) { if (title.empty()) { this->title = text; this->text = ""; } else { this->title = title; this->text = text; } this->icon = ""; if (!icon.empty() && gmenu2x->sc[icon] != NULL) { this->icon = icon; } input = startvalue; selCol = 0; selRow = 0; keyboard.resize(7); keyboard[0].push_back("abcdefghijklm"); keyboard[0].push_back("nopqrstuvwxyz"); keyboard[0].push_back("0123456789. "); keyboard[1].push_back("ABCDEFGHIJKLM"); keyboard[1].push_back("NOPQRSTUVWXYZ"); keyboard[1].push_back("_\"'`.,:;!? "); keyboard[2].push_back("¡¿*+-/\\&<=>|"); keyboard[2].push_back("()[]{}@#$%^~"); keyboard[2].push_back("_\"'`.,:;!? "); keyboard[3].push_back("àáèéìíòóùúýäõ"); keyboard[3].push_back("ëïöüÿâêîôûåãñ"); keyboard[3].push_back("čďěľĺňôřŕšťůž"); keyboard[3].push_back("ąćęłńśżź "); keyboard[4].push_back("ÀÁÈÉÌÍÒÓÙÚÝÄÕ"); keyboard[4].push_back("ËÏÖÜŸÂÊÎÔÛÅÃÑ"); keyboard[4].push_back("ČĎĚĽĹŇÔŘŔŠŤŮŽ"); keyboard[4].push_back("ĄĆĘŁŃŚŻŹ "); keyboard[5].push_back("æçабвгдеёжзий "); keyboard[5].push_back("клмнопрстуфхцч"); keyboard[5].push_back("шщъыьэюяøðßÐÞþ"); keyboard[6].push_back("ÆÇАБВГДЕЁЖЗИЙ "); keyboard[6].push_back("КЛМНОПРСТУФХЦЧ"); keyboard[6].push_back("ШЩЪЫЬЭЮЯØðßÐÞþ"); setKeyboard(0); buttonbox.add(unique_ptr<IconButton>(new IconButton( gmenu2x, ts, "skin:imgs/buttons/l.png", gmenu2x->tr["Backspace"], bind(&InputDialog::backspace, this)))); buttonbox.add(unique_ptr<IconButton>(new IconButton( gmenu2x, ts, "skin:imgs/buttons/r.png", gmenu2x->tr["Space"], bind(&InputDialog::space, this)))); buttonbox.add(unique_ptr<IconButton>(new IconButton( gmenu2x, ts, "skin:imgs/buttons/accept.png", gmenu2x->tr["Confirm"], bind(&InputDialog::confirm, this)))); buttonbox.add(unique_ptr<IconButton>(new IconButton( gmenu2x, ts, "skin:imgs/buttons/cancel.png", gmenu2x->tr["Change keys"], bind(&InputDialog::changeKeys, this)))); } void InputDialog::setKeyboard(int kb) { kb = constrain(kb, 0, keyboard.size() - 1); curKeyboard = kb; this->kb = &(keyboard[kb]); kbLength = this->kb->at(0).length(); for (int x = 0, l = kbLength; x < l; x++) { if (utf8Code(this->kb->at(0)[x])) { kbLength--; x++; } } kbLeft = 160 - kbLength * KEY_WIDTH / 2; kbWidth = kbLength * KEY_WIDTH + 3; kbHeight = (this->kb->size() + 1) * KEY_HEIGHT + 3; kbRect.x = kbLeft - 3; kbRect.y = KB_TOP - 2; kbRect.w = kbWidth; kbRect.h = kbHeight; } bool InputDialog::exec() { SDL_Rect box = { 0, 60, 0, static_cast<Uint16>(gmenu2x->font->getLineSpacing() + 4) }; Uint32 caretTick = 0, curTick; bool caretOn = true; OffscreenSurface bg(*gmenu2x->bg); drawTitleIcon(bg, icon, false); writeTitle(bg, title); writeSubTitle(bg, text); buttonbox.paint(bg, 5, gmenu2x->resY - 1); bg.convertToDisplayFormat(); close = false; ok = true; while (!close) { OutputSurface& s = *gmenu2x->s; bg.blit(s, 0, 0); box.w = gmenu2x->font->getTextWidth(input) + 18; box.x = 160 - box.w / 2; s.box(box.x, box.y, box.w, box.h, gmenu2x->skinConfColors[COLOR_SELECTION_BG]); s.rectangle(box.x, box.y, box.w, box.h, gmenu2x->skinConfColors[COLOR_SELECTION_BG]); gmenu2x->font->write(s, input, box.x + 5, box.y + box.h - 2, Font::HAlignLeft, Font::VAlignBottom); curTick = SDL_GetTicks(); if (curTick - caretTick >= 600) { caretOn = !caretOn; caretTick = curTick; } if (caretOn) { s.box(box.x + box.w - 12, box.y + 3, 8, box.h - 6, gmenu2x->skinConfColors[COLOR_SELECTION_BG]); } if (ts.available()) ts.poll(); drawVirtualKeyboard(); s.flip(); switch (inputMgr.waitForPressedButton()) { case InputManager::SETTINGS: ok = true; close = true; break; case InputManager::MENU: ok = false; close = true; break; case InputManager::UP: selRow--; break; case InputManager::DOWN: selRow++; if (selRow == (int)kb->size()) selCol = selCol < 8 ? 0 : 1; break; case InputManager::LEFT: selCol--; break; case InputManager::RIGHT: selCol++; break; case InputManager::ACCEPT: confirm(); break; case InputManager::CANCEL: changeKeys(); break; case InputManager::ALTLEFT: backspace(); break; case InputManager::ALTRIGHT: space(); break; default: break; } } return ok; } void InputDialog::backspace() { // Check for UTF8 characters. input = input.substr(0, input.length() - (utf8Code(input[input.length() - 2]) ? 2 : 1)); } void InputDialog::space() { input += " "; } void InputDialog::confirm() { if (selRow == (int)kb->size()) { if (selCol == 0) { ok = false; } close = true; } else { int xc = 0; for (uint x = 0; x < kb->at(selRow).length(); x++) { bool utf8 = utf8Code(kb->at(selRow)[x]); if (xc == selCol) input += kb->at(selRow).substr(x, utf8 ? 2 : 1); if (utf8) x++; xc++; } } } void InputDialog::changeKeys() { if (curKeyboard == 6) { setKeyboard(0); } else { setKeyboard(curKeyboard + 1); } } void InputDialog::drawVirtualKeyboard() { Surface& s = *gmenu2x->s; //keyboard border s.rectangle(kbRect, gmenu2x->skinConfColors[COLOR_SELECTION_BG]); if (selCol<0) selCol = selRow==(int)kb->size() ? 1 : kbLength-1; if (selCol>=(int)kbLength) selCol = 0; if (selRow<0) selRow = kb->size()-1; if (selRow>(int)kb->size()) selRow = 0; //selection if (selRow<(int)kb->size()) s.box(kbLeft + selCol * KEY_WIDTH - 1, KB_TOP + selRow * KEY_HEIGHT, KEY_WIDTH - 1, KEY_HEIGHT - 2, gmenu2x->skinConfColors[COLOR_SELECTION_BG]); else { if (selCol > 1) selCol = 0; if (selCol < 0) selCol = 1; s.box(kbLeft + selCol * kbLength * KEY_WIDTH / 2 - 1, KB_TOP + kb->size() * KEY_HEIGHT, kbLength * KEY_WIDTH / 2 - 1, KEY_HEIGHT - 1, gmenu2x->skinConfColors[COLOR_SELECTION_BG]); } //keys for (uint l=0; l<kb->size(); l++) { string line = kb->at(l); for (uint x=0, xc=0; x<line.length(); x++) { string charX; //utf8 characters if (utf8Code(line[x])) { charX = line.substr(x,2); x++; } else charX = line[x]; SDL_Rect re = { static_cast<Sint16>(kbLeft + xc * KEY_WIDTH - 1), static_cast<Sint16>(KB_TOP + l * KEY_HEIGHT), KEY_WIDTH - 1, KEY_HEIGHT - 2 }; //if ts on rect, change selection if (ts.available() && ts.pressed() && ts.inRect(re)) { selCol = xc; selRow = l; } s.rectangle(re, gmenu2x->skinConfColors[COLOR_SELECTION_BG]); gmenu2x->font->write(s, charX, kbLeft + xc * KEY_WIDTH + KEY_WIDTH / 2 - 1, KB_TOP + l * KEY_HEIGHT + KEY_HEIGHT / 2, Font::HAlignCenter, Font::VAlignMiddle); xc++; } } //Ok/Cancel SDL_Rect re = { static_cast<Sint16>(kbLeft - 1), static_cast<Sint16>(KB_TOP + kb->size() * KEY_HEIGHT), static_cast<Uint16>(kbLength * KEY_WIDTH / 2 - 1), KEY_HEIGHT - 1 }; s.rectangle(re, gmenu2x->skinConfColors[COLOR_SELECTION_BG]); if (ts.available() && ts.pressed() && ts.inRect(re)) { selCol = 0; selRow = kb->size(); } gmenu2x->font->write(s, gmenu2x->tr["Cancel"], (int)(160 - kbLength * KEY_WIDTH / 4), KB_TOP + kb->size() * KEY_HEIGHT + KEY_HEIGHT / 2, Font::HAlignCenter, Font::VAlignMiddle); re.x = kbLeft + kbLength * KEY_WIDTH / 2 - 1; s.rectangle(re, gmenu2x->skinConfColors[COLOR_SELECTION_BG]); if (ts.available() && ts.pressed() && ts.inRect(re)) { selCol = 1; selRow = kb->size(); } gmenu2x->font->write(s, gmenu2x->tr["OK"], (int)(160 + kbLength * KEY_WIDTH / 4), KB_TOP + kb->size() * KEY_HEIGHT + KEY_HEIGHT / 2, Font::HAlignCenter, Font::VAlignMiddle); }
Nebuleon/gmenu2x-gcw0
src/inputdialog.cpp
C++
gpl-2.0
9,774
package tracker.diagram.edit.parts; import org.eclipse.draw2d.ColorConstants; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.RectangleFigure; import org.eclipse.draw2d.Shape; import org.eclipse.draw2d.StackLayout; import org.eclipse.gef.EditPart; import org.eclipse.gef.EditPolicy; import org.eclipse.gef.Request; import org.eclipse.gef.commands.Command; import org.eclipse.gef.editpolicies.LayoutEditPolicy; import org.eclipse.gef.editpolicies.NonResizableEditPolicy; import org.eclipse.gef.requests.CreateRequest; import org.eclipse.gmf.runtime.diagram.ui.editparts.ShapeNodeEditPart; import org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles; import org.eclipse.gmf.runtime.gef.ui.figures.DefaultSizeNodeFigure; import org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure; import org.eclipse.gmf.runtime.notation.View; import org.eclipse.swt.graphics.Color; import tracker.diagram.edit.policies.ClerkItemSemanticEditPolicy; /** * @generated */ public class ClerkEditPart extends ShapeNodeEditPart { /** * @generated */ public static final int VISUAL_ID = 2003; /** * @generated */ protected IFigure contentPane; /** * @generated */ protected IFigure primaryShape; /** * @generated */ public ClerkEditPart(View view) { super(view); } /** * @generated */ protected void createDefaultEditPolicies() { super.createDefaultEditPolicies(); installEditPolicy(EditPolicyRoles.SEMANTIC_ROLE, new ClerkItemSemanticEditPolicy()); installEditPolicy(EditPolicy.LAYOUT_ROLE, createLayoutEditPolicy()); // XXX need an SCR to runtime to have another abstract superclass that would let children add reasonable editpolicies // removeEditPolicy(org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles.CONNECTION_HANDLES_ROLE); } /** * @generated */ protected LayoutEditPolicy createLayoutEditPolicy() { org.eclipse.gmf.runtime.diagram.ui.editpolicies.LayoutEditPolicy lep = new org.eclipse.gmf.runtime.diagram.ui.editpolicies.LayoutEditPolicy() { protected EditPolicy createChildEditPolicy(EditPart child) { EditPolicy result = child.getEditPolicy(EditPolicy.PRIMARY_DRAG_ROLE); if (result == null) { result = new NonResizableEditPolicy(); } return result; } protected Command getMoveChildrenCommand(Request request) { return null; } protected Command getCreateCommand(CreateRequest request) { return null; } }; return lep; } /** * @generated */ protected IFigure createNodeShape() { return primaryShape = new ClerkFigure(); } /** * @generated */ public ClerkFigure getPrimaryShape() { return (ClerkFigure) primaryShape; } /** * @generated */ protected NodeFigure createNodePlate() { DefaultSizeNodeFigure result = new DefaultSizeNodeFigure(40, 40); return result; } /** * Creates figure for this edit part. * * Body of this method does not depend on settings in generation model * so you may safely remove <i>generated</i> tag and modify it. * * @generated */ protected NodeFigure createNodeFigure() { NodeFigure figure = createNodePlate(); figure.setLayoutManager(new StackLayout()); IFigure shape = createNodeShape(); figure.add(shape); contentPane = setupContentPane(shape); return figure; } /** * Default implementation treats passed figure as content pane. * Respects layout one may have set for generated figure. * @param nodeShape instance of generated figure class * @generated */ protected IFigure setupContentPane(IFigure nodeShape) { return nodeShape; // use nodeShape itself as contentPane } /** * @generated */ public IFigure getContentPane() { if (contentPane != null) { return contentPane; } return super.getContentPane(); } /** * @generated */ protected void setForegroundColor(Color color) { if (primaryShape != null) { primaryShape.setForegroundColor(color); } } /** * @generated */ protected void setBackgroundColor(Color color) { if (primaryShape != null) { primaryShape.setBackgroundColor(color); } } /** * @generated */ protected void setLineWidth(int width) { if (primaryShape instanceof Shape) { ((Shape) primaryShape).setLineWidth(width); } } /** * @generated */ protected void setLineType(int style) { if (primaryShape instanceof Shape) { ((Shape) primaryShape).setLineStyle(style); } } /** * @generated */ public class ClerkFigure extends RectangleFigure { /** * @generated */ public ClerkFigure() { this.setBackgroundColor(ColorConstants.lightBlue); } } }
CarlAtComputer/tracker
src/java_version/tracker_model/tracker_model.diagram/src/tracker/diagram/edit/parts/ClerkEditPart.java
Java
gpl-2.0
4,561
<?php /** * @package Matukio * @author Yves Hoppe <yves@compojoom.com> * @date 10.11.13 * * @copyright Copyright (C) 2008 - 2013 Yves Hoppe - compojoom.com . All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ defined('_JEXEC') or die('Restricted access'); jimport('joomla.application.component.controller'); /** * Class MatukioControllerRequests * * @since 3.0 */ class MatukioControllerRequests extends JControllerLegacy { /** * Displays the form * * @param bool $cachable - * @param bool $urlparams - * * @return JControllerLegacy|void */ public function display($cachable = false, $urlparams = false) { $document = JFactory::getDocument(); $view = $this->getView('requests', 'raw'); $view->display(); } }
JonatanLiecheski/MeditecJoomla
administrator/components/com_matukio/controllers/requests.php
PHP
gpl-2.0
816
/* * File Name: Helper Js file * File Author: Design Arc * File Description: This is helper javascript file. Used for activating js plugins and Other javascript effects adding. Thanks */ /*------------------------------------- --------- TABLE OF CONTENT ------------ --------------------------------------- 1.bannerSlider 2. galleryMasonaryLayout 3. GalleryFilter 4. fancyboxInit 5. gMap 6. testimonialCarosule 7. SmoothMenuScroll 8. OnePageMenuScroll 9. DeadMenuConfig 10. contactFormValidation 11. videoFancybox 12. sliding gallery 13. hiddenBarMenuConfig 14. customScrollBarHiddenSidebar 15. hiddenBarToggler 16. handlePreloader 17. stickyHeader ---------------------------------------- --------------------------------------*/ "use strict"; var $ = jQuery; // 1.bannerSlider // 2. galleryMasonaryLayout function galleryMasonaryLayout () { if ($('.masonary-gallery').length) { var container = $('.masonary-gallery'); container.on('load', function(){ container.masonry({ itemSelector : '.masonryImage' }); }); } } // 3. GalleryFilter function GalleryFilter () { if ($('.image-gallery').length) { $('.image-gallery').each(function () { var filterSelector = $(this).data('filter-class'); var showItemOnLoad = $(this).data('show-on-load'); if (showItemOnLoad) { $(this).mixItUp({ load: { filter: '.'+showItemOnLoad }, selectors: { filter: '.'+filterSelector } }) }; $(this).mixItUp({ selectors: { filter: '.'+filterSelector } }); }); }; } // 4. fancyboxInit function fancyboxInit () { if ($('a.fancybox').length) { $('a.fancybox').fancybox(); }; } // 6. testimonialCarosule function testimonialCarosule () { if ($('.testimonial-wrap .owl-carousel').length) { $('.testimonial-wrap .owl-carousel').owlCarousel({ loop: true, margin: 0, nav: false, dots: true, items: 1, autoplayHoverPause: true }); } if ($('.testimonial-wrap-style-two .owl-carousel').length) { $('.testimonial-wrap-style-two .owl-carousel').owlCarousel({ loop: true, margin: 0, nav: true, dots: false, items: 1, navText: [ '<i class="fa fa-angle-left"></i>', '<i class="fa fa-angle-right"></i>' ], autoplayHoverPause: true }); } } // 7. SmoothMenuScroll /*function SmoothMenuScroll () { // must install jquery easein plugin var anchor = $('.scrollToLink'); if(anchor.length){ anchor.children('a').bind('click', function (event) { // if ($(window).scrollTop() > 10) { // var headerH = '73'; // }else { // var headerH = '73'; // } var target = $(this); var anchorHeight= target.height(); $('html, body').stop().animate({ scrollTop: $(target.attr('href')).offset().top - anchorHeight + 'px' }, 1200, 'easeInOutExpo'); anchor.removeClass('current'); target.parent().addClass('current'); event.preventDefault(); }); } }*/ // 8. OnePageMenuScroll function OnePageMenuScroll () { var windscroll = $(window).scrollTop(); if (windscroll >= 100) { var menuWrap = $('.navigation.scroll-menu'); // change as your menu wrap menuWrap.find('.scrollToLink a').each(function (){ // grabing section id dynamically var sections = $(this).attr('href'); $(sections).each(function() { // checking is scroll bar are in section if ($(this).offset().top <= windscroll + 100) { // grabing the dynamic id of section var Sectionid = $(sections).attr('id'); // removing current class from others menuWrap.find('li').removeClass('current'); // adding current class to related navigation menuWrap.find('a[href=#'+Sectionid+']').parent().addClass('current'); } }); }); } else { $('.mainmenu.one-page-scroll-menu li.current').removeClass('current'); $('.mainmenu.one-page-scroll-menu li:first').addClass('current'); } } // 9. DeadMenuConfig function DeadMenuConfig () { var menuWrap = $('.navigation.scroll-menu'); // change it as your menu wrapper var deadLink = menuWrap.find('li.deadLink'); if(deadLink.length) { deadLink.each(function () { $(this).children('a').on('click', function() { return false; }); }); } } // 10. contactFormValidation // 11. videoFancybox function videoFancybox () { if ($('.video-fancybox').length) { $('.video-fancybox').on('click', function () { $(this).fancybox({ 'padding' : 0, 'autoScale' : false, 'transitionIn' : 'none', 'transitionOut' : 'none', 'title' : this.title, 'width' : 640, 'height' : 385, 'href' : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'), 'type' : 'swf', 'swf' : { 'wmode' : 'transparent', 'allowfullscreen' : 'true' } }); return false; }) }; } // 12. sliding gallery function slidingGallery () { var galleryWrap = $('.sliding-gallery .image-gallery'); if (galleryWrap.length) { galleryWrap.bxSlider({ minSlides: 1, maxSlides: 4, slideWidth: 480, slideMargin: 0, useCSS: false, ticker: true, autoHover:true, tickerHover:true, speed: 100000, infiniteLoop: true }); }; } // 13. hiddenBarMenuConfig function hiddenBarMenuConfig () { var menuWrap = $('.hidden-bar .main-menu'); // appending expander button menuWrap.find('.dropdown').children('a').append(function () { return '<button type="button" class="btn expander"><i class="fa fa-chevron-down"></i></button>'; }); // hidding submenu menuWrap.find('.dropdown').children('ul').hide(); // toggling child ul menuWrap.find('.btn.expander').each(function () { $(this).on('click', function () { $(this).parent() // return parent of .btn.expander (a) .parent() // return parent of a (li) .children('ul').slideToggle(); // adding class to expander container $(this).parent().toggleClass('current'); // toggling arrow of expander $(this).find('i').toggleClass('fa-chevron-up fa-chevron-down'); return false; }); }); } // 14. customScrollBarHiddenSidebar function customScrollBarHiddenSidebar () { if ($('.hidden-bar-wrapper').length) { $('.hidden-bar-wrapper').mCustomScrollbar(); }; } // 15. hiddenBarToggler function hiddenBarToggler () { if ($('.hidden-bar-closer').length) { $('.hidden-bar-closer').on('click', function () { $('.hidden-bar').css({ 'right': '-150%' }); }); }; if ($('.hidden-bar-opener').length) { $('.hidden-bar-opener').on('click', function () { $('.hidden-bar').css({ 'right': '0%' }); }); }; } // 16. handlePreloader function handlePreloader() { if($('.preloader').length){ $('.preloader').fadeOut(); } } // 17. stickyHeader function stickyHeader () { if ($('.stricky').length) { var strickyScrollPos = $('.stricky').next().offset().top; if($(window).scrollTop() > strickyScrollPos) { $('.stricky').addClass('stricky-fixed'); } else if($(this).scrollTop() <= strickyScrollPos) { $('.stricky').removeClass('stricky-fixed'); } }; } // 18. zebraDatePickerInit function zebraDatePickerInit () { if ($('input.datepicker').length) { $('input.datepicker').Zebra_DatePicker({ default_position: 'below' }); }; } // 19. revolutionSliderActiver function revolutionSliderActiver () { if ($('.slider-banner').length) { var slideHeight = $('.slider-banner').data('height'); var fullScreenAlignForce = $('.slider-banner').data('full-screen-aling-force'); $('.slider-banner').revolution({ delay:5000, startwidth:1170, startheight:slideHeight, startWithSlide:0, fullScreenAlignForce: fullScreenAlignForce, autoHeight:"off", minHeight:"off", shuffle:"off", onHoverStop:"on", thumbWidth:100, thumbHeight:50, thumbAmount:3, hideThumbsOnMobile:"off", hideNavDelayOnMobile:1500, hideBulletsOnMobile:"off", hideArrowsOnMobile:"off", hideThumbsUnderResoluition:0, hideThumbs:0, hideTimerBar:"on", keyboardNavigation:"on", navigationType:"bullet", navigationArrows: "nexttobullets", navigationStyle:"preview4", navigationHAlign:"center", navigationVAlign:"bottom", navigationHOffset:30, navigationVOffset:30, soloArrowLeftHalign:"left", soloArrowLeftValign:"center", soloArrowLeftHOffset:20, soloArrowLeftVOffset:0, soloArrowRightHalign:"right", soloArrowRightValign:"center", soloArrowRightHOffset:20, soloArrowRightVOffset:0, touchenabled:"on", swipe_velocity:"0.7", swipe_max_touches:"1", swipe_min_touches:"1", drag_block_vertical:"false", parallax:"mouse", parallaxBgFreeze:"on", parallaxLevels:[10,7,4,3,2,5,4,3,2,1], parallaxDisableOnMobile:"off", stopAtSlide:-1, stopAfterLoops:-1, hideCaptionAtLimit:0, hideAllCaptionAtLilmit:0, hideSliderAtLimit:0, dottedOverlay:"none", spinned:"spinner4", fullWidth:"on", forceFullWidth:"on", fullScreen:"off", fullScreenOffsetContainer:"#banner", fullScreenOffset:"0px", panZoomDisableOnMobile:"off", simplifyAll:"off", shadow:0 }); } } // 20. galleryModal function galleryModal () { if ($('#single-gallery-modal').length && $('.single-gallery').length) { $('.single-gallery .link-view').children('a').on('click', function () { // grabing elements var parentDiv = $(this).parents('.single-gallery'); var modalContent = parentDiv.find('.modal-content'); var itemTitle = modalContent.find('.item-name').text(); var itemImg = modalContent.find('.item-image').attr('src'); var itemContent = modalContent.find('.item-text').html(); // doing reset $('#single-gallery-modal').find('.item-name').empty(); $('#single-gallery-modal').find('.img-holder img').attr('src', ''); $('#single-gallery-modal').find('.item-text').empty(); // adding content $('#single-gallery-modal').find('.item-name').text(itemTitle); $('#single-gallery-modal').find('.img-holder img').attr('src', itemImg); $('#single-gallery-modal').find('.item-text').append(itemContent); $('#single-gallery-modal').modal('show'); return false; }); }; } // instance of fuction while Document ready event jQuery(document).on('ready', function () { (function ($) { //bannerSlider(); galleryMasonaryLayout(); GalleryFilter(); fancyboxInit(); testimonialCarosule(); DeadMenuConfig(); videoFancybox(); slidingGallery(); hiddenBarMenuConfig(); hiddenBarToggler(); zebraDatePickerInit(); revolutionSliderActiver(); galleryModal(); $('.onepage_menu > ul > li:first-child').addClass('current'); $('.onepage_menu > ul').onePageNav(); })(jQuery); }); // instance of fuction while Window Load event jQuery(window).on('load', function () { (function ($) { //SmoothMenuScroll(); customScrollBarHiddenSidebar(); handlePreloader(); })(jQuery); }); // instance of fuction while Window Scroll event jQuery(window).on('scroll', function () { (function ($) { OnePageMenuScroll(); stickyHeader(); })(jQuery); });
indexcosmos/renzi
wp-content/themes/apartvilla/js/custom.js
JavaScript
gpl-2.0
11,100
# Routines for handling fasta sequences and tab sep files # std packages import sys, textwrap, operator, types, doctest,logging, gzip, struct, cPickle, gc, itertools, math from collections import defaultdict from types import * from os.path import basename, splitext # external packages try: import namedtuple except: pass try: import dist, math except: pass # --- CONVENIENCE --- def openFile(fname, mode="r"): """ opens file, recognizing stdout and stdin and none""" if hasattr(fname, "read") or hasattr(fname, "write"): return fname elif fname.endswith(".gz"): fh = gzip.open(fname, mode) elif fname=="stdout": fh = sys.stdout elif fname=="stdin": fh = sys.stdin elif fname==None or fname.lower()=="none": fh = None else: fh = open(fname, mode) return fh def flattenValues(dict): """ return all values in dictionary (key -> list) as one long flat list """ list = [] for value in dict.values(): list.extend(value) return list def writeToTsv(fileObj, rec): """ writes a namedtuple to a file as a tab-sep line """ if rec: rec = [x.encode("utf-8") for x in rec] string = "\t".join(rec) fileObj.write(string+"\n") # --- FASTA FILES --- def parseFastaAsDict(fname, inDict=None): if inDict==None: inDict = {} logging.info("Parsing %s" % fname) fr = FastaReader(fname) for (id, seq) in fr.parse(): if id in inDict: print inDict print inDict[id] raise Exception("%s already seen before" % id) inDict[id]=seq return inDict def parseFasta(fname): fr = FastaReader(fname) for (id, seq) in fr.parse(): yield id, seq class FastaReader: """ a class to parse a fasta file Example: fr = maxbio.FastaReader(filename) for (id, seq) in fr.parse(): print id,seq """ def __init__(self, fname): if hasattr(fname, 'read'): self.f = fname elif fname=="stdin": self.f=sys.stdin elif fname.endswith(".gz"): self.f=gzip.open(fname) else: self.f=open(fname) self.lastId=None def parse(self): """ Generator: returns sequences as tuple (id, sequence) """ lines = [] for line in self.f: if line.startswith("\n") or line.startswith("#"): continue elif not line.startswith(">"): lines.append(line.replace(" ","").strip()) continue else: if len(lines)!=0: # on first >, seq is empty faseq = (self.lastId, "".join(lines)) self.lastId=line.strip(">").strip() lines = [] yield faseq else: if self.lastId!=None: sys.stderr.write("warning: when reading fasta file: empty sequence, id: %s\n" % line) self.lastId=line.strip(">").strip() lines=[] # if it's the last sequence in a file, loop will end on the last line if len(lines)!=0: faseq = (self.lastId, "".join(lines)) yield faseq else: yield (None, None) def outputFasta(id, seq, fh=sys.stdout, width=80): """ output fasta seq to file object, break to 80 char width """ fh.write(">"+id+"\n") #fh.write("\n".join(textwrap.wrap(seq, width=width))) if len(seq)>width: last = 0 for l in range(width,len(seq),width): fh.write(seq[last:l]) fh.write("\n") last = l fh.write(seq[last:len(seq)]) else: fh.write(seq) fh.write("\n") def outputFastaFile(id, seq, fname, width=80): """ output fasta seq to fname and close file, break to 80 char width """ fh = openFile(fname) outputFasta(id, seq, fh, width=80) fh.close() ### functions for handling lists of tuples def _makeGetter(var): """ returns the right getter, depending on the type of var """ if type(var)==types.StringType: getter = operator.attrgetter(var) # to get elements from records with named fields else: getter = operator.itemgetter(var) # to get elements from lists return getter def sortList(list, field, reverse=True, key=None): """ sort list of tuples by a given field """ if not key: key = _makeGetter(field) list.sort(key=key, reverse=reverse) return list def bestIdentifiers(scoredList): """ given a list of tuples with a numeric last field and an id field, return the id fields with the highest last field. >>> bestIdentifiers ([("clinton", 1), ("obama", 3), ("washington", 10), ("lincoln", 10)]) ['washington', 'lincoln'] """ scoredList.sort(key=operator.itemgetter(-1), reverse=True) bestScore = scoredList[0][-1] bestElements = [e[0] for e in scoredList if e[-1] >= bestScore] return bestElements def bestScoreElements(list, scoreField): """ return only those tuples in a list that contain a score >= the best score in the list >>> import namedtuple >>> tuple = namedtuple.namedtuple("test", "f1, f2") >>> tuples = [tuple(1, 6), tuple(4, 7), tuple(2, 7)] >>> print bestScoreElements(tuples, scoreField="f2") [test(f1=4, f2=7), test(f1=2, f2=7)] """ scoreGetter = _makeGetter(scoreField) sortList(list, scoreField, reverse=True, key=scoreGetter) bestScore = scoreGetter(list[0]) bestElements = [e for e in list if scoreGetter(e) >= bestScore] return bestElements def indexByField(list, field): """ index by a given field: convert list of tuples to dict of tuples """ map = {} indexGetter = _makeGetter(field) for tuple in list: map.setdefault(indexGetter(tuple), []).append(tuple) return map def bestTuples(list, idField, scoreField): """ Index a list of a key-value-tuples, keep only the best tuples per value and return their keys. >>> import namedtuple >>> tuple = namedtuple.namedtuple("test", "f1, f2") >>> tuples = [tuple(1, 6), tuple(1, 3), tuple(2, 7), tuple(2,1000)] >>> print bestTuples(tuples, idField="f1", scoreField="f2") [test(f1=1, f2=6), test(f1=2, f2=1000)] """ map = indexByField(list, idField) filteredList = [] for id, idList in map.iteritems(): bestElements = bestScoreElements(idList, scoreField) filteredList.extend(bestElements) return filteredList def removeBigSets(predDict, limit): """ given a dict with string -> set , remove elements where len(set) >= than limit """ result = {} for key, predSet in predDict: if len(predSet)<limit: result[key] = predSet return result # return types for benchmark() BenchmarkResult = namedtuple.namedtuple("BenchResultRec", "TP, FN, FP, Prec, Recall, F, errList, objCount") ErrorDetails = namedtuple.namedtuple("ErrorDetails", "id, expected, predicted") def benchmark(predDict, refDict): """ returns a class with attributes for TP, FN, FP and various other counts and information about prediction errors >>> benchmark({"a" : set([1,2,3]), "b" : set([3,4,5])}, {"a":set([1]), "b":set([4])}) BenchResultRec(TP=2, FN=0, FP=4, Prec=0.3333333333333333, Recall=1.0, F=0.5, errList=[ErrorDetails(id='a', expected=set([1]), predicted=set([1, 2, 3])), ErrorDetails(id='b', expected=set([4]), predicted=set([3, 4, 5]))], objCount=2) """ OBJECTNAME="documents" TP, FN, FP = 0, 0, 0 objCount = 0 atLeastOneHit = 0 errDetails = [] completeMatch = 0 completeMismatch = 0 tooManyPred = 0 notEnoughPred = 0 limitPassed = 0 predCount = 0 # iterate over objects and update counters for obj, predSet in predDict.iteritems(): if obj not in refDict: logging.debug("%s not in reference, skipping" % obj) continue refSet = refDict[obj] objCount+=1 perfectMatch=False partialMatch=False predCount += len(predSet) tpSet = predSet.intersection(refSet) # true positives: are in pred and in reference fnSet = refSet.difference(predSet) # false negatives: are in reference but not in prediction fpSet = predSet.difference(refSet) # false positives: are in prediction but not in refernce TP += len (tpSet) FN += len (fnSet) FP += len (fpSet) if len(tpSet)>0: atLeastOneHit+=1 partialMatch=True if len(tpSet)==len(predSet)==len(refSet): completeMatch+=1 perfectMatch=True # set flag to avoid checking several times below if len(tpSet)==0: completeMismatch+=1 if len(predSet)>len(refSet): tooManyPred+=1 if len(predSet)<len(refSet): notEnoughPred+=1 if not perfectMatch: errDetails.append(ErrorDetails(id=obj, expected=refSet, predicted=predSet)) if objCount==0: logging.debug("number of %s in common between prediction and reference is zero" % OBJECTNAME) return None if TP+FP > 0: Prec = float(TP) / (TP + FP) else: print "Warning: Cannot calculate Prec because TP+FP = 0" Prec = 0 if TP+FN > 0: Recall = float(TP) / (TP + FN) else: print "Warning: Cannot calculate Recall because TP+FN = 0" Recall = 0 if Recall>0 and Prec>0: F = 2 * (Prec * Recall) / (Prec + Recall) else: print "Warning: Cannot calculate F because Recall and Prec = 0" F = 0 return BenchmarkResult(TP=TP, FN=FN, FP=FP, Prec=Prec, Recall=Recall, F=F, errList=errDetails, objCount=objCount) def allToString(list): """ converts all members to a list to strings. numbers -> string, lists/sets -> comma-sep strings """ newList = [] s = set() for e in list: if type(e)==types.ListType or type(e)==type(s): newList.append(",".join(e)) else: newList.append(str(e)) return newList def prettyPrintDict(dict): """ print dict to stdout """ for key, value in dict.iteritems(): print key, value def calcBinomScore(background, foreground, genes, backgroundProb): TP = len(genes.intersection(foreground)) binomProb = dist.pbinom(TP, len(genes), backgroundProb) binomScore = -math.log10(binomProb) return binomScore def packCoord(start, end): " pack start, end into 8 bytes " return struct.pack("<ll", int(start), int(end)) def unpackCoord(start, end): " undo packCoord " start, end = struct.unpack("<ll", arr) return start, end def packChromCoord(chrom, start, end): """ pack chrom,start,end into 9 little-endian bytes, return a byte string >>> s = packChromCoord("chr21", 1233,123232299) >>> unpackChromCoord(s) ('chr21', 1233, 123232299) >>> unpackChromCoord(packChromCoord("chrM", 1233,123232299)) ('chrM', 1233, 123232299) >>> packChromCoord("chr6_hap", 1,2) >>> len(packChromCoord("chr6", 1,2)) 9 """ if "_gl" in chrom or "hap" in chrom: return None chrom = chrom.replace("chr", "") if chrom in ["M","X","Y"]: chromInt = ord(chrom) else: chromInt = int(chrom) return struct.pack("<bll", chromInt, int(start), int(end)) def unpackChromCoord(arr): " undo packCoord " chrom, start, end = struct.unpack("<bll", arr) if(chrom)>22: chrom = "chr"+chr(chrom) else: chrom = "chr"+str(chrom) return chrom, start, end, def revComp(seq): table = { "a":"t", "A":"T", "t" :"a", "T":"A", "c":"g", "C":"G", "g":"c", "G":"C", "N":"N", "n":"n", "Y":"R", "R" : "Y", "M" : "K", "K" : "M", "W":"W", "S":"S", "H":"D", "B":"V", "V":"B", "D":"H", "y":"r", "r":"y","m":"k", "k":"m","w":"w","s":"s","h":"d","b":"v","d":"h","v":"b","y":"r","r":"y" } newseq = [] for nucl in reversed(seq): newseq += table[nucl] return "".join(newseq) # ----- if __name__ == "__main__": import doctest doctest.testmod()
maximilianh/maxtools
lib/maxbio.py
Python
gpl-2.0
12,239
using System; using System.Collections.Generic; using System.IO; namespace MediaPoint.Subtitles.Logic { public class SubtitleSequence { public long StartMilliseconds { get; set; } public long EndMilliseconds { get; set; } public byte[] BinaryData { get; set; } public SubtitleSequence(byte[] data, long startMilliseconds, long endMilliseconds) { BinaryData = data; StartMilliseconds = startMilliseconds; EndMilliseconds = endMilliseconds; } public string Text { get { if (BinaryData != null) return System.Text.Encoding.UTF8.GetString(BinaryData).Replace("\\N", Environment.NewLine); return string.Empty; } } } public class MatroskaSubtitleInfo { public long TrackNumber { get; set; } public string Name { get; set; } public string Language { get; set; } public string CodecId { get; set; } public string CodecPrivate { get; set; } public int ContentCompressionAlgorithm { get; set; } public int ContentEncodingType { get; set; } } public class Matroska { public delegate void LoadMatroskaCallback(long position, long total); [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Explicit, Pack = 2)] private struct ByteLayout16 { [System.Runtime.InteropServices.FieldOffset(0)] public byte B1; [System.Runtime.InteropServices.FieldOffset(1)] public byte B2; [System.Runtime.InteropServices.FieldOffset(0)] public Int16 IntData16; //16-bit signed int } [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Explicit, Pack = 2)] private struct FloatLayout32 { [System.Runtime.InteropServices.FieldOffset(0)] public byte B1; [System.Runtime.InteropServices.FieldOffset(1)] public byte B2; [System.Runtime.InteropServices.FieldOffset(2)] public byte B3; [System.Runtime.InteropServices.FieldOffset(3)] public byte B4; [System.Runtime.InteropServices.FieldOffset(0)] public Single FloatData32; //32-bit [System.Runtime.InteropServices.FieldOffset(0)] public UInt32 UintData32; //32-bit } [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Explicit, Pack = 2)] private struct FloatLayout64 { [System.Runtime.InteropServices.FieldOffset(0)] public byte B1; [System.Runtime.InteropServices.FieldOffset(1)] public byte B2; [System.Runtime.InteropServices.FieldOffset(2)] public byte B3; [System.Runtime.InteropServices.FieldOffset(3)] public byte B4; [System.Runtime.InteropServices.FieldOffset(4)] public byte B5; [System.Runtime.InteropServices.FieldOffset(5)] public byte B6; [System.Runtime.InteropServices.FieldOffset(6)] public byte B7; [System.Runtime.InteropServices.FieldOffset(7)] public byte B8; [System.Runtime.InteropServices.FieldOffset(0)] public Double FloatData64; //64-bit } FileStream f; int _pixelWidth, _pixelHeight; double _frameRate; string _videoCodecId; double _durationInMilliseconds; List<MatroskaSubtitleInfo> _subtitleList; int _subtitleRipTrackNumber = 0; List<SubtitleSequence> _subtitleRip = new List<SubtitleSequence>(); //Subtitle _subtitleRip = new Subtitle(); private static int GetMatroskaVariableIntLength(byte b) { byte result = 0; int a = 255; // 11111111 a = a | b; if (a == 255) result = 1; a = 127; // 01111111 a = a | b; if (a == 127) result = 2; a = 63; // 00111111 a = a | b; if (a == 63) result = 3; a = 31; // 00011111 a = a | b; if (a == 31) result = 4; a = 15; // 00001111 a = a | b; if (a == 15) result = 5; a = 7; // 00000111 a = a | b; if (a == 7) result = 6; a = 3; // 00000011 a = a | b; if (a == 3) result = 7; a = 1; // 00000001 a = a | b; if (a == 1) result = 8; return result; } private UInt32 GetUInt32(byte firstByte) { var floatLayout = new FloatLayout32(); floatLayout.B4 = firstByte; floatLayout.B3 = (byte)f.ReadByte(); floatLayout.B2 = (byte)f.ReadByte(); floatLayout.B1 = (byte)f.ReadByte(); return floatLayout.UintData32; } private UInt32 GetMatroskaId() { byte b = (byte)f.ReadByte(); if (b == 0xEC || // Void b == 0xBF) // CRC-32 return b; UInt32 x = GetUInt32(b); if (x == 0x1A45DFA3 || // ebml header x == 0x18538067 || // segment x == 0x114D9B74 || // seekhead x == 0x1549A966 || // segment info x == 0x1654AE6B || // track x == 0x1F43B675 || // cluster x == 0x1C53BB6B || // Cues x == 0x1941A469 || // Attachments x == 0x1043A770 || // Chapters x == 0x1254C367) // Tags return x; return 0; } private long GetMatroskaDataSize(long sizeOfSize, byte firstByte) { byte b4, b5, b6, b7, b8; long result = 0; if (sizeOfSize == 8) { long i = (long)f.ReadByte() << 48; i += (long)f.ReadByte() << 40; i += (long)f.ReadByte() << 32; i += (long)f.ReadByte() << 24; i += (long)f.ReadByte() << 16; i += (long)f.ReadByte() << 8; i += f.ReadByte(); return i; } else if (sizeOfSize == 7) { long i = firstByte << 48; i += (long)f.ReadByte() << 40; i += (long)f.ReadByte() << 32; i += (long)f.ReadByte() << 24; i += (long)f.ReadByte() << 16; i += (long)f.ReadByte() << 8; i += f.ReadByte(); return i; } else if (sizeOfSize == 6) { firstByte = (byte)(firstByte & 3); // 00000011 b4 = (byte)f.ReadByte(); b5 = (byte)f.ReadByte(); b6 = (byte)f.ReadByte(); b7 = (byte)f.ReadByte(); b8 = (byte)f.ReadByte(); result = b8 + (b7 * 256) + (b6 * 65536) + (b5 * 16777216) + (b4 * 4294967296) + (firstByte * 1099511627776); } else if (sizeOfSize == 5) { firstByte = (byte)(firstByte & 7); // 00000111 b5 = (byte)f.ReadByte(); b6 = (byte)f.ReadByte(); b7 = (byte)f.ReadByte(); b8 = (byte)f.ReadByte(); result = b8 + (b7 * 256) + (b6 * 65536) + (b5 * 16777216) + (firstByte * 4294967296); } else if (sizeOfSize == 4) { firstByte = (byte)(firstByte & 15); // 00001111 b6 = (byte)f.ReadByte(); b7 = (byte)f.ReadByte(); b8 = (byte)f.ReadByte(); return(long)( b8 + (b7 << 8) + (b6 << 16) + (firstByte << 24)); } else if (sizeOfSize == 3) { firstByte = (byte)(firstByte & 31); // 00011111 b7 = (byte)f.ReadByte(); b8 = (byte)f.ReadByte(); return (long) (b8 + (b7 << 8) + (firstByte << 16)); } else if (sizeOfSize == 2) { firstByte = (byte)(firstByte & 63); // 00111111 b8 = (byte)f.ReadByte(); return b8 + (firstByte << 8); } else if (sizeOfSize == 1) { return firstByte & 127; //01111111 } return result; } private long GetMatroskaVariableSizeUnsignedInt(long sizeOfSize) { byte firstByte = (byte)f.ReadByte(); byte b3, b4, b5, b6, b7, b8; long result = 0; if (sizeOfSize >= 8) { throw new NotImplementedException(); } else if (sizeOfSize == 7) { b3 = (byte)f.ReadByte(); b4 = (byte)f.ReadByte(); b5 = (byte)f.ReadByte(); b6 = (byte)f.ReadByte(); b7 = (byte)f.ReadByte(); b8 = (byte)f.ReadByte(); result = b8 + (b7 * 256) + (b6 * 65536) + (b5 * 16777216) + (b4 * 4294967296) + (b3 * 1099511627776) + (firstByte * 281474976710656); } else if (sizeOfSize == 6) { b4 = (byte)f.ReadByte(); b5 = (byte)f.ReadByte(); b6 = (byte)f.ReadByte(); b7 = (byte)f.ReadByte(); b8 = (byte)f.ReadByte(); result = b8 + (b7 * 256) + (b6 * 65536) + (b5 * 16777216) + (b4 * 4294967296) + (firstByte * 1099511627776); } else if (sizeOfSize == 5) { b5 = (byte)f.ReadByte(); b6 = (byte)f.ReadByte(); b7 = (byte)f.ReadByte(); b8 = (byte)f.ReadByte(); result = b8 + (b7 * 256) + (b6 * 65536) + (b5 * 16777216) + (firstByte * 4294967296); } else if (sizeOfSize == 4) { b6 = (byte)f.ReadByte(); b7 = (byte)f.ReadByte(); b8 = (byte)f.ReadByte(); result = b8 + (b7 * 256) + (b6 * 65536) + (firstByte * 16777216); } else if (sizeOfSize == 3) { b7 = (byte)f.ReadByte(); b8 = (byte)f.ReadByte(); result = b8 + (b7 * 256) + (firstByte * 65536); } else if (sizeOfSize == 2) { b8 = (byte)f.ReadByte(); result = b8 + (firstByte * 256); } else if (sizeOfSize == 1) { result = firstByte; } return result; } private UInt32 GetMatroskaTracksId() { byte b = (byte)f.ReadByte(); if (b == 0xEC || // Void b == 0xBF || // CRC-32 b == 0xAE) // TrackEntry return b; return 0; } private UInt32 GetMatroskaTrackEntryId() { UInt32 s = (UInt32)f.ReadByte(); if (s == 0xEC || // Void s == 0xBF || // CRC-32 s == 0xD7 || // Track number s == 0x83 || // Track type s == 0xB9 || // Flag enabled s == 0x88 || // Flag default s == 0x9C || // Flag lacing s == 0x4F || // Track Time Code Scale s == 0xAA || // CodecDecodeAll s == 0xE0 || // Track Video s == 0xE1 || // Track Audio s == 0x86) // Codec Id { return s; } s = s * 256 + (byte)f.ReadByte(); if (s == 0x73C5 || // TrackUID s == 0x55AA || // FlagForced s == 0x6DE7 || // MinCache s == 0x6DF8 || // MaxCache s == 0x55EE || // MaxBlockAdditionID s == 0x63A2 || // CodecPrivate s == 0x7446 || // AttachmentLink s == 0x6D80 || // ContentEncodings s == 0x537F || // TrackOffset s == 0x6FAB || // TrackOverlay s == 0x536E || // Name s == 0x6624 || // TrackTranslate s == 0x66FC || // TrackTranslateEditionUID s == 0x66BF || // TrackTranslateCodec s == 0x66A5) // TrackTranslateTrackID { return s; } s = s * 256 + (byte)f.ReadByte(); if (s == 0x23E383 || // Default Duration s == 0x22B59C || // Language s == 0x258688 || // CodecName s == 0x23314F) // TrackTimeCodeScale return s; return 0; } private UInt32 GetMatroskaTrackVideoId() { UInt32 s = (byte)f.ReadByte(); if (s == 0xEC || // Void s == 0xBF || // CRC-32 s == 0xB0 || // PixelWidth s == 0xBA || // PixelHeight s == 0x9A) // FlagInterlaced { return s; } s = s * 256 + (byte)f.ReadByte(); if (s == 0x54B0 || // DisplayWidth s == 0x54BA || // DisplayHeight s == 0x54BA || // DisplayHeight s == 0x54AA || // PixelCropButton s == 0x54BB || // PixelCropTop s == 0x54CC || // PixelCropLeft s == 0x54DD || // PixelCropRight s == 0x54DD || // PixelCropRight s == 0x54B2 || // DisplayUnit s == 0x54B3) // AspectRatioType return s; s = s * 256 + (byte)f.ReadByte(); if (s == 0x2EB524)// ColourSpace return s; return 0; } private UInt32 GetMatroskaSegmentId() { byte b = (byte)f.ReadByte(); if (b == 0xEC)// Void return b; if (b == 0xBF)// CRC-32 return b; UInt32 s = (UInt32)b * 256 + (byte)f.ReadByte(); if (s == 0x73A4 || // SegmentUID s == 0x7384 || // SegmentFilename s == 0x4444 || // SegmentFamily s == 0x6924 || // ChapterTranslate s == 0x69FC || // ChapterTranslateEditionUID s == 0x69BF || // ChapterTranslateCodec s == 0x69A5 || // ChapterTranslateID s == 0x4489 || // Duration s == 0x4461 || // DateUTC s == 0x7BA9 || // Title s == 0x4D80 || // MuxingApp s == 0x5741) // WritingApp { return s; } s = (UInt32)b * 256 + (byte)f.ReadByte(); if (s == 0x3CB923 || // PrevUID s == 0x3C83AB || // PrevFilename s == 0x3EB923 || // NextUID s == 0x3E83BB || // NextFilename s == 0x2AD7B1) // TimecodeScale return s; return 0; } private void AnalyzeMatroskaTrackVideo(long endPosition) { byte b; bool done = false; UInt32 matroskaId; int sizeOfSize; long dataSize; long afterPosition; while (f.Position < endPosition && done == false) { matroskaId = GetMatroskaTrackVideoId(); if (matroskaId == 0) done = true; else { b = (byte)f.ReadByte(); sizeOfSize = GetMatroskaVariableIntLength(b); dataSize = GetMatroskaDataSize(sizeOfSize, b); if (matroskaId == 0xB0) //// PixelWidth { afterPosition = f.Position + dataSize; b = (byte)f.ReadByte(); dataSize = GetMatroskaDataSize(dataSize, b); _pixelWidth = (int)dataSize; f.Seek(afterPosition, SeekOrigin.Begin); } else if (matroskaId == 0xBA) // // PixelHeight { afterPosition = f.Position + dataSize; b = (byte)f.ReadByte(); dataSize = GetMatroskaDataSize(dataSize, b); _pixelHeight = (int)dataSize; f.Seek(afterPosition, SeekOrigin.Begin); } else f.Seek(dataSize, SeekOrigin.Current); } } } private string GetMatroskaString(long size) { try { byte[] buffer = new byte[size]; f.Read(buffer, 0, (int)size); return System.Text.Encoding.UTF8.GetString(buffer); } catch { return string.Empty; } } private void AnalyzeMatroskaTrackEntry() { byte b; bool done = false; UInt32 matroskaId; int sizeOfSize; long dataSize; long defaultDuration = 0; long afterPosition; bool isVideo = false; bool isSubtitle = false; long trackNumber = 0; string name = string.Empty; string language = string.Empty; string codecId = string.Empty; string codecPrivate = string.Empty; string biCompression = string.Empty; int contentCompressionAlgorithm = -1; int contentEncodingType = -1; while (f.Position < f.Length && done == false) { matroskaId = GetMatroskaTrackEntryId(); if (matroskaId == 0) done = true; else { b = (byte)f.ReadByte(); sizeOfSize = GetMatroskaVariableIntLength(b); dataSize = GetMatroskaDataSize(sizeOfSize, b); if (matroskaId == 0x23E383)// Default Duration { afterPosition = f.Position + dataSize; b = (byte)f.ReadByte(); defaultDuration = GetMatroskaDataSize(dataSize, b); f.Seek(afterPosition, SeekOrigin.Begin); } else if (matroskaId == 0xE0)// Track Video { afterPosition = f.Position + dataSize; AnalyzeMatroskaTrackVideo(afterPosition); f.Seek(afterPosition, SeekOrigin.Begin); isVideo = true; } else if (matroskaId == 0xD7) // Track number { afterPosition = f.Position + dataSize; if (dataSize == 1) { trackNumber = (byte)f.ReadByte(); } f.Seek(afterPosition, SeekOrigin.Begin); } else if (matroskaId == 0x536E) // Name { afterPosition = f.Position + dataSize; name = GetMatroskaString(dataSize); f.Seek(afterPosition, SeekOrigin.Begin); } else if (matroskaId == 0x22B59C) // Language { afterPosition = f.Position + dataSize; language = GetMatroskaString(dataSize); f.Seek(afterPosition, SeekOrigin.Begin); } else if (matroskaId == 0x86) // CodecId { afterPosition = f.Position + dataSize; codecId = GetMatroskaString(dataSize); f.Seek(afterPosition, SeekOrigin.Begin); } else if (matroskaId == 0x83) // Track type { afterPosition = f.Position + dataSize; if (dataSize == 1) { byte trackType = (byte)f.ReadByte(); if (trackType == 0x11) // subtitle isSubtitle = true; } f.Seek(afterPosition, SeekOrigin.Begin); } else if (matroskaId == 0x63A2) // CodecPrivate { afterPosition = f.Position + dataSize; codecPrivate = GetMatroskaString(dataSize); if (codecPrivate.Length > 20) biCompression = codecPrivate.Substring(16, 4); f.Seek(afterPosition, SeekOrigin.Begin); } else if (matroskaId == 0x6D80) // ContentEncodings { afterPosition = f.Position + dataSize; contentCompressionAlgorithm = 0; // default value contentEncodingType = 0; // default value int contentEncoding1 = f.ReadByte(); int contentEncoding2 = f.ReadByte(); if (contentEncoding1 == 0x62 && contentEncoding2 == 0x40) { AnalyzeMatroskaContentEncoding(afterPosition, ref contentCompressionAlgorithm, ref contentEncodingType); } f.Seek(afterPosition, SeekOrigin.Begin); } else f.Seek(dataSize, SeekOrigin.Current); } } if (isVideo) { if (defaultDuration > 0) _frameRate = 1.0 / (defaultDuration / 1000000000.0); _videoCodecId = codecId + " " + biCompression.Trim(); } else if (isSubtitle) { _subtitleList.Add(new MatroskaSubtitleInfo { Name = name, TrackNumber = trackNumber, CodecId = codecId, Language = language, CodecPrivate = codecPrivate, ContentEncodingType = contentEncodingType, ContentCompressionAlgorithm = contentCompressionAlgorithm } ); } } private void AnalyzeMatroskaContentEncoding(long endPosition, ref int contentCompressionAlgorithm, ref int contentEncodingType) { bool done = false; while (f.Position < endPosition && done == false) { int ebmlId = f.ReadByte() * 256 + f.ReadByte(); if (ebmlId == 0) done = true; else { if (ebmlId == 0x5031)// ContentEncodingOrder { int contentEncodingOrder = f.ReadByte() * 256 + f.ReadByte(); System.Diagnostics.Debug.WriteLine("ContentEncodingOrder: " + contentEncodingOrder.ToString()); } else if (ebmlId == 0x5032)// ContentEncodingScope { int contentEncodingScope = f.ReadByte() * 256 + f.ReadByte(); System.Diagnostics.Debug.WriteLine("ContentEncodingScope: " + contentEncodingScope.ToString()); } else if (ebmlId == 0x5033)// ContentEncodingType { contentEncodingType = f.ReadByte() * 256 + f.ReadByte(); } else if (ebmlId == 0x5034)// ContentCompression { byte b = (byte)f.ReadByte(); long sizeOfSize = GetMatroskaVariableIntLength(b); long dataSize = GetMatroskaDataSize(sizeOfSize, b); long afterPosition = f.Position + dataSize; while (f.Position < afterPosition) { int contentCompressionId = f.ReadByte() * 256 + f.ReadByte(); if (contentCompressionId == 0x4254) { contentCompressionAlgorithm = f.ReadByte() * 256 + f.ReadByte(); } else if (contentCompressionId == 0x4255) { int contentCompSettings = f.ReadByte() * 256 + f.ReadByte(); System.Diagnostics.Debug.WriteLine("contentCompSettings: " + contentCompSettings.ToString()); } } f.Seek(afterPosition, SeekOrigin.Begin); } } } } private void AnalyzeMatroskaSegmentInformation(long endPosition) { byte b; bool done = false; UInt32 matroskaId; int sizeOfSize; long dataSize; long afterPosition; long timeCodeScale = 0; double duration8b = 0; while (f.Position < endPosition && done == false) { matroskaId = GetMatroskaSegmentId(); if (matroskaId == 0) done = true; else { b = (byte)f.ReadByte(); sizeOfSize = GetMatroskaVariableIntLength(b); dataSize = GetMatroskaDataSize(sizeOfSize, b); if (matroskaId == 0x2AD7B1)// TimecodeScale - u-integer Timecode scale in nanoseconds (1.000.000 means all timecodes in the segment are expressed in milliseconds). { afterPosition = f.Position + dataSize; b = (byte)f.ReadByte(); timeCodeScale = GetMatroskaDataSize(dataSize, b); f.Seek(afterPosition, SeekOrigin.Begin); } else if (matroskaId == 0x4489)// Duration (float) { afterPosition = f.Position + dataSize; if (dataSize == 4) { duration8b = GetFloat32(); } else { duration8b = GetFloat64(); } f.Seek(afterPosition, SeekOrigin.Begin); } else f.Seek(dataSize, SeekOrigin.Current); } } if (timeCodeScale > 0 && duration8b > 0) _durationInMilliseconds = duration8b / timeCodeScale * 1000000.0; else if (duration8b > 0) _durationInMilliseconds = duration8b; } private double GetFloat32() { FloatLayout32 floatLayout = new FloatLayout32(); // reverse byte ordering floatLayout.B4 = (byte)f.ReadByte(); floatLayout.B3 = (byte)f.ReadByte(); floatLayout.B2 = (byte)f.ReadByte(); floatLayout.B1 = (byte)f.ReadByte(); return floatLayout.FloatData32; } private double GetFloat64() { FloatLayout64 floatLayout = new FloatLayout64(); // reverse byte ordering floatLayout.B8 = (byte)f.ReadByte(); floatLayout.B7 = (byte)f.ReadByte(); floatLayout.B6 = (byte)f.ReadByte(); floatLayout.B5 = (byte)f.ReadByte(); floatLayout.B4 = (byte)f.ReadByte(); floatLayout.B3 = (byte)f.ReadByte(); floatLayout.B2 = (byte)f.ReadByte(); floatLayout.B1 = (byte)f.ReadByte(); return floatLayout.FloatData64; } private void AnalyzeMatroskaTracks() { byte b; bool done = false; UInt32 matroskaId; int sizeOfSize; long dataSize; long afterPosition; _subtitleList = new List<MatroskaSubtitleInfo>(); while (f.Position < f.Length && done == false) { matroskaId = GetMatroskaTracksId(); if (matroskaId == 0) done = true; else { b = (byte)f.ReadByte(); sizeOfSize = GetMatroskaVariableIntLength(b); dataSize = GetMatroskaDataSize(sizeOfSize, b); if (matroskaId == 0xAE) { afterPosition = f.Position + dataSize; AnalyzeMatroskaTrackEntry(); f.Seek(afterPosition, SeekOrigin.Begin); } else f.Seek(dataSize, SeekOrigin.Current); } } } public void GetMatroskaInfo(string fileName, ref bool isValid, ref bool hasConstantFrameRate, ref double frameRate, ref int pixelWidth, ref int pixelHeight, ref double millisecsDuration, ref string videoCodec) { byte b; bool done; UInt32 matroskaId; int sizeOfSize; long dataSize; long afterPosition; bool endOfFile; _durationInMilliseconds = 0; f = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); matroskaId = GetMatroskaId(); if (matroskaId != 0x1A45DFA3) // matroska file must start with ebml header { isValid = false; } else { isValid = true; b = (byte)f.ReadByte(); sizeOfSize = GetMatroskaVariableIntLength(b); dataSize = GetMatroskaDataSize(sizeOfSize, b); f.Seek(dataSize, SeekOrigin.Current); done = false; endOfFile = false; while (endOfFile == false && done == false) { matroskaId = GetMatroskaId(); if (matroskaId == 0) { done = true; } else { b = (byte)f.ReadByte(); sizeOfSize = GetMatroskaVariableIntLength(b); dataSize = GetMatroskaDataSize(sizeOfSize, b); if (matroskaId == 0x1549A966) // segment info { afterPosition = f.Position + dataSize; AnalyzeMatroskaSegmentInformation(afterPosition); f.Seek(afterPosition, SeekOrigin.Begin); } else if (matroskaId == 0x1654AE6B) // tracks { afterPosition = f.Position + dataSize; AnalyzeMatroskaTracks(); f.Seek(afterPosition, SeekOrigin.Begin); done = true; } else if (matroskaId == 0x1F43B675) // cluster { afterPosition = f.Position + dataSize; //if (f.Position > 8000000) // System.Windows.Forms.MessageBox.Show("8mb"); AnalyzeMatroskaCluster(); f.Seek(afterPosition, SeekOrigin.Begin); } else if (matroskaId != 0x18538067) // segment { f.Seek(dataSize, SeekOrigin.Current); } } endOfFile = f.Position >= f.Length; } } f.Close(); f.Dispose(); f = null; pixelWidth = _pixelWidth; pixelHeight = _pixelHeight; frameRate = _frameRate; hasConstantFrameRate = _frameRate > 0; millisecsDuration = _durationInMilliseconds; videoCodec = _videoCodecId; } private UInt32 GetMatroskaClusterId() { UInt32 s = (byte)f.ReadByte(); if (s == 0xE7 || // TimeCode s == 0xA7 || // Position s == 0xAB || // PrevSize s == 0xA0 || // BlockGroup s == 0xA1 || // Block s == 0xA2 || // BlockVirtual s == 0xA6 || // BlockMore s == 0xEE || // BlockAddID s == 0xA5 || // BlockAdditional s == 0x9B || // BlockDuration s == 0xFA || // ReferencePriority s == 0xFB || // ReferenceBlock s == 0xFD || // ReferenceVirtual s == 0xA4 || // CodecState s == 0x8E || // Slices s == 0x8E || // TimeSlice s == 0xCC || // LaceNumber s == 0xCD || // FrameNumber s == 0xCB || // BlockAdditionID s == 0xCE || // Delay s == 0xCF || // Duration s == 0xA3) // SimpleBlock { return s; } s = s * 256 + (byte)f.ReadByte(); if (s == 0x5854 || // SilentTracks s == 0x58D7 || // SilentTrackNumber s == 0x75A1) // BlockAdditions return s; return 0; } private void AnalyzeMatroskaCluster() { byte b; bool done = false; UInt32 matroskaId; int sizeOfSize; long dataSize; long afterPosition; long clusterTimeCode = 0; long duration = 0; while (f.Position < f.Length && done == false) { matroskaId = GetMatroskaClusterId(); if (matroskaId == 0) done = true; else { b = (byte)f.ReadByte(); sizeOfSize = GetMatroskaVariableIntLength(b); dataSize = GetMatroskaDataSize(sizeOfSize, b); if (matroskaId == 0xE7) // Timecode { afterPosition = f.Position + dataSize; clusterTimeCode = GetMatroskaVariableSizeUnsignedInt(dataSize); f.Seek(afterPosition, SeekOrigin.Begin); } else if (matroskaId == 0xA0) // BlockGroup { afterPosition = f.Position + dataSize; AnalyzeMatroskaBlock(clusterTimeCode); f.Seek(afterPosition, SeekOrigin.Begin); } else if (matroskaId == 0xA3) // SimpleBlock { afterPosition = f.Position + dataSize; long before = f.Position; b = (byte)f.ReadByte(); int sizeOftrackNumber = GetMatroskaVariableIntLength(b); long trackNumber = GetMatroskaDataSize(sizeOftrackNumber, b); if (trackNumber == _subtitleRipTrackNumber) { int timeCode = GetInt16(); // lacing byte flags = (byte)f.ReadByte(); byte numberOfFrames = 0; switch ((flags & 6)) // 6 = 00000110 { case 0: System.Diagnostics.Debug.Print("No lacing"); // No lacing break; case 2: System.Diagnostics.Debug.Print("Xiph lacing"); // 2 = 00000010 = Xiph lacing numberOfFrames = (byte)f.ReadByte(); numberOfFrames++; break; case 4: System.Diagnostics.Debug.Print("fixed-size"); // 4 = 00000100 = Fixed-size lacing numberOfFrames = (byte)f.ReadByte(); numberOfFrames++; for (int i = 1; i <= numberOfFrames; i++) b = (byte)f.ReadByte(); // frames break; case 6: System.Diagnostics.Debug.Print("EBML"); // 6 = 00000110 = EMBL numberOfFrames = (byte)f.ReadByte(); numberOfFrames++; break; } byte[] buffer = new byte[dataSize - (f.Position - before)]; f.Read(buffer, 0, buffer.Length); _subtitleRip.Add(new SubtitleSequence(buffer, timeCode + clusterTimeCode, timeCode + clusterTimeCode + duration)); } f.Seek(afterPosition, SeekOrigin.Begin); } else f.Seek(dataSize, SeekOrigin.Current); } } } private void AnalyzeMatroskaBlock(long clusterTimeCode) { long duration = 0; byte b = (byte)f.ReadByte(); if (b == 0xA1) // Block { b = (byte)f.ReadByte(); int sizeOfSize = GetMatroskaVariableIntLength(b); long dataSize = GetMatroskaDataSize(sizeOfSize, b); long afterPosition = f.Position + dataSize; // track number b = (byte)f.ReadByte(); int sizeOfTrackNo = GetMatroskaVariableIntLength(b); long trackNo = GetMatroskaDataSize(sizeOfTrackNo, b); // time code Int16 timeCode = GetInt16(); // lacing byte flags = (byte)f.ReadByte(); byte numberOfFrames = 0; switch ((flags & 6)) // 6 = 00000110 { case 0: System.Diagnostics.Debug.Print("No lacing"); // No lacing break; case 2: System.Diagnostics.Debug.Print("Xiph lacing"); // 2 = 00000010 = Xiph lacing numberOfFrames = (byte)f.ReadByte(); numberOfFrames++; break; case 4: System.Diagnostics.Debug.Print("fixed-size"); // 4 = 00000100 = Fixed-size lacing numberOfFrames = (byte)f.ReadByte(); numberOfFrames++; for (int i = 1; i <= numberOfFrames; i++) b = (byte)f.ReadByte(); // frames break; case 6: System.Diagnostics.Debug.Print("EBML"); // 6 = 00000110 = EMBL numberOfFrames = (byte)f.ReadByte(); numberOfFrames++; break; } // save subtitle data if (trackNo == _subtitleRipTrackNumber) { long sublength = afterPosition - f.Position; if (sublength > 0) { byte[] buffer = new byte[sublength]; f.Read(buffer, 0, (int)sublength); //string s = GetMatroskaString(sublength); //s = s.Replace("\\N", Environment.NewLine); f.Seek(afterPosition, SeekOrigin.Begin); b = (byte)f.ReadByte(); if (b == 0x9B) // BlockDuration { b = (byte)f.ReadByte(); sizeOfSize = GetMatroskaVariableIntLength(b); dataSize = GetMatroskaDataSize(sizeOfSize, b); duration = GetMatroskaVariableSizeUnsignedInt(dataSize); } _subtitleRip.Add(new SubtitleSequence(buffer, timeCode + clusterTimeCode, timeCode + clusterTimeCode + duration)); } } } } private Int16 GetInt16() { ByteLayout16 l16 = new ByteLayout16(); l16.B2 = (byte)f.ReadByte(); l16.B1 = (byte)f.ReadByte(); return l16.IntData16; } public List<MatroskaSubtitleInfo> GetMatroskaSubtitleTracks(string fileName, out bool isValid) { byte b; bool done; UInt32 matroskaId; int sizeOfSize; long dataSize; long afterPosition; bool endOfFile; f = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); matroskaId = GetMatroskaId(); if (matroskaId != 0x1A45DFA3) // matroska file must start with ebml header { isValid = false; } else { isValid = true; b = (byte)f.ReadByte(); sizeOfSize = GetMatroskaVariableIntLength(b); dataSize = GetMatroskaDataSize(sizeOfSize, b); f.Seek(dataSize, SeekOrigin.Current); done = false; endOfFile = false; while (endOfFile == false && done == false) { matroskaId = GetMatroskaId(); if (matroskaId == 0) { done = true; } else { b = (byte)f.ReadByte(); sizeOfSize = GetMatroskaVariableIntLength(b); dataSize = GetMatroskaDataSize(sizeOfSize, b); if (matroskaId == 0x1549A966) // segment info { afterPosition = f.Position + dataSize; AnalyzeMatroskaSegmentInformation(afterPosition); f.Seek(afterPosition, SeekOrigin.Begin); } else if (matroskaId == 0x1654AE6B) // tracks { afterPosition = f.Position + dataSize; AnalyzeMatroskaTracks(); f.Seek(afterPosition, SeekOrigin.Begin); done = true; } else if (matroskaId != 0x18538067) // segment { f.Seek(dataSize, SeekOrigin.Current); } } endOfFile = f.Position >= f.Length; } } f.Close(); f.Dispose(); f = null; return _subtitleList; } public List<SubtitleSequence> GetMatroskaSubtitle(string fileName, int trackNumber, out bool isValid, Matroska.LoadMatroskaCallback callback) { byte b; bool done; UInt32 matroskaId; int sizeOfSize; long dataSize; long afterPosition; bool endOfFile; _subtitleRipTrackNumber = trackNumber; f = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); matroskaId = GetMatroskaId(); if (matroskaId != 0x1A45DFA3) // matroska file must start with ebml header { isValid = false; } else { isValid = true; b = (byte)f.ReadByte(); sizeOfSize = GetMatroskaVariableIntLength(b); dataSize = GetMatroskaDataSize(sizeOfSize, b); f.Seek(dataSize, SeekOrigin.Current); done = false; endOfFile = false; while (endOfFile == false && done == false) { matroskaId = GetMatroskaId(); if (matroskaId == 0) { done = true; } else { b = (byte)f.ReadByte(); sizeOfSize = GetMatroskaVariableIntLength(b); dataSize = GetMatroskaDataSize(sizeOfSize, b); if (matroskaId == 0x1549A966) // segment info { afterPosition = f.Position + dataSize; AnalyzeMatroskaSegmentInformation(afterPosition); f.Seek(afterPosition, SeekOrigin.Begin); } else if (matroskaId == 0x1654AE6B) // tracks { afterPosition = f.Position + dataSize; AnalyzeMatroskaTracks(); f.Seek(afterPosition, SeekOrigin.Begin); } else if (matroskaId == 0x1F43B675) // cluster { afterPosition = f.Position + dataSize; AnalyzeMatroskaCluster(); f.Seek(afterPosition, SeekOrigin.Begin); } else if (matroskaId != 0x18538067) // segment { f.Seek(dataSize, SeekOrigin.Current); } } if (callback != null) callback.Invoke(f.Position, f.Length); endOfFile = f.Position >= f.Length; } } f.Close(); f.Dispose(); f = null; return _subtitleRip; } } }
msimic/MediaPoint
MediaPoint_Common/Subtitles/VideoFormats/Matroska.cs
C#
gpl-2.0
47,613
#!/usr/bin/env python ############################################################################### # # searchMappedPairs.py # # Given a bam file, this srcipt will calculate where the mate of the read # is mapped or unmappedand in which contig that mate is mapped to. The aim # being to generate a graphviz image and report file of all of the pairs that # map to a different contigs and to no contigs at all. Hopefully this will # help with assemblies and stuff like that to piece together contigs. # # Copyright (C) 2011, 2012, 2014 Connor Skennerton # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################### import argparse import sys import pysam import networkx as nx from operator import itemgetter def getSubList(subFile): subList = set() for line in subFile: subList.add(line.rstrip()) return subList def findEndLinks(G, bamFile, contig, length, endLength=500): # get the links at the start of the reference for read in bamFile.fetch(contig, 1, endLength): if checkLink(bamFile, read, length, contig): mate_contig = bamFile.getrname(read.mrnm) G.add_node(contig, length=length) G.add_node(mate_contig, length=bamFile.lengths[read.mrnm]) addLink(G, contig, mate_contig) # now get oll of the links at the end of the reference for read in bamFile.fetch(contig, length - endLength, length): if checkLink(bamFile, read, length, contig): mate_contig = bamFile.getrname(read.mrnm) G.add_node(contig, length=length) G.add_node(mate_contig, length=bamFile.lengths[read.mrnm]) addLink(G, contig, mate_contig) def addLink(G, contig, mate_contig): if contig < mate_contig: G.add_edge(contig, mate_contig) try: G[contig][mate_contig]['weight'] += 1 except: G[contig][mate_contig]['weight'] = 1 else: G.add_edge(mate_contig, contig) try: G[mate_contig][contig]['weight'] += 1 except: G[mate_contig][contig]['weight'] = 1 def checkLink(bamFile, read, length, contig): if isMated(read): if hasMissingMates(bamFile, read, contig): # mate is on a different contig return True # checks for a number of features for each aligned read. If a read's mate is # on a different contig then it returns that contig name. For all other # possibilities returns None def hasMissingMates(bamFile, alignedRead, contig): mate_contig = bamFile.getrname(alignedRead.mrnm) if (mate_contig != contig): return True return False # checks the position of the read and it's mate to see if they are on oposite # ends of a contig. Returns True if they are, False if not def isCircularLink(alignedReadPos, matePos, contigLength, endLength=500): if ((alignedReadPos < endLength) and (matePos > contigLength - endLength)): return True elif (alignedReadPos > (contigLength - endLength) and (matePos < endLength)): return True else: return False def isMated(alignedRead): if alignedRead.is_paired: if not alignedRead.mate_is_unmapped: return True return False if __name__ =='__main__': # intialise the options parser parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("bam", help="the name of the input bam file") parser.add_argument('outfile', help='Name of output file of graph in GML format') parser.add_argument('-f', '--wanted-contigs', dest='wantedContigs', type=argparse.FileType(), help='A file of contig names to be considered') parser.add_argument("-n","--numberLinks", type=int, dest="numOfLinks", default=3, help="the number of links that two contigs must share for the links to even be considered 'real'") parser.add_argument('-m', '--min-contig-len', type=int, dest='minContigLen', default=500, help='The minimum length of the contig to be considered for adding links') # get and check options args = parser.parse_args() endLength = 500 sublist = None if args.wantedContigs is not None: sublist = getSubList(args.wantedContigs) try: bamFile = pysam.Samfile(args.bam, 'rb') except: print "The input file must be in bam format" sys.exit(1) G = nx.Graph() for contig, length in zip(bamFile.references, bamFile.lengths): if length < args.minContigLen: continue if contig not in sublist: continue findEndLinks(G, bamFile, contig, length) # now subset the graph based on the edge conditions SG = nx.Graph( [ (u,v,d) for u,v,d in G.edges(data=True) if d ['weight'] >= args.numOfLinks] ) nx.write_gml(SG, args.outfile)
JoshDaly/scriptShed
searchMappedPairs.py
Python
gpl-2.0
5,548
<?php /** * Partial: Related article for main article */ ?> <?php $single_id = $post->ID; $categories = get_the_category( $post->ID); $intCategoryId = $categories[0]->cat_ID; $strCategoryName = $categories[0]->cat_name; $args = array( 'cat' => $intCategoryId ,'order' => 'DESC' , 'posts_per_page' =>'2','post__not_in' =>array($single_id)); // The Query $the_query = new WP_Query( $args ); // The Loop echo '<h3>Related Articles</h3>'; if ( $the_query->have_posts() ) { $i = 0; while ( $the_query->have_posts() ) { $the_query->the_post(); if($single_id != $post->ID){ ?> <div class="mod-list-item left <?php if($i == 0 ){ echo "first-col "; } ?>first-row"> <div class="row"> <div class="img-wrap"> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"> <?php if (class_exists('MultiPostThumbnails')){ if(MultiPostThumbnails::get_the_post_thumbnail('post', 'home-image', NULL, 'home-thumb', NULL, false) == ''){ ?><img src="<?php bloginfo('template_directory'); ?>/assets/img/jkc-no-image-288x140.jpg" alt="<?php the_title(); ?>" draggable="false"><?php }else{ echo MultiPostThumbnails::get_the_post_thumbnail('post', 'home-image', NULL, 'home-thumb', NULL, false); } }else{ ?><img src="<?php bloginfo('template_directory'); ?>/assets/img/jkc-no-image-288x140.jpg" alt="<?php the_title(); ?>" draggable="false"><?php } ?> </a> </div> <div class="category"> <a href="<?php get_category_link( $intCategoryId ); ?>"><?php echo $strCategoryName;?></a> </div> <div class="info-wrap"> <?php $strFromatedtitleforReleatedArticle = get_the_title(); $strlen = strlen($strFromatedtitleforReleatedArticle); if($strlen >= 45){ $formatedC = substr($strFromatedtitleforReleatedArticle, 0, 45 ).'...'; }else{ $formatedC = $strFromatedtitleforReleatedArticle; } ?> <h4 class="title-wrap"><a class="list-title" href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php echo $formatedC; ?></a></h4> <div class="desc"><?php the_excerpt(); ?></div> </div> </div> </div> <?php $i++; } } } else { echo "no posts found"; } ?>
srinivas-qfor/jkc-wp
wp-content/themes/jeanknowscars/template-parts/related.php
PHP
gpl-2.0
3,140
<section id="intro" class="intro-section"> <div class="container"> <div class="row"> <div class="col-lg-12"> <center> <h1>Login</h1> <form name="f" method="post" action="?page=login"> <p><input class="form-control" style="color:#000;width:300px;" placeholder="ID" type="text" name="id" /> <input class="form-control" style="color:#000;width:300px;" placeholder="PW" type="text" name="pw" /></p> <a class="btn btn-default page-scroll" onclick="f.submit();">Login</a> </form> <?php if($_POST){ if($_SESSION[id]){ echo "<script>alert('You have already logged in.');history.go(-1);</script>"; exit(); } $sql = "select * from member where id = '".trim($_POST[id])."'"; $result = @mysql_query($sql); $data = @mysql_fetch_array($result); if($data[id]){ if($_POST[pw] == $data[pw]){ $_SESSION[id] = $data[id]; echo "<script>alert('Hello $_SESSION[id]');location.href='./';</script>"; }else{ echo "<script>history.go(-1);</script>"; exit(); } }else{ echo "<script>history.go(-1);</script>"; exit(); } } ?> </center> </div> </div> </div> </section>
Qwaz/solved-hacking-problem
sciencewar/2016/wargame_easy/login.php
PHP
gpl-2.0
1,287
/* * Copyright (C) 2008-2011 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "CreatureAI.h" #include "CreatureAIImpl.h" #include "Creature.h" #include "World.h" #include "SpellMgr.h" #include "Vehicle.h" #include "Group.h" #include "Log.h" #include "MapReference.h" #include "Player.h" #include "Group.h" //Disable CreatureAI when charmed void CreatureAI::OnCharmed(bool /*apply*/) { //me->IsAIEnabled = !apply;*/ me->NeedChangeAI = true; me->IsAIEnabled = false; } AISpellInfoType* UnitAI::AISpellInfo; AISpellInfoType* GetAISpellInfo(uint32 i) { return &CreatureAI::AISpellInfo[i]; } void CreatureAI::Talk(uint8 id, uint64 WhisperGuid) { sCreatureTextMgr->SendChat(me, id, WhisperGuid); } void CreatureAI::DoZoneInCombat(Creature* creature /*= NULL*/, float maxRangeToNearestTarget /* = 50.0f*/) { if (!creature) creature = me; if (!creature->CanHaveThreatList()) return; Map* map = creature->GetMap(); if (!map->IsDungeon()) //use IsDungeon instead of Instanceable, in case battlegrounds will be instantiated { sLog->outError("DoZoneInCombat call for map that isn't an instance (creature entry = %d)", creature->GetTypeId() == TYPEID_UNIT ? creature->ToCreature()->GetEntry() : 0); return; } if (!creature->HasReactState(REACT_PASSIVE) && !creature->getVictim()) { if (Unit* nearTarget = creature->SelectNearestTarget(maxRangeToNearestTarget)) creature->AI()->AttackStart(nearTarget); else if (creature->isSummon()) { if (Unit* summoner = creature->ToTempSummon()->GetSummoner()) { Unit* target = summoner->getAttackerForHelper(); if (!target && summoner->CanHaveThreatList() && !summoner->getThreatManager().isThreatListEmpty()) target = summoner->getThreatManager().getHostilTarget(); if (target && (creature->IsFriendlyTo(summoner) || creature->IsHostileTo(target))) creature->AI()->AttackStart(target); } } } if (!creature->HasReactState(REACT_PASSIVE) && !creature->getVictim()) { sLog->outError("DoZoneInCombat called for creature that has empty threat list (creature entry = %u)", creature->GetEntry()); return; } Map::PlayerList const& playerList = map->GetPlayers(); if (playerList.isEmpty()) return; for (Map::PlayerList::const_iterator itr = playerList.begin(); itr != playerList.end(); ++itr) { if (Player* player = itr->getSource()) { if (player->isGameMaster()) continue; if (player->isAlive()) { creature->SetInCombatWith(player); player->SetInCombatWith(creature); creature->AddThreat(player, 0.0f); } /* Causes certain things to never leave the threat list (Priest Lightwell, etc): for (Unit::ControlList::const_iterator itr = player->m_Controlled.begin(); itr != player->m_Controlled.end(); ++itr) { creature->SetInCombatWith(*itr); (*itr)->SetInCombatWith(creature); creature->AddThreat(*itr, 0.0f); }*/ } } } // scripts does not take care about MoveInLineOfSight loops // MoveInLineOfSight can be called inside another MoveInLineOfSight and cause stack overflow void CreatureAI::MoveInLineOfSight_Safe(Unit* who) { if (m_MoveInLineOfSight_locked == true) return; m_MoveInLineOfSight_locked = true; MoveInLineOfSight(who); m_MoveInLineOfSight_locked = false; } void CreatureAI::DoAttackerAreaInCombat(Unit* attacker, float range, Unit* pUnit) { if (!attacker) attacker = me; if (!pUnit) pUnit = me; Map *map = pUnit->GetMap(); if (!map->IsDungeon()) return; if (!pUnit->CanHaveThreatList() || pUnit->getThreatManager().isThreatListEmpty()) return; Map::PlayerList const &PlayerList = map->GetPlayers(); for(Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) { if (Player* i_pl = i->getSource()) if (i_pl->isAlive() && attacker->GetDistance(i_pl) <= range ) { pUnit->SetInCombatWith(i_pl); i_pl->SetInCombatWith(pUnit); pUnit->AddThreat(i_pl, 0.0f); } } } void CreatureAI::DoAttackerGroupInCombat(Player* attacker) { if (attacker) { if (Group* pGroup = attacker->GetGroup() ) { for (GroupReference* itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next()) { Player* pGroupGuy = itr->getSource(); if (pGroupGuy && pGroupGuy->isAlive() && pGroupGuy->GetMapId() == me->GetMapId()) { me->SetInCombatWith(pGroupGuy); pGroupGuy->SetInCombatWith(me); me->AddThreat(pGroupGuy, 0.0f); } } } } } void CreatureAI::MoveInLineOfSight(Unit* who) { if (me->getVictim()) return; if (me->GetCreatureType() == CREATURE_TYPE_NON_COMBAT_PET) // non-combat pets should just stand there and look good;) return; if (me->canStartAttack(who, false)) AttackStart(who); //else if (who->getVictim() && me->IsFriendlyTo(who) // && me->IsWithinDistInMap(who, sWorld->getIntConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS)) // && me->canStartAttack(who->getVictim(), true)) // TODO: if we use true, it will not attack it when it arrives // me->GetMotionMaster()->MoveChase(who->getVictim()); } void CreatureAI::EnterEvadeMode() { if (!_EnterEvadeMode()) return; sLog->outDebug(LOG_FILTER_UNITS, "Creature %u enters evade mode.", me->GetEntry()); if (!me->GetVehicle()) // otherwise me will be in evade mode forever { if (Unit* owner = me->GetCharmerOrOwner()) { me->GetMotionMaster()->Clear(false); me->GetMotionMaster()->MoveFollow(owner, PET_FOLLOW_DIST, me->GetFollowAngle(), MOTION_SLOT_ACTIVE); } else me->GetMotionMaster()->MoveTargetedHome(); } Reset(); if (me->IsVehicle()) // use the same sequence of addtoworld, aireset may remove all summons! me->GetVehicleKit()->Reset(true); } /*void CreatureAI::AttackedBy(Unit* attacker) { if (!me->getVictim()) AttackStart(attacker); }*/
V1rd/ReanEmu
src/server/game/AI/CreatureAI.cpp
C++
gpl-2.0
7,304
/*************************************************************************** * Copyright (C) 2004-2017 by Michael Griffin * * mrmisticismo@hotmail.com * * * * Purpose: Working on IPC Node Chat * * * * Node Messaging Modeled after Day Dream particially. * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * ***************************************************************************/ #include "console.h" #include "struct.h" #include <cstdio> #include <cstdlib> #include <errno.h> #include <fcntl.h> #include <signal.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <sys/un.h> #include <termios.h> #include <iostream> #include <clocale> #include <cwchar> #include <string> #include <fstream> std::string screen_buffer; /** * Wijnand Modderman-Lenstra * CP437 is a tuple of length 256, mapping equivalent unicode * characters for each CP437(n), where n is index of CP437. * * Characters 1-31 remapped for CP437 control Codes to UTF-8 Glyphs * * Excluded from Translation to Glyphs. * http://en.wikipedia.org/wiki/Code_page_437#Characters * * 13 is mapped to CR Excluded 'Music Note' * 27 is mapped to ESC Excluded 'Left Arrow' * -- Micahel Griffin */ wchar_t CP437TABLE[] = { L'\u0000', L'\u263A', L'\u263B', L'\u2665', L'\u2666', L'\u2663', L'\u2660', L'\u2022', L'\u0008', L'\u0009', L'\u000A', L'\u2642', L'\u2640', L'\u000D', L'\u266C', L'\u263C', L'\u25BA', L'\u25C4', L'\u2195', L'\u203C', L'\u00B6', L'\u00A7', L'\u25AC', L'\u21A8', L'\u2191', L'\u2193', L'\u2192', L'\u001B', L'\u221F', L'\u2194', L'\u25B2', L'\u25BC', L'\u0020', L'\u0021', L'\u0022', L'\u0023', L'\u0024', L'\u0025', L'\u0026', L'\u0027', L'\u0028', L'\u0029', L'\u002A', L'\u002B', L'\u002C', L'\u002D', L'\u002E', L'\u002F', L'\u0030', L'\u0031', L'\u0032', L'\u0033', L'\u0034', L'\u0035', L'\u0036', L'\u0037', L'\u0038', L'\u0039', L'\u003A', L'\u003B', L'\u003C', L'\u003D', L'\u003E', L'\u003F', L'\u0040', L'\u0041', L'\u0042', L'\u0043', L'\u0044', L'\u0045', L'\u0046', L'\u0047', L'\u0048', L'\u0049', L'\u004A', L'\u004B', L'\u004C', L'\u004D', L'\u004E', L'\u004F', L'\u0050', L'\u0051', L'\u0052', L'\u0053', L'\u0054', L'\u0055', L'\u0056', L'\u0057', L'\u0058', L'\u0059', L'\u005A', L'\u005B', L'\u005C', L'\u005D', L'\u005E', L'\u005F', L'\u0060', L'\u0061', L'\u0062', L'\u0063', L'\u0064', L'\u0065', L'\u0066', L'\u0067', L'\u0068', L'\u0069', L'\u006A', L'\u006B', L'\u006C', L'\u006D', L'\u006E', L'\u006F', L'\u0070', L'\u0071', L'\u0072', L'\u0073', L'\u0074', L'\u0075', L'\u0076', L'\u0077', L'\u0078', L'\u0079', L'\u007A', L'\u007B', L'\u007C', L'\u007D', L'\u007E', L'\u007F', L'\u00C7', L'\u00FC', L'\u00E9', L'\u00E2', L'\u00E4', L'\u00E0', L'\u00E5', L'\u00E7', L'\u00EA', L'\u00EB', L'\u00E8', L'\u00EF', L'\u00EE', L'\u00EC', L'\u00C4', L'\u00C5', L'\u00C9', L'\u00E6', L'\u00C6', L'\u00F4', L'\u00F6', L'\u00F2', L'\u00FB', L'\u00F9', L'\u00FF', L'\u00D6', L'\u00DC', L'\u00A2', L'\u00A3', L'\u00A5', L'\u20A7', L'\u0192', L'\u00E1', L'\u00ED', L'\u00F3', L'\u00FA', L'\u00F1', L'\u00D1', L'\u00AA', L'\u00BA', L'\u00BF', L'\u2310', L'\u00AC', L'\u00BD', L'\u00BC', L'\u00A1', L'\u00AB', L'\u00BB', L'\u2591', L'\u2592', L'\u2593', L'\u2502', L'\u2524', L'\u2561', L'\u2562', L'\u2556', L'\u2555', L'\u2563', L'\u2551', L'\u2557', L'\u255D', L'\u255C', L'\u255B', L'\u2510', L'\u2514', L'\u2534', L'\u252C', L'\u251C', L'\u2500', L'\u253C', L'\u255E', L'\u255F', L'\u255A', L'\u2554', L'\u2569', L'\u2566', L'\u2560', L'\u2550', L'\u256C', L'\u2567', L'\u2568', L'\u2564', L'\u2565', L'\u2559', L'\u2558', L'\u2552', L'\u2553', L'\u256B', L'\u256A', L'\u2518', L'\u250C', L'\u2588', L'\u2584', L'\u258C', L'\u2590', L'\u2580', L'\u03B1', L'\u00DF', L'\u0393', L'\u03C0', L'\u03A3', L'\u03C3', L'\u00B5', L'\u03C4', L'\u03A6', L'\u0398', L'\u03A9', L'\u03B4', L'\u221E', L'\u03C6', L'\u03B5', L'\u2229', L'\u2261', L'\u00B1', L'\u2265', L'\u2264', L'\u2320', L'\u2321', L'\u00F7', L'\u2248', L'\u00B0', L'\u2219', L'\u00B7', L'\u221A', L'\u207F', L'\u00B2', L'\u25A0', L'\u00A0' }; static int conin = 0; static int conout = 0; static int conon = 0; static int dummyfd = 0; int sockfd; int serhandle; struct List *olms; static struct sockaddr_un sock; /** * Create Internode PIPE Sockets for Node Communication */ static void create_internode_socket() { char socket_name[4096] = {0}; if ((sockfd = socket(AF_UNIX, SOCK_DGRAM, 0)) < 0) { fprintf(stderr,"%s ***cannot create communication socket, check permissions!",ENTHRALTMP); } snprintf(socket_name, sizeof socket_name, "%s/enthral_sock%d", ENTHRALTMP, NODE_NUM); unlink(socket_name); strncpy(sock.sun_path, socket_name, sizeof sock.sun_path); sock.sun_path[sizeof sock.sun_path - 1] = 0; sock.sun_family = AF_UNIX; if (bind(sockfd, (struct sockaddr *) &sock, sizeof sock) < 0) { fprintf(stderr,"%s ***cannot bind communication socket, check permissions!",ENTHRALTMP); close(sockfd); } } /** * Clear Node Files on System Exit. */ void clear_nodes() { char buff[512] = {0}; finalize_console(); snprintf(buff, sizeof(buff), "%s/enthral%dr", ENTHRALTMP, NODE_NUM); unlink(buff); close(sockfd); snprintf(buff, sizeof(buff), "%s/enthral_sock%d", ENTHRALTMP, NODE_NUM); unlink(buff); snprintf(buff, sizeof(buff), "%s/enthral%dw", ENTHRALTMP, NODE_NUM); unlink(buff); snprintf(buff, sizeof(buff), "%s/nodeinfo%d.data", ENTHRALTMP, NODE_NUM); unlink(buff); // Clear Terminal file from Telnetd snprintf(buff, sizeof(buff), "%s", CLIENT_TERM); remove(buff); } /** * Initalize And Create Node Sockets */ int init_nodes() { serhandle = open(ttyname(0), O_RDWR); create_internode_socket(); if (init_console() == -1) { fprintf(stderr,"%s ***communication socket(s) failed to init, check permissions!",ENTHRALTMP); } return 1; } /** * Set block on Nodes */ int set_blocking_mode(int fd, int mode) { int fl; if ((fl = fcntl(fd, F_GETFL)) == -1) return -1; fl &= ~O_NONBLOCK; return fcntl(fd, F_SETFL, fl | (mode ? O_NONBLOCK : 0)); } /** * Read from Console/Node socket */ ssize_t safe_read(int fd, void *buf, size_t buflen) { char *p; ssize_t bread, n; bread = 0; p = (char *) buf; while (buflen) { if ((n = read(fd, p, buflen)) == -1) { if (errno == EINTR) continue; return -1; } p += n; bread += n; buflen -= n; } return bread; } /** * Write Console/Node socket */ ssize_t safe_write(int fd, const void *buf, size_t buflen) { char *p; ssize_t bwrite, n; bwrite = 0; p = (char *) buf; while (buflen) { if ((n = write(fd, p, buflen)) == -1) { if (errno == EINTR) continue; return -1; } p += n; bwrite += n; buflen -= n; } return bwrite; } /** * Check if console is blocking or Not. */ int console_active() { return conon != 0; } /** * Initalize console node pipe i/o */ int init_console() { char buffer[4096] = {0}; struct sigaction sigact; sigset_t sigset; /* Writing to pipe with no readers on the other side raises * SIGPIPE and its default action is to terminate the program. */ sigact.sa_handler = SIG_IGN; sigemptyset(&sigset); sigact.sa_mask = sigset; sigact.sa_flags = SA_RESTART; if (sigaction(SIGPIPE, &sigact, NULL) == -1) abort(); snprintf(buffer, sizeof buffer, "%s/enthral%dw", ENTHRALTMP, NODE_NUM); unlink(buffer); if (mkfifo(buffer, 0777) == -1) { fprintf(stderr,"%s Cannot create communication FIFO\r\n",ENTHRALTMP); exit(1); } /* We must first open the writing FIFO as O_RDONLY, if we're * ever going to get it opened as O_WRONLY. Without this trick * open() would always return ENXIO. * * We can still know whether there are no readers on the other * side of pipe, since safe_write() will return EPIPE on such case. */ if ((dummyfd = open(buffer, O_RDONLY | O_NONBLOCK)) == -1 || (conout = open(buffer, O_WRONLY | O_NONBLOCK)) == -1) abort(); close(dummyfd); set_blocking_mode(conout, 0); snprintf(buffer, sizeof(buffer), "%s/enthral%dr", ENTHRALTMP, NODE_NUM); unlink(buffer); if (mkfifo(buffer, 0777) == -1) { fprintf(stderr,"%s ***cannot create communication FIFO socket (Nodes), check permissions!",ENTHRALTMP); exit(1); } /* Opening a FIFO for O_RDONLY in non blocking mode should * work on all systems. */ if ((conin = open(buffer, O_RDONLY | O_NONBLOCK)) == -1 || (dummyfd = open(buffer, O_WRONLY | O_NONBLOCK)) == -1) abort(); set_blocking_mode(conin, 0); return 0; } /** * Finialize console node pipe i/o */ void finalize_console() { close(conin); close(conout); close(dummyfd); conon = 0; } /** * Open descriptor */ void open_console() { if (conon != 2) conon = 1; } /** * Close descriptor */ void close_console() { if (conon != 2) conon = 0; } /** * Select where to get input from, Console / Node */ int console_select_input(int maxfd, fd_set *set) { FD_SET(conin, set); return maxfd < conin ? conin : maxfd; } /** * Check for waiting Data */ int console_pending_input(fd_set *set) { return FD_ISSET(conin, set); } /** * Get single Character Input */ int console_getc(void) { char ch; switch (read(conin, &ch, 1)) { case 0: return EOF; case -1: if (errno == EPIPE) { conon = 0; return EOF; } return -1; default: return ch; } } /** * Used for printing multibyte (UTF-8) Characters * To Console / STDOUT */ void print_wide(const std::wstring& wstr) { std::mbstate_t state = std::mbstate_t(); for(wchar_t wc : wstr) { std::string mb(MB_CUR_MAX, '\0'); int ret = std::wcrtomb(&mb[0], wc, &state); if ((ret == 0)) break; // Skip any Trailing / Embedded null from Wide -> multibtye // Conversion, don't send NULL's to the screen. for(char ch: mb) { if (ch != '\0') std::cout << ch << flush; } } } /** * Main Translation loop from cp437 to Wide Unicode. * */ void cp437toUTF8(std::string cp347) { std::wstring wstr; int ascii_value = 0; // Loop and wirte out after translation to UTF-8 for (int i = 0; i < (signed)cp347.size(); i++) { ascii_value = std::char_traits<char>().to_int_type(cp347[i]); if (ascii_value < 256) wstr = CP437TABLE[ascii_value]; else wstr = cp347[i]; print_wide(wstr); } } /** * Main call to write output to console * */ int console_putsn(char *str, size_t n, int buffering) { int writecnt = 0; std::string::size_type id1 = 0; std::string myCP437; myCP437 = static_cast<char *>(str); // Find Most Recent Screen Clear, Restart buffer fresh // Otherwise Keep appending to the buffer if (buffering) { id1 = myCP437.rfind("\x1b[2J",myCP437.size()-1); if (id1 != std::string::npos) { screen_buffer.erase(); screen_buffer = myCP437.substr(id1); } else screen_buffer += myCP437; } if (UTF8Output) { cp437toUTF8(myCP437); } else { // Write to console first for Telnet Users Connection writecnt = write(1,(char*)str,n); //- - Normal Output for Connection. } // Safe Write to Sockets for Snooping IPC Connections locally. // - Local connection For snoop sysop utils. writecnt = safe_write(conout, str, n); if (writecnt == -1 && errno == EPIPE) { return 0; } else { return writecnt; } }
M-griffin/Enthral
src/console.cpp
C++
gpl-2.0
12,703
# Copyright (c) Facebook, Inc. and its affiliates. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2. # This module will be shared with other services. Therefore, please refrain from # importing anything from Mercurial and creating a dependency on Mercurial. This # module is only for specifying classes based on simple types to represent the # data required for creating commits. from __future__ import absolute_import from typing import Any, Dict, List, Optional, Union class params(object): def __init__( self, changelist: "changelist", metadata: "metadata", destination: "destination" ) -> None: self.changelist = changelist self.metadata = metadata self.destination = destination def todict(self) -> "Dict[str, Any]": d = {} d["changelist"] = self.changelist.todict() d["metadata"] = self.metadata.todict() d["destination"] = self.destination.todict() return d @classmethod def fromdict(cls, d: "Dict[str, Any]") -> "params": return cls( changelist=changelist.fromdict(d["changelist"]), metadata=metadata.fromdict(d["metadata"]), destination=destination.fromdict(d["destination"]), ) class metadata(object): def __init__( self, author: "Optional[str]", description: "Optional[str]", parents: "Optional[List[str]]", extra: "Optional[Dict[str, str]]" = None, ) -> None: self.author = author self.description = description self.parents = parents self.extra = extra def todict(self) -> "Dict[str, Any]": d = {} d["author"] = self.author d["description"] = self.description d["parents"] = self.parents d["extra"] = self.extra return d @classmethod def fromdict(cls, d: "Dict[str, Any]") -> "metadata": author = d.get("author") # type: Optional[str] description: "Optional[str]" = d.get("description") parents: "Optional[List[str]]" = d.get("parents") extra: "Optional[Dict[str, str]]" = d.get("extra") return cls(author, description, parents, extra) class destination(object): def __init__( self, bookmark: "Optional[str]" = None, pushrebase: "Optional[bool]" = False ) -> None: self.bookmark = bookmark self.pushrebase = pushrebase def todict(self) -> "Dict[str, Any]": d = {} d["bookmark"] = self.bookmark d["pushrebase"] = self.pushrebase return d @classmethod def fromdict(cls, d: "Dict[str, Any]") -> "destination": bookmark = d.get("bookmark") # type: Optional[str] pushrebase: "Optional[bool]" = d.get("pushrebase") return cls(bookmark, pushrebase) class changelistbuilder(object): def __init__(self, parent: str) -> None: self.parent = parent self.files: "Dict[str, fileinfo]" = {} def addfile(self, path: str, fileinfo: "fileinfo") -> None: self.files[path] = fileinfo def build(self) -> "changelist": return changelist(self.parent, self.files) class changelist(object): def __init__(self, parent: "Optional[str]", files: "Dict[str, fileinfo]") -> None: self.parent = parent self.files = files def todict(self) -> "Dict[str, Any]": d = {} d["parent"] = self.parent d["files"] = {path: info.todict() for path, info in self.files.items()} return d @classmethod def fromdict(cls, d: "Dict[str, Any]") -> "changelist": parent = d.get("parent") # type: Optional[str] files: "Dict[str, fileinfo]" = { path: fileinfo.fromdict(info) for path, info in d["files"].items() } return cls(parent, files) class fileinfo(object): def __init__( self, deleted: "Optional[bool]" = False, flags: "Optional[str]" = None, content: "Optional[str]" = None, copysource: "Optional[str]" = None, ) -> None: self.deleted = deleted self.flags = flags self.content = content self.copysource = copysource def islink(self) -> bool: flags = self.flags return flags is not None and "l" in flags def isexec(self) -> bool: flags = self.flags return flags is not None and "x" in flags def todict(self) -> "Dict[str, Union[bool, str]]": d = {} d["deleted"] = self.deleted d["flags"] = self.flags d["content"] = self.content d["copysource"] = self.copysource return d @classmethod def fromdict(cls, d: "Dict[str, Any]") -> "fileinfo": deleted = d.get("deleted") # type: Optional[bool] flags: "Optional[str]" = d.get("flags") content: "Optional[str]" = d.get("content") copysource: "Optional[str]" = d.get("copysource") return cls(deleted, flags, content, copysource)
facebookexperimental/eden
eden/hg-server/edenscm/hgext/memcommit/commitdata.py
Python
gpl-2.0
5,031
/** \file swps3.c * * Main procedure and multi-threading code. */ /* * Copyright (c) 2007-2008 ETH Zürich, Institute of Computational Science * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include "SWPS3_swps3.h" #include "SWPS3_matrix.h" #include "SWPS3_fasta.h" #include "SWPS3_DynProgr_scalar.h" #ifdef SSE2 #include "SWPS3_DynProgr_sse_byte.h" #include "SWPS3_DynProgr_sse_short.h" #endif #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/select.h> #include <unistd.h> #include <string.h> #include <assert.h> #include <float.h> #include "sequence.h" static ssize_t write_all(int fd, const void *data, size_t len) { size_t sent = 0; while(sent < len) { ssize_t res; res = write(fd,(const int8_t*)data+sent,len-sent); switch(res) { case 0: return sent; case -1: return -1; default: sent += res; } } return sent; } static ssize_t read_all(int fd, void *buf, size_t len) { size_t recv = 0; while(recv < len) { ssize_t res; res = read(fd,(int8_t*)buf+recv,len-recv); switch(res) { case 0: return recv; case -1: return -1; default: recv += res; } } return recv; } /* * switch( argv[i][1] ){ case 'h': matrixFile = NULL; i = argc; break; case 's': type = SCALAR; break; case 't': options.threshold = atoi( argv[++i] ); break; case 'i': options.gapOpen = atoi( argv[++i] ); break; case 'e': options.gapExt = atoi( argv[++i] ); break; case 'j': threads = atoi( argv[++i] ); break; default: matrixFile = NULL; i = argc; break; } */ /* * have to send the matrix, which should be read in first * using SBMatrix swps3_readSBMatrix( char * filename ); * long before sending to this * * send along the known seqs in the first and the query in * the second * * return the max score * query = known * db = test */ #include "SWPS3_fasta.h" //changing from const Sequence * known to Sequence * known int swps3_maxscores ( SBMatrix matrix , Sequence * known, Sequence * test){ int i,queryLen; const char * query; //SWType type = SSE2; Options options = {-12,-2,DBL_MAX}; char * x1; bool validKnownSeq; x1 = (char*)malloc(sizeof(char)*known->get_sequence().size()); memcpy(x1, known->get_sequence().c_str(), known->get_sequence().size()); validKnownSeq = swps3_translateSequence(x1,known->get_sequence().size(),NULL); query = x1; //query = known->toString().c_str(); queryLen = known->get_sequence().size(); double score = 0; #ifdef SSE2 ProfileByte * profileByte = swps3_createProfileByteSSE( query, queryLen, matrix ); ProfileShort * profileShort = swps3_createProfileShortSSE( query, queryLen, matrix ); #endif int dbLen; const char * db; char * x2; bool validTestSeq; x2 = (char*)malloc(sizeof(char)*test->get_sequence().size()); memcpy(x2, test->get_sequence().c_str(), test->get_sequence().size()); validTestSeq = swps3_translateSequence(x2,test->get_sequence().size(),NULL); if (validTestSeq) { db = x2; //db=test->toString().c_str(); dbLen = test->get_sequence().size(); } else { printf("sequence %s is corrupt\n", test->get_ncbi_gi_id().c_str()); throw 1; } #ifdef DEBUG for(i=0; i<queryLen; ++i) printf("\t%c",query[i]); printf("\n"); #endif #ifdef SSE2 //if(type == SSE2) { if( (score = swps3_alignmentByteSSE( profileByte, db, dbLen, &options )) >= DBL_MAX ) { score = swps3_alignmentShortSSE( profileShort, db, dbLen, &options ); //assert(score >= 250 && "score too low"); } //} #else //if(type == SCALAR) { /* * doesn't work!! */ double dmatrix[MATRIX_DIM*MATRIX_DIM]; for(i=0;i<MATRIX_DIM*MATRIX_DIM;++i) dmatrix[i]=matrix[i]; score = swps3_alignScalar( dmatrix, query, queryLen, db, dbLen, &options); //} #endif #ifdef SSE2 swps3_freeProfileByteSSE( profileByte ); swps3_freeProfileShortSSE( profileShort ); #endif free(x1);free(x2); return int(score); }
blackrim/phlawd
src/SWPS3_swps3.cpp
C++
gpl-2.0
5,109
/* * Corsen development code * * This code may be freely distributed and modified under the * terms of the GNU General Public Licence version 2 or later. This * should be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/licenses/gpl-2.0.txt * * Copyright for this code is held jointly by the microarray platform * of the École Normale Supérieure and the individual authors. * These should be listed in @author doc comments. * * For more information on the Corsen project and its aims, * or to join the Corsen google group, visit the home page * at: * * http://transcriptome.ens.fr/corsen * */ package fr.ens.transcriptome.corsen.model; import fr.ens.transcriptome.corsen.Globals; /** * This class define a factory for AbstractListPoint3D. * @author Laurent Jourdren */ public final class ListPoint3DFactory { private static boolean packed = Globals.LIST_POINT_PACKED_MODE; /** * Set the backend to use to store list of Points * @param packedMode true enable packed mode */ public static void setPackedMode(final boolean packedMode) { packed = packedMode; } /** * Test if the packed mode is enable * @return true if the packed mode is enabled */ public static boolean isPackedMode() { return packed; } /** * Create a AbstractListPoint3D object. * @return a new AbstractListPoint3D object */ public static AbstractListPoint3D createListPoint3D() { if (packed) return new ArrayListPackedPoint3D(); return new ArrayListPoint3D(); } /** * Create a AbstractListPoint3D object. * @param xPrecision Precision for x values. * @param yPrecision Precision for y values. * @param zPrecision Precision for z values. * @return a new AbstractListPoint3D object */ public static AbstractListPoint3D createListPoint3D(final float xPrecision, final float yPrecision, final float zPrecision) { if (packed) return new ArrayListPackedPoint3D(xPrecision, yPrecision, zPrecision); return new ArrayListPoint3D(); } // // Constructor // /** * Private constructor. */ private ListPoint3DFactory() { } }
GenomicParisCentre/corsen
src/main/java/fr/ens/transcriptome/corsen/model/ListPoint3DFactory.java
Java
gpl-2.0
2,212
#include <QtGui/QApplication> #include "MainWindow.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); MainWindow mainPage; mainPage.show(); return app.exec(); }
MarcGrenier/PicModifier
Source/PicModifier/main.cpp
C++
gpl-2.0
185
 /** * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * This file was added automatically by CKEditor builder. * You may re-use it at any time at http://ckeditor.com/builder to build CKEditor again. * * NOTE: * This file is not used by CKEditor, you may remove it. * Changing this file will not change your CKEditor configuration. */ var CKBUILDER_CONFIG = { skin: 'moonocolor', preset: 'full', ignore: [ 'dev', '.gitignore', '.gitattributes', 'README.md', '.mailmap' ], plugins : { 'about' : 1, 'a11yhelp' : 1, 'dialogadvtab' : 1, 'basicstyles' : 1, 'bidi' : 1, 'blockquote' : 1, 'clipboard' : 1, 'colorbutton' : 1, 'colordialog' : 1, 'templates' : 1, 'contextmenu' : 1, 'div' : 1, 'resize' : 1, 'toolbar' : 1, 'elementspath' : 1, 'enterkey' : 1, 'entities' : 1, 'filebrowser' : 1, 'find' : 1, 'flash' : 1, 'floatingspace' : 1, 'font' : 1, 'forms' : 1, 'format' : 1, 'horizontalrule' : 1, 'htmlwriter' : 1, 'iframe' : 1, 'wysiwygarea' : 1, 'image' : 1, 'indentblock' : 1, 'indentlist' : 1, 'smiley' : 1, 'justify' : 1, 'language' : 1, 'link' : 1, 'list' : 1, 'liststyle' : 1, 'magicline' : 1, 'maximize' : 1, 'newpage' : 1, 'pagebreak' : 1, 'pastetext' : 1, 'pastefromword' : 1, 'preview' : 1, 'print' : 1, 'removeformat' : 1, 'save' : 1, 'selectall' : 1, 'showblocks' : 1, 'showborders' : 1, 'sourcearea' : 1, 'specialchar' : 1, 'scayt' : 1, 'stylescombo' : 1, 'tab' : 1, 'table' : 1, 'tabletools' : 1, 'undo' : 1, 'wsc' : 1, 'dialog' : 1, 'dialogui' : 1, 'panelbutton' : 1, 'button' : 1, 'floatpanel' : 1, 'panel' : 1, 'menu' : 1, 'popup' : 1, 'fakeobjects' : 1, 'richcombo' : 1, 'listblock' : 1, 'indent' : 1, 'menubutton' : 1, 'autogrow' : 1, 'lineutils' : 1, 'widget' : 1, 'placeholder' : 1, 'stylesheetparser' : 1 }, languages : { 'en' : 1, 'fr' : 1 } };
SecondBureau/refinerycms-activebackend
app/assets/javascripts/vendor/ckeditor/build-config.js
JavaScript
gpl-2.0
2,095
package com.nbcedu.function.schoolmaster2.tags; import com.nbcedu.function.schoolmaster2.data.vo.PersonVo; import com.nbcedu.function.schoolmaster2.tags.display.AbstractDisplayTag; import com.nbcedu.function.schoolmaster2.utils.Utils; @SuppressWarnings("serial") public class ShowWhenManager extends AbstractDisplayTag{ @Override protected boolean display() { for (PersonVo person : Utils.getAllManager()) { if(person.getUid().equalsIgnoreCase(Utils.curUserUid())){ return Boolean.TRUE; } } return Boolean.FALSE; } }
LuckyStars/nbc
function-schoolmaster2/java/function-schoolmaster2/src/main/com/nbcedu/function/schoolmaster2/tags/ShowWhenManager.java
Java
gpl-2.0
541
<?php /** * @version SVN: <svn_id> * @package Quick2cart * @author Techjoomla <extensions@techjoomla.com> * @copyright Copyright (c) 2009-2015 TechJoomla. All rights reserved. * @license GNU General Public License version 2 or later. */ // No direct access. defined('_JEXEC') or die(); // Load Quick2cart Controller for list views require_once __DIR__ . '/q2clist.php'; /** * Taxprofiles list controller class. * * @package Quick2cart * @subpackage com_quick2cart * @since 2.2 */ class Quick2cartControllerShipping extends Quick2cartControllerQ2clist { /** * constructor */ function __construct() { parent::__construct(); $this->set('suffix', 'shipping'); } function getShipView() { $app = JFactory::getApplication(); $qtcshiphelper = new qtcshiphelper; $comquick2cartHelper=new comquick2cartHelper; $plgActionRes = array(); $jinput = $app->input; $extension_id = $jinput->get('extension_id'); $plugview = $jinput->get('plugview'); // Plugin view is not found in URL then check in post array. if (empty($plugview)) { $plugview = $jinput->post->get('plugview'); } // If extension related view if (!empty($extension_id)) { // Task is not empty then then call plugin save handler //if (!empty($plugTask)) { $plugName = $qtcshiphelper->getPluginDetail($extension_id); // Call specific plugin trigger JPluginHelper::importPlugin('tjshipping', $plugName); $dispatcher = JDispatcher::getInstance(); $plgRes = $dispatcher->trigger('TjShip_plugActionkHandler', array($jinput)); if (!empty($plgRes)) { $plgActionRes = $plgRes[0]; } } } // Enque msg if (!empty($plgActionRes['statusMsg'])) { $app->enqueueMessage($plgActionRes['statusMsg']); } // Extra plugin Url params. if (!empty($plgActionRes['urlPramStr'])) { $plgUrlParam = '&' . $plgActionRes['urlPramStr']; } else { $plgUrlParam = '&plugview='; } //print" kasdflkjsdk $plgUrlParam"; die; $itemid = $comquick2cartHelper->getitemid('index.php?option=com_quick2cart&view=vendor&layout=cp'); $link = 'index.php?option=com_quick2cart&view=shipping&layout=list' . $plgUrlParam . '&extension_id=' . $extension_id . '&Itemid='.$itemid; $this->setRedirect(JRoute::_($link,false)); } /** * This function calls respective task on respective plugin */ function qtcHandleShipAjaxCall () { $plgActionRes = ''; $app=JFactory::getApplication(); $qtcshiphelper = new qtcshiphelper; $comquick2cartHelper=new comquick2cartHelper; $jinput = JFactory::getApplication()->input; $extension_id = $jinput->get('extension_id'); // Get plugin detail $plugName = $qtcshiphelper->getPluginDetail($extension_id); // Call specific plugin trigger JPluginHelper::importPlugin('tjshipping', $plugName); $dispatcher = JDispatcher::getInstance(); $plgRes = $dispatcher->trigger('TjShip_AjaxCallHandler', array($jinput)); if (!empty($plgRes)) { $plgActionRes = $plgRes[0]; } echo $plgActionRes; $app->close(); } }
BetterBetterBetter/B3App
administrator/components/com_quick2cart/controllers/shipping.php
PHP
gpl-2.0
3,064
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2012 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } */ #include "Look/AirspaceLook.hpp" #include "Screen/Layout.hpp" #include "Renderer/AirspaceRendererSettings.hpp" #include "resource.h" #include "Util/Macros.hpp" #ifdef USE_GDI #include "Screen/GDI/AlphaBlend.hpp" #endif const Color AirspaceLook::preset_colors[] = { COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN, DarkColor(COLOR_RED), DarkColor(COLOR_GREEN), DarkColor(COLOR_BLUE), DarkColor(COLOR_YELLOW), DarkColor(COLOR_MAGENTA), DarkColor(COLOR_CYAN), COLOR_WHITE, COLOR_LIGHT_GRAY, COLOR_GRAY, COLOR_BLACK, }; void AirspaceLook::Initialise(const AirspaceRendererSettings &settings) { for (unsigned i = 0; i < AIRSPACECLASSCOUNT; ++i) { const AirspaceClassRendererSettings &class_settings = settings.classes[i]; pens[i].Set(Layout::ScalePenWidth(class_settings.border_width), class_settings.color); #ifdef HAVE_ALPHA_BLEND if (AlphaBlendAvailable()) #endif #if defined(HAVE_ALPHA_BLEND) || !defined(HAVE_HATCHED_BRUSH) solid_brushes[i].Set(class_settings.color); #endif } // airspace brushes and colors #ifdef HAVE_HATCHED_BRUSH bitmaps[0].Load(IDB_AIRSPACE0); bitmaps[1].Load(IDB_AIRSPACE1); bitmaps[2].Load(IDB_AIRSPACE2); bitmaps[3].Load(IDB_AIRSPACE3); bitmaps[4].Load(IDB_AIRSPACE4); bitmaps[5].Load(IDB_AIRSPACE5); bitmaps[6].Load(IDB_AIRSPACE6); bitmaps[7].Load(IDB_AIRSPACE7); for (unsigned i = 0; i < ARRAY_SIZE(AirspaceLook::brushes); i++) brushes[i].Set(bitmaps[i]); #endif thick_pen.Set(Layout::ScalePenWidth(10), COLOR_BLACK); intercept_icon.Load(IDB_AIRSPACEI, IDB_AIRSPACEI_HD); }
aharrison24/XCSoar
src/Look/AirspaceLook.cpp
C++
gpl-2.0
2,534
import pyterpol import matplotlib.pyplot as plt wmin = 3600 wmax = 4100 sygri = pyterpol.SyntheticGrid(flux_type='absolute') params = dict(teff=9950, logg=3.7, z=1.0) spec1 = sygri.get_synthetic_spectrum(params, [wmin, wmax], order=4, step=0.1) params = dict(teff=10000, logg=3.5, z=1.0) spec2 = sygri.get_synthetic_spectrum(params, [wmin, wmax], order=4, step=0.1) params = dict(teff=10000, logg=4.0, z=1.0) spec3 = sygri.get_synthetic_spectrum(params, [wmin, wmax], order=4, step=0.1) ax = plt.subplot(111) spec1.plot(ax=ax) spec2.plot(ax=ax) spec3.plot(ax=ax) plt.show()
chrysante87/pyterpol
pyterpol_test/test_absolute_spectra/test.py
Python
gpl-2.0
575
<?php /** * Joomla! 1.5 component LISTBINGO * * @version $Id: view.html.php 2010-01-10 00:57:37 svn $ * @author gobingoo.com * @package Joomla * @subpackage LISTBINGO * @license GNU/GPL * * A classified ad component from gobingoo.com. * * @code Bruce * */ // no direct access defined ( '_JEXEC' ) or die ( 'Restricted access' ); gbimport ( "gobingoo.template" ); /** * HTML View class for the Listbingo component */ class ListbingoViewAds extends GTemplate { function display($tpl = null) { global $mainframe, $option, $listitemid; $country = 0; $region = 0; $user = JFactory::getUser (); $configmodel = gbimport ( "listbingo.model.configuration" ); $params = $configmodel->getParams (); $menus = & JSite::getMenu (); $menu = $menus->getActive (); $pathway = & $mainframe->getPathWay (); $query = "index.php?option=$option&task=ads&time=" . time () . "&Itemid=$listitemid"; $mainframe->setUserState ( "hereiam", base64_encode ( $query ) ); $countrymodel = gbimport ( "listbingo.model.country" ); $regionmodel = gbimport ( "listbingo.model.region" ); $country = $countrymodel->getCurrentCountry ( $params ); $region = $regionmodel->getCurrentRegion ( $params ); $countrytitle = $countrymodel->getCountryTitle ( $params ); $regiontitle = $regionmodel->getRegionTitle ( $params ); $forceads = $params->get ( 'force_ads', 0 ); if ($country != 0 && $region != 0) { gbimport ( "gobingoo.currency" ); $filter = new stdClass (); $catid = JRequest::getInt ( 'catid', 0 ); $filter->limit = JRequest::getInt ( 'limit', $params->get ( 'ads_per_page', 10 ) ); $filter->limitstart = JRequest::getInt ( 'limitstart', 0 ); $filter->category_id = $catid; $filter->searchtxt = JRequest::getVar ( 'q', '' ); $filter->alpha = JFilterOutput::cleanText ( substr ( JRequest::getVar ( 'alpha', '' ), 0, 6 ) ); $filter->checkExpiryDate = 1; $order = $mainframe->getUserStateFromRequest ( $option . 'adsfilter_order', 'order', $params->get ( 'layout_ordering' ), 'cmd' ); $filter->order_dir = $mainframe->getUserStateFromRequest ( $option . 'adsfilter_order_Dir', 'dir', '', 'word' ); $orderingtype = strtolower ( JFilterOutput::cleanText ( JRequest::getVar ( 'orderingtype', '' ) ) ); if (! empty ( $orderingtype )) { if ($orderingtype == "desc") { $orderingtype = "asc"; } else { $orderingtype = "desc"; } } else { $orderingtype = "desc"; } $filter->orderingtype = $orderingtype; switch ($order) { case 'latest' : $filter->order = "a.created_date $orderingtype"; break; case 'price' : $filter->order = "a.price $orderingtype"; break; default : $filter->order = "a.ordering $orderingtype"; break; } $model = gbimport ( "listbingo.model.ad" ); $filter->country = $country > 0 ? $country : 0; $filter->region = $region > 0 ? $region : 0; $filter->regiontitle = $regiontitle; $filter->expiry_days = $params->get ( 'expiry_days' ); $filter->access = ( int ) $user->get ( 'aid', 0 ); $filter->price_from = JRequest::getVar ( 'searchpricefrom', '' ); $filter->price_from = JRequest::getVar ( 'searchpriceto', '' ); $filter->params = $params; $rows = $model->getListWithInfobar ( true, $filter ); //Add searches to queue for futher navigation if (count ( $rows ) > 1) { gbimport ( "listbingo.searchqueue" ); $queue = new SearchQueue (); $queue->loadFromObjects ( $rows ); $queue->save (); } $total = $model->getListCountForSearch ( true, $filter ); jimport ( 'joomla.html.pagination' ); $pagenav = new JPagination ( $total, $filter->limitstart, $filter->limit ); /* * shows category lists */ $catfilter = new stdClass (); $catfilter->order = $mainframe->getUserStateFromRequest ( $option . 'listfilter_order', 'order', 'c.title', 'cmd' ); $catfilter->order_dir = $mainframe->getUserStateFromRequest ( $option . 'listfilter_order_Dir', 'dir', '', 'word' ); $catfilter->country = $country; $catfilter->region = $region; $catfilter->countrytitle = $countrytitle; $catfilter->regiontitle = $regiontitle; $catfilter->catid = $catid; $catfilter->access = ( int ) $user->get ( 'aid', 0 ); $catmodel = gbimport ( "listbingo.model.category" ); $childcategories = $catmodel->getListForProduct ( true, $catfilter ); if (! is_array ( $childcategories )) { $childcategories = array ($childcategories ); } $category = $model->load ( $catid ); if (is_object ( $menu )) { $menu_params = new JParameter ( $menu->params ); if (! $menu_params->get ( 'page_title' )) { if ($category) { $params->set ( 'page_title', $category->title ); } else { $params->set ( 'page_title', JText::_ ( "CATEGORY" ) ); } } } else { if ($category) { $params->set ( 'page_title', $category->title ); } else { $params->set ( 'page_title', JText::_ ( "CATEGORY" ) ); } } /** * Work on Pathways here */ /*if ($category) { $parents = $catmodel->getParentlist ( $catid ); for($p = 0; $p < count ( $parents ); $p ++) { // Do not add the above and root categories when coming from a directory view $pathway->addItem ( $this->escape ( $parents [$p]->title ), JRoute::_ ( 'index.php?option=' . $option . '&task=categories&catid=' . $parents [$p]->categoryslug ) ); } }*/ /* * shows related category lists */ $relatedtable = & JTable::getInstance ( 'relatedcategory' ); $relatedtable->id = $catid; $relatedcat = $relatedtable->getRelatedCategoryLists (); $db = JFactory::getDBO (); $nulldate = $db->getNullDate (); $userid = $user->get ( 'id' ); $document = & JFactory::getDocument (); if (isset ( $childcategories [0] ) && $catid) { $document->setTitle ( html_entity_decode ( $childcategories [0]->title ) ); $document->setMetadata ( 'keywords', html_entity_decode ( $childcategories [0]->title ) ); $desc = GHelper::trunchtml ( trim ( strip_tags ( html_entity_decode ( $childcategories [0]->description ) ) ), 200 ); } if (isset ( $rows ) && count ( $rows ) > 0) { foreach ( $rows as &$row ) { $row->title = JFilterOutput::cleanText ( $row->title ); $row->id = JFilterOutput::cleanText ( $row->id ); $row->address1 = JFilterOutput::cleanText ( $row->address1 ); $row->address2 = JFilterOutput::cleanText ( $row->address2 ); $row->price = JFilterOutput::cleanText ( $row->price ); } } JFilterOutput::objectHTMLSafe ( $pagenav ); JFilterOutput::objectHTMLSafe ( $filter ); JFilterOutput::objectHTMLSafe ( $params ); JFilterOutput::objectHTMLSafe ( $indcount ); JFilterOutput::objectHTMLSafe ( $childcategories ); JFilterOutput::objectHTMLSafe ( $relatedcat ); JFilterOutput::objectHTMLSafe ( $user ); GApplication::triggerEvent ( 'onBeforeListDisplay', array (&$rows, &$params ) ); if (empty ( $filter->searchtxt )) { $filter->searchtxt = JText::_ ( 'ALL' ); } $menus = &JSite::getMenu (); $menu = $menus->getActive (); $menu_params = new JParameter ( $menu->params ); if ($menu_params && $menu_params->get('list_layout')!="") { $params->set ( 'default_listing_layout', $menu_params->get ( 'list_layout' ) ); } $this->assignRef ( 'rows', $rows ); $this->assignRef ( 'pagination', $pagenav ); $this->assignRef ( 'filter', $filter ); $this->assignRef ( 'params', $params ); $this->assignRef ( 'indcount', $indcount ); $this->assignRef ( 'categories', $childcategories ); $this->assignRef ( 'relatedcat', $relatedcat ); $this->assign ( 'user', $user ); $this->assign ( 'userid', $userid ); $this->assign ( 'guest', $user->guest ); $this->assign ( 'nulldate', $nulldate ); parent::display ( $tpl ); GApplication::triggerEvent ( 'onAfterListDisplay', array (&$rows, &$params ) ); } else { $redirlink = JRoute::_ ( "index.php?option=$option&task=regions&Itemid=$listitemid&time=" . time (), false ); GApplication::redirect ( $redirlink ); } } function searchDisplay($tpl = null) { parent::display ( $tpl ); } function customDisplay($tpl = null) { parent::display ( $tpl ); } } ?>
ger4003/int14_ger_joomla
components/com_listbingo/views/ads/view.html.php
PHP
gpl-2.0
8,466
package helpers import ( "encoding/json" "fmt" "io/ioutil" "log" "strconv" "sync/atomic" "time" "application/libraries/toml" "github.com/coreos/etcd/clientv3" "github.com/garyburd/redigo/redis" _ "github.com/go-sql-driver/mysql" "github.com/go-xorm/xorm" "gopkg.in/mgo.v2" ) func AnyTypeInt(sint interface{}) (ret int) { switch sint.(type) { case string: ret, _ = strconv.Atoi(sint.(string)) break case int: ret = sint.(int) break case int64: ret = int(sint.(int64)) break } return } func LoadFile(filename string) (filedata string, err error) { fileDataByte, err := ioutil.ReadFile(filename) if err != nil { fmt.Println("Read failed", err) return } filedata = string(fileDataByte) return } func MongoDail(mongoconfig toml.DBConfig) *mgo.Session { mgoUrl := fmt.Sprintf("%s:%s@%s", mongoconfig.User, mongoconfig.Password, mongoconfig.Host) session, err := mgo.Dial(mgoUrl) if err != nil { panic(err) } //defer session.Close() // Optional. Switch the session to a monotonic behavior. session.SetMode(mgo.Monotonic, true) return session } func RedisDail(redisconfig toml.DBConfig) redis.Conn { redisClient, err := redis.Dial("tcp", fmt.Sprintf("%s:%d", redisconfig.Host, redisconfig.Port)) if err != nil { panic(err) } redisClient.Do("AUTH", redisconfig.Password) return redisClient } func MysqlDail(mysqlconfig toml.DBConfig) *xorm.Engine { db, err := xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", mysqlconfig.User, mysqlconfig.Password, mysqlconfig.Host, mysqlconfig.Port, mysqlconfig.DBname)) if err != nil { panic(err) } return db } func MysqlDailName(mysqlconfig toml.DBConfig, dbName string) *xorm.Engine { db, err := xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", mysqlconfig.User, mysqlconfig.Password, mysqlconfig.Host, mysqlconfig.Port, dbName)) if err != nil { panic(err) } return db } func EtcdDail(etcdconfig toml.DBConfig) *clientv3.Client { cfg := clientv3.Config{ Endpoints: []string{etcdconfig.Host}, //Transport: client.DefaultTransport, DialTimeout: 5 * time.Second, } c, err := clientv3.New(cfg) if err != nil { log.Fatal(err) } return c } func Pack(v interface{}) (string, error) { data, err := json.Marshal(v) return string(data), err } func UnPack(data []byte, v interface{}) error { return json.Unmarshal(data, v) } func snakeCasedName(name string) string { newstr := make([]rune, 0) for idx, chr := range name { if isUpper := 'A' <= chr && chr <= 'Z'; isUpper { if idx > 0 { newstr = append(newstr, '_') } chr -= ('A' - 'a') } newstr = append(newstr, chr) } return string(newstr) } //计算64位int中1的位数 func BitCount(i uint64) int { i = i - ((i >> 1) & 0x5555555555555555) i = (i & 0x3333333333333333) + ((i >> 2) & 0x3333333333333333) return int((((i + (i >> 4)) & 0xF0F0F0F0F0F0F0F) * 0x101010101010101) >> 56) } func GenDayIncrId(filed string) int { day := time.Now().Format("20060102") key := "$:dayincr" + day num, _ := GlobalRedis.HIncrBy(key, filed, 1) //为key设置过期时间 //GlobalRedis.Conn.Do("EXPIREAT", time.Now().Add(86400*time.Second).Unix()) //GlobalRedis.Conn.Do("EXPIRE", 86400) return int(num) } var innerId int32 = 49999999 func GenInnerIncrId() int { num := atomic.AddInt32(&innerId, 1) return int(num) } func GenIncrId(filed string) int { key := "$:incr" num, _ := GlobalRedis.HIncrBy(key, filed, 1) //为key设置过期时间 //GlobalRedis.Conn.Do("EXPIREAT", time.Now().Add(86400*time.Second).Unix()) return int(num) }
beck917/pillX
src/application/libraries/helpers/utils.go
GO
gpl-2.0
3,555
<?php /** * Register all actions and filters for the plugin * * @link http://www.blogfoster.com/ * @since 1.0.0 * * @package Blogfoster_Insights * @subpackage Blogfoster_Insights/includes */ /** * Register all actions and filters for the plugin. * * Maintain a list of all hooks that are registered throughout * the plugin, and register them with the WordPress API. Call the * run function to execute the list of actions and filters. * * @package Blogfoster_Insights * @subpackage Blogfoster_Insights/includes */ class Blogfoster_Insights_Loader { /** * The array of actions registered with WordPress. * * @since 1.0.0 * @access protected * @var array $actions The actions registered with WordPress to fire when the plugin loads. */ protected $actions; /** * The array of filters registered with WordPress. * * @since 1.0.0 * @access protected * @var array $filters The filters registered with WordPress to fire when the plugin loads. */ protected $filters; /** * Initialize the collections used to maintain the actions and filters. * * @since 1.0.0 */ public function __construct() { $this->actions = array(); $this->filters = array(); } /** * Add a new action to the collection to be registered with WordPress. * * @since 1.0.0 * @param string $hook The name of the WordPress action that is being registered. * @param object $component A reference to the instance of the object on which the action is defined. * @param string $callback The name of the function definition on the $component. * @param int $priority Optional. he priority at which the function should be fired. Default is 10. * @param int $accepted_args Optional. The number of arguments that should be passed to the $callback. Default is 1. */ public function add_action( $hook, $component, $callback, $priority = 10, $accepted_args = 1 ) { $this->actions = $this->add( $this->actions, $hook, $component, $callback, $priority, $accepted_args ); } /** * Add a new filter to the collection to be registered with WordPress. * * @since 1.0.0 * @param string $hook The name of the WordPress filter that is being registered. * @param object $component A reference to the instance of the object on which the filter is defined. * @param string $callback The name of the function definition on the $component. * @param int $priority Optional. he priority at which the function should be fired. Default is 10. * @param int $accepted_args Optional. The number of arguments that should be passed to the $callback. Default is 1 */ public function add_filter( $hook, $component, $callback, $priority = 10, $accepted_args = 1 ) { $this->filters = $this->add( $this->filters, $hook, $component, $callback, $priority, $accepted_args ); } /** * A utility function that is used to register the actions and hooks into a single * collection. * * @since 1.0.0 * @access private * @param array $hooks The collection of hooks that is being registered (that is, actions or filters). * @param string $hook The name of the WordPress filter that is being registered. * @param object $component A reference to the instance of the object on which the filter is defined. * @param string $callback The name of the function definition on the $component. * @param int $priority The priority at which the function should be fired. * @param int $accepted_args The number of arguments that should be passed to the $callback. * @return array The collection of actions and filters registered with WordPress. */ private function add( $hooks, $hook, $component, $callback, $priority, $accepted_args ) { $hooks[] = array( 'hook' => $hook, 'component' => $component, 'callback' => $callback, 'priority' => $priority, 'accepted_args' => $accepted_args ); return $hooks; } /** * Register the filters and actions with WordPress. * * @since 1.0.0 */ public function run() { foreach ( $this->filters as $hook ) { add_filter( $hook['hook'], array( $hook['component'], $hook['callback'] ), $hook['priority'], $hook['accepted_args'] ); } foreach ( $this->actions as $hook ) { add_action( $hook['hook'], array( $hook['component'], $hook['callback'] ), $hook['priority'], $hook['accepted_args'] ); } } }
FlorianTopf/pixie
wp-content/plugins/wp-blogfoster-insights/includes/class-wp-blogfoster-insights-loader.php
PHP
gpl-2.0
4,970
<?php /* Plugin Name: Shortcodes Ultimate Plugin URI: http://shortcodes-ultimate.com/ Version: 3.9.5 Author: Vladimir Anokhin Author URI: http://gndev.info/ Description: Provides support for many easy to use shortcodes Text Domain: shortcodes-ultimate Domain Path: /languages License: GPL2 */ // Load libs require_once 'lib/available.php'; require_once 'lib/admin.php'; require_once 'lib/color.php'; require_once 'lib/csv.php'; require_once 'lib/media.php'; require_once 'lib/twitter.php'; require_once 'lib/images.php'; require_once 'lib/shortcodes.php'; require_once 'lib/widget.php'; /** * Plugin initialization */ function su_plugin_init() { // Make plugin available for translation load_plugin_textdomain( 'shortcodes-ultimate', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' ); // Enable shortcodes in text widgets add_filter( 'widget_text', 'do_shortcode' ); // Register styles wp_register_style( 'shortcodes-ultimate', su_plugin_url() . '/css/style.css', false, 'all' ); wp_register_style( 'shortcodes-ultimate-admin', su_plugin_url() . '/css/admin.css', false, 'all' ); wp_register_style( 'shortcodes-ultimate-generator', su_plugin_url() . '/css/generator.css', false, 'all' ); wp_register_style( 'codemirror', su_plugin_url() . '/css/codemirror.css', false, 'all' ); wp_register_style( 'codemirror-css', su_plugin_url() . '/css/codemirror-css.css', false, 'all' ); wp_register_style( 'chosen', su_plugin_url() . '/css/chosen.css', false, 'all' ); // Register scripts wp_register_script( 'shortcodes-ultimate', su_plugin_url() . '/js/init.js', array( 'jquery' ), false ); wp_register_script( 'shortcodes-ultimate-admin', su_plugin_url() . '/js/admin.js', array( 'jquery' ), false ); wp_register_script( 'shortcodes-ultimate-generator', su_plugin_url() . '/js/generator.js', array( 'jquery' ), false ); wp_register_script( 'codemirror', su_plugin_url() . '/js/codemirror.js', false, false ); wp_register_script( 'codemirror-css', su_plugin_url() . '/js/codemirror-css.js', false, false ); wp_register_script( 'chosen', su_plugin_url() . '/js/chosen.js', false, false ); wp_register_script( 'ajax-form', su_plugin_url() . '/js/jquery.form.js', false, false ); wp_register_script( 'jwplayer', su_plugin_url() . '/js/jwplayer.js', false, false ); // Front-end scripts and styles if ( !is_admin() ) { $disabled_scripts = get_option( 'su_disabled_scripts' ); $disabled_styles = get_option( 'su_disabled_styles' ); if ( !isset( $disabled_styles['style'] ) ) { wp_enqueue_style( 'shortcodes-ultimate' ); } // Enqueue scripts if ( !isset( $disabled_scripts['jwplayer'] ) ) { wp_enqueue_script( 'jwplayer' ); } if ( !isset( $disabled_scripts['init'] ) ) { wp_enqueue_script( 'shortcodes-ultimate' ); } } // Back-end scripts and styles elseif ( isset( $_GET['page'] ) && $_GET['page'] == 'shortcodes-ultimate' ) { // Enqueue styles wp_enqueue_style( 'codemirror' ); wp_enqueue_style( 'codemirror-css' ); wp_enqueue_style( 'shortcodes-ultimate-admin' ); // Enqueue scripts wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'codemirror' ); wp_enqueue_script( 'codemirror-css' ); wp_enqueue_script( 'ajax-form' ); wp_enqueue_script( 'shortcodes-ultimate-admin' ); } // Scripts and stylesheets for editing pages (shortcode generator popup) elseif ( is_admin() ) { // Get current page type global $pagenow; // Pages for including $su_generator_includes_pages = array( 'post.php', 'edit.php', 'post-new.php', 'index.php', 'edit-tags.php', 'widgets.php' ); if ( in_array( $pagenow, $su_generator_includes_pages ) ) { // Enqueue styles wp_enqueue_style( 'farbtastic' ); wp_enqueue_style( 'chosen' ); wp_enqueue_style( 'shortcodes-ultimate-generator' ); // Enqueue scripts wp_enqueue_script( 'farbtastic' ); wp_enqueue_script( 'chosen' ); wp_enqueue_script( 'shortcodes-ultimate-generator' ); } } // Register shortcodes foreach ( su_shortcodes() as $shortcode => $params ) { if ( $params['type'] != 'opengroup' && $params['type'] != 'closegroup' ) add_shortcode( su_compatibility_mode_prefix() . $shortcode, 'su_' . $shortcode . '_shortcode' ); } } add_action( 'init', 'su_plugin_init' ); /** * Returns current plugin url * * @return string Plugin url */ function su_plugin_url() { return get_template_directory_uri() .'/lib/shortcodes-ultimate/'; } /** * Shortcode names prefix in compatibility mode * * @return string Special prefix */ function su_compatibility_mode_prefix() { $prefix = ( get_option( 'su_compatibility_mode' ) == 'on' ) ? 'gn_' : ''; return $prefix; } /** * Hook to translate plugin information */ function su_add_locale_strings() { $strings = __( 'Shortcodes Ultimate', 'shortcodes-ultimate' ) . __( 'Vladimir Anokhin', 'shortcodes-ultimate' ) . __( 'Provides support for many easy to use shortcodes', 'shortcodes-ultimate' ); } /* * Custom shortcode function for nested shortcodes support */ function su_do_shortcode( $content, $modifier ) { if ( strpos( $content, '[_' ) !== false ) { $content = preg_replace( '@(\[_*)_(' . $modifier . '|/)@', "$1$2", $content ); } return do_shortcode( $content ); } /** * Print custom CSS styles in wp_head * * @return string Custom CSS */ function su_print_custom_css() { if ( get_option( 'su_custom_css' ) ) { echo "\n<!-- Shortcodes Ultimate custom CSS - begin -->\n<style type='text/css'>\n" . str_replace( '%theme%', get_template_directory_uri(), get_option( 'su_custom_css' ) ) . "\n</style>\n<!-- Shortcodes Ultimate custom CSS - end -->\n\n"; } } add_action( 'wp_head', 'su_print_custom_css' ); /** * Manage settings */ function su_manage_settings() { // Insert default CSS if ( !get_option( 'su_custom_css' ) ) { $default_css = ''; update_option( 'su_custom_css', $default_css ); } // Save main settings if ( isset( $_POST['save'] ) && (isset($_GET['page'])) == 'shortcodes-ultimate' ) { update_option( 'su_disable_custom_formatting', $_POST['su_disable_custom_formatting'] ); update_option( 'su_compatibility_mode', $_POST['su_compatibility_mode'] ); update_option( 'su_disabled_scripts', $_POST['su_disabled_scripts'] ); update_option( 'su_disabled_styles', $_POST['su_disabled_styles'] ); } // Save custom css if ( isset( $_POST['save-css'] ) && $_GET['page'] == 'shortcodes-ultimate' ) { update_option( 'su_custom_css', $_POST['su_custom_css'] ); } } add_action( 'admin_init', 'su_manage_settings' ); /** * Add settings link to plugins dashboard * * @param array $links Links * @return array Links */ function su_add_settings_link( $links ) { $links[] = '<a href="' . admin_url( 'options-general.php?page=shortcodes-ultimate' ) . '">' . __( 'Settings', 'shortcodes-ultimate' ) . '</a>'; $links[] = '<a href="' . admin_url( 'options-general.php?page=shortcodes-ultimate#tab-3' ) . '">' . __( 'Docs', 'shortcodes-ultimate' ) . '</a>'; return $links; } add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), 'su_add_settings_link', -10 ); /** * Print notification if options saved */ function su_save_notification() { // Save main settings if ( isset( $_POST['save'] ) && $_GET['page'] == 'shortcodes-ultimate' ) { echo '<div class="updated"><p><strong>' . __( 'Settings saved', 'shortcodes-ultimate' ) . '</strong></p></div>'; } // Save custom css if ( isset( $_POST['save-css'] ) && $_GET['page'] == 'shortcodes-ultimate' ) { echo '<div class="updated"><p><strong>' . __( 'Custom CSS saved', 'shortcodes-ultimate' ) . '</strong></p></div>'; } } /** * Add generator button to Upload/Insert buttons */ function su_add_generator_button( $page = null, $target = null ) { echo '<a href="#TB_inline?width=640&height=600&inlineId=su-generator-wrap" class="thickbox" title="' . __( 'Insert shortcode', 'shortcodes-ultimate' ) . '" data-page="' . $page . '" data-target="' . $target . '"><img src="' . su_plugin_url() . '/images/admin/media-icon.png" alt="" /></a>'; } add_action( 'media_buttons', 'su_add_generator_button', 100 ); /** * Generator popup box */ function su_generator_popup() { ?> <div id="su-generator-wrap" style="display:none"> <div id="su-generator"> <div id="su-generator-shell"> <div id="su-generator-header"> <select id="su-generator-select" data-placeholder="<?php _e( 'Select shortcode', 'shortcodes-ultimate' ); ?>" data-no-results-text="<?php _e( 'Shortcode not found', 'shortcodes-ultimate' ); ?>"> <option value="raw"></option> <?php foreach ( su_shortcodes() as $name => $shortcode ) { // Open optgroup if ( $shortcode['type'] == 'opengroup' ) echo '<optgroup label="' . $shortcode['name'] . '">'; // Close optgroup elseif ( $shortcode['type'] == 'closegroup' ) echo '</optgroup>'; // Option else echo '<option value="' . $name . '">' . strtoupper( $name ) . ':&nbsp;&nbsp;' . $shortcode['desc'] . '</option>'; } ?> </select> <div id="su-generator-tools"> <a href="<?php echo admin_url( 'options-general.php?page=shortcodes-ultimate' ); ?>" target="_blank" title="<?php _e( 'Settings', 'shortcodes-ultimate' ); ?>"><?php _e( 'Settings', 'shortcodes-ultimate' ); ?></a> </div> </div> <div id="su-generator-settings"></div> <input type="hidden" name="su-generator-url" id="su-generator-url" value="<?php echo su_plugin_url(); ?>" /> <input type="hidden" name="su-compatibility-mode-prefix" id="su-compatibility-mode-prefix" value="<?php echo su_compatibility_mode_prefix(); ?>" /> </div> </div> </div> <?php } add_action( 'admin_footer', 'su_generator_popup' ); ?>
b00y0h/reverse-cumi
lib/shortcodes-ultimate/shortcodes-ultimate.php
PHP
gpl-2.0
10,198
/**************************************************************** * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) * ============================================================= * License Information: http://lamsfoundation.org/licensing/lams/2.0/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2.0 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA * * http://www.gnu.org/licenses/gpl.txt * **************************************************************** */ package org.lamsfoundation.lams.learningdesign; /** * Null activity object. * * @author dgarth */ public class NullActivity extends Activity { /** * @see org.lamsfoundation.lams.util.Nullable#isNull() */ @Override public boolean isNull() { return true; } /** * Create a deep copy of the this activity. It should return the same * subclass as the activity being copied * * @return deep copy of this object */ @Override public Activity createCopy(int uiidOffset) { return new NullActivity(); } }
lamsfoundation/lams
lams_common/src/java/org/lamsfoundation/lams/learningdesign/NullActivity.java
Java
gpl-2.0
1,614
#!/usr/bin/env python # -*- coding: <utf-8> -*- """ This file is part of Spartacus project Copyright (C) 2016 CSE This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ from Configuration.Configuration import MEMORY_START_AT __author__ = "CSE" __copyright__ = "Copyright 2015, CSE" __credits__ = ["CSE"] __license__ = "GPL" __version__ = "2.0" __maintainer__ = "CSE" __status__ = "Dev" DEFAULT_LOAD_ADDRESS = MEMORY_START_AT UNDEFINED = "&&undefined&&"
CommunicationsSecurityEstablishment/spartacus
ToolChain/Linker/Constants.py
Python
gpl-2.0
1,090
package ie.ucd.srg.koa.esb.beans; import ie.ucd.srg.ejs.container.*; /** * EJSCMPDecryptedesbHomeBean * @generated */ public class EJSCMPDecryptedesbHomeBean extends EJSHome { /** * EJSCMPDecryptedesbHomeBean * @generated */ public EJSCMPDecryptedesbHomeBean() throws java.rmi.RemoteException { super(); } /** * findByPrimaryKey * @generated */ public ie.ucd.srg.koa.esb.beans.Decryptedesb findByPrimaryKey(ie.ucd.srg.koa.esb.beans.DecryptedesbKey primaryKey) throws javax.ejb.FinderException, java.rmi.RemoteException { return ((ie.ucd.srg.koa.esb.beans.EJSJDBCPersisterCMPDecryptedesbBean) persister).findByPrimaryKey(primaryKey); } /** * create * @generated */ public ie.ucd.srg.koa.esb.beans.Decryptedesb create(java.math.BigDecimal stemnummer, java.lang.String sKandidaatCode, java.lang.String sKieskringnummer, java.lang.String sDistrictnummer, java.lang.String sKieslijstnummer, java.lang.String sPositienummer, java.lang.String sLijstnaam, java.lang.String sAchternaam, java.lang.String sVoorletters) throws javax.ejb.CreateException, java.rmi.RemoteException { BeanO beanO = null; ie.ucd.srg.koa.esb.beans.Decryptedesb _EJS_result = null; boolean createFailed = false; try { beanO = super.createBeanO(); ie.ucd.srg.koa.esb.beans.DecryptedesbBean bean = (ie.ucd.srg.koa.esb.beans.DecryptedesbBean) beanO.getEnterpriseBean(); bean.ejbCreate(stemnummer, sKandidaatCode, sKieskringnummer, sDistrictnummer, sKieslijstnummer, sPositienummer, sLijstnaam, sAchternaam, sVoorletters); _EJS_result = (ie.ucd.srg.koa.esb.beans.Decryptedesb) super.postCreate(beanO, keyFromBean(bean)); bean.ejbPostCreate(stemnummer, sKandidaatCode, sKieskringnummer, sDistrictnummer, sKieslijstnummer, sPositienummer, sLijstnaam, sAchternaam, sVoorletters); } catch (javax.ejb.CreateException ex) { createFailed = true; throw ex; } catch (java.rmi.RemoteException ex) { createFailed = true; throw ex; } catch (Throwable ex) { createFailed = true; throw new CreateFailureException(ex); } finally { if (createFailed) { super.createFailure(beanO); } } return _EJS_result; } /** * create * @generated */ public ie.ucd.srg.koa.esb.beans.Decryptedesb create(java.math.BigDecimal stemnummer) throws javax.ejb.CreateException, java.rmi.RemoteException { BeanO beanO = null; ie.ucd.srg.koa.esb.beans.Decryptedesb _EJS_result = null; boolean createFailed = false; try { beanO = super.createBeanO(); ie.ucd.srg.koa.esb.beans.DecryptedesbBean bean = (ie.ucd.srg.koa.esb.beans.DecryptedesbBean) beanO.getEnterpriseBean(); bean.ejbCreate(stemnummer); _EJS_result = (ie.ucd.srg.koa.esb.beans.Decryptedesb) super.postCreate(beanO, keyFromBean(bean)); bean.ejbPostCreate(stemnummer); } catch (javax.ejb.CreateException ex) { createFailed = true; throw ex; } catch (java.rmi.RemoteException ex) { createFailed = true; throw ex; } catch (Throwable ex) { createFailed = true; throw new CreateFailureException(ex); } finally { if (createFailed) { super.createFailure(beanO); } } return _EJS_result; } /** * findByLijstpositie * @generated */ public ie.ucd.srg.koa.esb.beans.Decryptedesb findByLijstpositie(java.lang.String sKieskringnummer, java.lang.String sKieslijstnummer, java.lang.String sPositienummer) throws javax.ejb.FinderException, java.rmi.RemoteException { return ((ie.ucd.srg.koa.esb.beans.EJSJDBCPersisterCMPDecryptedesbBean)persister).findByLijstpositie(sKieskringnummer, sKieslijstnummer, sPositienummer); } /** * keyFromBean * @generated */ public Object keyFromBean(javax.ejb.EntityBean generalEJB) { ie.ucd.srg.koa.esb.beans.DecryptedesbBean tmpEJB = (ie.ucd.srg.koa.esb.beans.DecryptedesbBean) generalEJB; ie.ucd.srg.koa.esb.beans.DecryptedesbKey keyClass = new ie.ucd.srg.koa.esb.beans.DecryptedesbKey(); keyClass.stemnummer = tmpEJB.stemnummer; return keyClass; } /** * keyFromFields * @generated */ public ie.ucd.srg.koa.esb.beans.DecryptedesbKey keyFromFields(java.math.BigDecimal f0) { ie.ucd.srg.koa.esb.beans.DecryptedesbKey keyClass = new ie.ucd.srg.koa.esb.beans.DecryptedesbKey(); keyClass.stemnummer = f0; return keyClass; } }
GaloisInc/KOA
infrastructure/source/WebVotingSystem/src/ie/ucd/srg/koa/esb/beans/EJSCMPDecryptedesbHomeBean.java
Java
gpl-2.0
4,232
<?php /* * Phake - Mocking Framework * * Copyright (c) 2010-2012, Mike Lively <m@digitalsandwich.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Mike Lively nor the names of his * 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. * * @category Testing * @package Phake * @author Mike Lively <m@digitalsandwich.com> * @copyright 2010 Mike Lively <m@digitalsandwich.com> * @license http://www.opensource.org/licenses/bsd-license.php BSD License * @link http://www.digitalsandwich.com/ */ require_once 'Phake/Proxies/AnswerBinderProxy.php'; require_once 'Phake/Stubber/AnswerBinder.php'; /** * Description of AnswerBinderProxyTest * * @author Mike Lively <m@digitalsandwich.com> */ class Phake_Proxies_AnswerBinderProxyTest extends PHPUnit_Framework_TestCase { /** * @var Phake_Proxies_AnswerBinderProxy */ private $proxy; /** * @var Phake_Stubber_AnswerBinder */ private $binder; /** * Sets up the test fixture */ public function setUp() { $this->binder = $this->getMock('Phake_Stubber_AnswerBinder', array(), array(), '', FALSE); $this->proxy = new Phake_Proxies_AnswerBinderProxy($this->binder); } /** * Tests the thenReturn functionality of the proxy. * * It should result in the binder being called with a static answer. * * @todo we need argument capturing so I can make sure the answer matches. */ public function testThenReturn() { $this->binder->expects($this->once()) ->method('bindAnswer') ->with($this->logicalAnd($this->isInstanceOf('Phake_Stubber_Answers_StaticAnswer'), $this->attributeEqualTo('answer', 42))) ->will($this->returnValue($this->binder)); $this->assertSame($this->binder, $this->proxy->thenReturn(42)); } /** * Tests the thenGetReturnByLambda functionality of the proxy * * It should result in the binder being called with a lambda answer */ public function testThenGetReturnByLambda() { $func = create_function('$arg1', 'return $arg1;'); $this->binder->expects($this->once()) ->method('bindAnswer') ->with($this->logicalAnd($this->isInstanceOf('Phake_Stubber_Answers_LambdaAnswer'), $this->attributeEqualTo('answerLambda', $func))) ->will($this->returnValue($this->binder)); $this->assertSame($this->binder, $this->proxy->thenGetReturnByLambda($func)); } /** * Tests that thenGetReturnByLambda throws an exception if the given lambda is not callable */ public function testThenGetReturnByLambdaThrowsExceptionForUncallableLambda() { $this->setExpectedException('InvalidArgumentException'); $func = 'some_unknown_function'; $this->proxy->thenGetReturnByLambda($func); } /** * Tests the thenCallParent functionality of the proxy */ public function testThenCallParent() { $this->binder->expects($this->once()) ->method('bindAnswer') ->with($this->isInstanceOf('Phake_Stubber_Answers_ParentDelegate')) ->will($this->returnValue($this->binder)); $this->assertSame($this->binder, $this->proxy->thenCallParent()); } /** * Tests that captureReturnTo does it's thing */ public function testCaptureReturnTo() { $this->binder->expects($this->once()) ->method('bindAnswer') ->with($this->isInstanceOf('Phake_Stubber_Answers_ParentDelegate')) ->will($this->returnValue($this->binder)); $this->assertSame($this->binder, $this->proxy->captureReturnTo($var)); } /** * Tests the thenThrow functionality of the proxy. */ public function testThenThrow() { $exception = new RuntimeException(); $this->binder->expects($this->once()) ->method('bindAnswer') ->with($this->logicalAnd($this->isInstanceOf('Phake_Stubber_Answers_ExceptionAnswer'), $this->attributeEqualTo('answer', $exception))) ->will($this->returnValue($this->binder)); $this->assertSame($this->binder, $this->proxy->thenThrow($exception)); } } ?>
hosniah/Trias
utils/php-lcs-develop/vendor/phake/phake/tests/Phake/Proxies/AnswerBinderProxyTest.php
PHP
gpl-2.0
5,293
// { dg-do compile } // 2007-09-20 Benjamin Kosnik <bkoz@redhat.com> // Copyright (C) 2007 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 2, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING. If not, write to the Free // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, // USA. // As a special exception, you may use this file as part of a free software // library without restriction. Specifically, if other files instantiate // templates or use macros or inline functions from this file, or you compile // this file and link it with other files to produce an executable, this // file does not by itself cause the resulting executable to be covered by // the GNU General Public License. This exception does not however // invalidate any other reasons why the executable file might be covered by // the GNU General Public License. #include <algorithm> #include <testsuite_api.h> namespace std { using __gnu_test::NonDefaultConstructible; typedef NonDefaultConstructible value_type; typedef value_type* iterator_type; template iterator_type remove_copy(iterator_type, iterator_type, iterator_type, const value_type&); }
epicsdeb/rtems-gcc-newlib
libstdc++-v3/testsuite/25_algorithms/remove_copy/requirements/explicit_instantiation/2.cc
C++
gpl-2.0
1,767
<?php /* Template Name: Home Page */ /** * The template for displaying all pages. * * This is the template that displays all pages by default. * Please note that this is the WordPress construct of pages * and that other 'pages' on your WordPress site will use a * different template. * * @package _s * @since _s 1.0 */ get_header(); ?> <div id="primary" class="site-content span12 full-width"> <div id="content" role="main"> <div class="row-fluid entry-content"> <div class="span12"> <?php while ( have_posts() ) : the_post(); ?> <?php the_content(); ?> <?php endwhile; // end of the loop. ?> </div> </div> <div class="row-fluid"> <div class="span7"> <h2>Lastest posts from my blogs</h2> <?php wprss_display_feed_items( $args = array( 'links_before' => '<ul class="post-list">', 'links_after' => '</ul>', 'link_before' => '<li class="clearfix">', 'link_after' => '</li>', )); ?> </div> <div class="span4 offset1"> <?php echo do_shortcode('[twitter-widget username="julienbourdeau" before_widget="<div class=\'widget_twitter\'>" after_widget="</div>" before_title="<h3>" after_title="</h3>" errmsg="Uh oh!" hiderss="true" hidereplies="true" targetBlank="true" items="3" showts="259200" showintents="false" showfollow="true"]Lastest from Twitter[/twitter-widget]'); ?> </div> </div> </div><!-- #content --> </div><!-- #primary .site-content --> <?php get_footer(); ?>
julienbourdeau/sigerr-theme
page-home.php
PHP
gpl-2.0
1,576
#include <iostream> #include <algorithm> #include <cmath> using namespace std; const int MAXM = 10001; int f[MAXM], n, m, v; int main() { cin >> n >> m; int i, j; for(i = 1; i <= n; i++) { cin >> v; for(j = m; j >= v; j--) f[j] = max(f[j], f[j-v]+v); } cout << "answer:" << abs(m - f[m]); return 0; }
iwtwiioi/OnlineJudge
wikioi/Run_325977_Score_0_Date_2013-10-29.cpp
C++
gpl-2.0
334
<?php // +-------------------------------------------------+ // © 2002-2004 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net) // +-------------------------------------------------+ // $Id: empr_caddie.class.php,v 1.5 2013-04-11 08:08:11 mbertin Exp $ if (stristr($_SERVER['REQUEST_URI'], ".class.php")) die("no access"); // définition de la classe de gestion des paniers define( 'CADDIE_ITEM_NULL', 0 ); define( 'CADDIE_ITEM_OK', 1 ); define( 'CADDIE_ITEM_DEJA', 1 ); // identique car on peut ajouter des liés avec l'item et non pas l'item saisi lui-même ... define( 'CADDIE_ITEM_IMPOSSIBLE_BULLETIN', 2 ); define( 'CADDIE_ITEM_EXPL_PRET' , 3 ); define( 'CADDIE_ITEM_BULL_USED', 4) ; define( 'CADDIE_ITEM_NOTI_USED', 5) ; define( 'CADDIE_ITEM_SUPPR_BASE_OK', 6) ; define( 'CADDIE_ITEM_INEXISTANT', 7 ); class empr_caddie { // propriétés var $idemprcaddie ; var $name = '' ; // nom de référence var $comment = "" ; // description du contenu du panier var $nb_item = 0 ; // nombre d'enregistrements dans le panier var $nb_item_pointe = 0 ; // nombre d'enregistrements pointés dans le panier var $autorisations = "" ; // autorisations accordées sur ce panier // --------------------------------------------------------------- // empr_caddie($id) : constructeur // --------------------------------------------------------------- function empr_caddie($empr_caddie_id=0) { if($empr_caddie_id) { $this->idemprcaddie = $empr_caddie_id; $this->getData(); } else { $this->idemprcaddie = 0; $this->getData(); } } // --------------------------------------------------------------- // getData() : récupération infos caddie // --------------------------------------------------------------- function getData() { global $dbh; if(!$this->idemprcaddie) { // pas d'identifiant. $this->name = ''; $this->comment = ''; $this->nb_item = 0; $this->autorisations = ""; } else { $requete = "SELECT * FROM empr_caddie WHERE idemprcaddie='$this->idemprcaddie' "; $result = @mysql_query($requete, $dbh); if(mysql_num_rows($result)) { $temp = mysql_fetch_object($result); mysql_free_result($result); $this->idemprcaddie = $temp->idemprcaddie; $this->name = $temp->name; $this->comment = $temp->comment; $this->autorisations = $temp->autorisations; } else { // pas de caddie avec cet id $this->idemprcaddie = 0; $this->name = ''; $this->comment = ''; $this->autorisations = ""; } $this->compte_items(); } } // liste des paniers disponibles static function get_cart_list() { global $dbh, $PMBuserid; $cart_list=array(); if ($PMBuserid!=1) $where=" where (autorisations='$PMBuserid' or autorisations like '$PMBuserid %' or autorisations like '% $PMBuserid %' or autorisations like '% $PMBuserid') "; $requete = "SELECT * FROM empr_caddie $where order by name "; $result = @mysql_query($requete, $dbh); if(mysql_num_rows($result)) { while ($temp = mysql_fetch_object($result)) { $nb_item = 0 ; $nb_item_pointe = 0 ; $rqt_nb_item="select count(1) from empr_caddie_content where empr_caddie_id='".$temp->idemprcaddie."' "; $nb_item = mysql_result(mysql_query($rqt_nb_item, $dbh), 0, 0); $rqt_nb_item_pointe = "select count(1) from empr_caddie_content where empr_caddie_id='".$temp->idemprcaddie."' and (flag is not null and flag!='') "; $nb_item_pointe = mysql_result(mysql_query($rqt_nb_item_pointe, $dbh), 0, 0); $cart_list[] = array( 'idemprcaddie' => $temp->idemprcaddie, 'name' => $temp->name, 'comment' => $temp->comment, 'autorisations' => $temp->autorisations, 'nb_item' => $nb_item, 'nb_item_pointe' => $nb_item_pointe ); } } return $cart_list; } // création d'un panier vide function create_cart() { global $dbh; $requete = "insert into empr_caddie set name='".$this->name."', comment='".$this->comment."', autorisations='".$this->autorisations."' "; $result = @mysql_query($requete, $dbh); $this->idemprcaddie = mysql_insert_id($dbh); $this->compte_items(); } // ajout d'un item function add_item($item=0) { global $dbh; if (!$item) return CADDIE_ITEM_NULL ; $requete = "replace into empr_caddie_content set empr_caddie_id='".$this->idemprcaddie."', object_id='".$item."' "; $result = @mysql_query($requete, $dbh); return CADDIE_ITEM_OK ; } // suppression d'un item function del_item($item=0) { global $dbh; $requete = "delete FROM empr_caddie_content where empr_caddie_id='".$this->idemprcaddie."' and object_id='".$item."' "; $result = @mysql_query($requete, $dbh); $this->compte_items(); } function del_item_base($item=0) { global $dbh; if (!$item) return CADDIE_ITEM_NULL ; if (!$this->verif_empr_item($item)) { emprunteur::del_empr($item); return CADDIE_ITEM_SUPPR_BASE_OK ; } else return CADDIE_ITEM_EXPL_PRET ; } // suppression d'un item de tous les caddies du même type le contenant function del_item_all_caddies($item) { global $dbh; $requete = "select idemprcaddie FROM empr_caddie "; $result = mysql_query($requete, $dbh); for($i=0;$i<mysql_num_rows($result);$i++) { $temp=mysql_fetch_object($result); $requete_suppr = "delete from empr_caddie_content where empr_caddie_id='".$temp->idemprcaddie."' and object_id='".$item."' "; $result_suppr = mysql_query($requete_suppr, $dbh); } } function del_item_flag() { global $dbh; $requete = "delete FROM empr_caddie_content where empr_caddie_id='".$this->idemprcaddie."' and (flag is not null and flag!='') "; $result = @mysql_query($requete, $dbh); $this->compte_items(); } function del_item_no_flag() { global $dbh; $requete = "delete FROM empr_caddie_content where empr_caddie_id='".$this->idemprcaddie."' and (flag is null or flag='') "; $result = @mysql_query($requete, $dbh); $this->compte_items(); } // Dépointage de tous les items function depointe_items() { global $dbh; $requete = "update empr_caddie_content set flag=null where empr_caddie_id='".$this->idemprcaddie."' "; $result = @mysql_query($requete, $dbh); $this->compte_items(); } function pointe_item($item=0) { global $dbh; $requete = "update empr_caddie_content set flag='1' where empr_caddie_id='".$this->idemprcaddie."' and object_id='".$item."' "; $result = @mysql_query($requete, $dbh); $this->compte_items(); return CADDIE_ITEM_OK ; } // suppression d'un panier function delete() { global $dbh; $requete = "delete FROM empr_caddie_content where empr_caddie_id='".$this->idemprcaddie."' "; $result = @mysql_query($requete, $dbh); $requete = "delete FROM empr_caddie where idemprcaddie='".$this->idemprcaddie."' "; $result = @mysql_query($requete, $dbh); } // sauvegarde du panier function save_cart() { global $dbh; $requete = "update empr_caddie set name='".$this->name."', comment='".$this->comment."', autorisations='".$this->autorisations."' where idemprcaddie='".$this->idemprcaddie."'"; $result = @mysql_query($requete, $dbh); } // get_cart() : ouvre un panier et récupère le contenu function get_cart($flag="") { global $dbh; $cart_list=array(); switch ($flag) { case "FLAG" : $requete = "SELECT * FROM empr_caddie_content where empr_caddie_id='".$this->idemprcaddie."' and (flag is not null and flag!='') "; break ; case "NOFLAG" : $requete = "SELECT * FROM empr_caddie_content where empr_caddie_id='".$this->idemprcaddie."' and (flag is null or flag='') "; break ; case "ALL" : default : $requete = "SELECT * FROM empr_caddie_content where empr_caddie_id='".$this->idemprcaddie."' "; break ; } $result = @mysql_query($requete, $dbh); if(mysql_num_rows($result)) { while ($temp = mysql_fetch_object($result)) { $cart_list[] = $temp->object_id; } } return $cart_list; } // compte_items function compte_items() { global $dbh; $this->nb_item = 0 ; $this->nb_item_pointe = 0 ; $rqt_nb_item="select count(1) from empr_caddie_content where empr_caddie_id='".$this->idemprcaddie."' "; $this->nb_item = mysql_result(mysql_query($rqt_nb_item, $dbh), 0, 0); $rqt_nb_item_pointe = "select count(1) from empr_caddie_content where empr_caddie_id='".$this->idemprcaddie."' and (flag is not null and flag!='') "; $this->nb_item_pointe = mysql_result(mysql_query($rqt_nb_item_pointe, $dbh), 0, 0); } function verif_empr_item($id) { global $dbh; if ($id) { $query = "select count(1) from pret where pret_idempr=".$id." limit 1 "; $result = mysql_query($query, $dbh); if(mysql_result($result, 0, 0)) return 1 ; return 0 ; } else return 0 ; } } // fin de déclaration de la classe
Gambiit/pmb-on-docker
web_appli/pmb/classes/empr_caddie.class.php
PHP
gpl-2.0
8,518
package com.gollum.core.common.items; import com.gollum.core.tools.helper.items.HItem; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; public class ItemWrench extends HItem { public ItemWrench(String registerName) { super(registerName); this.setFull3D(); this.setMaxStackSize(1); this.setHarvestLevel("wrench", 0); } /** * This is called when the item is used, before the block is activated. * @param stack The Item Stack * @param player The Player that used the item * @param world The Current World * @param pos Target position * @param side The side of the target hit * @return Return true to prevent any further processing. */ @Override public boolean onItemUseFirst(ItemStack itemStack, EntityPlayer player, World world, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ) { IBlockState state = world.getBlockState(pos); if (state == null) { return false; } Block block = state.getBlock(); if (block == null) { return false; } if (block.rotateBlock(world, pos, side)) { player.swingItem(); return !world.isRemote; } return false; } }
GollumTeam/GollumCoreLib
src/main/java/com/gollum/core/common/items/ItemWrench.java
Java
gpl-2.0
1,363
<div class="post"> <?php if(!empty($title)) {?> <h2 class="window-title"><?=$title?></h2> <?php }?> <div class="window-main" style="text-align: <?=$align?>;"> <?=$content?> </div> </div>
Den1xxx/ReloadCMS
skins/websat/skin.window.php
PHP
gpl-2.0
191
/** @file SFTP filesystem item using libssh2 backend. @if license Copyright (C) 2012 Alexander Lamaison <awl03@doc.ic.ac.uk> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. If you modify this Program, or any covered work, by linking or combining it with the OpenSSL project's OpenSSL library (or a modified version of that library), containing parts covered by the terms of the OpenSSL or SSLeay licenses, the licensors of this Program grant you additional permission to convey the resulting work. @endif */ #ifndef SWISH_PROVIDER_LIBSSH2_SFTP_FILESYSTEM_ITEM_HPP #define SWISH_PROVIDER_LIBSSH2_SFTP_FILESYSTEM_ITEM_HPP #include "swish/provider/sftp_filesystem_item.hpp" #include <boost/cstdint.hpp> // uint64_t #include <boost/optional.hpp> #include <comet/datetime.h> // datetime_t #include <string> namespace ssh { namespace filesystem { class file_attributes; class sftp_file; } } namespace swish { namespace provider { /** * An entry in an SFTP directory retrieved by the libssh2 backend. */ class libssh2_sftp_filesystem_item : public sftp_filesystem_item_interface { public: /** * Create filesystem entry from libssh2 filesystem item representation. */ static sftp_filesystem_item create_from_libssh2_file( const ssh::filesystem::sftp_file& file); /** * Create filesystem entry from libssh2 filesystem item representation using * only the attributes and filename. * * This constructor is for use with a stat-style situation where the full * file info isn't available. * * Items created with this constructor will *not* be able to return the * user name or group name as a string. * * @param file_name * Filename. * * @param attributes * Object containing the file's details. */ static sftp_filesystem_item create_from_libssh2_attributes( const ssh::filesystem::path& file_name, const ssh::filesystem::file_attributes& attributes); virtual BOOST_SCOPED_ENUM(type) type() const; virtual ssh::filesystem::path filename() const; virtual unsigned long permissions() const; virtual boost::optional<std::wstring> owner() const; virtual unsigned long uid() const; virtual boost::optional<std::wstring> group() const; virtual unsigned long gid() const; virtual boost::uint64_t size_in_bytes() const; virtual comet::datetime_t last_accessed() const; virtual comet::datetime_t last_modified() const; private: libssh2_sftp_filesystem_item( const ssh::filesystem::sftp_file& file); libssh2_sftp_filesystem_item( const ssh::filesystem::path& file_name, const ssh::filesystem::file_attributes& attributes); void common_init( const ssh::filesystem::path& file_name, const ssh::filesystem::file_attributes& attributes); BOOST_SCOPED_ENUM(type) m_type; ssh::filesystem::path m_path; unsigned long m_permissions; boost::optional<std::wstring> m_owner; boost::optional<std::wstring> m_group; unsigned long m_uid; unsigned long m_gid; boost::uint64_t m_size; comet::datetime_t m_modified; comet::datetime_t m_accessed; }; }} #endif
alamaison/swish
swish/provider/libssh2_sftp_filesystem_item.hpp
C++
gpl-2.0
3,862
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.apache.poi.ss.util; import java.math.BigInteger; import static org.apache.poi.ss.util.IEEEDouble.*; /** * Represents a 64 bit IEEE double quantity expressed with both decimal and binary exponents * Does not handle negative numbers or zero * <p> * The value of a {@link ExpandedDouble} is given by<br> * <tt> a &times; 2<sup>b</sup></tt> * <br> * where:<br> * * <tt>a</tt> = <i>significand</i><br> * <tt>b</tt> = <i>binaryExponent</i> - bitLength(significand) + 1<br> * * @author Josh Micich */ final class ExpandedDouble { private static final BigInteger BI_FRAC_MASK = BigInteger.valueOf(FRAC_MASK); private static final BigInteger BI_IMPLIED_FRAC_MSB = BigInteger.valueOf(FRAC_ASSUMED_HIGH_BIT); private static BigInteger getFrac(long rawBits) { return BigInteger.valueOf(rawBits).and(BI_FRAC_MASK).or(BI_IMPLIED_FRAC_MSB).shiftLeft(11); } public static ExpandedDouble fromRawBitsAndExponent(long rawBits, int exp) { return new ExpandedDouble(getFrac(rawBits), exp); } /** * Always 64 bits long (MSB, bit-63 is '1') */ private final BigInteger _significand; private final int _binaryExponent; public ExpandedDouble(long rawBits) { int biasedExp = Math.toIntExact(rawBits >> 52); if (biasedExp == 0) { // sub-normal numbers BigInteger frac = BigInteger.valueOf(rawBits).and(BI_FRAC_MASK); int expAdj = 64 - frac.bitLength(); _significand = frac.shiftLeft(expAdj); _binaryExponent = (biasedExp & 0x07FF) - 1023 - expAdj; } else { _significand = getFrac(rawBits); _binaryExponent = (biasedExp & 0x07FF) - 1023; } } ExpandedDouble(BigInteger frac, int binaryExp) { if (frac.bitLength() != 64) { throw new IllegalArgumentException("bad bit length"); } _significand = frac; _binaryExponent = binaryExp; } /** * Convert to an equivalent {@link NormalisedDecimal} representation having 15 decimal digits of precision in the * non-fractional bits of the significand. */ public NormalisedDecimal normaliseBaseTen() { return NormalisedDecimal.create(_significand, _binaryExponent); } /** * @return the number of non-fractional bits after the MSB of the significand */ public int getBinaryExponent() { return _binaryExponent; } public BigInteger getSignificand() { return _significand; } }
lamsfoundation/lams
3rdParty_sources/poi/org/apache/poi/ss/util/ExpandedDouble.java
Java
gpl-2.0
3,247
<?php /** * Writepanel class */ if ( !class_exists( 'WooCommerce_PDF_Invoices_Writepanels' ) ) { class WooCommerce_PDF_Invoices_Writepanels { public $bulk_actions; /** * Constructor */ public function __construct() { add_action( 'woocommerce_admin_order_actions_end', array( $this, 'add_listing_actions' ) ); add_filter( 'manage_edit-shop_order_columns', array( $this, 'add_invoice_number_column' ), 999 ); add_action( 'manage_shop_order_posts_custom_column', array( $this, 'invoice_number_column_data' ), 2 ); add_action( 'add_meta_boxes_shop_order', array( $this, 'add_box' ) ); add_filter( 'woocommerce_my_account_my_orders_actions', array( $this, 'my_account_pdf_link' ), 10, 2 ); add_action( 'admin_print_scripts', array( $this, 'add_scripts' ) ); add_action( 'admin_print_styles', array( $this, 'add_styles' ) ); add_action( 'admin_footer', array(&$this, 'bulk_actions') ); add_action( 'woocommerce_admin_order_data_after_order_details', array(&$this, 'edit_invoice_number') ); add_action( 'save_post', array( &$this,'save_invoice_number_date' ) ); $this->general_settings = get_option('wpo_wcpdf_general_settings'); $this->template_settings = get_option('wpo_wcpdf_template_settings'); $this->bulk_actions = array( 'invoice' => __( 'PDF Invoices', 'wpo_wcpdf' ), 'packing-slip' => __( 'PDF Packing Slips', 'wpo_wcpdf' ), ); } /** * Add the styles */ public function add_styles() { if( $this->is_order_edit_page() ) { wp_enqueue_style( 'thickbox' ); if ( version_compare( WOOCOMMERCE_VERSION, '2.1' ) >= 0 ) { // WC 2.1 or newer (MP6) is used: bigger buttons wp_enqueue_style( 'wpo-wcpdf', WooCommerce_PDF_Invoices::$plugin_url . 'css/style-wc21.css' ); } else { wp_enqueue_style( 'wpo-wcpdf', WooCommerce_PDF_Invoices::$plugin_url . 'css/style.css' ); } } } /** * Add the scripts */ public function add_scripts() { if( $this->is_order_edit_page() ) { wp_enqueue_script( 'wpo-wcpdf', WooCommerce_PDF_Invoices::$plugin_url . 'js/script.js', array( 'jquery' ) ); wp_localize_script( 'wpo-wcpdf', 'wpo_wcpdf_ajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), // URL to WordPress ajax handling page 'nonce' => wp_create_nonce('generate_wpo_wcpdf'), 'bulk_actions' => array_keys( apply_filters( 'wpo_wcpdf_bulk_actions', $this->bulk_actions ) ), ) ); } } /** * Is order page */ public function is_order_edit_page() { global $post_type; if( $post_type == 'shop_order' ) { return true; } else { return false; } } /** * Add PDF actions to the orders listing */ public function add_listing_actions( $order ) { $listing_actions = array( 'invoice' => array ( 'url' => wp_nonce_url( admin_url( 'admin-ajax.php?action=generate_wpo_wcpdf&template_type=invoice&order_ids=' . $order->id ), 'generate_wpo_wcpdf' ), 'img' => WooCommerce_PDF_Invoices::$plugin_url . 'images/invoice.png', 'alt' => __( 'PDF Invoice', 'wpo_wcpdf' ), ), 'dist-invoice' => array ( 'url' => wp_nonce_url( admin_url( 'admin-ajax.php?action=generate_wpo_wcpdf&template_type=dist-invoice&order_ids=' . $order->id ), 'generate_wpo_wcpdf' ), 'img' => WooCommerce_PDF_Invoices::$plugin_url . 'images/invoice.png', 'alt' => __( 'PDF Distributor Invoice', 'wpo_wcpdf' ), ), 'packing-slip' => array ( 'url' => wp_nonce_url( admin_url( 'admin-ajax.php?action=generate_wpo_wcpdf&template_type=packing-slip&order_ids=' . $order->id ), 'generate_wpo_wcpdf' ), 'img' => WooCommerce_PDF_Invoices::$plugin_url . 'images/packing-slip.png', 'alt' => __( 'PDF Packing Slip', 'wpo_wcpdf' ), ), ); $listing_actions = apply_filters( 'wpo_wcpdf_listing_actions', $listing_actions, $order ); foreach ($listing_actions as $action => $data) { ?> <a href="<?php echo $data['url']; ?>" class="button tips wpo_wcpdf <?php echo $action; ?>" target="_blank" alt="<?php echo $data['alt']; ?>" data-tip="<?php echo $data['alt']; ?>"> <img src="<?php echo $data['img']; ?>" alt="<?php echo $data['alt']; ?>" width="16"> </a> <?php } } /** * Create additional Shop Order column for Invoice Numbers * @param array $columns shop order columns */ public function add_invoice_number_column( $columns ) { // Check user setting if ( !isset($this->general_settings['invoice_number_column'] ) ) { return $columns; } // put the column after the Status column $new_columns = array_slice($columns, 0, 2, true) + array( 'pdf_invoice_number' => __( 'Invoice Number', 'wpo_wcpdf' ) ) + array_slice($columns, 2, count($columns) - 1, true) ; return $new_columns; } /** * Display Invoice Number in Shop Order column (if available) * @param string $column column slug */ public function invoice_number_column_data( $column ) { global $post, $the_order; if ( $column == 'pdf_invoice_number' && get_post_meta($the_order->id,'_wcpdf_invoice_number',true) ) { if ( empty( $the_order ) || $the_order->id != $post->ID ) { $the_order = new WC_Order( $post->ID ); } // collect data for invoice number filter $invoice_number = get_post_meta($the_order->id,'_wcpdf_invoice_number',true); $order_number = $the_order->get_order_number(); $order_id = $the_order->id; $order_date = $the_order->order_date; echo apply_filters( 'wpo_wcpdf_invoice_number', $invoice_number, $order_number, $order_id, $order_date ); } } /** * Display download link on My Account page */ public function my_account_pdf_link( $actions, $order ) { $pdf_url = wp_nonce_url( admin_url( 'admin-ajax.php?action=generate_wpo_wcpdf&template_type=invoice&order_ids=' . $order->id . '&my-account'), 'generate_wpo_wcpdf' ); // Check if invoice has been created already or if status allows download (filter your own array of allowed statuses) if ( get_post_meta($order->id,'_wcpdf_invoice_exists',true) || in_array($order->status, apply_filters( 'wpo_wcpdf_myaccount_allowed_order_statuses', array() ) ) ) { $actions['invoice'] = array( 'url' => $pdf_url, 'name' => apply_filters( 'wpo_wcpdf_myaccount_button_text', __( 'Download invoice (PDF)', 'wpo_wcpdf' ) ) ); } return apply_filters( 'wpo_wcpdf_myaccount_actions', $actions, $order ); } /** * Add the meta box on the single order page */ public function add_box() { add_meta_box( 'wpo_wcpdf-box', __( 'Create PDF', 'wpo_wcpdf' ), array( $this, 'create_box_content' ), 'shop_order', 'side', 'default' ); } /** * Create the meta box content on the single order page */ public function create_box_content() { global $post_id; $meta_actions = array( 'invoice' => array ( 'url' => wp_nonce_url( admin_url( 'admin-ajax.php?action=generate_wpo_wcpdf&template_type=invoice&order_ids=' . $post_id ), 'generate_wpo_wcpdf' ), 'alt' => esc_attr__( 'PDF Invoice', 'wpo_wcpdf' ), 'title' => __( 'PDF Invoice', 'wpo_wcpdf' ), ), 'packing-slip' => array ( 'url' => wp_nonce_url( admin_url( 'admin-ajax.php?action=generate_wpo_wcpdf&template_type=packing-slip&order_ids=' . $post_id ), 'generate_wpo_wcpdf' ), 'alt' => esc_attr__( 'PDF Packing Slip', 'wpo_wcpdf' ), 'title' => __( 'PDF Packing Slip', 'wpo_wcpdf' ), ), ); $meta_actions = apply_filters( 'wpo_wcpdf_meta_box_actions', $meta_actions, $post_id ); ?> <ul class="wpo_wcpdf-actions"> <?php foreach ($meta_actions as $action => $data) { printf('<li><a href="%1$s" class="button" target="_blank" alt="%2$s">%3$s</a></li>', $data['url'], $data['alt'],$data['title']); } ?> </ul> <?php } /** * Add actions to menu */ public function bulk_actions() { global $post_type; $bulk_actions = apply_filters( 'wpo_wcpdf_bulk_actions', $this->bulk_actions ); if ( 'shop_order' == $post_type ) { ?> <script type="text/javascript"> jQuery(document).ready(function() { <?php foreach ($bulk_actions as $action => $title) { ?> jQuery('<option>').val('<?php echo $action; ?>').html('<?php echo esc_attr( $title ); ?>').appendTo("select[name='action'], select[name='action2']"); <?php } ?> }); </script> <?php } } /** * Add box to edit invoice number to order details page */ public function edit_invoice_number($order) { $invoice_exists = get_post_meta( $order->id, '_wcpdf_invoice_exists', true ); if (!empty($invoice_exists)) { woocommerce_wp_text_input( array( 'id' => '_wcpdf_invoice_number', 'label' => __( 'PDF Invoice Number (unformatted!)', 'wpo_wcpdf' ) ) ); $invoice_date = get_post_meta($order->id,'_wcpdf_invoice_date',true); ?> <p class="form-field form-field-wide"><label for="wcpdf_invoice_date"><?php _e( 'Invoice Date:', 'wpo_wcpdf' ); ?></label> <input type="text" class="date-picker-field" name="wcpdf_invoice_date" id="wcpdf_invoice_date" maxlength="10" value="<?php echo date_i18n( 'Y-m-d', strtotime( $invoice_date ) ); ?>" pattern="[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|1[0-9]|2[0-9]|3[01])" />@<input type="text" class="hour" placeholder="<?php _e( 'h', 'woocommerce' ) ?>" name="wcpdf_invoice_date_hour" id="wcpdf_invoice_date_hour" maxlength="2" size="2" value="<?php echo date_i18n( 'H', strtotime( $invoice_date ) ); ?>" pattern="\-?\d+(\.\d{0,})?" />:<input type="text" class="minute" placeholder="<?php _e( 'm', 'woocommerce' ) ?>" name="wcpdf_invoice_date_minute" id="wcpdf_invoice_date_minute" maxlength="2" size="2" value="<?php echo date_i18n( 'i', strtotime( $invoice_date ) ); ?>" pattern="\-?\d+(\.\d{0,})?" /> </p> <?php } } /** * Save invoice number */ public function save_invoice_number_date($post_id) { global $post_type; if( $post_type == 'shop_order' ) { if ( isset($_POST['_wcpdf_invoice_number']) ) { update_post_meta( $post_id, '_wcpdf_invoice_number', stripslashes( $_POST['_wcpdf_invoice_number'] )); } if ( isset($_POST['wcpdf_invoice_date']) ) { if ( empty($_POST['wcpdf_invoice_date']) ) { delete_post_meta( $post_id, '_wcpdf_invoice_date' ); } else { $invoice_date = strtotime( $_POST['wcpdf_invoice_date'] . ' ' . (int) $_POST['wcpdf_invoice_date_hour'] . ':' . (int) $_POST['wcpdf_invoice_date_minute'] . ':00' ); $invoice_date = date_i18n( 'Y-m-d H:i:s', $invoice_date ); update_post_meta( $post_id, '_wcpdf_invoice_date', $invoice_date ); } } if ( empty($_POST['wcpdf_invoice_date']) && empty($_POST['wcpdf_invoice_number'])) { delete_post_meta( $post_id, '_wcpdf_invoice_exists' ); } } } } }
integrait/wp_ds
wp-content/plugins/woocommerce-pdf-invoices-packing-slips/includes/class-wcpdf-writepanels.php
PHP
gpl-2.0
10,805
<?php namespace Dennis\Tournament\Controller; /** * Description of the class 'Tournament1on1Controller.php' * * @author Dennis Römmich <dennis@roemmich.eu> * @copyright Copyright belongs to the respective authors * @license http://www.gnu.org/licenses/gpl.html * GNU General Public License, version 3 or later */ /** * Class TournamentdisabledController * * @package Dennis\Tournament\Controller */ class TournamentdisabledController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController { /** * Main Function if no Type was selected * * @throws \TYPO3\CMS\Extbase\Mvc\Exception\NoSuchActionException * @return void */ public function indexAction() { throw new \TYPO3\CMS\Extbase\Mvc\Exception\NoSuchActionException('Please select a tournament type'); } }
TildBJ/tournament
Classes/Controller/TournamentdisabledController.php
PHP
gpl-2.0
792
enyo.kind({ name: "CoreNavi", style: "background-color: black;", layoutKind: "FittableColumnsLayout", fingerTracking: false, //Use legacy keyEvents by default, set to true to enable finger-tracking events components:[ {style: "width: 33%;"}, {kind: "Image", src: "$lib/webos-lib/assets/lightbar.png", fit: true, style: "width: 33%; height: 24px; padding-top: 2px;", ondragstart: "handleDragStart", ondrag: "handleDrag", ondragfinish: "handleDragFinish"}, {style: "width: 33%;"}, ], //Hide on hosts with a hardware gesture area create: function() { this.inherited(arguments); if(window.PalmSystem) this.addStyles("display: none;"); }, //CoreNaviDrag Event Synthesis handleDragStart: function(inSender, inEvent) { //Back Gesture if(this.fingerTracking == false) { if(inEvent.xDirection == -1) { //Back Gesture evB = document.createEvent("HTMLEvents"); evB.initEvent("keyup", "true", "true"); evB.keyIdentifier = "U+1200001"; document.dispatchEvent(evB); } else { //Forward Gesture } } else { //Custom drag event enyo.Signals && enyo.Signals.send && enyo.Signals.send('onCoreNaviDragStart', inEvent); } }, handleDrag: function(inSender, inEvent) { if(this.fingerTracking == true) { //Custom drag event enyo.Signals && enyo.Signals.send && enyo.Signals.send('onCoreNaviDrag', inEvent); } }, handleDragFinish: function(inSender, inEvent) { if(this.fingerTracking == true) { //Custom drag event enyo.Signals && enyo.Signals.send && enyo.Signals.send('onCoreNaviDragFinish', inEvent); } }, });
janthiemen/owo_filemanager
filemanager.application/lib/webos-lib/source/CoreNavi.js
JavaScript
gpl-2.0
1,600
<?php /** * View all details of review, edit answers from user */ require_once( ABSPATH . 'wp-content/plugins/buildable-reviews/admin/sql-quieries.php' ); $sql = new BR_SQL_Quieries(); if(isset($_GET['review-id'])) { $review_id = $_GET['review-id']; //the review we are looking at $where = 'WHERE R.review_id = '.$review_id.' '; $result = $sql->get_reviews(25, 1, $where); $review =$result[0]; } else { echo '<p>Invalid review id</p>'; die; } ?> <div class="wrap"> <h2><?php _e( 'Granska recension', 'textdomain' ); ?></h2> <form method="post" action="<?php echo esc_url( admin_url('admin-post.php') ); ?>"> <table class="form-table"> <tbody> <tr valign="top"> <th scope="row">Uppgiftslämnare</th> <td><?php echo $review['user']?></td> </tr> <tr valign="top"> <th scope="row">Datum</th> <td><?php echo $review['created_at']?></td> </tr> <tr valign="top"> <th scope="row">Betyg</th> <td><?php $score = Buildable_reviews_Admin::get_total_score_of_review($review_id); echo $score .' av 5'; ?> </td> </tr> <tr> <th scope="row">Frågor</th> </tr> <?php $answers = $sql->get_review_answers($review_id); foreach ($answers as $answer) { if($answer['question_type_name'] == 'Textfield') { echo '<tr valign="top"> <th scope="row">'.$answer['question_name'].'</th> <td> <textarea id="answer-id" name="answer-id-'. $answer['answer_id'] .'" type="text" maxlength="350" cols="100">' . $answer['answer']. '</textarea> </td> </tr>'; } else { echo '<tr valign="top"> <th scope="row">'.$answer['question_name'].'</th> <td> '. $answer['answer'].' </td> </tr>'; } } ?> </tbody> </table> <fieldset> <legend>Status</legend> <input type="radio" name="status" value="1" <?=($review['status_name'] == 'Godkänd')?'checked':''?>/>Godkänd <input type="radio" name="status" value="2" <?=($review['status_name'] == 'Ej granskad')?'checked':''?>/>Ej granskad <input type="radio" name="status" value="3" <?=($review['status_name'] == 'Anmäld')?'checked':''?>/>Anmäld </fieldset> <input type="hidden" name="action" value="br_update_review" /> <input type="hidden" name="review-id" value="<?php echo $review_id ?>" /> <?php submit_button( __( 'Uppdatera', 'textdomain' ), 'primary'); //submit_button( __( 'Ta bort hela recensionen', 'textdomain' ), 'delete' ); //TODO: delete review ?> <input type="submit" name="delete" id="submit" class="button delete" value="Ta bort hela recensionen"> </form> </div>
fh222dt/buildable-reviews
admin/partials/buildable-reviews-admin-review-details.php
PHP
gpl-2.0
3,466
/**************************************************************** * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) * ============================================================= * License Information: http://lamsfoundation.org/licensing/lams/2.0/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2.0 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA * * http://www.gnu.org/licenses/gpl.txt * **************************************************************** */ package org.lamsfoundation.lams.tool.daco.web.controller; import java.io.IOException; import java.text.ParseException; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.lamsfoundation.lams.notebook.model.NotebookEntry; import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants; import org.lamsfoundation.lams.tool.daco.DacoConstants; import org.lamsfoundation.lams.tool.daco.dto.MonitoringSummarySessionDTO; import org.lamsfoundation.lams.tool.daco.dto.MonitoringSummaryUserDTO; import org.lamsfoundation.lams.tool.daco.dto.QuestionSummaryDTO; import org.lamsfoundation.lams.tool.daco.model.Daco; import org.lamsfoundation.lams.tool.daco.model.DacoAnswer; import org.lamsfoundation.lams.tool.daco.model.DacoAnswerOption; import org.lamsfoundation.lams.tool.daco.model.DacoQuestion; import org.lamsfoundation.lams.tool.daco.model.DacoUser; import org.lamsfoundation.lams.tool.daco.service.IDacoService; import org.lamsfoundation.lams.tool.daco.util.DacoExcelUtil; import org.lamsfoundation.lams.usermanagement.dto.UserDTO; import org.lamsfoundation.lams.util.CommonConstants; import org.lamsfoundation.lams.util.FileUtil; import org.lamsfoundation.lams.util.NumberUtil; import org.lamsfoundation.lams.util.WebUtil; import org.lamsfoundation.lams.web.session.SessionManager; import org.lamsfoundation.lams.web.util.AttributeNames; import org.lamsfoundation.lams.web.util.SessionMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.util.HtmlUtils; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; @Controller @RequestMapping("/monitoring") public class MonitoringController { public static Logger log = Logger.getLogger(MonitoringController.class); @Autowired private IDacoService dacoService; @RequestMapping("/listRecords") protected String listRecords(HttpServletRequest request) { return listRecords(request, false); } @RequestMapping("/changeView") protected String changeView(HttpServletRequest request) { return listRecords(request, true); } private String listRecords(HttpServletRequest request, boolean changeView) { String sessionMapID = request.getParameter(DacoConstants.ATTR_SESSION_MAP_ID); SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID); Long toolSessionId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID, true); Long userId = WebUtil.readLongParam(request, DacoConstants.USER_ID, true); Integer sortOrder = WebUtil.readIntParam(request, DacoConstants.ATTR_SORT, true); if (sortOrder == null) { sortOrder = DacoConstants.SORT_BY_NO; } sessionMap.put(DacoConstants.ATTR_MONITORING_SUMMARY, dacoService.getAnswersAsRecords(toolSessionId, userId, sortOrder)); request.setAttribute(DacoConstants.ATTR_SESSION_MAP_ID, sessionMapID); request.setAttribute(AttributeNames.PARAM_TOOL_SESSION_ID, toolSessionId); request.setAttribute(DacoConstants.ATTR_SORT, sortOrder); request.setAttribute(DacoConstants.USER_ID, userId); if (changeView) { String currentView = (String) sessionMap.get(DacoConstants.ATTR_LEARNING_VIEW); if (DacoConstants.LEARNING_VIEW_HORIZONTAL.equals(currentView)) { sessionMap.put(DacoConstants.ATTR_LEARNING_VIEW, DacoConstants.LEARNING_VIEW_VERTICAL); } else { sessionMap.put(DacoConstants.ATTR_LEARNING_VIEW, DacoConstants.LEARNING_VIEW_HORIZONTAL); } } return "pages/monitoring/listRecords"; } @RequestMapping("/summary") protected String summary(HttpServletRequest request, HttpServletResponse response) { // initial Session Map String sessionMapID = WebUtil.readStrParam(request, DacoConstants.ATTR_SESSION_MAP_ID, true); boolean newSession = sessionMapID == null || request.getSession().getAttribute(sessionMapID) == null; SessionMap sessionMap = null; if (newSession) { sessionMap = new SessionMap(); sessionMapID = sessionMap.getSessionID(); request.getSession().setAttribute(sessionMapID, sessionMap); sessionMap.put(DacoConstants.ATTR_LEARNING_VIEW, DacoConstants.LEARNING_VIEW_VERTICAL); } else { sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID); } Long contentId = sessionMap.get(AttributeNames.PARAM_TOOL_CONTENT_ID) == null ? WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID) : (Long) sessionMap.get(AttributeNames.PARAM_TOOL_CONTENT_ID); Daco daco = dacoService.getDacoByContentId(contentId); List<MonitoringSummarySessionDTO> monitoringSummaryList = dacoService.getMonitoringSummary(contentId, DacoConstants.MONITORING_SUMMARY_MATCH_NONE); Long userUid = WebUtil.readLongParam(request, DacoConstants.USER_UID, true); if (userUid == null) { userUid = (Long) sessionMap.get(DacoConstants.USER_UID); request.setAttribute(DacoConstants.ATTR_MONITORING_CURRENT_TAB, 1); } else { request.setAttribute(DacoConstants.ATTR_MONITORING_CURRENT_TAB, 3); } request.setAttribute(DacoConstants.ATTR_SESSION_MAP_ID, sessionMapID); sessionMap.put(DacoConstants.USER_UID, userUid); sessionMap.put(DacoConstants.PAGE_EDITABLE, !daco.isContentInUse()); sessionMap.put(DacoConstants.ATTR_MONITORING_SUMMARY, monitoringSummaryList); if (newSession) { boolean isGroupedActivity = dacoService.isGroupedActivity(contentId); sessionMap.put(DacoConstants.ATTR_IS_GROUPED_ACTIVITY, isGroupedActivity); sessionMap.put(DacoConstants.ATTR_DACO, daco); sessionMap.put(AttributeNames.PARAM_TOOL_CONTENT_ID, contentId); sessionMap.put(AttributeNames.PARAM_CONTENT_FOLDER_ID, WebUtil.readStrParam(request, AttributeNames.PARAM_CONTENT_FOLDER_ID)); HttpSession ss = SessionManager.getSession(); UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER); } return "pages/monitoring/monitoring"; } @RequestMapping(path = "/getUsers") @ResponseBody protected String getUsers(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String sessionMapID = WebUtil.readStrParam(request, DacoConstants.ATTR_SESSION_MAP_ID, true); SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID); Long sessionId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID); Long contentId = sessionMap.get(AttributeNames.PARAM_TOOL_CONTENT_ID) == null ? WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID) : (Long) sessionMap.get(AttributeNames.PARAM_TOOL_CONTENT_ID); // paging parameters of tablesorter int size = WebUtil.readIntParam(request, "size"); int page = WebUtil.readIntParam(request, "page"); Integer isSort1 = WebUtil.readIntParam(request, "column[0]", true); Integer isSort2 = WebUtil.readIntParam(request, "column[1]", true); String searchString = request.getParameter("fcol[0]"); int sorting = DacoConstants.SORT_BY_NO; if ((isSort1 != null) && isSort1.equals(0)) { sorting = DacoConstants.SORT_BY_USER_NAME_ASC; } else if ((isSort1 != null) && isSort1.equals(1)) { sorting = DacoConstants.SORT_BY_USER_NAME_DESC; } else if ((isSort2 != null) && isSort2.equals(0)) { sorting = DacoConstants.SORT_BY_NUM_RECORDS_ASC; } else if ((isSort2 != null) && isSort2.equals(1)) { sorting = DacoConstants.SORT_BY_NUM_RECORDS_DESC; } Daco daco = dacoService.getDacoByContentId(contentId); List<Object[]> users = dacoService.getUsersForTablesorter(sessionId, page, size, sorting, searchString, daco.isReflectOnActivity()); ArrayNode rows = JsonNodeFactory.instance.arrayNode(); ObjectNode responsedata = JsonNodeFactory.instance.objectNode(); responsedata.put("total_rows", dacoService.getCountUsersBySession(sessionId, searchString)); for (Object[] userAndReflection : users) { ObjectNode responseRow = JsonNodeFactory.instance.objectNode(); DacoUser user = (DacoUser) userAndReflection[0]; responseRow.put(DacoConstants.USER_ID, user.getUserId()); responseRow.put(DacoConstants.USER_FULL_NAME, HtmlUtils.htmlEscape(user.getFullName())); if (userAndReflection.length > 1 && userAndReflection[1] != null) { responseRow.put(DacoConstants.RECORD_COUNT, (Integer) userAndReflection[1]); } else { responseRow.put(DacoConstants.RECORD_COUNT, 0); } if (userAndReflection.length > 2 && userAndReflection[2] != null) { responseRow.put(DacoConstants.NOTEBOOK_ENTRY, HtmlUtils.htmlEscape((String) userAndReflection[2])); } if (userAndReflection.length > 3 && userAndReflection[3] != null) { responseRow.put(DacoConstants.PORTRAIT_ID, (String) userAndReflection[3]); } rows.add(responseRow); } responsedata.set("rows", rows); response.setContentType("application/json;charset=UTF-8"); return responsedata.toString(); } @RequestMapping("/viewReflection") protected String viewReflection(HttpServletRequest request) { String sessionMapID = request.getParameter(DacoConstants.ATTR_SESSION_MAP_ID); SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID); Integer userId = WebUtil.readIntParam(request, DacoConstants.USER_ID); Long sessionId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID); DacoUser user = dacoService.getUserByUserIdAndSessionId(userId.longValue(), sessionId); NotebookEntry notebookEntry = dacoService.getEntry(sessionId, CoreNotebookConstants.NOTEBOOK_TOOL, DacoConstants.TOOL_SIGNATURE, userId); MonitoringSummaryUserDTO userDTO = new MonitoringSummaryUserDTO(null, userId, user.getFullName(), null); userDTO.setReflectionEntry(notebookEntry.getEntry()); sessionMap.put(DacoConstants.ATTR_USER, userDTO); request.setAttribute(DacoConstants.ATTR_SESSION_MAP_ID, sessionMapID); return "pages/monitoring/notebook"; } /** * Exports all learners' data to an Excel or CSV file. * * @param request * @param response * @return * @throws IOException * @throws JXLException * @throws ParseException */ @RequestMapping("/exportToSpreadsheet") protected String exportToSpreadsheet(HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException { // Get required parameters String sessionMapID = request.getParameter(DacoConstants.ATTR_SESSION_MAP_ID); SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID); Daco daco = (Daco) sessionMap.get(DacoConstants.ATTR_DACO); // Prepare headers and column names String title = dacoService.getLocalisedMessage(DacoConstants.KEY_LABEL_EXPORT_FILE_TITLE, null); String dateHeader = dacoService.getLocalisedMessage(DacoConstants.KEY_LABEL_EXPORT_FILE_DATE, null); Set<DacoQuestion> questions = daco.getDacoQuestions(); HashMap<Long, Integer> questionUidToSpreadsheetColumnIndex = new HashMap<>(); // First two columns are "user" and date when was the answer added int columnIndex = 2; String[] columnNames = new String[questions.size() + 2]; columnNames[0] = dacoService.getLocalisedMessage(DacoConstants.KEY_LABEL_EXPORT_FILE_USER, null); columnNames[1] = dacoService.getLocalisedMessage(DacoConstants.KEY_LABEL_EXPORT_FILE_ANSWER_DATE, null); for (DacoQuestion question : questions) { questionUidToSpreadsheetColumnIndex.put(question.getUid(), columnIndex); columnNames[columnIndex] = WebUtil.removeHTMLtags(question.getDescription()); columnIndex++; } // Some strings used in building cell values String longitudeHeader = dacoService.getLocalisedMessage(DacoConstants.KEY_LABEL_LEARNING_LONGLAT_LONGITUDE, null); String longitudeUnit = dacoService.getLocalisedMessage(DacoConstants.KEY_LABEL_LEARNING_LONGLAT_LONGITUDE_UNIT, null); String latitudeHeader = dacoService.getLocalisedMessage(DacoConstants.KEY_LABEL_LEARNING_LONGLAT_LATITUDE, null); String latitudeUnit = dacoService.getLocalisedMessage(DacoConstants.KEY_LABEL_LEARNING_LONGLAT_LATITUDE_UNIT, null); List<Object[]> rows = new LinkedList<>(); // We get all sessions with all users with all their records from the given Daco content List<MonitoringSummarySessionDTO> monitoringSummary = dacoService.getSummaryForExport(daco.getContentId(), null); // Get current user's locale to format numbers properly Locale monitoringUserLocale = null; HttpSession ss = SessionManager.getSession(); if (ss != null) { UserDTO systemUser = (UserDTO) ss.getAttribute(AttributeNames.USER); if (systemUser != null) { monitoringUserLocale = new Locale(systemUser.getLocaleLanguage(), systemUser.getLocaleCountry()); } } for (MonitoringSummarySessionDTO summarySession : monitoringSummary) { // Maybe we'll need delimiter between sessions one day - here is the place to add an empty row for (MonitoringSummaryUserDTO user : summarySession.getUsers()) { List<List<DacoAnswer>> records = user.getRecords(); for (int rowIndex = 0; rowIndex < records.size(); rowIndex++) { Object[] row = new Object[questions.size() + 2]; row[0] = user.getFullName(); List<DacoAnswer> record = records.get(rowIndex); for (int answerIndex = 0; answerIndex < record.size(); answerIndex++) { DacoAnswer answer = record.get(answerIndex); // we set the date of the whole row to the latest from all the participating answers if (row[1] == null) { row[1] = answer.getCreateDate(); } else { Date currentDate = (Date) row[1]; Date newDate = answer.getCreateDate(); if (currentDate.compareTo(newDate) < 0) { row[1] = newDate; } } Object cell = null; String answerString = answer.getAnswer(); columnIndex = questionUidToSpreadsheetColumnIndex.get(answer.getQuestion().getUid()); // we extract answers and add them to "data" array in readable form switch (answer.getQuestion().getType()) { case DacoConstants.QUESTION_TYPE_NUMBER: if (!StringUtils.isBlank(answerString)) { Short fractionDigits = answer.getQuestion().getDigitsDecimal(); if (fractionDigits == null) { fractionDigits = Short.MAX_VALUE; } cell = NumberUtil.formatLocalisedNumber(Double.parseDouble(answerString), monitoringUserLocale, fractionDigits); } break; case DacoConstants.QUESTION_TYPE_DATE: if (!StringUtils.isBlank(answerString)) { cell = DacoConstants.DEFAULT_DATE_FORMAT.parse(answerString); } break; case DacoConstants.QUESTION_TYPE_CHECKBOX: if (!StringUtils.isBlank(answerString)) { DacoQuestion question = answer.getQuestion(); DacoQuestion currentQuestion = question; List<DacoAnswerOption> answerOptions = new LinkedList<>( question.getAnswerOptions()); StringBuilder cellStringBuilder = new StringBuilder(); // instead of number, we create a comma-separated string of chosen options do { try { int chosenAnswer = Integer.parseInt(answerString) - 1; String chosenAnswerOption = answerOptions.get(chosenAnswer) .getAnswerOption(); cellStringBuilder.append(chosenAnswerOption).append(", "); } catch (Exception e) { log.error("exportToSpreadsheet encountered '" + e + "' while parsing checkbox answer; answer was " + answerString); } answerIndex++; // LDEV-3648 If the checkbox is the last entry, then there won't be any more answers so don't trigger an out of bounds exception! if (answerIndex < record.size()) { answer = record.get(answerIndex); currentQuestion = answer.getQuestion(); answerString = answer.getAnswer(); } } while (answerIndex < record.size() && currentQuestion.equals(question)); // we went one answer too far, so we go back answerIndex--; cell = (cellStringBuilder.length() > 1 ? cellStringBuilder .delete(cellStringBuilder.length() - 2, cellStringBuilder.length()) .toString() : cellStringBuilder.toString()); } break; case DacoConstants.QUESTION_TYPE_LONGLAT: // Both longitude and latitude go in the same cell if (StringUtils.isBlank(answerString)) { // If longitude was not entered, then latitude also is blank, so skip the next answer answerIndex++; } else { StringBuilder cellStringBuilder = new StringBuilder(longitudeHeader).append(' ') .append(answerString).append(' ').append(longitudeUnit).append("; "); answerIndex++; answer = record.get(answerIndex); cellStringBuilder.append(latitudeHeader).append(' ').append(answer.getAnswer()) .append(' ').append(latitudeUnit); cell = cellStringBuilder.toString(); } break; case DacoConstants.QUESTION_TYPE_FILE: case DacoConstants.QUESTION_TYPE_IMAGE: if (!StringUtils.isBlank(answer.getFileName())) { // Just get the file name, instead of the real file cell = answer.getFileName(); } break; case DacoConstants.QUESTION_TYPE_RADIO: case DacoConstants.QUESTION_TYPE_DROPDOWN: if (!StringUtils.isBlank(answerString)) { List<DacoAnswerOption> answerOptions = new LinkedList<>( answer.getQuestion().getAnswerOptions()); try { int chosenAnswer = Integer.parseInt(answerString) - 1; cell = answerOptions.get(chosenAnswer).getAnswerOption(); } catch (Exception e) { log.error("exportToSpreadsheet encountered '" + e + "' while parsing dropdown or radio answer; answer was " + answerString); } } break; default: cell = answer.getAnswer(); break; } row[columnIndex] = cell; } rows.add(row); } } } // Convert from Collection to array Object[][] data = rows.toArray(new Object[][] {}); // Prepare response headers String fileName = DacoConstants.EXPORT_TO_SPREADSHEET_FILE_NAME; fileName = FileUtil.encodeFilenameForDownload(request, fileName); response.setContentType(CommonConstants.RESPONSE_CONTENT_TYPE_DOWNLOAD); response.setHeader(CommonConstants.HEADER_CONTENT_DISPOSITION, CommonConstants.HEADER_CONTENT_ATTACHMENT + fileName); MonitoringController.log.debug("Exporting to a spreadsheet tool content with UID: " + daco.getUid()); ServletOutputStream out = response.getOutputStream(); // Export to XLS String sheetName = dacoService.getLocalisedMessage(DacoConstants.KEY_LABEL_EXPORT_FILE_SHEET, null); DacoExcelUtil.exportToExcel(out, sheetName, title, dateHeader, columnNames, data); // Return the file inside response, but not any JSP page return null; } @SuppressWarnings({ "rawtypes", "unchecked" }) @RequestMapping("/getQuestionSummaries") protected String getQuestionSummaries(HttpServletRequest request) { String sessionMapID = WebUtil.readStrParam(request, DacoConstants.ATTR_SESSION_MAP_ID); SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID); Long sessionId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID); DacoUser user; Long userId = WebUtil.readLongParam(request, DacoConstants.USER_ID, true); user = userId != null ? dacoService.getUserByUserIdAndSessionId(userId, sessionId) : null; if (user != null) { List<QuestionSummaryDTO> summaries = dacoService.getQuestionSummaries(user.getUid()); sessionMap.put(DacoConstants.ATTR_QUESTION_SUMMARIES, summaries); Integer totalRecordCount = dacoService.getGroupRecordCount(sessionId); sessionMap.put(DacoConstants.ATTR_TOTAL_RECORD_COUNT, totalRecordCount); Integer userRecordCount = dacoService.getRecordNum(userId, sessionId); sessionMap.put(DacoConstants.RECORD_COUNT, userRecordCount); sessionMap.put(DacoConstants.USER_FULL_NAME, user.getFullName()); } else { sessionMap.put(DacoConstants.ATTR_QUESTION_SUMMARIES, new LinkedList<QuestionSummaryDTO>()); sessionMap.put(DacoConstants.ATTR_TOTAL_RECORD_COUNT, 0); sessionMap.put(DacoConstants.RECORD_COUNT, 0); sessionMap.put(DacoConstants.USER_FULL_NAME, ""); } request.setAttribute(DacoConstants.ATTR_SESSION_MAP_ID, sessionMapID); return "pages/monitoring/questionSummaries"; } /** * Show statistics page. * * @param mapping * @param form * @param request * @param response * @return */ @RequestMapping("/statistic") private String statistic(HttpServletRequest request) { String sessionMapID = WebUtil.readStrParam(request, DacoConstants.ATTR_SESSION_MAP_ID); SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID); Long contentId = sessionMap.get(AttributeNames.PARAM_TOOL_CONTENT_ID) == null ? WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID) : (Long) sessionMap.get(AttributeNames.PARAM_TOOL_CONTENT_ID); Daco daco = dacoService.getDacoByContentId(contentId); List<MonitoringSummarySessionDTO> sessList = dacoService.getSessionStatistics(daco.getUid()); request.setAttribute(DacoConstants.ATTR_SESSION_SUMMARIES, sessList); request.setAttribute(DacoConstants.ATTR_SESSION_MAP_ID, sessionMapID); return "pages/monitoring/statistics"; } }
lamsfoundation/lams
lams_tool_daco/src/java/org/lamsfoundation/lams/tool/daco/web/controller/MonitoringController.java
Java
gpl-2.0
22,813
# BGFit - Bacterial Growth Curve Fitting # Copyright (C) 2012-2012 André Veríssimo # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; version 2 # of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class LinesController < ApplicationController respond_to :html, :json before_filter :determine_models before_filter :authenticate_user!, :except => [:index,:show] load_and_authorize_resource :except => [:new,:create] #TODO move to initializer once all controllers have this support include ActiveModel::ForbiddenAttributesProtection # GET /lines # GET /lines.json def index @lines = @measurement.lines respond_with(@measurement,@lines) do |format| format.html { redirect_to [@experiment,@measurement]}# index.html.erb end end # GET /lines/1 # GET /lines/1.json def show respond_with(@measurement,@line) do |format| format.html { redirect_to [@experiment,@measurement] }# show.html.erb end end # GET /lines/new # GET /lines/new.json def new @line = @measurement.lines.build authorize! :update, @measurement respond_with [@measurement,@line] do |format| format.html # new.html.erb format.json { render json: @line } end end # GET /lines/1/edit def edit respond_with [@measurement,@line] end # POST /lines # POST /lines.json def create @line = @measurement.lines.build(permitted_params.line) authorize! :create, @line respond_with(@measurement,@lines) do |format| if @line.save format.html { redirect_to [@experiment,@measurement], notice: 'Measurement line was successfully created.' } format.json { render json: @line, status: :created, location: [@measurement,@line] } else format.html { render action: "new" } format.json { render json: @line.errors, status: :unprocessable_entity } end end end # PUT /lines/1 # PUT /lines/1.json def update respond_with [@measurement,@line] do |format| if @line.update_attributes(permitted_params.line) format.html { redirect_to [@experiment,@measurement], notice: 'Measurement line was successfully updated.' } format.json { head :ok } else format.html { render action: "edit" } format.json { render json: @line.errors, status: :unprocessable_entity } end end end # DELETE /lines/1 # DELETE /lines/1.json def destroy flash[:notice] = t('flash.actions.destroy.notice', :resource_name => "Line") @line.destroy respond_to do |format| format.html { redirect_to [@experiment,@measurement] } format.json { head :ok } end end private def determine_models @measurement = Measurement.find(params[:measurement_id]) @line = @measurement.lines.find(params[:id]) if params[:id] @experiment = @measurement.experiment @model = @experiment.model end end
averissimo/BGFit
app/controllers/lines_controller.rb
Ruby
gpl-2.0
3,463
<?php get_header(); ?> <div id="content"> <?php if ( !is_archive() ) { ?> <a href="http://localhost:8001/forums/forum/何でも掲示板"><div id="notice_board_img"><img src="/wp-content/uploads/2016/06/good_1-2.jpg" width="100%" alt="notice-board" /></div></a> <?php } ?> <?php if ( is_archive() ) { ?> <h2 class="heading-font archive-title"><?php wptouch_fdn_archive_title_text(); ?></h2> <?php } ?> <?php while ( wptouch_have_posts() ) { ?> <?php wptouch_the_post(); ?> <div class="<?php wptouch_post_classes(); ?>"> <?php get_template_part( 'post-loop' ); ?> </div> <!-- post classes --> <?php } ?> <?php if ( foundation_is_theme_using_module( 'infinite-scroll' ) ) { ?> <?php if ( get_next_posts_link() ) { ?> <a class="infinite-link" href="#" rel="<?php echo get_next_posts_page_link(); ?>"><!-- hidden in css --></a> <?php } ?> <?php } elseif ( foundation_is_theme_using_module( 'load-more' ) ) { ?> <!-- show the load more if we have more posts/pages --> <?php if ( get_next_posts_link() ) { ?> <a class="load-more-link no-ajax" href="javascript:return false;" rel="<?php echo get_next_posts_page_link(); ?>"> <?php wptouch_fdn_archive_load_more_text(); ?>&hellip; </a> <?php } ?> <?php } else { ?> <div class="posts-nav"> <?php posts_nav_link( ' | ', '&lsaquo; ' . __( 'newer posts', 'wptouch-pro' ), __( 'older posts', 'wptouch-pro' ) . ' &rsaquo;' ); ?> </div> <?php } ?> </div> <!-- content --> <?php get_footer(); ?>
satoshishimazaki/notice-board3
wp-content/wptouch-data/themes/classic-redux/default/index.php
PHP
gpl-2.0
1,499
<?php /** * Managing core Dashboard settings. * * @copyright 2009-2015 Vanilla Forums Inc. * @license http://www.opensource.org/licenses/gpl-2.0.php GNU GPL v2 * @package Dashboard * @since 2.0 */ /** * Handles /settings endpoint. */ class SettingsController extends DashboardController { /** @var array Models to automatically instantiate. */ public $Uses = array('Form', 'Database'); /** @var string */ public $ModuleSortContainer = 'Dashboard'; /** @var Gdn_Form */ public $Form; /** @var array List of permissions that should all have access to main dashboard. */ public $RequiredAdminPermissions = array(); /** * Hightlight menu path. Automatically run on every use. * * @since 2.0.0 * @access public */ public function initialize() { parent::initialize(); Gdn_Theme::section('Dashboard'); if ($this->Menu) { $this->Menu->highlightRoute('/dashboard/settings'); } } /** * Application management screen. * * @since 2.0.0 * @access public * @param string $Filter 'enabled', 'disabled', or 'all' (default) * @param string $ApplicationName Unique ID of app to be modified. * @param string $TransientKey Security token. */ public function applications($Filter = '', $ApplicationName = '', $TransientKey = '') { $this->permission('Garden.Settings.Manage'); // Page setup $this->addJsFile('addons.js'); $this->addJsFile('applications.js'); $this->title(t('Applications')); $this->addSideMenu('dashboard/settings/applications'); // Validate & set parameters $Session = Gdn::session(); if ($ApplicationName && !$Session->validateTransientKey($TransientKey)) { $ApplicationName = ''; } if (!in_array($Filter, array('enabled', 'disabled'))) { $Filter = 'all'; } $this->Filter = $Filter; $ApplicationManager = new Gdn_ApplicationManager(); $this->AvailableApplications = $ApplicationManager->availableVisibleApplications(); $this->EnabledApplications = $ApplicationManager->enabledVisibleApplications(); if ($ApplicationName != '') { $this->EventArguments['ApplicationName'] = $ApplicationName; if (array_key_exists($ApplicationName, $this->EnabledApplications) === true) { try { $ApplicationManager->disableApplication($ApplicationName); Gdn_LibraryMap::clearCache(); $this->fireEvent('AfterDisableApplication'); } catch (Exception $e) { $this->Form->addError(strip_tags($e->getMessage())); } } else { try { $ApplicationManager->checkRequirements($ApplicationName); } catch (Exception $e) { $this->Form->addError(strip_tags($e->getMessage())); } if ($this->Form->errorCount() == 0) { $Validation = new Gdn_Validation(); $ApplicationManager->registerPermissions($ApplicationName, $Validation); $ApplicationManager->enableApplication($ApplicationName, $Validation); Gdn_LibraryMap::clearCache(); $this->Form->setValidationResults($Validation->results()); $this->EventArguments['Validation'] = $Validation; $this->fireEvent('AfterEnableApplication'); } } if ($this->Form->errorCount() == 0) { redirect('settings/applications/'.$this->Filter); } } $this->render(); } /** * Application management screen. * * @since 2.0.0 * @access protected * @param array $Ban Data about the ban. * Valid keys are BanType and BanValue. BanValue is what is to be banned. * Valid values for BanType are email, ipaddress or name. */ protected function _banFilter($Ban) { $BanModel = $this->_BanModel; $BanWhere = $BanModel->banWhere($Ban); foreach ($BanWhere as $Name => $Value) { if (!in_array($Name, array('u.Admin', 'u.Deleted'))) { return "$Name $Value"; } } } /** * Banner management screen. * * @since 2.0.0 * @access public */ public function banner() { $this->permission('Garden.Community.Manage'); $this->addSideMenu('dashboard/settings/banner'); $this->title(t('Banner')); $Validation = new Gdn_Validation(); $ConfigurationModel = new Gdn_ConfigurationModel($Validation); $ConfigurationModel->setField(array( 'Garden.HomepageTitle' => c('Garden.Title'), 'Garden.Title', 'Garden.Description' )); // Set the model on the form. $this->Form->setModel($ConfigurationModel); // Get the current logo. $Logo = c('Garden.Logo'); if ($Logo) { $Logo = ltrim($Logo, '/'); // Fix the logo path. if (stringBeginsWith($Logo, 'uploads/')) { $Logo = substr($Logo, strlen('uploads/')); } $this->setData('Logo', $Logo); } // Get the current mobile logo. $MobileLogo = c('Garden.MobileLogo'); if ($MobileLogo) { $MobileLogo = ltrim($MobileLogo, '/'); // Fix the logo path. if (stringBeginsWith($MobileLogo, 'uploads/')) { $MobileLogo = substr($MobileLogo, strlen('uploads/')); } $this->setData('MobileLogo', $MobileLogo); } // Get the current favicon. $Favicon = c('Garden.FavIcon'); $this->setData('Favicon', $Favicon); $ShareImage = c('Garden.ShareImage'); $this->setData('ShareImage', $ShareImage); // If seeing the form for the first time... if (!$this->Form->authenticatedPostBack()) { // Apply the config settings to the form. $this->Form->setData($ConfigurationModel->Data); } else { $SaveData = array(); if ($this->Form->save() !== false) { $Upload = new Gdn_Upload(); try { // Validate the upload $TmpImage = $Upload->validateUpload('Logo', false); if ($TmpImage) { // Generate the target image name $TargetImage = $Upload->generateTargetName(PATH_UPLOADS); $ImageBaseName = pathinfo($TargetImage, PATHINFO_BASENAME); // Delete any previously uploaded images. if ($Logo) { $Upload->delete($Logo); } // Save the uploaded image $Parts = $Upload->SaveAs( $TmpImage, $ImageBaseName ); $ImageBaseName = $Parts['SaveName']; $SaveData['Garden.Logo'] = $ImageBaseName; $this->setData('Logo', $ImageBaseName); } $TmpMobileImage = $Upload->validateUpload('MobileLogo', false); if ($TmpMobileImage) { // Generate the target image name $TargetImage = $Upload->generateTargetName(PATH_UPLOADS); $ImageBaseName = pathinfo($TargetImage, PATHINFO_BASENAME); // Delete any previously uploaded images. if ($MobileLogo) { $Upload->delete($MobileLogo); } // Save the uploaded image $Parts = $Upload->saveAs( $TmpMobileImage, $ImageBaseName ); $ImageBaseName = $Parts['SaveName']; $SaveData['Garden.MobileLogo'] = $ImageBaseName; $this->setData('MobileLogo', $ImageBaseName); } $ImgUpload = new Gdn_UploadImage(); $TmpFavicon = $ImgUpload->validateUpload('Favicon', false); if ($TmpFavicon) { $ICOName = 'favicon_'.substr(md5(microtime()), 16).'.ico'; if ($Favicon) { $Upload->delete($Favicon); } // Resize the to a png. $Parts = $ImgUpload->SaveImageAs($TmpFavicon, $ICOName, 16, 16, array('OutputType' => 'ico', 'Crop' => true)); $SaveData['Garden.FavIcon'] = $Parts['SaveName']; $this->setData('Favicon', $Parts['SaveName']); } $TmpShareImage = $Upload->ValidateUpload('ShareImage', false); if ($TmpShareImage) { $TargetImage = $Upload->GenerateTargetName(PATH_UPLOADS, false); $ImageBaseName = pathinfo($TargetImage, PATHINFO_BASENAME); if ($ShareImage) { $Upload->delete($ShareImage); } $Parts = $Upload->SaveAs($TmpShareImage, $ImageBaseName); $SaveData['Garden.ShareImage'] = $Parts['SaveName']; $this->setData('ShareImage', $Parts['SaveName']); } } catch (Exception $ex) { $this->Form->addError($ex); } // If there were no errors, save the path to the logo in the config if ($this->Form->errorCount() == 0) { saveToConfig($SaveData); } $this->informMessage(t("Your settings have been saved.")); } } $this->render(); } /** * Manage user bans (add, edit, delete, list). * * @since 2.0.18 * @access public * @param string $Action Add, edit, delete, or none. * @param string $Search Term to filter ban list by. * @param int $Page Page number. * @param int $ID Ban ID we're editing or deleting. */ public function bans($Action = '', $Search = '', $Page = '', $ID = '') { $this->permission('Garden.Settings.Manage'); // Page setup $this->addSideMenu(); $this->title(t('Banning Options')); $this->addJsFile('bans.js'); list($Offset, $Limit) = offsetLimit($Page, 20); $BanModel = new BanModel(); $this->_BanModel = $BanModel; switch (strtolower($Action)) { case 'add': case 'edit': $this->Form->setModel($BanModel); if ($this->Form->authenticatedPostBack()) { if ($ID) { $this->Form->setFormValue('BanID', $ID); } try { // Save the ban. $NewID = $this->Form->save(); } catch (Exception $Ex) { $this->Form->addError($Ex); } } else { if ($ID) { $this->Form->setData($BanModel->getID($ID)); } } $this->setData('_BanTypes', array('IPAddress' => t('IP Address'), 'Email' => t('Email'), 'Name' => t('Name'))); $this->View = 'Ban'; break; case 'delete': if ($this->Form->authenticatedPostBack()) { $BanModel->delete(array('BanID' => $ID)); $this->View = 'BanDelete'; } break; default: $Bans = $BanModel->getWhere(array(), 'BanType, BanValue', 'asc', $Limit, $Offset)->resultArray(); $this->setData('Bans', $Bans); break; } $this->render(); } /** * Homepage management screen. * * @since 2.0.0 * @access public */ public function homepage() { $this->permission('Garden.Settings.Manage'); // Page setup $this->addSideMenu('dashboard/settings/homepage'); $this->title(t('Homepage')); $CurrentRoute = val('Destination', Gdn::router()->getRoute('DefaultController'), ''); $this->setData('CurrentTarget', $CurrentRoute); if (!$this->Form->authenticatedPostBack()) { $this->Form->setData(array( 'Target' => $CurrentRoute )); } else { $NewRoute = val('Target', $this->Form->formValues(), ''); Gdn::router()->deleteRoute('DefaultController'); Gdn::router()->setRoute('DefaultController', $NewRoute, 'Internal'); $this->setData('CurrentTarget', $NewRoute); // Save the preferred layout setting saveToConfig(array( 'Vanilla.Discussions.Layout' => val('DiscussionsLayout', $this->Form->formValues(), ''), 'Vanilla.Categories.Layout' => val('CategoriesLayout', $this->Form->formValues(), '') )); $this->informMessage(t("Your changes were saved successfully.")); } $this->render(); } /** * * * @throws Exception */ public function configuration() { $this->permission('Garden.Settings.Manage'); $this->deliveryMethod(DELIVERY_METHOD_JSON); $this->deliveryType(DELIVERY_TYPE_DATA); $ConfigData = array( 'Title' => c('Garden.Title'), 'Domain' => c('Garden.Domain'), 'Cookie' => c('Garden.Cookie'), 'Theme' => c('Garden.Theme'), 'Analytics' => array( 'InstallationID' => c('Garden.InstallationID'), 'InstallationSecret' => c('Garden.InstallationSecret') ) ); $Config = Gdn_Configuration::format($ConfigData, array( 'FormatStyle' => 'Dotted', 'WrapPHP' => false, 'SafePHP' => false, 'Headings' => false, 'ByLine' => false, )); $Configuration = array(); eval($Config); $this->setData('Configuration', $Configuration); $this->render(); } /** * Outgoing Email management screen. * * @since 2.0.0 * @access public */ public function email() { $this->permission('Garden.Settings.Manage'); $this->addSideMenu('dashboard/settings/email'); $this->addJsFile('email.js'); $this->title(t('Outgoing Email')); $Validation = new Gdn_Validation(); $ConfigurationModel = new Gdn_ConfigurationModel($Validation); $ConfigurationModel->setField(array( 'Garden.Email.SupportName', 'Garden.Email.SupportAddress', 'Garden.Email.UseSmtp', 'Garden.Email.SmtpHost', 'Garden.Email.SmtpUser', 'Garden.Email.SmtpPassword', 'Garden.Email.SmtpPort', 'Garden.Email.SmtpSecurity' )); // Set the model on the form. $this->Form->setModel($ConfigurationModel); // If seeing the form for the first time... if ($this->Form->authenticatedPostBack() === false) { // Apply the config settings to the form. $this->Form->setData($ConfigurationModel->Data); } else { // Define some validation rules for the fields being saved $ConfigurationModel->Validation->applyRule('Garden.Email.SupportName', 'Required'); $ConfigurationModel->Validation->applyRule('Garden.Email.SupportAddress', 'Required'); $ConfigurationModel->Validation->applyRule('Garden.Email.SupportAddress', 'Email'); if ($this->Form->save() !== false) { $this->informMessage(t("Your settings have been saved.")); } } $this->render(); } /** * Main dashboard. * * You can override this method with a method in your plugin named * SettingsController_Index_Create. You can hook into it with methods named * SettingsController_Index_Before and SettingsController_Index_After. * * @since 2.0.0 * @access public */ public function xIndex() { $this->addJsFile('settings.js'); $this->title(t('Dashboard')); $this->RequiredAdminPermissions[] = 'Garden.Settings.View'; $this->RequiredAdminPermissions[] = 'Garden.Settings.Manage'; $this->RequiredAdminPermissions[] = 'Garden.Community.Manage'; $this->RequiredAdminPermissions[] = 'Garden.Users.Add'; $this->RequiredAdminPermissions[] = 'Garden.Users.Edit'; $this->RequiredAdminPermissions[] = 'Garden.Users.Delete'; $this->RequiredAdminPermissions[] = 'Garden.Users.Approve'; $this->fireEvent('DefineAdminPermissions'); $this->permission($this->RequiredAdminPermissions, false); $this->addSideMenu('dashboard/settings'); $UserModel = Gdn::userModel(); // Get recently active users $this->ActiveUserData = $UserModel->getActiveUsers(5); // Check for updates $this->addUpdateCheck(); // Fire an event so other applications can add some data to be displayed $this->fireEvent('DashboardData'); $this->render(); } /** * Adds information to the definition list that causes the app to "phone * home" and see if there are upgrades available. * * Currently added to the dashboard only. Nothing renders with this method. * It is public so it can be added by plugins. */ public function addUpdateCheck() { if (c('Garden.NoUpdateCheck')) { return; } // Check to see if the application needs to phone-home for updates. Doing // this here because this method is always called when admin pages are // loaded regardless of the application loading them. $UpdateCheckDate = Gdn::config('Garden.UpdateCheckDate', ''); if ($UpdateCheckDate == '' // was not previous defined || !IsTimestamp($UpdateCheckDate) // was not a valid timestamp || $UpdateCheckDate < strtotime("-1 day") // was not done within the last day ) { $UpdateData = array(); // Grab all of the plugins & versions $Plugins = Gdn::pluginManager()->availablePlugins(); foreach ($Plugins as $Plugin => $Info) { $Name = arrayValue('Name', $Info, $Plugin); $Version = arrayValue('Version', $Info, ''); if ($Version != '') { $UpdateData[] = array( 'Name' => $Name, 'Version' => $Version, 'Type' => 'Plugin' ); } } // Grab all of the applications & versions $ApplicationManager = Gdn::factory('ApplicationManager'); $Applications = $ApplicationManager->availableApplications(); foreach ($Applications as $Application => $Info) { $Name = arrayValue('Name', $Info, $Application); $Version = arrayValue('Version', $Info, ''); if ($Version != '') { $UpdateData[] = array( 'Name' => $Name, 'Version' => $Version, 'Type' => 'Application' ); } } // Grab all of the themes & versions $ThemeManager = new Gdn_ThemeManager; $Themes = $ThemeManager->availableThemes(); foreach ($Themes as $Theme => $Info) { $Name = arrayValue('Name', $Info, $Theme); $Version = arrayValue('Version', $Info, ''); if ($Version != '') { $UpdateData[] = array( 'Name' => $Name, 'Version' => $Version, 'Type' => 'Theme' ); } } // Dump the entire set of information into the definition list (jQuery // will pick it up and ping the VanillaForums.org server with this info). $this->addDefinition('UpdateChecks', Gdn_Format::serialize($UpdateData)); } } /** * Manage list of locales. * * @since 2.0.0 * @access public * @param string $Op 'enable' or 'disable' * @param string $LocaleKey Unique ID of locale to be modified. * @param string $TransientKey Security token. */ public function locales($Op = null, $LocaleKey = null, $TransientKey = null) { $this->permission('Garden.Settings.Manage'); $this->title(t('Locales')); $this->addSideMenu('dashboard/settings/locales'); $this->addJsFile('addons.js'); $LocaleModel = new LocaleModel(); // Get the available locale packs. $AvailableLocales = $LocaleModel->availableLocalePacks(); // Get the enabled locale packs. $EnabledLocales = $LocaleModel->enabledLocalePacks(); // Check to enable/disable a locale. if (($TransientKey && Gdn::session()->validateTransientKey($TransientKey)) || $this->Form->authenticatedPostBack()) { if ($Op) { $Refresh = false; switch (strtolower($Op)) { case 'enable': $Locale = val($LocaleKey, $AvailableLocales); if (!is_array($Locale)) { $this->Form->addError('@'.sprintf(t('The %s locale pack does not exist.'), htmlspecialchars($LocaleKey)), 'LocaleKey'); } elseif (!isset($Locale['Locale'])) { $this->Form->addError('ValidateRequired', 'Locale'); } else { saveToConfig("EnabledLocales.$LocaleKey", $Locale['Locale']); $EnabledLocales[$LocaleKey] = $Locale['Locale']; $Refresh = true; } break; case 'disable': RemoveFromConfig("EnabledLocales.$LocaleKey"); unset($EnabledLocales[$LocaleKey]); $Refresh = true; break; } // Set default locale field if just doing enable/disable $this->Form->setValue('Locale', Gdn_Locale::canonicalize(c('Garden.Locale', 'en'))); } elseif ($this->Form->authenticatedPostBack()) { // Save the default locale. saveToConfig('Garden.Locale', $this->Form->getFormValue('Locale')); $Refresh = true; $this->informMessage(t("Your changes have been saved.")); } if ($Refresh) { Gdn::locale()->refresh(); redirect('/settings/locales'); } } elseif (!$this->Form->isPostBack()) { $this->Form->setValue('Locale', Gdn_Locale::canonicalize(c('Garden.Locale', 'en'))); } // Check for the default locale warning. $DefaultLocale = Gdn_Locale::canonicalize(c('Garden.Locale')); if ($DefaultLocale !== 'en') { $LocaleFound = false; $MatchingLocales = array(); foreach ($AvailableLocales as $Key => $LocaleInfo) { $Locale = val('Locale', $LocaleInfo); if ($Locale == $DefaultLocale) { $MatchingLocales[] = val('Name', $LocaleInfo, $Key); } if (val($Key, $EnabledLocales) == $DefaultLocale) { $LocaleFound = true; } } $this->setData('DefaultLocale', $DefaultLocale); $this->setData('DefaultLocaleWarning', !$LocaleFound); $this->setData('MatchingLocalePacks', htmlspecialchars(implode(', ', $MatchingLocales))); } $this->setData('AvailableLocales', $AvailableLocales); $this->setData('EnabledLocales', $EnabledLocales); $this->setData('Locales', $LocaleModel->availableLocales()); $this->render(); } /** * Manage list of plugins. * * @since 2.0.0 * @access public * @param string $Filter 'enabled', 'disabled', or 'all' (default) * @param string $PluginName Unique ID of plugin to be modified. * @param string $TransientKey Security token. */ public function plugins($Filter = '', $PluginName = '', $TransientKey = '') { $this->permission('Garden.Settings.Manage'); // Page setup $this->addJsFile('addons.js'); $this->title(t('Plugins')); $this->addSideMenu('dashboard/settings/plugins'); // Validate and set properties $Session = Gdn::session(); if ($PluginName && !$Session->validateTransientKey($TransientKey)) { $PluginName = ''; } if (!in_array($Filter, array('enabled', 'disabled'))) { $Filter = 'all'; } $this->Filter = $Filter; // Retrieve all available plugins from the plugins directory $this->EnabledPlugins = Gdn::pluginManager()->enabledPlugins(); self::sortAddons($this->EnabledPlugins); $this->AvailablePlugins = Gdn::pluginManager()->availablePlugins(); self::sortAddons($this->AvailablePlugins); if ($PluginName != '') { try { $this->EventArguments['PluginName'] = $PluginName; if (array_key_exists($PluginName, $this->EnabledPlugins) === true) { Gdn::pluginManager()->disablePlugin($PluginName); Gdn_LibraryMap::clearCache(); $this->fireEvent('AfterDisablePlugin'); } else { $Validation = new Gdn_Validation(); if (!Gdn::pluginManager()->enablePlugin($PluginName, $Validation)) { $this->Form->setValidationResults($Validation->results()); } else { Gdn_LibraryMap::ClearCache(); } $this->EventArguments['Validation'] = $Validation; $this->fireEvent('AfterEnablePlugin'); } } catch (Exception $e) { $this->Form->addError($e); } if ($this->Form->errorCount() == 0) { redirect('/settings/plugins/'.$this->Filter); } } $this->render(); } /** * Configuration of registration settings. * * Events: BeforeRegistrationUpdate * * @since 2.0.0 * @access public * @param string $RedirectUrl Where to send user after registration. */ public function registration($RedirectUrl = '') { $this->permission('Garden.Settings.Manage'); $this->addSideMenu('dashboard/settings/registration'); $this->addJsFile('registration.js'); $this->title(t('Registration')); // Create a model to save configuration settings $Validation = new Gdn_Validation(); $ConfigurationModel = new Gdn_ConfigurationModel($Validation); $ConfigurationModel->setField(array( 'Garden.Registration.Method' => 'Captcha', 'Garden.Registration.CaptchaPrivateKey', 'Garden.Registration.CaptchaPublicKey', 'Garden.Registration.InviteExpiration', 'Garden.Registration.ConfirmEmail' )); // Set the model on the forms. $this->Form->setModel($ConfigurationModel); // Load roles with sign-in permission $RoleModel = new RoleModel(); $this->RoleData = $RoleModel->getByPermission('Garden.SignIn.Allow'); $this->setData('_Roles', array_column($this->RoleData->resultArray(), 'Name', 'RoleID')); // Get currently selected InvitationOptions $this->ExistingRoleInvitations = Gdn::config('Garden.Registration.InviteRoles'); if (is_array($this->ExistingRoleInvitations) === false) { $this->ExistingRoleInvitations = array(); } // Get the currently selected Expiration Length $this->InviteExpiration = Gdn::config('Garden.Registration.InviteExpiration', ''); // Registration methods. $this->RegistrationMethods = array( // 'Closed' => "Registration is closed.", // 'Basic' => "The applicants are granted access immediately.", 'Captcha' => "New users fill out a simple form and are granted access immediately.", 'Approval' => "New users are reviewed and approved by an administrator (that's you!).", 'Invitation' => "Existing members send invitations to new members.", 'Connect' => "New users are only registered through SSO plugins." ); // Options for how many invitations a role can send out per month. $this->InvitationOptions = array( '0' => t('None'), '1' => '1', '2' => '2', '5' => '5', '-1' => t('Unlimited') ); // Options for when invitations should expire. $this->InviteExpirationOptions = array( '1 week' => t('1 week after being sent'), '2 weeks' => t('2 weeks after being sent'), '1 month' => t('1 month after being sent'), 'FALSE' => t('never') ); if ($this->Form->authenticatedPostBack() === false) { $this->Form->setData($ConfigurationModel->Data); } else { // Define some validation rules for the fields being saved $ConfigurationModel->Validation->applyRule('Garden.Registration.Method', 'Required'); // Define the Garden.Registration.RoleInvitations setting based on the postback values $InvitationRoleIDs = $this->Form->getValue('InvitationRoleID'); $InvitationCounts = $this->Form->getValue('InvitationCount'); $this->ExistingRoleInvitations = arrayCombine($InvitationRoleIDs, $InvitationCounts); $ConfigurationModel->forceSetting('Garden.Registration.InviteRoles', $this->ExistingRoleInvitations); // Event hook $this->EventArguments['ConfigurationModel'] = &$ConfigurationModel; $this->fireEvent('BeforeRegistrationUpdate'); // Save! if ($this->Form->save() !== false) { $this->informMessage(t("Your settings have been saved.")); if ($RedirectUrl != '') { $this->RedirectUrl = $RedirectUrl; } } } $this->render(); } /** * Sort list of addons for display. * * @since 2.0.0 * @access public * @param array $Array Addon data (e.g. $PluginInfo). * @param bool $Filter Whether to exclude hidden addons (defaults to TRUE). */ public static function sortAddons(&$Array, $Filter = true) { // Make sure every addon has a name. foreach ($Array as $Key => $Value) { if ($Filter && val('Hidden', $Value)) { unset($Array[$Key]); continue; } $Name = val('Name', $Value, $Key); setValue('Name', $Array[$Key], $Name); } uasort($Array, array('SettingsController', 'CompareAddonName')); } /** * Compare addon names for uasort. * * @since 2.0.0 * @access public * @see self::SortAddons() * @param array $A First addon data. * @param array $B Second addon data. * @return int Result of strcasecmp. */ public static function compareAddonName($A, $B) { return strcasecmp(val('Name', $A), val('Name', $B)); } /** * Test and addon to see if there are any fatal errors during install. * * @since 2.0.0 * @access public * @param string $AddonType * @param string $AddonName * @param string $TransientKey Security token. */ public function testAddon($AddonType = '', $AddonName = '', $TransientKey = '') { if (!in_array($AddonType, array('Plugin', 'Application', 'Theme', 'Locale'))) { $AddonType = 'Plugin'; } $Session = Gdn::session(); $AddonName = $Session->validateTransientKey($TransientKey) ? $AddonName : ''; if ($AddonType == 'Locale') { $AddonManager = new LocaleModel(); $TestMethod = 'TestLocale'; } else { $AddonManagerName = $AddonType.'Manager'; $TestMethod = 'Test'.$AddonType; $AddonManager = Gdn::Factory($AddonManagerName); } if ($AddonName != '') { $Validation = new Gdn_Validation(); try { $AddonManager->$TestMethod($AddonName, $Validation); } catch (Exception $Ex) { if (Debug()) { throw $Ex; } else { echo $Ex->getMessage(); return; } } } ob_clean(); echo 'Success'; } /** * Manage options for a theme. * * @since 2.0.0 * @access public * @param string $Style Unique ID. * @todo Why is this in a giant try/catch block? */ public function themeOptions($Style = null) { $this->permission('Garden.Settings.Manage'); try { $this->addJsFile('addons.js'); $this->addSideMenu('dashboard/settings/themeoptions'); $ThemeManager = new Gdn_ThemeManager(); $this->setData('ThemeInfo', $ThemeManager->enabledThemeInfo()); if ($this->Form->authenticatedPostBack()) { // Save the styles to the config. $StyleKey = $this->Form->getFormValue('StyleKey'); $ConfigSaveData = array( 'Garden.ThemeOptions.Styles.Key' => $StyleKey, 'Garden.ThemeOptions.Styles.Value' => $this->data("ThemeInfo.Options.Styles.$StyleKey.Basename")); // Save the text to the locale. $Translations = array(); foreach ($this->data('ThemeInfo.Options.Text', array()) as $Key => $Default) { $Value = $this->Form->getFormValue($this->Form->escapeString('Text_'.$Key)); $ConfigSaveData["ThemeOption.{$Key}"] = $Value; //$this->Form->setFormValue('Text_'.$Key, $Value); } saveToConfig($ConfigSaveData); $this->informMessage(t("Your changes have been saved.")); } elseif ($Style) { saveToConfig(array( 'Garden.ThemeOptions.Styles.Key' => $Style, 'Garden.ThemeOptions.Styles.Value' => $this->data("ThemeInfo.Options.Styles.$Style.Basename"))); } $this->setData('ThemeOptions', c('Garden.ThemeOptions')); $StyleKey = $this->data('ThemeOptions.Styles.Key'); if (!$this->Form->isPostBack()) { foreach ($this->data('ThemeInfo.Options.Text', array()) as $Key => $Options) { $Default = val('Default', $Options, ''); $Value = c("ThemeOption.{$Key}", '#DEFAULT#'); if ($Value === '#DEFAULT#') { $Value = $Default; } $this->Form->setFormValue($this->Form->escapeString('Text_'.$Key), $Value); } } $this->setData('ThemeFolder', $ThemeManager->enabledTheme()); $this->title(t('Theme Options')); $this->Form->addHidden('StyleKey', $StyleKey); } catch (Exception $Ex) { $this->Form->addError($Ex); } $this->render(); } /** * Manage options for a mobile theme. * * @since 2.0.0 * @access public * @param string $Style Unique ID. * @todo Why is this in a giant try/catch block? */ public function mobileThemeOptions($Style = null) { $this->permission('Garden.Settings.Manage'); try { $this->addJsFile('addons.js'); $this->addSideMenu('dashboard/settings/mobilethemeoptions'); $ThemeManager = Gdn::themeManager(); $EnabledThemeName = $ThemeManager->mobileTheme(); $EnabledThemeInfo = $ThemeManager->getThemeInfo($EnabledThemeName); $this->setData('ThemeInfo', $EnabledThemeInfo); if ($this->Form->authenticatedPostBack()) { // Save the styles to the config. $StyleKey = $this->Form->getFormValue('StyleKey'); $ConfigSaveData = array( 'Garden.MobileThemeOptions.Styles.Key' => $StyleKey, 'Garden.MobileThemeOptions.Styles.Value' => $this->data("ThemeInfo.Options.Styles.$StyleKey.Basename")); // Save the text to the locale. $Translations = array(); foreach ($this->data('ThemeInfo.Options.Text', array()) as $Key => $Default) { $Value = $this->Form->getFormValue($this->Form->escapeString('Text_'.$Key)); $ConfigSaveData["ThemeOption.{$Key}"] = $Value; //$this->Form->setFormValue('Text_'.$Key, $Value); } saveToConfig($ConfigSaveData); $this->informMessage(t("Your changes have been saved.")); } elseif ($Style) { saveToConfig(array( 'Garden.MobileThemeOptions.Styles.Key' => $Style, 'Garden.MobileThemeOptions.Styles.Value' => $this->data("ThemeInfo.Options.Styles.$Style.Basename"))); } $this->setData('ThemeOptions', c('Garden.MobileThemeOptions')); $StyleKey = $this->data('ThemeOptions.Styles.Key'); if (!$this->Form->authenticatedPostBack()) { foreach ($this->data('ThemeInfo.Options.Text', array()) as $Key => $Options) { $Default = val('Default', $Options, ''); $Value = c("ThemeOption.{$Key}", '#DEFAULT#'); if ($Value === '#DEFAULT#') { $Value = $Default; } $this->Form->setFormValue($this->Form->escapeString('Text_'.$Key), $Value); } } $this->setData('ThemeFolder', $EnabledThemeName); $this->title(t('Mobile Theme Options')); $this->Form->addHidden('StyleKey', $StyleKey); } catch (Exception $Ex) { $this->Form->addError($Ex); } $this->render('themeoptions'); } /** * Themes management screen. * * @since 2.0.0 * @access public * @param string $ThemeName Unique ID. * @param string $TransientKey Security token. */ public function themes($ThemeName = '', $TransientKey = '') { $this->addJsFile('addons.js'); $this->setData('Title', t('Themes')); $this->permission('Garden.Settings.Manage'); $this->addSideMenu('dashboard/settings/themes'); $ThemeInfo = Gdn::themeManager()->enabledThemeInfo(true); $this->setData('EnabledThemeFolder', val('Folder', $ThemeInfo)); $this->setData('EnabledTheme', Gdn::themeManager()->enabledThemeInfo()); $this->setData('EnabledThemeName', val('Name', $ThemeInfo, val('Index', $ThemeInfo))); $Themes = Gdn::themeManager()->availableThemes(); uasort($Themes, array('SettingsController', '_NameSort')); // Remove themes that are archived $Remove = array(); foreach ($Themes as $Index => $Theme) { $Archived = val('Archived', $Theme); if ($Archived) { $Remove[] = $Index; } // Remove mobile themes, as they have own page. if (isset($Theme['IsMobile']) && $Theme['IsMobile']) { unset($Themes[$Index]); } } foreach ($Remove as $Index) { unset($Themes[$Index]); } $this->setData('AvailableThemes', $Themes); if ($ThemeName != '' && Gdn::session()->validateTransientKey($TransientKey)) { try { $ThemeInfo = Gdn::themeManager()->getThemeInfo($ThemeName); if ($ThemeInfo === false) { throw new Exception(sprintf(t("Could not find a theme identified by '%s'"), $ThemeName)); } Gdn::session()->setPreference(array('PreviewThemeName' => '', 'PreviewThemeFolder' => '')); // Clear out the preview Gdn::themeManager()->enableTheme($ThemeName); $this->EventArguments['ThemeName'] = $ThemeName; $this->EventArguments['ThemeInfo'] = $ThemeInfo; $this->fireEvent('AfterEnableTheme'); } catch (Exception $Ex) { $this->Form->addError($Ex); } if ($this->Form->errorCount() == 0) { redirect('/settings/themes'); } } $this->render(); } /** * Mobile Themes management screen. * * @since 2.2.10.3 * @access public * @param string $ThemeName Unique ID. * @param string $TransientKey Security token. */ public function mobileThemes($ThemeName = '', $TransientKey = '') { $IsMobile = true; $this->addJsFile('addons.js'); $this->addJsFile('addons.js'); $this->setData('Title', t('Mobile Themes')); $this->permission('Garden.Settings.Manage'); $this->addSideMenu('dashboard/settings/mobilethemes'); // Get currently enabled theme. $EnabledThemeName = Gdn::ThemeManager()->MobileTheme(); $ThemeInfo = Gdn::themeManager()->getThemeInfo($EnabledThemeName); $this->setData('EnabledThemeInfo', $ThemeInfo); $this->setData('EnabledThemeFolder', val('Folder', $ThemeInfo)); $this->setData('EnabledTheme', $ThemeInfo); $this->setData('EnabledThemeName', val('Name', $ThemeInfo, val('Index', $ThemeInfo))); // Get all themes. $Themes = Gdn::themeManager()->availableThemes(); // Filter themes. foreach ($Themes as $ThemeKey => $ThemeData) { // Only show mobile themes. if (empty($ThemeData['IsMobile'])) { unset($Themes[$ThemeKey]); } // Remove themes that are archived if (!empty($ThemeData['Archived'])) { unset($Themes[$ThemeKey]); } } uasort($Themes, array('SettingsController', '_NameSort')); $this->setData('AvailableThemes', $Themes); // Process self-post. if ($ThemeName != '' && Gdn::session()->validateTransientKey($TransientKey)) { try { $ThemeInfo = Gdn::themeManager()->getThemeInfo($ThemeName); if ($ThemeInfo === false) { throw new Exception(sprintf(t("Could not find a theme identified by '%s'"), $ThemeName)); } Gdn::session()->setPreference(array('PreviewThemeName' => '', 'PreviewThemeFolder' => '')); // Clear out the preview Gdn::themeManager()->enableTheme($ThemeName, $IsMobile); $this->EventArguments['ThemeName'] = $ThemeName; $this->EventArguments['ThemeInfo'] = $ThemeInfo; $this->fireEvent('AfterEnableTheme'); } catch (Exception $Ex) { $this->Form->addError($Ex); } $AsyncRequest = ($this->deliveryType() === DELIVERY_TYPE_VIEW) ? true : false; if ($this->Form->errorCount() == 0) { if ($AsyncRequest) { echo 'Success'; $this->render('Blank', 'Utility', 'Dashboard'); exit; } else { redirect('/settings/mobilethemes'); } } else { if ($AsyncRequest) { echo $this->Form->errorString(); $this->render('Blank', 'Utility', 'Dashboard'); exit; } } } $this->render(); } protected static function _nameSort($A, $B) { return strcasecmp(val('Name', $A), val('Name', $B)); } /** * Show a preview of a theme. * * @since 2.0.0 * @access public * @param string $ThemeName Unique ID. */ public function previewTheme($ThemeName = '') { $this->permission('Garden.Settings.Manage'); $ThemeInfo = Gdn::themeManager()->getThemeInfo($ThemeName); $PreviewThemeName = $ThemeName; $PreviewThemeFolder = val('Folder', $ThemeInfo); $IsMobile = val('IsMobile', $ThemeInfo); // If we failed to get the requested theme, cancel preview if ($ThemeInfo === false) { $PreviewThemeName = ''; $PreviewThemeFolder = ''; } Gdn::session()->setPreference(array( 'PreviewThemeName' => $PreviewThemeName, 'PreviewThemeFolder' => $PreviewThemeFolder, 'PreviewIsMobile' => $IsMobile )); redirect('/'); } /** * Closes current theme preview. * * @since 2.0.0 * @access public */ public function cancelPreview() { $Session = Gdn::session(); $IsMobile = $Session->User->Preferences['PreviewIsMobile']; $Session->setPreference(array('PreviewThemeName' => '', 'PreviewThemeFolder' => '', 'PreviewIsMobile' => '')); if ($IsMobile) { redirect('settings/mobilethemes'); } else { redirect('settings/themes'); } } /** * Remove the logo from config & delete it. * * @since 2.1 * @param string $TransientKey Security token. */ public function removeFavicon($TransientKey = '') { $Session = Gdn::session(); if ($Session->validateTransientKey($TransientKey) && $Session->checkPermission('Garden.Community.Manage')) { $Favicon = c('Garden.FavIcon', ''); RemoveFromConfig('Garden.FavIcon'); $Upload = new Gdn_Upload(); $Upload->delete($Favicon); } redirect('/settings/banner'); } /** * Remove the share image from config & delete it. * * @since 2.1 * @param string $TransientKey Security token. */ public function removeShareImage($TransientKey = '') { $this->permission('Garden.Community.Manage'); if (Gdn::request()->isAuthenticatedPostBack()) { $ShareImage = c('Garden.ShareImage', ''); removeFromConfig('Garden.ShareImage'); $Upload = new Gdn_Upload(); $Upload->delete($ShareImage); } $this->RedirectUrl = '/settings/banner'; $this->render('Blank', 'Utility'); } /** * Remove the logo from config & delete it. * * @since 2.0.0 * @access public * @param string $TransientKey Security token. */ public function removeLogo($TransientKey = '') { $Session = Gdn::session(); if ($Session->validateTransientKey($TransientKey) && $Session->checkPermission('Garden.Community.Manage')) { $Logo = c('Garden.Logo', ''); RemoveFromConfig('Garden.Logo'); @unlink(PATH_ROOT.DS.$Logo); } redirect('/settings/banner'); } /** * Remove the mobile logo from config & delete it. * * @since 2.0.0 * @access public * @param string $TransientKey Security token. */ public function removeMobileLogo($TransientKey = '') { $Session = Gdn::session(); if ($Session->validateTransientKey($TransientKey) && $Session->checkPermission('Garden.Community.Manage')) { $MobileLogo = c('Garden.MobileLogo', ''); RemoveFromConfig('Garden.MobileLogo'); @unlink(PATH_ROOT.DS.$MobileLogo); } redirect('/settings/banner'); } /** * Prompts new admins how to get started using new install. * * @since 2.0.0 * @access public */ public function gettingStarted() { $this->permission('Garden.Settings.Manage'); $this->setData('Title', t('Getting Started')); $this->addSideMenu('dashboard/settings/gettingstarted'); $this->TextEnterEmails = t('TextEnterEmails', 'Type email addresses separated by commas here'); if ($this->Form->authenticatedPostBack()) { // Do invitations to new members. $Message = $this->Form->getFormValue('InvitationMessage'); $Message .= "\n\n".Gdn::request()->Url('/', true); $Message = trim($Message); $Recipients = $this->Form->getFormValue('Recipients'); if ($Recipients == $this->TextEnterEmails) { $Recipients = ''; } $Recipients = explode(',', $Recipients); $CountRecipients = 0; foreach ($Recipients as $Recipient) { if (trim($Recipient) != '') { $CountRecipients++; if (!validateEmail($Recipient)) { $this->Form->addError(sprintf(t('%s is not a valid email address'), $Recipient)); } } } if ($CountRecipients == 0) { $this->Form->addError(t('You must provide at least one recipient')); } if ($this->Form->errorCount() == 0) { $Email = new Gdn_Email(); $Email->subject(t('Check out my new community!')); $Email->message($Message); foreach ($Recipients as $Recipient) { if (trim($Recipient) != '') { $Email->to($Recipient); try { $Email->send(); } catch (Exception $ex) { $this->Form->addError($ex); } } } } if ($this->Form->errorCount() == 0) { $this->informMessage(t('Your invitations were sent successfully.')); } } $this->render(); } /** * * * @param string $Tutorial */ public function tutorials($Tutorial = '') { $this->setData('Title', t('Help &amp; Tutorials')); $this->addSideMenu('dashboard/settings/tutorials'); $this->setData('CurrentTutorial', $Tutorial); $this->render(); } }
ych06/vanilla
applications/dashboard/controllers/class.settingscontroller.php
PHP
gpl-2.0
51,584
<?php /** * Comments Loop Widget * * @since 0.1 */ // WIDGET CLASS class Bizz_Widget_Comments_Loop extends WP_Widget { function Bizz_Widget_Comments_Loop() { $widget_ops = array( 'classname' => 'bizz-comments-loop', 'description' => __( 'Display Comments', 'bizzthemes' ) ); $control_ops = array( 'width' => 500, 'height' => 350, 'id_base' => 'bizz-comments-loop' ); $this->WP_Widget( 'bizz-comments-loop', __('Comments', 'bizzthemes'), $widget_ops, $control_ops ); } function widget( $args, $instance ) { global $wpdb, $wp_query, $post, $user_ID, $comment, $overridden_bizzpage; $form_args = array_merge( $args, $instance ); // If the comments have been modified by a third-party plugin (there is a filter hook on comments_template) then call the WordPress default comments if ( has_filter('comments_template') && !class_exists('Woocommerce') ): // call the WordPress default comment template comments_template(); // show the bizz comments else: // Will not display the comments template if not on single post or page. if ( !is_singular() || empty($post) ) return false; // Will not display the comments loop if the post does not have comments. if ( '0' != $post->comment_count ) { // Comment author information fetched from the comment cookies. $commenter = wp_get_current_commenter(); // The name of the current comment author escaped for use in attributes. $comment_author = $commenter['comment_author']; // Escaped by sanitize_comment_cookies() // The email address of the current comment author escaped for use in attributes. $comment_author_email = $commenter['comment_author_email']; // Escaped by sanitize_comment_cookies() // The url of the current comment author escaped for use in attributes. $comment_author_url = esc_url($commenter['comment_author_url']); // allow widget to override $post->ID $post_id = $post->ID; // Grabs the comments for the $post->ID from the db. if ( $user_ID ) $comments = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND (comment_approved = '1' OR ( user_id = %d AND comment_approved = '0' ) ) ORDER BY comment_date_gmt", $post_id, $user_ID)); else if ( empty($comment_author) ) $comments = get_comments( array('post_id' => $post_id, 'status' => 'approve', 'order' => 'ASC') ); else $comments = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND ( comment_approved = '1' OR ( comment_author = %s AND comment_author_email = %s AND comment_approved = '0' ) ) ORDER BY comment_date_gmt", $post_id, wp_specialchars_decode($comment_author,ENT_QUOTES), $comment_author_email)); // Adds the comments retrieved from the db into the main $wp_query $wp_query->comments = apply_filters( 'comments_array', $comments, $post_id ); // keep $comments for legacy's sake $comments = &$wp_query->comments; // Set the comment count $wp_query->comment_count = count($wp_query->comments); // Update the cache update_comment_cache( $wp_query->comments ); // Paged comments $overridden_bizzpage = FALSE; if ( '' == get_query_var('bizzpage') && get_option('page_comments') ) { set_query_var( 'bizzpage', 'newest' == get_option('default_comments_page') ? get_comment_pages_count() : 1 ); $overridden_bizzpage = TRUE; } /**//**/// All the preliminary work is complete. Let's get down to business... $wp_list_comments_args = array(); $wp_list_comments_args['type'] = $instance['type']; $wp_list_comments_args['reply_text'] = (string) $instance['reply_text']; $wp_list_comments_args['login_text'] = (string) $instance['login_text']; $wp_list_comments_args['max_depth'] = (int) $instance['max_depth']; $wp_list_comments_args['enable_reply'] = $instance['enable_reply']; $wp_list_comments_args['comment_meta'] = $instance['comment_meta']; $wp_list_comments_args['comment_moderation'] = $instance['comment_moderation']; $wp_list_comments_args['callback'] = 'bizz_comments_loop_callback'; $wp_list_comments_args['password_text'] = $instance['password_text']; $wp_list_comments_args['pass_protected_text'] = $instance['pass_protected_text']; $wp_list_comments_args['sing_comment_text'] = $instance['sing_comment_text']; $wp_list_comments_args['plu_comment_text'] = $instance['plu_comment_text']; $wp_list_comments_args['sing_trackback_text'] = $instance['sing_trackback_text']; $wp_list_comments_args['plu_trackback_text'] = $instance['plu_trackback_text']; $wp_list_comments_args['sing_pingback_text'] = $instance['sing_pingback_text']; $wp_list_comments_args['plu_pingback_text'] = $instance['plu_pingback_text']; $wp_list_comments_args['sing_ping_text'] = $instance['sing_ping_text']; $wp_list_comments_args['plu_ping_text'] = $instance['plu_ping_text']; $wp_list_comments_args['no_text'] = $instance['no_text']; $wp_list_comments_args['to_text'] = $instance['to_text']; $paginate_comments_links = paginate_comments_links( array('echo' => false) ); $wp_list_comments_args['reverse_top_level'] = $instance['reverse_top_level']; $comment_type = 'all' == $instance['type'] ? 'comment' : $instance['type']; $type_plural = 'pings' == $comment_type ? $comment_type : "{$comment_type}s"; $type_singular = 'pings' == $comment_type ? 'ping' : $comment_type; ($type_plural=='comments') ? $type_plural=$wp_list_comments_args['plu_comment_text'] : $type_plural=$type_plural; ($type_plural=='trackbacks') ? $type_plural=$wp_list_comments_args['plu_trackback_text'] : $type_plural=$type_plural; ($type_plural=='pingbacks') ? $type_plural=$wp_list_comments_args['plu_pingback_text'] : $type_plural=$type_plural; ($type_plural=='pings') ? $type_plural=$wp_list_comments_args['plu_ping_text'] : $type_plural=$type_plural; ($type_singular=='comment') ? $type_singular=$wp_list_comments_args['sing_comment_text'] : $type_singular=$type_singular; ($type_singular=='trackback') ? $type_singular=$wp_list_comments_args['sing_trackback_text'] : $type_singular=$type_singular; ($type_singular=='pingback') ? $type_singular=$wp_list_comments_args['sing_pingback_text'] : $type_singular=$type_singular; ($type_singular=='ping') ? $type_singular=$wp_list_comments_args['sing_ping_text'] : $type_singular=$type_singular; // Check to see if post is password protected if ( post_password_required() ) { echo "<{$instance['comment_header']}>".$wp_list_comments_args['password_text']."</{$instance['comment_header']}>"; echo '<p class="'. $post->post_type .'_password_required">'. $post->post_type . $wp_list_comments_args['pass_protected_text'] .'</p>'; do_action( "{$post->post_type}_password_required" ); return false; } echo '<div id="bizz-comments-loop-'. $post_id .'" class="widget-bizz-comments-loop">'; /* Open the output of the widget. */ echo $args['before_widget']; // If we have comments if ( have_comments() ) : do_action( "before_{$comment_type}_div" ); $div_id = ( 'comment' == $comment_type ) ? 'comments' : $comment_type; echo '<div id="'. $div_id .'">'; // div#comments $title = the_title( '&#8220;', '&#8221;', false ); $local_comments = $comments; $_comments_by_type = &separate_comments( $local_comments ); echo "<{$instance['comment_header']} id=\"comments-number\" class=\"comments-header\">"; bizz_comments_number( "".$wp_list_comments_args['no_text']." $type_plural ".$wp_list_comments_args['to_text']." $title", "1 $type_singular ".$wp_list_comments_args['to_text']." $title", "% $type_plural ".$wp_list_comments_args['to_text']." $title", $instance['type'], $_comments_by_type ); echo "</{$instance['comment_header']}>"; unset( $local_comments, $_comments_by_type ); ?> <?php if ( $instance['enable_pagination'] and get_option( 'page_comments' ) and $paginate_comments_links ) : ?> <div class="comment-navigation paged-navigation"> <?php echo $paginate_comments_links; ?> <?php do_action( "{$comment_type}_pagination" ); ?> </div><!-- .comment-navigation --> <?php endif; ?> <?php do_action( "before_{$comment_type}_list" ); ?> <ol class="commentlist"> <?php wp_list_comments( $wp_list_comments_args ); ?> </ol> <?php do_action( "after_{$comment_type}_list" ); ?> <?php if ( $instance['enable_pagination'] and get_option( 'page_comments' ) and $paginate_comments_links ) : ?> <div class="comment-navigation paged-navigation"> <?php echo $paginate_comments_links; ?> <?php do_action( "{$comment_type}_pagination" ); ?> </div><!-- .comment-navigation --> <?php endif; ?> <?php echo '</div>'; // div#comments do_action( "after_{$comment_type}_div" ); endif; /* Close the output of the widget. */ echo $args['after_widget']; echo '</div>'; } /* Load Comments Form. */ bizz_comment_form( $form_args ); endif; } function update( $new_instance, $old_instance ) { $instance = $old_instance; $instance = $new_instance; // Checkboxes $instance['enable_pagination'] = $new_instance['enable_pagination'] ? true : false; $instance['enable_reply'] = $new_instance['enable_reply'] ? true : false; $instance['reverse_top_level'] = $new_instance['reverse_top_level'] ? true : false; $instance['comments_closed'] = esc_html( $new_instance['comments_closed'] ); $instance['req'] = $new_instance['req'] ? true : false; // update $instance with $new_instance; return $instance; } function form( $instance ) { $defaults = array( 'max_depth' => get_option('thread_comments_depth'), 'type' => 'all', 'enable_pagination' => true, 'enable_reply' => true, 'comment_header' => 'h3', 'reverse_top_level' => false, //'reverse_children' => false, 'reply_text' => __( 'Reply', 'bizzthemes' ), 'login_text' => __( 'Log in to Reply', 'bizzthemes' ), 'comment_meta' => '[author] [date before="&middot; "] [link before="&middot; "] [edit before="&middot; "]', 'comment_moderation' => __( 'Your comment is awaiting moderation.', 'bizzthemes' ), 'password_text' => __( 'Password Protected', 'bizzthemes' ), 'pass_protected_text' => __( 'is password protected. Enter the password to view comments.', 'bizzthemes' ), 'sing_comment_text' => __( 'comment', 'bizzthemes' ), 'plu_comment_text' => __( 'comments', 'bizzthemes' ), 'sing_trackback_text' => __( 'trackback', 'bizzthemes' ), 'plu_trackback_text' => __( 'trackbacks', 'bizzthemes' ), 'sing_pingback_text' => __( 'pingback', 'bizzthemes' ), 'plu_pingback_text' => __( 'pingbacks', 'bizzthemes' ), 'sing_ping_text' => __( 'ping', 'bizzthemes' ), 'plu_ping_text' => __( 'pings', 'bizzthemes' ), 'no_text' => __( 'No', 'bizzthemes' ), 'to_text' => __( 'to', 'bizzthemes' ), 'req' => true, 'req_str' => __( '(required)', 'bizzthemes' ), 'name' => __( 'Name', 'bizzthemes' ), 'email' => __( 'Mail (will not be published)', 'bizzthemes' ), 'url' => __( 'Website', 'bizzthemes' ), 'must_log_in' => __( 'You must be <a href="%s">logged in</a> to post a comment.', 'bizzthemes' ), 'logged_in_as' => __( 'Logged in as <a href="%s">%s</a>. <a href="%s" title="Log out of this account">Log out &raquo;</a>', 'bizzthemes' ), 'title_reply' => __( 'Leave a Reply', 'bizzthemes' ), 'title_reply_to' => __( 'Leave a Reply to %s', 'bizzthemes' ), 'cancel_reply_link' => __( 'Click here to cancel reply.', 'bizzthemes' ), 'label_submit' => __( 'Submit Comment', 'bizzthemes' ), 'title_reply_tag' => 'h3', 'comments_closed' => __( 'Comments are closed.', 'bizzthemes' ) ); $instance = wp_parse_args( $instance, $defaults ); $tags = array( 'h1' => 'h1', 'h2' => 'h2', 'h3' => 'h3', 'h4' => 'h4', 'h5' => 'h5', 'h6' => 'h6', 'p' => 'p', 'span' => 'span', 'div' => 'div' ); $type = array( 'all' => 'All', 'comment' => 'Comments', 'trackback' => 'Trackbacks', 'pingback' => 'Pingbacks', 'pings' => 'Trackbacks and Pingbacks' ); ?> <p> <label for="<?php echo $this->get_field_id( 'type' ); ?>"><?php _e( 'Comment type', 'bizzthemes' ); ?></label> <select class="widefat" id="<?php echo $this->get_field_id( 'type' ); ?>" name="<?php echo $this->get_field_name( 'type' ); ?>"> <?php foreach ( $type as $option_value => $option_label ) { ?> <option value="<?php echo $option_value; ?>" <?php selected( $instance['type'], $option_value ); ?>><?php echo $option_label; ?></option> <?php } ?> </select> </p> <p> <label for="<?php echo $this->get_field_id( 'comment_header' ); ?>"><?php _e( 'Comments headline tag', 'bizzthemes' ); ?></label> <select class="widefat" id="<?php echo $this->get_field_id( 'comment_header' ); ?>" name="<?php echo $this->get_field_name( 'comment_header' ); ?>"> <?php foreach ( $tags as $option_value => $option_label ) { ?> <option value="<?php echo $option_value; ?>" <?php selected( $instance['comment_header'], $option_value ); ?>><?php echo $option_label; ?></option> <?php } ?> </select> </p> <p> <label for="<?php echo $this->get_field_id( 'title_reply_tag' ); ?>"><?php _e( 'Reply headline tag', 'bizzthemes' ); ?></label> <select class="widefat" id="<?php echo $this->get_field_id( 'title_reply_tag' ); ?>" name="<?php echo $this->get_field_name( 'title_reply_tag' ); ?>"> <?php foreach ( $tags as $option_value => $option_label ) { ?> <option value="<?php echo $option_value; ?>" <?php selected( $instance['title_reply_tag'], $option_value ); ?>><?php echo $option_label; ?></option> <?php } ?> </select> </p> <p> <label for="<?php echo $this->get_field_id( 'comment_meta' ); ?>"><?php _e( 'Comment meta', 'bizzthemes' ); ?></label> <input type="text" class="widefat" id="<?php echo $this->get_field_id( 'comment_meta' ); ?>" name="<?php echo $this->get_field_name( 'comment_meta' ); ?>" value="<?php echo esc_attr($instance['comment_meta']); ?>" /> </p> <p> <label for="<?php echo $this->get_field_id( 'max_depth' ); ?>"><?php _e( 'Max depth', 'bizzthemes' ); ?></label> <input type="text" class="widefat" id="<?php echo $this->get_field_id( 'max_depth' ); ?>" name="<?php echo $this->get_field_name( 'max_depth' ); ?>" value="<?php echo $instance['max_depth']; ?>" /> </p> <p> <label for="<?php echo $this->get_field_id( 'req' ); ?>"> <input class="checkbox" type="checkbox" <?php checked( $instance['req'], true ); ?> id="<?php echo $this->get_field_id( 'req' ); ?>" name="<?php echo $this->get_field_name( 'req' ); ?>" /> <?php _e('Require name and email', 'bizzthemes'); ?></label> </p> <p> <label for="<?php echo $this->get_field_id( 'enable_pagination' ); ?>"> <input class="checkbox" type="checkbox" <?php checked( $instance['enable_pagination'], true ); ?> id="<?php echo $this->get_field_id( 'enable_pagination' ); ?>" name="<?php echo $this->get_field_name( 'enable_pagination' ); ?>" /> <?php _e('Enable pagination', 'bizzthemes'); ?></label> </p> <p> <label for="<?php echo $this->get_field_id( 'enable_reply' ); ?>"> <input class="checkbox" type="checkbox" <?php checked( $instance['enable_reply'], true ); ?> id="<?php echo $this->get_field_id( 'enable_reply' ); ?>" name="<?php echo $this->get_field_name( 'enable_reply' ); ?>" /> <?php _e('Enable comment reply', 'bizzthemes'); ?></label> </p> <p> <label for="<?php echo $this->get_field_id( 'reverse_top_level' ); ?>"> <input class="checkbox" type="checkbox" <?php checked( $instance['reverse_top_level'], true ); ?> id="<?php echo $this->get_field_id( 'reverse_top_level' ); ?>" name="<?php echo $this->get_field_name( 'reverse_top_level' ); ?>" /> <?php _e('Reverse the comment order', 'bizzthemes'); ?></label> </p> <p> <br/><label><span class="translate"><?php _e('Translations', 'bizzthemes'); ?></span></label> </p> <p> <label class="spb tog"><?php _e('comment list', 'bizzthemes'); ?></label> </p> <p> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'comment_moderation' ); ?>" name="<?php echo $this->get_field_name( 'comment_moderation' ); ?>" value="<?php echo $instance['comment_moderation']; ?>" /> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'reply_text' ); ?>" name="<?php echo $this->get_field_name( 'reply_text' ); ?>" value="<?php echo $instance['reply_text']; ?>" /> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'login_text' ); ?>" name="<?php echo $this->get_field_name( 'login_text' ); ?>" value="<?php echo $instance['login_text']; ?>" /> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'password_text' ); ?>" name="<?php echo $this->get_field_name( 'password_text' ); ?>" value="<?php echo $instance['password_text']; ?>" /> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'pass_protected_text' ); ?>" name="<?php echo $this->get_field_name( 'pass_protected_text' ); ?>" value="<?php echo $instance['pass_protected_text']; ?>" /> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'sing_comment_text' ); ?>" name="<?php echo $this->get_field_name( 'sing_comment_text' ); ?>" value="<?php echo $instance['sing_comment_text']; ?>" /> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'plu_comment_text' ); ?>" name="<?php echo $this->get_field_name( 'plu_comment_text' ); ?>" value="<?php echo $instance['plu_comment_text']; ?>" /> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'sing_trackback_text' ); ?>" name="<?php echo $this->get_field_name( 'sing_trackback_text' ); ?>" value="<?php echo $instance['sing_trackback_text']; ?>" /> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'plu_trackback_text' ); ?>" name="<?php echo $this->get_field_name( 'plu_trackback_text' ); ?>" value="<?php echo $instance['plu_trackback_text']; ?>" /> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'sing_pingback_text' ); ?>" name="<?php echo $this->get_field_name( 'sing_pingback_text' ); ?>" value="<?php echo $instance['sing_pingback_text']; ?>" /> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'plu_pingback_text' ); ?>" name="<?php echo $this->get_field_name( 'plu_pingback_text' ); ?>" value="<?php echo $instance['plu_pingback_text']; ?>" /> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'sing_ping_text' ); ?>" name="<?php echo $this->get_field_name( 'sing_ping_text' ); ?>" value="<?php echo $instance['sing_ping_text']; ?>" /> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'plu_ping_text' ); ?>" name="<?php echo $this->get_field_name( 'plu_ping_text' ); ?>" value="<?php echo $instance['plu_ping_text']; ?>" /> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'no_text' ); ?>" name="<?php echo $this->get_field_name( 'no_text' ); ?>" value="<?php echo $instance['no_text']; ?>" /> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'to_text' ); ?>" name="<?php echo $this->get_field_name( 'to_text' ); ?>" value="<?php echo $instance['to_text']; ?>" /> </p> <p> <label class="spb tog"><?php _e('comment form', 'bizzthemes'); ?></label> </p> <p> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'name' ); ?>" name="<?php echo $this->get_field_name( 'name' ); ?>" value="<?php echo esc_attr($instance['name']); ?>" /> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'email' ); ?>" name="<?php echo $this->get_field_name( 'email' ); ?>" value="<?php echo esc_attr($instance['email']); ?>" /> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'url' ); ?>" name="<?php echo $this->get_field_name( 'url' ); ?>" value="<?php echo esc_attr($instance['url']); ?>" /> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'req_str' ); ?>" name="<?php echo $this->get_field_name( 'req_str' ); ?>" value="<?php echo esc_attr($instance['req_str']); ?>" /> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'label_submit' ); ?>" name="<?php echo $this->get_field_name( 'label_submit' ); ?>" value="<?php echo esc_attr($instance['label_submit']); ?>" /> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'must_log_in' ); ?>" name="<?php echo $this->get_field_name( 'must_log_in' ); ?>" value="<?php echo esc_attr($instance['must_log_in']); ?>" /> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'logged_in_as' ); ?>" name="<?php echo $this->get_field_name( 'logged_in_as' ); ?>" value="<?php echo esc_attr($instance['logged_in_as']); ?>" /> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'title_reply' ); ?>" name="<?php echo $this->get_field_name( 'title_reply' ); ?>" value="<?php echo esc_attr($instance['title_reply']); ?>" /> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'title_reply_to' ); ?>" name="<?php echo $this->get_field_name( 'title_reply_to' ); ?>" value="<?php echo esc_attr($instance['title_reply_to']); ?>" /> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'cancel_reply_link' ); ?>" name="<?php echo $this->get_field_name( 'cancel_reply_link' ); ?>" value="<?php echo esc_attr($instance['cancel_reply_link']); ?>" /> <input type="text" class="widefat spb tog" id="<?php echo $this->get_field_id( 'comments_closed' ); ?>" name="<?php echo $this->get_field_name( 'comments_closed' ); ?>" value="<?php echo esc_attr($instance['comments_closed']); ?>" /> </p> <div class="clear">&nbsp;</div> <?php } } // INITIATE WIDGET register_widget( 'Bizz_Widget_Comments_Loop' ); // CUSTOM COMMENTS FUNCTIONS /** * Custom Loop callback for wp_list_comments() * * @since 0.1 **/ // Callback function function bizz_comments_loop_callback( $comment, $args, $depth ) { $GLOBALS['comment'] = $comment; $GLOBALS['comment_depth'] = $depth; ?> <li <?php comment_class( empty( $args['has_children'] ) ? '' : 'parent' ); ?> id="comment-<?php comment_ID() ?>"> <?php do_action( "before_{$args['type']}" ); do_action( "comment_container", $comment, $args, $depth ); do_action( "after_{$args['type']}" ); } // Custom comment loop hook add_action('comment_container', 'bizz_comment_container', 10, 3); function bizz_comment_container( $comment, $args, $depth ) { if ( 'div' == $args['style'] ) { $tag = 'div'; $add_below = 'comment'; } else { $tag = 'li'; $add_below = 'div-comment'; } ?> <div id="div-comment-<?php comment_ID(); ?>" class="comment-container"> <div class="avatar-wrap"> <?php echo get_avatar( $comment, 48, BIZZ_THEME_IMAGES .'/gravatar.png' ); ?> </div><!-- /.meta-wrap --> <div class="text-right"> <div class="comm-reply<?php if (1 == $comment->user_id) echo " authcomment"; ?>"> <?php echo bizz_comment_meta( $args['comment_meta'] ); ?> <?php if ( $args['enable_reply'] ): ?> <span class="fr"> <?php comment_reply_link( array_merge( $args, array('add_below' => $add_below, 'depth' => $depth, 'max_depth' => $args['max_depth'])) ); ?> </span> <?php endif; ?> </div><!-- /.comm-reply --> <div class="comment-entry"> <?php comment_text() ?> <?php if ( '0' == $comment->comment_approved ) : ?> <p class="comment-moderation"><?php echo $args['comment_moderation']; ?></p> <?php endif; ?> </div><!-- /.comment-entry --> </div><!-- /.text-right --> </div><!-- /.comment-container --> <?php } /** * Display the language string for the number of comments the current post has. * * @since 0.71 * @uses $id * @uses apply_filters() Calls the 'comments_number' hook on the output and number of comments respectively. * * @param string $zero Text for no comments * @param string $one Text for one comment * @param string $more Text for more than one comment * @param string $type Comment Type * @param array $comments Comments by type */ function bizz_comments_number( $zero = false, $one = false, $more = false, $type = 'all', $comments ) { $number = ( 'all' == $type ) ? count( $comments['comment'] ) + count( $comments['pings'] ) : count($comments[$type]); if ( $number > 1 ) $output = str_replace('%', number_format_i18n($number), ( false === $more ) ? __('% Comments', 'bizzthemes') : $more); elseif ( $number == 0 ) $output = ( false === $zero ) ? __('No Comments', 'bizzthemes') : $zero; else // must be one $output = ( false === $one ) ? __('One Comment', 'bizzthemes') : $one; echo apply_filters('comments_number', $output, $number); } /** * Process any shortcodes applied to $content * * @since 0.1 **/ function bizz_comment_meta( $content ) { $content = preg_replace( '/\[(.+?)\]/', '[comment_$1]', $content ); return apply_filters( 'bizz_comment_meta', do_shortcode( $content ) ); } /** * Displays the author's avatar and the author's name/link * * @since 0.1 **/ function bizz_comment_author_avatar( $comment, $args ) { ?> <div class="comment-author vcard"> <?php if ( $args['avatar_size'] != 0 ) echo get_avatar( $comment, $args['avatar_size'] ); ?> <cite class="fn"><?php echo bizz_comment_author(); ?></cite> </div> <?php } /** * Returns the author's name/link microformatted * * @since 0.1 **/ function bizz_comment_author( $atts = array() ) { $defaults = array( 'before' => '', 'after' => '' ); $args = shortcode_atts( $defaults, $atts ); extract( $args, EXTR_SKIP ); $author = esc_html( get_comment_author() ); $url = esc_url( get_comment_author_url() ); /* Display link and cite if URL is set. Also, properly cites trackbacks/pingbacks. */ if ( $url ) $output = '<cite class="fn" title="' . $url . '"><a href="' . $url . '" title="' . $author . '" class="url" rel="external nofollow">' . $author . '</a></cite>'; else $output = '<cite class="fn">' . $author . '</cite>'; $output = '<span class="comment-author vcard">' . apply_filters( 'get_comment_author_link', $output ) . '</span>'; return apply_filters( 'bizz_comment_author', $before . $output . $after ); } /** * Displays the comment date * * @since 0.1 */ function bizz_comment_date( $atts = array() ) { $defaults = array( 'before' => '', 'after' => '' ); $args = shortcode_atts( $defaults, $atts ); extract( $args, EXTR_SKIP ); $output = '<abbr class="comment-date" title="' . get_comment_date(get_option('date_format')) . '">' . get_comment_date() . '</abbr>'; return apply_filters( 'bizz_comment_date', $before . $output . $after ); } /** * Displays the comment time * * @since 0.1 */ function bizz_comment_time( $atts = array() ) { $defaults = array( 'before' => '', 'after' => '' ); $args = shortcode_atts( $defaults, $atts ); extract( $args, EXTR_SKIP ); $output = '<span class="comment-time"><abbr title="' . get_comment_date( __( 'g:i a', 'bizzthemes' ) ) . '">' . get_comment_time() . '</abbr></span>'; return apply_filters( 'bizz_comment_time', $before . $output . $after ); } /** * Displays the comment count * * @since 0.1 **/ function bizz_comment_count( $atts = array() ) { $defaults = array( 'before' => '', 'after' => '' ); $args = shortcode_atts( $defaults, $atts ); extract( $args, EXTR_SKIP ); global $comment_count; if ( !isset($comment_count) ) $comment_count = 1; $comment_type = get_comment_type(); $output = "<span class=\"$comment_type-count\">$comment_count</span>"; $comment_count++; return apply_filters( 'bizz_comment_count', $before . $output . $after ); } /** * Displays a list of comma seperated tags * * @since 0.1 **/ function bizz_comment_link( $atts = array() ) { $defaults = array( 'before' => '', 'after' => '', 'label' => __( 'Permalink', 'bizzthemes' ) ); $args = shortcode_atts( $defaults, $atts ); extract( $args, EXTR_SKIP ); $output = '<span class="comment-permalink"><a href="' . esc_url(get_comment_link()) . '" title="' . sprintf( __( 'Permalink to %1$s %2$s', 'bizzthemes' ), get_comment_type(), get_comment_ID() ) . '">' . $label . '</a></span>'; return apply_filters( 'bizz_comment_link', $before . $output . $after ); } /** * Comment Reply link * * @since 0.1 */ function bizz_comment_reply( $atts = array() ) { $defaults = array( 'reply_text' => __( 'Reply', 'bizzthemes' ), 'login_text' => __( 'Log in to reply.', 'bizzthemes' ), 'depth' => $GLOBALS['comment_depth'], 'max_depth' => get_option( 'thread_comments_depth' ), 'before' => '', 'after' => '' ); $args = shortcode_atts( $defaults, $args ); if ( !get_option( 'thread_comments' ) || 'comment' !== get_comment_type() ) return ''; return get_comment_reply_link( $args ); } /** * Comment Edit link * * @since 0.1 **/ function bizz_comment_edit( $atts = array() ) { $defaults = array( 'before' => '', 'after' => '', 'label' => __( 'Edit', 'bizzthemes' ) ); $args = shortcode_atts( $defaults, $atts ); extract( $args, EXTR_SKIP ); $edit_link = get_edit_comment_link( get_comment_ID() ); if ( !$edit_link ) return ''; $output = '<span class="comment-edit"><a href="' . $edit_link . '" title="' . $label . '">' . $label . '</a></span>'; return apply_filters( 'bizz_comment_edit', $before . $output . $after ); } // Shortcodes add_shortcode( 'comment_author', 'bizz_comment_author' ); add_shortcode( 'comment_date', 'bizz_comment_date' ); add_shortcode( 'comment_time', 'bizz_comment_time' ); add_shortcode( 'comment_count', 'bizz_comment_count' ); add_shortcode( 'comment_link', 'bizz_comment_link' ); add_shortcode( 'comment_reply', 'bizz_comment_reply' ); add_shortcode( 'comment_edit', 'bizz_comment_edit' ); /** * Outputs a complete commenting form for use within a template. * Most strings and form fields may be controlled through the $args array passed * into the function, while you may also choose to use the comments_form_default_fields * filter to modify the array of default fields if you'd just like to add a new * one or remove a single field. All fields are also individually passed through * a filter of the form comments_form_field_$name where $name is the key used * in the array of fields. * * @since 3.0 * @param array $args Options for strings, fields etc in the form * @param mixed $post_id Post ID to generate the form for, uses the current post if null * @return void */ function bizz_comment_form( $form_args = array(), $post_id = null ) { global $user_identity, $id; $form_args['comments_closed'] = ( isset($form_args['comments_closed']) ) ? $form_args['comments_closed'] :__( 'Comments are closed.', 'bizzthemes' ); $form_args['req'] = ( isset($form_args['req']) ) ? $form_args['req'] : true; $form_args['req_str'] = ( isset($form_args['req_str']) ) ? $form_args['req_str'] : __( '(required)', 'bizzthemes' ); $form_args['name'] = ( isset($form_args['name']) ) ? $form_args['name'] : __( 'Name', 'bizzthemes' ); $form_args['email'] = ( isset($form_args['email']) ) ? $form_args['email'] : __( 'Mail (will not be published)', 'bizzthemes' ); $form_args['url'] = ( isset($form_args['url']) ) ? $form_args['url'] : __( 'Website', 'bizzthemes' ); $form_args['must_log_in'] = ( isset($form_args['must_log_in']) ) ? $form_args['must_log_in'] : __( 'You must be <a href="%s">logged in</a> to post a comment.', 'bizzthemes' ); $form_args['logged_in_as'] = ( isset($form_args['logged_in_as']) ) ? $form_args['logged_in_as'] : __( 'Logged in as <a href="%s">%s</a>. <a href="%s" title="Log out of this account">Log out &raquo;</a>', 'bizzthemes' ); $form_args['title_reply_tag'] = ( isset($form_args['title_reply_tag']) ) ? $form_args['title_reply_tag'] : 'h3'; $form_args['title_reply'] = ( isset($form_args['title_reply']) ) ? $form_args['title_reply'] : __( 'Leave a Reply', 'bizzthemes' ); $form_args['title_reply_to'] = ( isset($form_args['title_reply_to']) ) ? $form_args['title_reply_to'] : __( 'Leave a Reply to %s', 'bizzthemes' ); $form_args['cancel_reply_link'] = ( isset($form_args['cancel_reply_link']) ) ? $form_args['cancel_reply_link'] : __( 'Click here to cancel reply.', 'bizzthemes' ); $form_args['label_submit'] = ( isset($form_args['label_submit']) ) ? $form_args['label_submit'] : __( 'Submit Comment', 'bizzthemes' ); $post_id = ( null === $post_id ) ? $id : $post_id; $commenter = wp_get_current_commenter(); $req = $form_args['req']; $aria_req = ( $req ? " aria-required='true'" : '' ); $req_str = ( $req ? ' ' . $form_args['req_str'] : '' ); $args = array( 'fields' => apply_filters( 'comment_form_default_fields', array( 'author' => '<input type="text" name="author" id="author" value="' . esc_attr( $commenter['comment_author'] ) . '" size="22" tabindex="1"' . $aria_req . ' /> <label for="author"><small>' . $form_args['name'] . $req_str . '</small></label>', 'email' => '<input type="text" name="email" id="email" value="' . esc_attr( $commenter['comment_author_email'] ) . '" size="22" tabindex="2"' . $aria_req . ' /> <label for="email"><small>' . $form_args['email'] . $req_str . '</small></label>', 'url' => '<input type="text" name="url" id="url" value="' . esc_attr( $commenter['comment_author_url'] ) . '" size="22" tabindex="3" /> <label for="url"><small>' . $form_args['url'] . '</small></label>' ) ), 'comment_field' => '<p><textarea name="comment" id="comment" cols="58" rows="10" tabindex="4"></textarea></p>', 'must_log_in' => '<p class="must_log_in">' . sprintf( $form_args['must_log_in'], wp_login_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) ) ) . '</p>', 'logged_in_as' => '<p class="logged_in_as">' . sprintf( $form_args['logged_in_as'], admin_url( 'profile.php' ), $user_identity, wp_logout_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) ) ) . '</p>', 'id_form' => 'commentform', 'id_submit' => 'submit', 'title_reply' => $form_args['title_reply'], 'title_reply_to' => $form_args['title_reply_to'], 'cancel_reply_link' => $form_args['cancel_reply_link'], 'label_submit' => $form_args['label_submit'], ); if ( comments_open() ) : echo '<div id="comments-form-'. $post_id .'" class="widget-comments-form">'; do_action( 'comment_form_before' ); ?> <div id="respond"> <?php echo $form_args['before_widget']; // Title echo "<{$form_args['title_reply_tag']} class=\"title-reply\">"; comment_form_title( $args['title_reply'], $args['title_reply_to'] ); echo "</{$form_args['title_reply_tag']}>"; ?> <div class="cancel-comment-reply"> <small><?php cancel_comment_reply_link( $args['cancel_reply_link'] ); ?></small> </div> <?php if ( get_option( 'comment_registration' ) && !is_user_logged_in() ) : ?> <?php echo $args['must_log_in']; ?> <?php do_action( 'comment_form_must_log_in_after' ); ?> <?php else : ?> <form action="<?php echo site_url( '/wp-comments-post.php' ); ?>" method="post" id="<?php echo esc_attr( $args['id_form'] ); ?>"> <?php do_action( 'comment_form_top' ); ?> <?php if ( is_user_logged_in() ) : ?> <?php echo $args['logged_in_as']; ?> <?php do_action( 'comment_form_logged_in_after', $commenter, $user_identity ); ?> <?php else : ?> <?php do_action( 'comment_form_before_fields' ); foreach ( (array) $args['fields'] as $name => $field ) { echo '<p class="commpadd">' . apply_filters( "comment_form_field_{$name}", $field ) . "</p>\n"; } do_action( 'comment_form_after_fields' ); ?> <?php endif; ?> <?php echo apply_filters( 'comment_form_field_comment', $args['comment_field'] ); ?> <p> <button class="btn" name="submit" type="submit" id="submit" tabindex="<?php echo ( count( $args['fields'] ) + 2 ); ?>" value="<?php echo esc_attr( $args['label_submit'] ); ?>"><span><span><?php echo stripslashes(__('Add Comment', 'bizzthemes')); ?></span></span></button> <?php comment_id_fields(); ?> </p> <?php do_action( 'comments_form', $post_id ); ?> </form> <?php endif; ?> <?php echo $form_args['after_widget']; ?> </div> <?php do_action( 'comment_form' ); do_action( 'comment_form_after' ); echo '</div>'; else : // comments are closed echo '<!-- If comments are closed. -->'; if ( $form_args['comments_closed'] ){ echo $form_args['before_widget']; echo '<p class="comments-closed">'. $form_args['comments_closed'] .'</p>'; echo $form_args['after_widget']; } do_action( 'comment_form_comments_closed' ); endif; }
pereiracruz2002/vaniaSalgados
wp-content/themes/restaurant/lib_frame/widgets/widget-comments.php
PHP
gpl-2.0
37,700
#include "JsVlcSubtitles.h" #include "NodeTools.h" #include "JsVlcPlayer.h" v8::Persistent<v8::Function> JsVlcSubtitles::_jsConstructor; void JsVlcSubtitles::initJsApi() { using namespace v8; Isolate* isolate = Isolate::GetCurrent(); HandleScope scope( isolate ); Local<FunctionTemplate> constructorTemplate = FunctionTemplate::New( isolate, jsCreate ); constructorTemplate->SetClassName( String::NewFromUtf8( isolate, "VlcSubtitles", v8::String::kInternalizedString ) ); Local<ObjectTemplate> protoTemplate = constructorTemplate->PrototypeTemplate(); Local<ObjectTemplate> instanceTemplate = constructorTemplate->InstanceTemplate(); instanceTemplate->SetInternalFieldCount( 1 ); SET_RO_INDEXED_PROPERTY( instanceTemplate, &JsVlcSubtitles::description ); SET_RO_PROPERTY( instanceTemplate, "count", &JsVlcSubtitles::count ); SET_RW_PROPERTY( instanceTemplate, "track", &JsVlcSubtitles::track, &JsVlcSubtitles::setTrack ); SET_RW_PROPERTY( instanceTemplate, "delay", &JsVlcSubtitles::delay, &JsVlcSubtitles::setDelay ); SET_METHOD( constructorTemplate, "load", &JsVlcSubtitles::load ); Local<Function> constructor = constructorTemplate->GetFunction(); _jsConstructor.Reset( isolate, constructor ); } v8::UniquePersistent<v8::Object> JsVlcSubtitles::create( JsVlcPlayer& player ) { using namespace v8; Isolate* isolate = Isolate::GetCurrent(); HandleScope scope( isolate ); Local<Function> constructor = Local<Function>::New( isolate, _jsConstructor ); Local<Value> argv[] = { player.handle() }; return { isolate, constructor->NewInstance( sizeof( argv ) / sizeof( argv[0] ), argv ) }; } void JsVlcSubtitles::jsCreate( const v8::FunctionCallbackInfo<v8::Value>& args ) { using namespace v8; Isolate* isolate = Isolate::GetCurrent(); HandleScope scope( isolate ); Local<Object> thisObject = args.Holder(); if( args.IsConstructCall() && thisObject->InternalFieldCount() > 0 ) { JsVlcPlayer* jsPlayer = ObjectWrap::Unwrap<JsVlcPlayer>( Handle<Object>::Cast( args[0] ) ); if( jsPlayer ) { JsVlcSubtitles* jsPlaylist = new JsVlcSubtitles( thisObject, jsPlayer ); args.GetReturnValue().Set( thisObject ); } } else { Local<Function> constructor = Local<Function>::New( isolate, _jsConstructor ); Local<Value> argv[] = { args[0] }; args.GetReturnValue().Set( constructor->NewInstance( sizeof( argv ) / sizeof( argv[0] ), argv ) ); } } JsVlcSubtitles::JsVlcSubtitles( v8::Local<v8::Object>& thisObject, JsVlcPlayer* jsPlayer ) : _jsPlayer( jsPlayer ) { Wrap( thisObject ); } std::string JsVlcSubtitles::description( uint32_t index ) { vlc_player& p = _jsPlayer->player(); std::string name; libvlc_track_description_t* rootDesc = libvlc_video_get_spu_description( p.get_mp() ); if( !rootDesc ) return name; unsigned count = libvlc_video_get_spu_count( p.get_mp() ); if( count && index < count ) { libvlc_track_description_t* desc = rootDesc; for( ; index && desc; --index ){ desc = desc->p_next; } if ( desc && desc->psz_name ) { name = desc->psz_name; } } libvlc_track_description_list_release( rootDesc ); return name; } unsigned JsVlcSubtitles::count() { return _jsPlayer->player().subtitles().track_count(); } int JsVlcSubtitles::track() { return _jsPlayer->player().subtitles().get_track(); } void JsVlcSubtitles::setTrack( int track ) { return _jsPlayer->player().subtitles().set_track( track ); } int JsVlcSubtitles::delay() { return static_cast<int>( _jsPlayer->player().subtitles().get_delay() ); } void JsVlcSubtitles::setDelay( int delay ) { _jsPlayer->player().subtitles().set_delay( delay ); } bool JsVlcSubtitles::load( const std::string& path ) { return _jsPlayer->player().subtitles().load( path ); }
jaruba/WebChimera.js
src/JsVlcSubtitles.cpp
C++
gpl-2.0
4,021
# Portions Copyright (c) Meta Platforms, Inc. and affiliates. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2. # convert.py Foreign SCM converter # # Copyright 2005-2007 Matt Mackall <mpm@selenic.com> # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. """import revisions from foreign VCS repositories into Mercurial""" from __future__ import absolute_import from edenscm.mercurial import registrar from edenscm.mercurial.i18n import _ from . import convcmd, subversion cmdtable = {} command = registrar.command(cmdtable) # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should # be specifying the version(s) of Mercurial they are tested with, or # leave the attribute unspecified. testedwith = "ships-with-hg-core" # Commands definition was moved elsewhere to ease demandload job. @command( "convert", [ ( "", "authors", "", _("username mapping filename (DEPRECATED) (use --authormap instead)"), _("FILE"), ), ("s", "source-type", "", _("source repository type"), _("TYPE")), ("d", "dest-type", "", _("destination repository type"), _("TYPE")), ("r", "rev", [], _("import up to source revision REV"), _("REV")), ("A", "authormap", "", _("remap usernames using this file"), _("FILE")), ("", "filemap", "", _("remap file names using contents of file"), _("FILE")), ("", "full", None, _("apply filemap changes by converting all files again")), ("", "splicemap", "", _("splice synthesized history into place"), _("FILE")), ("", "branchmap", "", _("change branch names while converting"), _("FILE")), ("", "branchsort", None, _("try to sort changesets by branches")), ("", "datesort", None, _("try to sort changesets by date")), ("", "sourcesort", None, _("preserve source changesets order")), ("", "closesort", None, _("try to reorder closed revisions")), ], _("hg convert [OPTION]... SOURCE [DEST [REVMAP]]"), norepo=True, ) def convert(ui, src, dest=None, revmapfile=None, **opts): """convert a foreign SCM repository to a Mercurial one. Accepted source formats [identifiers]: - Mercurial [hg] - git [git] - Subversion [svn] - Perforce [p4] - Google Repo [repo] Accepted destination formats [identifiers]: - Mercurial [hg] - Subversion [svn] (history on branches is not preserved) If no revision is given, all revisions will be converted. Otherwise, convert will only import up to the named revision (given in a format understood by the source). If no destination directory name is specified, it defaults to the basename of the source with ``-hg`` appended. If the destination repository doesn't exist, it will be created. By default, all sources except Mercurial will use --branchsort. Mercurial uses --sourcesort to preserve original revision numbers order. Sort modes have the following effects: --branchsort convert from parent to child revision when possible, which means branches are usually converted one after the other. It generates more compact repositories. --datesort sort revisions by date. Converted repositories have good-looking changelogs but are often an order of magnitude larger than the same ones generated by --branchsort. --sourcesort try to preserve source revisions order, only supported by Mercurial sources. --closesort try to move closed revisions as close as possible to parent branches, only supported by Mercurial sources. If ``REVMAP`` isn't given, it will be put in a default location (``<dest>/.hg/shamap`` by default). The ``REVMAP`` is a simple text file that maps each source commit ID to the destination ID for that revision, like so:: <source ID> <destination ID> If the file doesn't exist, it's automatically created. It's updated on each commit copied, so :hg:`convert` can be interrupted and can be run repeatedly to copy new commits. The authormap is a simple text file that maps each source commit author to a destination commit author. It is handy for source SCMs that use unix logins to identify authors (e.g.: CVS). One line per author mapping and the line format is:: source author = destination author Empty lines and lines starting with a ``#`` are ignored. The filemap is a file that allows filtering and remapping of files and directories. Each line can contain one of the following directives:: include path/to/file-or-dir exclude path/to/file-or-dir rename path/to/source path/to/destination Comment lines start with ``#``. A specified path matches if it equals the full relative name of a file or one of its parent directories. The ``include`` or ``exclude`` directive with the longest matching path applies, so line order does not matter. The ``include`` directive causes a file, or all files under a directory, to be included in the destination repository. The default if there are no ``include`` statements is to include everything. If there are any ``include`` statements, nothing else is included. The ``exclude`` directive causes files or directories to be omitted. The ``rename`` directive renames a file or directory if it is converted. To rename from a subdirectory into the root of the repository, use ``.`` as the path to rename to. ``--full`` will make sure the converted changesets contain exactly the right files with the right content. It will make a full conversion of all files, not just the ones that have changed. Files that already are correct will not be changed. This can be used to apply filemap changes when converting incrementally. This is currently only supported for Mercurial and Subversion. The splicemap is a file that allows insertion of synthetic history, letting you specify the parents of a revision. This is useful if you want to e.g. give a Subversion merge two parents, or graft two disconnected series of history together. Each entry contains a key, followed by a space, followed by one or two comma-separated values:: key parent1, parent2 The key is the revision ID in the source revision control system whose parents should be modified (same format as a key in .hg/shamap). The values are the revision IDs (in either the source or destination revision control system) that should be used as the new parents for that node. For example, if you have merged "release-1.0" into "trunk", then you should specify the revision on "trunk" as the first parent and the one on the "release-1.0" branch as the second. The branchmap is a file that allows you to rename a branch when it is being brought in from whatever external repository. When used in conjunction with a splicemap, it allows for a powerful combination to help fix even the most badly mismanaged repositories and turn them into nicely structured Mercurial repositories. The branchmap contains lines of the form:: original_branch_name new_branch_name where "original_branch_name" is the name of the branch in the source repository, and "new_branch_name" is the name of the branch is the destination repository. No whitespace is allowed in the new branch name. This can be used to (for instance) move code in one repository from "default" to a named branch. Mercurial Source ################ The Mercurial source recognizes the following configuration options, which you can set on the command line with ``--config``: :convert.hg.ignoreerrors: ignore integrity errors when reading. Use it to fix Mercurial repositories with missing revlogs, by converting from and to Mercurial. Default is False. :convert.hg.saverev: store original revision ID in changeset (forces target IDs to change). It takes a boolean argument and defaults to False. :convert.hg.startrev: specify the initial Mercurial revision. The default is 0. :convert.hg.revs: revset specifying the source revisions to convert. Subversion Source ################# Subversion source detects classical trunk/branches layouts. By default, the supplied ``svn://repo/path/`` source URL is converted as a single branch. If ``svn://repo/path/trunk`` exists it replaces the default branch. If ``svn://repo/path/branches`` exists, its subdirectories are listed as possible branches. Default ``trunk`` and ``branches`` values can be overridden with following options. Set them to paths relative to the source URL, or leave them blank to disable auto detection. The following options can be set with ``--config``: :convert.svn.branches: specify the directory containing branches. The default is ``branches``. :convert.svn.trunk: specify the name of the trunk branch. The default is ``trunk``. :convert.localtimezone: use local time (as determined by the TZ environment variable) for changeset date/times. The default is False (use UTC). Source history can be retrieved starting at a specific revision, instead of being integrally converted. Only single branch conversions are supported. :convert.svn.startrev: specify start Subversion revision number. The default is 0. Git Source ########## The Git importer converts commits from all reachable branches (refs in refs/heads) and remotes (refs in refs/remotes) to Mercurial. Branches are converted to bookmarks with the same name, with the leading 'refs/heads' stripped. Git submodules are not supported. The following options can be set with ``--config``: :convert.git.similarity: specify how similar files modified in a commit must be to be imported as renames or copies, as a percentage between ``0`` (disabled) and ``100`` (files must be identical). For example, ``90`` means that a delete/add pair will be imported as a rename if more than 90% of the file hasn't changed. The default is ``50``. :convert.git.findcopiesharder: while detecting copies, look at all files in the working copy instead of just changed ones. This is very expensive for large projects, and is only effective when ``convert.git.similarity`` is greater than 0. The default is False. :convert.git.renamelimit: perform rename and copy detection up to this many changed files in a commit. Increasing this will make rename and copy detection more accurate but will significantly slow down computation on large projects. The option is only relevant if ``convert.git.similarity`` is greater than 0. The default is ``400``. :convert.git.committeractions: list of actions to take when processing author and committer values. Git commits have separate author (who wrote the commit) and committer (who applied the commit) fields. Not all destinations support separate author and committer fields (including Mercurial). This config option controls what to do with these author and committer fields during conversion. A value of ``messagedifferent`` will append a ``committer: ...`` line to the commit message if the Git committer is different from the author. The prefix of that line can be specified using the syntax ``messagedifferent=<prefix>``. e.g. ``messagedifferent=git-committer:``. When a prefix is specified, a space will always be inserted between the prefix and the value. ``messagealways`` behaves like ``messagedifferent`` except it will always result in a ``committer: ...`` line being appended to the commit message. This value is mutually exclusive with ``messagedifferent``. ``dropcommitter`` will remove references to the committer. Only references to the author will remain. Actions that add references to the committer will have no effect when this is set. ``replaceauthor`` will replace the value of the author field with the committer. Other actions that add references to the committer will still take effect when this is set. The default is ``messagedifferent``. :convert.git.extrakeys: list of extra keys from commit metadata to copy to the destination. Some Git repositories store extra metadata in commits. By default, this non-default metadata will be lost during conversion. Setting this config option can retain that metadata. Some built-in keys such as ``parent`` and ``branch`` are not allowed to be copied. :convert.git.remoteprefix: remote refs are converted as bookmarks with ``convert.git.remoteprefix`` as a prefix followed by a /. The default is 'remote'. :convert.git.saverev: whether to store the original Git commit ID in the metadata of the destination commit. The default is True. :convert.git.skipsubmodules: does not convert root level .gitmodules files or files with 160000 mode indicating a submodule. Default is False. Perforce Source ############### The Perforce (P4) importer can be given a p4 depot path or a client specification as source. It will convert all files in the source to a flat Mercurial repository, ignoring labels, branches and integrations. Note that when a depot path is given you then usually should specify a target directory, because otherwise the target may be named ``...-hg``. The following options can be set with ``--config``: :convert.p4.encoding: specify the encoding to use when decoding standard output of the Perforce command line tool. The default is default system encoding. :convert.p4.startrev: specify initial Perforce revision (a Perforce changelist number). Mercurial Destination ##################### The following options are supported: :convert.hg.clonebranches: dispatch source branches in separate clones. The default is False. :convert.hg.usebranchnames: preserve branch names. The default is True. :convert.hg.sourcename: records the given string as a 'convert_source' extra value on each commit made in the target repository. The default is None. """ return convcmd.convert(ui, src, dest, revmapfile, **opts) @command("debugsvnlog", [], "hg debugsvnlog", norepo=True) def debugsvnlog(ui, **opts): return subversion.debugsvnlog(ui, **opts) def kwconverted(ctx, name): rev = ctx.extra().get("convert_revision", "") if rev.startswith("svn:"): if name == "svnrev": return str(subversion.revsplit(rev)[2]) elif name == "svnpath": return subversion.revsplit(rev)[1] elif name == "svnuuid": return subversion.revsplit(rev)[0] return rev templatekeyword = registrar.templatekeyword() @templatekeyword("svnrev") def kwsvnrev(repo, ctx, **args): """String. Converted subversion revision number.""" return kwconverted(ctx, "svnrev") @templatekeyword("svnpath") def kwsvnpath(repo, ctx, **args): """String. Converted subversion revision project path.""" return kwconverted(ctx, "svnpath") @templatekeyword("svnuuid") def kwsvnuuid(repo, ctx, **args): """String. Converted subversion revision repository identifier.""" return kwconverted(ctx, "svnuuid") # tell hggettext to extract docstrings from these functions: i18nfunctions = [kwsvnrev, kwsvnpath, kwsvnuuid]
facebookexperimental/eden
eden/scm/edenscm/hgext/convert/__init__.py
Python
gpl-2.0
16,126
class Photo < ActiveRecord::Base belongs_to :imageable, polymorphic: true, counter_cache: true, touch: true scope :processed, ->{ where(image_processing: nil) } def url_for(version_key, asset_host = ENV['ASSET_HOST']) version(version_key).url_for(asset_host) end def is_processed? !self.image_processing end def upload(file, blob_storage) image = Image.new(file) self.original_filename = File.basename(file) self.image = image.filename self.content_type = image.content_type self.latitude, self.longitude = image.geolocation self.image_processing = nil self.sha256 = image.sha256 versions.each do |version| version.adjust(image) blob_storage.upload(version.blob_key, image.path) end end def version(key) versions.detect { |version| version.for?(key) } end private def versions @versions ||= [OriginalVersion.new(self), LargeVersion.new(self), ThumbnailVersion.new(self)] end end
mokhan/cakeside
app/models/photo.rb
Ruby
gpl-2.0
975
<?php /* * Project: GoogleMapAPI V3: a PHP library inteface to the Google Map API v3 * File: GoogleMapV3.php * * 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 * * ORIGINAL INFO * link http://www.phpinsider.com/php/code/GoogleMapAPI/ * copyright 2005 New Digital Group, Inc. * author Monte Ohrt <monte at ohrt dot com> * package GoogleMapAPI * version 2.5 * * REVISION NOTIFICATION * NOTE: This is a modified version of the original listed above. This version * maintains all original GNU software licenses. */ /** * @link http://code.google.com/p/phpgooglemapapiv3/ * @copyright 2010 Brad wedell * @author Brad Wedell * @package GoogleMapAPI (version 3) * @version 3.0beta */ /* * To view the full CHANGELOG, visit * http://code.google.com/p/php-google-map-api/wiki/ChangeLog3 /* For database caching, you will want to use this schema: CREATE TABLE GEOCODES ( address varchar(255) NOT NULL default '', lon float default NULL, lat float default NULL, PRIMARY KEY (address) ); */ /** * PHP Google Maps API class * @package GoogleMapAPI * @version 3.0beta */ class GoogleMapAPI { /** * PEAR::DB DSN for geocode caching. example: * $dsn = 'mysql://user:pass@localhost/dbname'; * * @var string */ var $dsn = null; /** * current map id, set when you instantiate * the GoogleMapAPI object. * * @var string */ var $map_id = null; /** * determines whether or not to display the map and associated JS on the page * this is used if you just want to display a streetview with no map */ var $display_map = true; /** * sidebar <div> used along with this map. * * @var string */ var $sidebar_id = null; /** * Whether to use new V3 mobile functionality * * @var bool */ var $mobile=false; /** * DEPRECATED: Google now has geocoding service. * NOTE: Note even sure if this still works * GoogleMapAPI used to use the Yahoo geocode lookup API. * This is the application ID for YOUR application. * This is set upon instantiating the GoogleMapAPI object. * (http://developer.yahoo.net/faq/index.html#appid) * * @var string */ var $app_id = null; /** * use onLoad() to load the map javascript. * if enabled, be sure to include on your webpage: * <?php echo $mapobj->printOnLoad?> or manually create an onload function * that calls the map's onload function using $this->printOnLoadFunction * * @var bool * @default true */ var $onload = true; /** * map center latitude (horizontal) * calculated automatically as markers * are added to the map. * * @var float */ var $center_lat = null; /** * map center longitude (vertical) * calculated automatically as markers * are added to the map. * * @var float */ var $center_lon = null; /** * enables map controls (zoom/move/center) * * @var bool */ var $map_controls = true; /** * determines the map control type * small -> show move/center controls * large -> show move/center/zoom controls * * @var string */ var $control_size = 'large'; /** * enables map type controls (map/satellite/hybrid/terrain) * * @var bool */ var $type_controls = true; /** * sets default option for type controls(DEFAULT, HORIZONTAL_BAR, DROPDOWN_MENU) * * @var string */ var $type_controls_style = "DEFAULT"; /** * sets default option for controls positin (TOP_LEFT, TOP_RIGHT, etc.) * * @var string */ var $type_controls_position = "TOP_RIGHT"; /** * sets default option control selections (ROADMAP, SATELLITE, HYBRID, TERRAIN) * * @var string */ var $type_controls_list = array('ROADMAP', 'SATELLITE', 'HYBRID', 'TERRAIN'); /** * default map type google.maps.MapTypeId.(ROADMAP, SATELLITE, HYBRID, TERRAIN) * * @var string */ var $map_type = 'HYBRID'; /** * enables scale map control * * @var bool */ var $scale_control = true; /** * enables overview map control * * @var bool */ var $overview_control = false; /** * enables Google Adsense Adsmanager on page, not currently supported in beta * * @var bool */ var $ads_manager = false; /** * Google Adsense Publisher ID * * @var string */ var $ads_pub_id = ""; /** * Google Adsense Channel ID * * @var string */ var $ads_channel = ""; /** * The Max number of Adsmanager ads to show on a map * * @var int */ var $ads_max = 10; /** * enables/disables local search on page * * @var bool */ var $local_search = false; /** * enables local search ads on page NOTE: will only display ads if local_search == true, otherwise just use ad_manager and settings. * * @var bool */ var $local_search_ads = false; /** * enables/disables walking directions option * * @var bool */ var $walking_directions = false; /** * enables/disables biking directions on directions * * @var bool */ var $biking_directions = false; /** * enables/disables avoid highways on directions * * @var bool */ var $avoid_highways = false; /** * determines if avoid tollways is used in directions * * @var bool */ var $avoid_tollways = false; /** * determines the default zoom level * * @var int */ var $zoom = 16; /** * determines the map width * * @var string */ var $width = '500px'; /** * determines the map height * * @var string */ var $height = '500px'; /** * message that pops up when the browser is incompatible with Google Maps. * set to empty string to disable. * * @var string */ var $browser_alert = 'Sorry, the Google Maps API is not compatible with this browser.'; /** * message that appears when javascript is disabled. * set to empty string to disable. * * @var string */ var $js_alert = '<b>Javascript must be enabled in order to use Google Maps.</b>'; /** * determines if sidebar is enabled * * @var bool */ var $sidebar = true; /** * determines if to/from directions are included inside info window * * @var bool * @deprecated */ var $directions = true; /** * determines if map markers bring up an info window * * @var bool */ var $info_window = true; /** * determines if info window appears with a click or mouseover * * @var string click/mouseover */ var $window_trigger = 'click'; /** * determines whether or not to use the MarkerClusterer plugin */ var $marker_clusterer = false; /** * set default marker clusterer *webserver* file location */ var $marker_clusterer_location = "/MarkerClusterer-1.0/markerclusterer_compiled.js"; /** * set default marker clusterer options */ var $marker_clusterer_options = array( "maxZoom"=>"null", "gridSize"=>"null", "styles"=>"null" ); /** * determines if traffic overlay is displayed on map * * @var bool */ var $traffic_overlay = false; /** * determines if biking overlay is displayed on map * * @var bool */ var $biking_overlay = false; /** * determines whether or not to display street view controls */ var $street_view_controls = false; /** * ID of the container that will hold a street view if streetview controls = true. */ var $street_view_dom_id = ""; /** * what server geocode lookups come from * * available: YAHOO Yahoo! API. US geocode lookups only. * GOOGLE Google Maps. This can do international lookups, * but not an official API service so no guarantees. * Note: GOOGLE is the default lookup service, please read * the Yahoo! terms of service before using their API. * * @var string service name */ var $lookup_service = 'GOOGLE'; var $lookup_server = array('GOOGLE' => 'maps.google.com', 'YAHOO' => 'api.local.yahoo.com'); /** * * @var array * @deprecated */ var $driving_dir_text = array( 'dir_to' => 'Start address: (include addr, city st/region)', 'to_button_value' => 'Get Directions', 'to_button_type' => 'submit', 'dir_from' => 'End address: (include addr, city st/region)', 'from_button_value' => 'Get Directions', 'from_button_type' => 'submit', 'dir_text' => 'Directions: ', 'dir_tohere' => 'To here', 'dir_fromhere' => 'From here' ); /** * version number * * @var string */ var $_version = '3.0beta'; /** * list of added markers * * @var array */ var $_markers = array(); /** * maximum longitude of all markers * * @var float */ var $_max_lon = -1000000; /** * minimum longitude of all markers * * @var float */ var $_min_lon = 1000000; /** * max latitude * * @var float */ var $_max_lat = -1000000; /** * min latitude * * @var float */ var $_min_lat = 1000000; /** * determines if we should zoom to minimum level (above this->zoom value) that will encompass all markers * * @var bool */ var $zoom_encompass = true; /** * factor by which to fudge the boundaries so that when we zoom encompass, the markers aren't too close to the edge * * @var float */ var $bounds_fudge = 0.001; /** * use the first suggestion by a google lookup if exact match not found * * @var float */ var $use_suggest = false; /** * list of added polylines * * @var array */ var $_polylines = array(); /** * list of polylines that should have an elevation profile rendered. */ var $_elevation_polylines = array(); /** * determines whether or not to display a marker on the "line" when * mousing over the elevation chart */ var $elevation_markers = true; /** * determines whether or not to display an elevation chart * for directions that are added to the map. */ var $elevation_directions = false; /** * icon info array * * @var array * @deprecated * @version 2.5 */ var $_icons = array(); /** * marker icon info array * * @var array * @version 3.0 */ var $_marker_icons = array(); /** * Default icon image location. * * @var string */ var $default_icon = ""; /** * Default icon shadow image location. * * @var string */ var $default_icon_shadow = ""; /** * list of added overlays * * @var array */ var $_overlays = array(); /** * list of added kml overlays */ var $_kml_overlays = array(); /** * database cache table name * * @var string */ var $_db_cache_table = 'GEOCODES'; /** * Class variable that will store generated header code for JS to display directions * * @var string */ var $_directions_header = ''; /** * Class variable that will store information to render directions */ var $_directions = array(); /** * Class variable to store whether or not to display JS functions in the header */ var $_display_js_functions = true; /** * Class variable that will store flag to minify js - this can be overwritten after object is instantiated. Include JSMin.php if * you want to use JS Minification. * * @var bool */ var $_minify_js = true; /** * Class variable for localization */ var $locale = NULL; /** * class constructor * * @param string $map_id the DOM element ID for the map * @param string $app_id YOUR Yahoo App ID */ function GoogleMapAPI($map_id = 'map', $app_id = 'MyMapApp') { $this->map_id = $map_id; $this->sidebar_id = 'sidebar_' . $map_id; $this->app_id = $app_id; } function setLocale($loc) { if (empty($loc)) { $this->locale = ''; } else { $this->locale = '&amp;language='.$loc; } } /** * function to enable map display */ function enableMapDisplay(){ $this->display_map = true; } /** * function to disable map display (used to display street view only) */ function disableMapDisplay(){ $this->display_map = true; } /** * sets the PEAR::DB dsn * * @param string $dsn Takes the form of "mysql://user:pass@localhost/db_name" */ function setDSN($dsn) { $this->dsn = $dsn; } /** * sets the width of the map * * @param string $width * @return string|false Width or false if not a valid value */ function setWidth($width) { if(!preg_match('!^(\d+)(.*)$!',$width,$_match)) return false; $_width = $_match[1]; $_type = $_match[2]; if($_type == '%') $this->width = $_width . '%'; else $this->width = $_width . 'px'; return true; } /** * sets the height of the map * * @param string $height * @return string|false Height or false if not a valid value */ function setHeight($height) { if(!preg_match('!^(\d+)(.*)$!',$height,$_match)) return false; $_height = $_match[1]; $_type = $_match[2]; if($_type == '%') $this->height = $_height . '%'; else $this->height = $_height . 'px'; return true; } /** * sets the default map zoom level * * @param string $level Initial zoom level value */ function setZoomLevel($level) { $this->zoom = (int) $level; } /** * enables the map controls (zoom/move) * */ function enableMapControls() { $this->map_controls = true; } /** * disables the map controls (zoom/move) * */ function disableMapControls() { $this->map_controls = false; } /** * sets the map control size (large/small) * * @param string $size Large/Small */ function setControlSize($size) { if(in_array($size,array('large','small'))) $this->control_size = $size; } /** * enables the type controls (map/satellite/hybrid) * */ function enableLocalSearch() { $this->local_search = true; } /** * disables the type controls (map/satellite/hybrid) * */ function disableLocalSearch() { $this->local_search = false; } /** * enables the type controls (map/satellite/hybrid) * */ function enableLocalSearchAds() { $this->local_search_ads = true; } /** * disables the type controls (map/satellite/hybrid) * */ function disableLocalSearchAds() { $this->local_search_ads = false; } /** * enables walking directions * */ function enableWalkingDirections() { $this->walking_directions = true; } /** * disables walking directions * */ function disableWalkingDirections() { $this->walking_directions = false; } /** * enables biking directions * */ function enableBikingDirections() { $this->biking_directions = true; } /** * disables biking directions * */ function disableBikingDirections() { $this->biking_directions = false; } /** * enables avoid highways in directions * */ function enableAvoidHighways() { $this->avoid_highways = true; } /** * disables avoid highways in directions * */ function disableAvoidHighways() { $this->avoid_highways = false; } /** * enables avoid tolls in directions * */ function enableAvoidTolls() { $this->avoid_tolls = true; } /** * disables avoid tolls in directions * */ function disableAvoidTolls() { $this->avoid_tolls = false; } /** * Add directions route to the map and adds text directions container with id=$dom_id * * @param string $start_address * @param string $dest_address * @param string $dom_id DOM Element ID for directions container. * @param bool $add_markers Add a marker at start and dest locations. */ function addDirections($start_address='',$dest_address='',$dom_id='', $add_markers=true, $elevation_samples=256, $elevation_width="", $elevation_height="", $elevation_dom_id=''){ if($elevation_dom_id=="") $elevation_dom_id = "elevation".$dom_id; if($start_address != '' && $dest_address != '' && $dom_id != ''){ $this->_directions[$dom_id] = array( "dom_id"=>$dom_id, "start"=>$start_address, "dest"=>$dest_address, "markers"=>true, "elevation_samples"=>$elevation_samples, "width"=>($elevation_width!=""?$elevation_width:str_replace("px","",$this->width)), "height"=>($elevation_height!=""?$elevation_height:str_replace("px","",$this->height)/2), "elevation_dom_id"=>$elevation_dom_id ); if($add_markers==true){ $this->addMarkerByAddress($start_address,$start_address, $start_address); $this->addMarkerByAddress($dest_address,$dest_address, $dest_address); } } } /** * enables the type controls (map/satellite/hybrid) * */ function enableTypeControls() { $this->type_controls = true; } /** * disables the type controls (map/satellite/hybrid) * */ function disableTypeControls() { $this->type_controls = false; } /** * sets map control style */ function setTypeControlsStyle($type){ switch($type){ case "dropdown": $this->type_controls_style = "DROPDOWN_MENU"; break; case "horizontal": $this->type_controls_style = "HORIZONTAL_BAR"; break; default: $this->type_controls_style = "DEFAULT"; break; } } function setTypeControlPosition($pos) { $this->type_controls_position = $pos; } function setTypeControlTypes($list) { $this->type_controls_list = $list; } /** * set default map type (map/satellite/hybrid) * * @param string $type New V3 Map Types, only include ending word (HYBRID,SATELLITE,TERRAIN,ROADMAP) */ function setMapType($type) { switch($type) { case 'hybrid': $this->map_type = 'HYBRID'; break; case 'satellite': $this->map_type = 'SATELLITE'; break; case 'terrain': $this->map_type = 'TERRAIN'; break; case 'map': default: $this->map_type = 'ROADMAP'; break; } } /** * enables onload * */ function enableOnLoad() { $this->onload = true; } /** * disables onload * */ function disableOnLoad() { $this->onload = false; } /** * enables sidebar * */ function enableSidebar() { $this->sidebar = true; } /** * disables sidebar * */ function disableSidebar() { $this->sidebar = false; } /** * enables map directions inside info window * */ function enableDirections() { $this->directions = true; } /** * disables map directions inside info window * */ function disableDirections() { $this->directions = false; } /** * set browser alert message for incompatible browsers * * @param string $message */ function setBrowserAlert($message) { $this->browser_alert = $message; } /** * set <noscript> message when javascript is disabled * * @param string $message */ function setJSAlert($message) { $this->js_alert = $message; } /** * enable traffic overlay */ function enableTrafficOverlay() { $this->traffic_overlay= true; } /** * disable traffic overlay (default) */ function disableTrafficOverlay() { $this->traffic_overlay= false; } /** * enable biking overlay */ function enableBikingOverlay() { $this->biking_overlay= true; } /** * disable biking overlay (default) */ function disableBikingOverlay() { $this->biking_overlay= false; } /** * enable biking overlay */ function enableStreetViewControls() { $this->street_view_controls= true; } /** * disable biking overlay (default) */ function disableStreetViewControls() { $this->street_view_controls= false; } /** * attach a dom id object as a streetview container to the map * NOTE: Only one container can be attached to a map. **/ function attachStreetViewContainer($dom_id){ $this->street_view_dom_id = $dom_id; } /** * enable Google Adsense admanager on Map (not supported in V3 API) */ function enableAds(){ $this->ads_manager = true; } /** * disable Google Adsense admanager on Map (not supported in V3 API) */ function disableAds(){ $this->ads_manager = false; } /** * enable map marker info windows */ function enableInfoWindow() { $this->info_window = true; } /** * disable map marker info windows */ function disableInfoWindow() { $this->info_window = false; } /** * enable elevation marker to be displayed */ function enableElevationMarker(){ $this->elevation_markers = true; } /** * disable elevation marker */ function disableElevationMarker(){ $this->elevation_markers = false; } /** * enable elevation to be displayed for directions */ function enableElevationDirections(){ $this->elevation_directions = true; } /** * disable elevation to be displayed for directions */ function disableElevationDirections(){ $this->elevation_directions = false; } /** * enable map marker clustering */ function enableClustering() { $this->marker_clusterer = true; } /** * disable map marker clustering */ function disableClustering() { $this->marker_clusterer = false; } /** * set clustering options */ function setClusterOptions($zoom="null", $gridsize="null", $styles="null"){ $this->marker_clusterer_options["maxZoom"]=$zoom; $this->marker_clusterer_options["gridSize"]=$gridsize; $this->marker_clusterer_options["styles"]=$styles; } /** * Set clustering library file location */ function setClusterLocation($file){ $this->marker_clusterer_location=$file; } /** * set the info window trigger action * * @param string $message click/mouseover */ function setInfoWindowTrigger($type) { switch($type) { case 'mouseover': $this->window_trigger = 'mouseover'; break; default: $this->window_trigger = 'click'; break; } } /** * enable zoom to encompass makers */ function enableZoomEncompass() { $this->zoom_encompass = true; } /** * disable zoom to encompass makers */ function disableZoomEncompass() { $this->zoom_encompass = false; } /** * set the boundary fudge factor * @param float */ function setBoundsFudge($val) { $this->bounds_fudge = $val; } /** * enables the scale map control * */ function enableScaleControl() { $this->scale_control = true; } /** * disables the scale map control * */ function disableScaleControl() { $this->scale_control = false; } /** * enables the overview map control * */ function enableOverviewControl() { $this->overview_control = true; } /** * disables the overview map control * */ function disableOverviewControl() { $this->overview_control = false; } /** * set the lookup service to use for geocode lookups * default is YAHOO, you can also use GOOGLE. * NOTE: GOOGLE can to intl lookups, but is not an * official API, so use at your own risk. * * @param string $service * @deprecated */ function setLookupService($service) { switch($service) { case 'GOOGLE': $this->lookup_service = 'GOOGLE'; break; case 'YAHOO': default: $this->lookup_service = 'YAHOO'; break; } } /** * adds a map marker by address - DEPRECATION WARNING: Tabs are no longer supported in V3, if this changes this can be easily updated. * * @param string $address the map address to mark (street/city/state/zip) * @param string $title the title display in the sidebar * @param string $html the HTML block to display in the info bubble (if empty, title is used) * @param string $tooltip Tooltip to display (deprecated?) * @param string $icon_filename Web file location (eg http://somesite/someicon.gif) to use for icon * @param string $icon_shadow_filename Web file location (eg http://somesite/someicon.gif) to use for icon shadow * @return int|bool */ function addMarkerByAddress($address,$title = '',$html = '',$tooltip = '', $icon_filename = '', $icon_shadow_filename='') { if(($_geocode = $this->getGeocode($address)) === false) return false; return $this->addMarkerByCoords($_geocode['lon'],$_geocode['lat'],$title,$html,$tooltip, $icon_filename, $icon_shadow_filename); } /** * adds a map marker by lat/lng coordinates - DEPRECATION WARNING: Tabs are no longer supported in V3, if this changes this can be easily updated. * * @param string $lon the map longitude (horizontal) * @param string $lat the map latitude (vertical) * @param string $title the title display in the sidebar * @param string $html the HTML block to display in the info bubble (if empty, title is used) * @param string $tooltip Tooltip to display (deprecated?) * @param string $icon_filename Web file location (eg http://somesite/someicon.gif) to use for icon * @param string $icon_shadow_filename Web file location (eg http://somesite/someicon.gif) to use for icon shadow * @return int|bool */ function addMarkerByCoords($lon,$lat,$title = '',$html = '',$tooltip = '', $icon_filename = '', $icon_shadow_filename='') { $_marker['lon'] = $lon; $_marker['lat'] = $lat; $_marker['html'] = (is_array($html) || strlen($html) > 0) ? $html : $title; $_marker['title'] = $title; $_marker['tooltip'] = $tooltip; if($icon_filename!=""){ $_marker['icon_key'] = $this->setMarkerIconKey($icon_filename, $icon_shadow_filename); if($icon_shadow_filename!=""){ $_marker['shadow_icon']=1; } }else if( $this->default_icon != ''){ $_marker['icon_key'] = $this->setMarkerIconKey($this->default_icon, $this->default_icon_shadow); if($this->default_icon_shadow!=""){ $_marker['shadow_icon']=1; } } $this->_markers[] = $_marker; $this->adjustCenterCoords($_marker['lon'],$_marker['lat']); // return index of marker return count($this->_markers) - 1; } /** * adds a DOM object ID to specified marker to open the marker's info window. * Does nothing if the info windows is disabled. * @param string $marker_id ID of the marker to associate to * @param string $dom_id ID of the DOM object to use to open marker info window * @return bool true/false status */ function addMarkerOpener($marker_id, $dom_id){ if($this->info_window === false || !isset($this->_markers[$marker_id])) return false; if(!isset($this->_markers[$marker_id]["openers"])) $this->_markers[$marker_id]["openers"] = array(); $this->_markers[$marker_id]["openers"][] = $dom_id; } /** * adds polyline by passed array * if color, weight and opacity are not defined, use the google maps defaults * @param array $polyline_array array of lat/long coords * @param string $id An array id to use to append coordinates to a line * @param string $color the color of the line (format: #000000) * @param string $weight the weight of the line in pixels * @param string $opacity the line opacity (percentage) * @return bool|int Array id of newly added point or false */ function addPolylineByCoordsArray($polyline_array,$id=false,$color='',$weight=0,$opacity=0){ if(!is_array($polyline_array) || sizeof($polyline_array) < 2) return false; $_prev_coords = ""; $_next_coords = ""; foreach($polyline_array as $_coords){ $_prev_coords = $_next_coords; $_next_coords = $_coords; if($_prev_coords !== ""){ $_lt1=$_prev_coords["lat"]; $_ln1=$_prev_coords["long"]; $_lt2=$_next_coords["lat"]; $_ln2=$_next_coords["long"]; $id = $this->addPolyLineByCoords($_ln1, $_lt1, $_ln2, $_lt2, $id, $color, $weight, $opacity); } } return $id; } /** * adds polyline by passed array * if color, weight and opacity are not defined, use the google maps defaults * @param array $polyline_array array of addresses * @param string $id An array id to use to append coordinates to a line * @param string $color the color of the line (format: #000000) * @param string $weight the weight of the line in pixels * @param string $opacity the line opacity (percentage) * @return bool|int Array id of newly added point or false */ function addPolylineByAddressArray($polyline_array,$id=false,$color='',$weight=0,$opacity=0){ if(!is_array($polyline_array) || sizeof($polyline_array) < 2) return false; $_prev_address = ""; $_next_address = ""; foreach($polyline_array as $_address){ $_prev_address = $_next_address; $_next_address = $_address; if($_prev_address !== ""){ $id = $this->addPolyLineByAddress($_prev_address, $_next_address, $id, $color, $weight, $opacity); } } return $id; } /** * adds a map polyline by address * if color, weight and opacity are not defined, use the google maps defaults * * @param string $address1 the map address to draw from * @param string $address2 the map address to draw to * @param string $id An array id to use to append coordinates to a line * @param string $color the color of the line (format: #000000) * @param string $weight the weight of the line in pixels * @param string $opacity the line opacity (percentage) * @return bool|int Array id of newly added point or false */ function addPolyLineByAddress($address1,$address2,$id=false,$color='',$weight=0,$opacity=0) { if(($_geocode1 = $this->getGeocode($address1)) === false) return false; if(($_geocode2 = $this->getGeocode($address2)) === false) return false; return $this->addPolyLineByCoords($_geocode1['lon'],$_geocode1['lat'],$_geocode2['lon'],$_geocode2['lat'],$id,$color,$weight,$opacity); } /** * adds a map polyline by map coordinates * if color, weight and opacity are not defined, use the google maps defaults * * @param string $lon1 the map longitude to draw from * @param string $lat1 the map latitude to draw from * @param string $lon2 the map longitude to draw to * @param string $lat2 the map latitude to draw to * @param string $id An array id to use to append coordinates to a line * @param string $color the color of the line (format: #000000) * @param string $weight the weight of the line in pixels * @param string $opacity the line opacity (percentage) * @return string $id id of the created/updated polyline array */ function addPolyLineByCoords($lon1,$lat1,$lon2,$lat2,$id=false,$color='',$weight=0,$opacity=0) { if($id !== false && isset($this->_polylines[$id]) && is_array($this->_polylines[$id])){ $_polyline = $this->_polylines[$id]; }else{ //only set color,weight,and opacity if new polyline $_polyline = array( "color"=>$color, "weight"=>$weight, "opacity"=>$opacity ); } if(!isset($_polyline['coords']) || !is_array($_polyline['coords'])){ $_polyline['coords'] = array( "0"=> array("lat"=>$lat1, "long"=>$lon1), "1"=> array("lat"=>$lat2, "long"=>$lon2) ); }else{ $last_index = sizeof($_polyline['coords'])-1; //check if lat1/lon1 point is already on polyline if($_polyline['coords'][$last_index]["lat"] != $lat1 || $_polyline['coords'][$last_index]["long"] != $lon1){ $_polyline['coords'][] = array("lat"=>$lat1, "long"=>$lon1); } $_polyline['coords'][] = array("lat"=>$lat2, "long"=>$lon2); } if($id === false){ $this->_polylines[] = $_polyline; $id = count($this->_polylines) - 1; }else{ $this->_polylines[$id] = $_polyline; } $this->adjustCenterCoords($lon1,$lat1); $this->adjustCenterCoords($lon2,$lat2); // return index of polyline return $id; } /** * function to add an elevation profile for a polyline to the page */ function addPolylineElevation($polyline_id, $elevation_dom_id, $samples=256, $width="", $height="", $focus_color="#00ff00"){ if(isset($this->_polylines[$polyline_id])){ $this->_elevation_polylines[$polyline_id] = array( "dom_id"=>$elevation_dom_id, "samples"=>$samples, "width"=>($width!=""?$width:str_replace("px","",$this->width)), "height"=>($height!=""?$height:str_replace("px","",$this->height)/2), "focus_color"=>$focus_color ); } } /** * function to add an overlay to the map. */ function addOverlay($bds_lat1, $bds_lon1, $bds_lat2, $bds_lon2, $img_src, $opacity = 100){ $_overlay = array( "bounds" => array( "ne"=>array( "lat"=>$bds_lat1, "long"=>$bds_lon1 ), "sw"=>array( "lat"=>$bds_lat2, "long"=>$bds_lon2 ) ), "img" => $img_src, "opacity" => $opacity/10 ); $this->adjustCenterCoords($bds_lon1,$bds_lat1); $this->adjustCenterCoords($bds_lon2,$bds_lat2); $this->_overlays[] = $_overlay; return count($this->_overlays)-1; } /** * function to add a KML overlay to the map. * *Note that this expects a filename and file parsing/processing is done * on the client side */ function addKMLOverlay($file){ $this->_kml_overlays[] = $file; return count($this->_kml_overlays)-1; } /** * adjust map center coordinates by the given lat/lon point * * @param string $lon the map latitude (horizontal) * @param string $lat the map latitude (vertical) */ function adjustCenterCoords($lon,$lat) { if(strlen((string)$lon) == 0 || strlen((string)$lat) == 0) return false; $this->_max_lon = (float) max($lon, $this->_max_lon); $this->_min_lon = (float) min($lon, $this->_min_lon); $this->_max_lat = (float) max($lat, $this->_max_lat); $this->_min_lat = (float) min($lat, $this->_min_lat); $this->center_lon = (float) ($this->_min_lon + $this->_max_lon) / 2; $this->center_lat = (float) ($this->_min_lat + $this->_max_lat) / 2; return true; } /** * set map center coordinates to lat/lon point * * @param string $lon the map latitude (horizontal) * @param string $lat the map latitude (vertical) */ function setCenterCoords($lon,$lat) { $this->center_lat = (float) $lat; $this->center_lon = (float) $lon; } /** * generate an array of params for a new marker icon image * iconShadowImage is optional * If anchor coords are not supplied, we use the center point of the image by default. * Can be called statically. For private use by addMarkerIcon() and setMarkerIcon() and addIcon() * * @param string $iconImage URL to icon image * @param string $iconShadowImage URL to shadow image * @param string $iconAnchorX X coordinate for icon anchor point * @param string $iconAnchorY Y coordinate for icon anchor point * @param string $infoWindowAnchorX X coordinate for info window anchor point * @param string $infoWindowAnchorY Y coordinate for info window anchor point * @return array Array with information about newly /previously created icon. */ function createMarkerIcon($iconImage,$iconShadowImage = '',$iconAnchorX = 'x',$iconAnchorY = 'x',$infoWindowAnchorX = 'x',$infoWindowAnchorY = 'x') { $_icon_image_path = strpos($iconImage,'http') === 0 ? $iconImage : $_SERVER['DOCUMENT_ROOT'] . $iconImage; if(!($_image_info = @getimagesize($_icon_image_path))) { die('GoogleMapAPI:createMarkerIcon: Error reading image: ' . $iconImage); } if($iconShadowImage) { $_shadow_image_path = strpos($iconShadowImage,'http') === 0 ? $iconShadowImage : $_SERVER['DOCUMENT_ROOT'] . $iconShadowImage; if(!($_shadow_info = @getimagesize($_shadow_image_path))) { die('GoogleMapAPI:createMarkerIcon: Error reading shadow image: ' . $iconShadowImage); } } if($iconAnchorX === 'x') { $iconAnchorX = (int) ($_image_info[0] / 2); } if($iconAnchorY === 'x') { $iconAnchorY = (int) ($_image_info[1] / 2); } if($infoWindowAnchorX === 'x') { $infoWindowAnchorX = (int) ($_image_info[0] / 2); } if($infoWindowAnchorY === 'x') { $infoWindowAnchorY = (int) ($_image_info[1] / 2); } $icon_info = array( 'image' => $iconImage, 'iconWidth' => $_image_info[0], 'iconHeight' => $_image_info[1], 'iconAnchorX' => $iconAnchorX, 'iconAnchorY' => $iconAnchorY, 'infoWindowAnchorX' => $infoWindowAnchorX, 'infoWindowAnchorY' => $infoWindowAnchorY ); if($iconShadowImage) { $icon_info = array_merge($icon_info, array('shadow' => $iconShadowImage, 'shadowWidth' => $_shadow_info[0], 'shadowHeight' => $_shadow_info[1])); } return $icon_info; } /** * set the default marker icon for ALL markers on the map * NOTE: This MUST be set prior to adding markers in order for the defaults * to be set correctly. * @param string $iconImage URL to icon image * @param string $iconShadowImage URL to shadow image * @param string $iconAnchorX X coordinate for icon anchor point * @param string $iconAnchorY Y coordinate for icon anchor point * @param string $infoWindowAnchorX X coordinate for info window anchor point * @param string $infoWindowAnchorY Y coordinate for info window anchor point * @return string A marker icon key. */ function setMarkerIcon($iconImage,$iconShadowImage = '',$iconAnchorX = 'x',$iconAnchorY = 'x',$infoWindowAnchorX = 'x',$infoWindowAnchorY = 'x') { $this->default_icon = $iconImage; $this->default_icon_shadow = $iconShadowImage; return $this->setMarkerIconKey($iconImage,$iconShadowImage,$iconAnchorX,$iconAnchorY,$infoWindowAnchorX,$infoWindowAnchorY); } /** * function to check if icon is in class "marker_iconset", if it is, * returns the key, if not, creates a new array indice and returns the key * @param string $iconImage URL to icon image * @param string $iconShadowImage URL to shadow image * @param string $iconAnchorX X coordinate for icon anchor point * @param string $iconAnchorY Y coordinate for icon anchor point * @param string $infoWindowAnchorX X coordinate for info window anchor point * @param string $infoWindowAnchorY Y coordinate for info window anchor point * @return string A marker icon key. */ function setMarkerIconKey($iconImage,$iconShadow='',$iconAnchorX = 'x',$iconAnchorY = 'x',$infoWindowAnchorX = 'x',$infoWindowAnchorY = 'x'){ $_iconKey = $this->getIconKey($iconImage,$iconShadow); if(isset($this->_marker_icons[$_iconKey])){ return $_iconKey; }else{ return $this->addIcon($iconImage,$iconShadow,$iconAnchorX,$iconAnchorY,$infoWindowAnchorX,$infoWindowAnchorY); } } /** * function to get icon key * @param string $iconImage URL to marker icon image * @param string $iconShadow URL to marker icon shadow image * @return string Returns formatted icon key from icon or icon+shadow image name pairs */ function getIconKey($iconImage,$iconShadow=""){ return str_replace(array("/",":","."),"",$iconImage.$iconShadow); } /** * add an icon to "iconset" * @param string $iconImage URL to marker icon image * @param string $iconShadow URL to marker icon shadow image * @param string $iconAnchorX X coordinate for icon anchor point * @param string $iconAnchorY Y coordinate for icon anchor point * @param string $infoWindowAnchorX X coordinate for info window anchor point * @param string $infoWindowAnchorY Y coordinate for info window anchor point * @return string Returns the icon's key. */ function addIcon($iconImage,$iconShadowImage = '',$iconAnchorX = 'x',$iconAnchorY = 'x',$infoWindowAnchorX = 'x',$infoWindowAnchorY = 'x') { $_iconKey = $this->getIconKey($iconImage, $iconShadowImage); $this->_marker_icons[$_iconKey] = $this->createMarkerIcon($iconImage,$iconShadowImage,$iconAnchorX,$iconAnchorY,$infoWindowAnchorX,$infoWindowAnchorY); return $_iconKey; } /** * updates a marker's icon key. * NOTE: To be used in lieu of addMarkerIcon, now use addIcon + updateMarkerIconKey for explicit icon association * @param string $markerKey Marker key to define which marker's icon to update * @param string $iconKey Icon key to define which icon to use. */ function updateMarkerIconKey($markerKey, $iconKey){ if(isset($this->_markers[$markerKey])){ $this->_markers[$markerKey]['icon_key'] = $iconKey; } } /** * print map header javascript (goes between <head></head>) * */ function printHeaderJS() { echo $this->getHeaderJS(); } /** * return map header javascript (goes between <head></head>) * */ function getHeaderJS() { $_headerJS = ""; if( $this->mobile == true){ $_headerJS .= " <meta name='viewport' content='initial-scale=1.0, user-scalable=no' /> "; } if(!empty($this->_elevation_polylines)||(!empty($this->_directions)&&$this->elevation_directions)){ $_headerJS .= "<script type='text/javascript' src='http://www.google.com/jsapi'></script>"; $_headerJS .= " <script type='text/javascript'> // Load the Visualization API and the piechart package. google.load('visualization', '1', {packages: ['columnchart']}); </script>"; } $_headerJS .= "<script type='text/javascript' src='http://maps.google.com/maps/api/js?sensor=".(($this->mobile==true)?"true":"false").$this->locale."'></script>"; if($this->marker_clusterer){ $_headerJS .= "<script type='text/javascript' src='".$this->marker_clusterer_location."' ></script>"; } if($this->local_search){ /* Load Local Search API V3 when available*/} return $_headerJS; } /** * prints onLoad() without having to manipulate body tag. * call this after the print map like so... * $map->printMap(); * $map->printOnLoad(); */ function printOnLoad() { echo $this->getOnLoad(); } /** * print onLoad function name */ function printOnLoadFunction(){ echo $this->getOnLoadFunction(); } /** * return js to set onload function */ function getOnLoad() { return '<script language="javascript" type="text/javascript" charset="utf-8">window.onload=onLoad'.$this->map_id.';</script>'; } /** * return js to set onload function */ function getOnLoadFunction() { return 'onLoad'.$this->map_id; } /** * print map javascript (put just before </body>, or in <header> if using onLoad()) * */ function printMapJS() { echo $this->getMapJS(); } /** * return map javascript * */ function getMapJS() { $_script = ""; $_key = $this->map_id; $_output = '<script type="text/javascript" charset="utf-8">' . "\n"; $_output .= '//<![CDATA[' . "\n"; $_output .= "/*************************************************\n"; $_output .= " * Created with GoogleMapAPI" . $this->_version . "\n"; $_output .= " * Author: Brad Wedell <brad AT mycnl DOT com>\n"; $_output .= " * Link http://code.google.com/p/phpgooglemapapiv3/\n"; $_output .= " * Copyright 2010 Brad Wedell\n"; $_output .= " * Original Author: Monte Ohrt <monte AT ohrt DOT com>\n"; $_output .= " * Original Copyright 2005-2006 New Digital Group\n"; $_output .= " * Originial Link http://www.phpinsider.com/php/code/GoogleMapAPI/\n"; $_output .= " *************************************************/\n"; if($this->street_view_dom_id!=""){ $_script .= " var panorama".$this->street_view_dom_id."$_key = ''; "; if(!empty($this->_markers)){ $_script .= " var panorama".$this->street_view_dom_id."markers$_key = []; "; } } if(!empty($this->_markers)){ $_script .= " var markers$_key = []; "; if($this->sidebar) { $_script .= " var sidebar_html$_key = ''; var marker_html$_key = []; "; } } if($this->marker_clusterer){ $_script .= " var markerClusterer$_key = null; "; } if($this->directions) { $_script .= " var to_htmls$_key = []; var from_htmls$_key = []; "; } if(!empty($this->_directions)){ $_script .= " var directions$_key = []; "; } //Polylines if(!empty($this->_polylines)){ $_script .= " var polylines$_key = []; var polylineCoords$_key = []; "; if(!empty($this->_elevation_polylines)){ $_script .= " var elevationPolylines$_key = []; "; } } //Elevation stuff if(!empty($this->_elevation_polylines)||(!empty($this->_directions)&&$this->elevation_directions)){ $_script .= " var elevationCharts$_key = []; "; } //Overlays if(!empty($this->_overlays)){ $_script .= " var overlays$_key = []; "; } //KML Overlays if(!empty($this->_kml_overlays)){ $_script .= " var kml_overlays$_key = []; "; } //New Icons if(!empty($this->_marker_icons)){ $_script .= "var icon$_key = []; \n"; foreach($this->_marker_icons as $icon_key=>$icon_info){ //no need to check icon key here since that's already done with setters $_script .= " icon".$_key."['$icon_key'] = {}; icon".$_key."['$icon_key'].image = new google.maps.MarkerImage('".$icon_info["image"]."', // The size new google.maps.Size(".$icon_info['iconWidth'].", ".$icon_info['iconHeight']."), // The origin(sprite) new google.maps.Point(0,0), // The anchor new google.maps.Point(".$icon_info['iconAnchorX'].", ".$icon_info['iconAnchorY'].") ); "; if(isset($icon_info['shadow']) && $icon_info['shadow']!=""){ $_script .= " icon".$_key."['$icon_key'].shadow = new google.maps.MarkerImage('".$icon_info["shadow"]."', // The size new google.maps.Size(".$icon_info['shadowWidth'].", ".$icon_info['shadowHeight']."), // The origin(sprite) new google.maps.Point(0,0), // The anchor new google.maps.Point(".$icon_info['iconAnchorX'].", ".$icon_info['iconAnchorY'].") ); "; } } } $_script .= "var map$_key = null;\n"; //start setting script var if($this->onload) { $_script .= 'function onLoad'.$this->map_id.'() {' . "\n"; } if(!empty($this->browser_alert)) { //$_output .= 'if (GBrowserIsCompatible()) {' . "\n"; } /* $strMapOptions = ""; if($this->local_search){ $_output .= " mapOptions.googleBarOptions= { style : 'new' ".(($this->local_search_ads)?", adsOptions: { client: '".$this->ads_pub_id."', channel: '".$this->ads_channel."', language: 'en' ":"")." }; "; $strMapOptions .= ", mapOptions"; } */ if($this->display_map){ $_script .= sprintf('var mapObj%s = document.getElementById("%s");', $_key, $this->map_id) . "\n"; $_script .= "if (mapObj$_key != 'undefined' && mapObj$_key != null) {\n"; $selectorlist = array(); foreach ($this->type_controls_list as $listOption) { $selectorlist[] = 'google.maps.MapTypeId.'.$listOption; } $_script .= " var allowedtypes = [".implode(', ',$selectorlist)."];"; $_script .= " var mapOptions$_key = { zoom: ".$this->zoom.", mapTypeId: google.maps.MapTypeId.".$this->map_type.", mapTypeControl: ".($this->type_controls?"true":"false").", mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.".$this->type_controls_style.", position: google.maps.ControlPosition.".$this->type_controls_position.", mapTypeIds: allowedtypes } }; "; if(isset($this->center_lat) && isset($this->center_lon)) { // Special care for decimal point in lon and lat, would get lost if "wrong" locale is set; applies to (s)printf only $_script .= " mapOptions".$_key.".center = new google.maps.LatLng( ".number_format($this->center_lat, 6, ".", "").", ".number_format($this->center_lon, 6, ".", "")." ); "; } if($this->street_view_controls){ $_script .= " mapOptions".$_key.".streetViewControl= true; "; } $_script .= " map$_key = new google.maps.Map(mapObj$_key,mapOptions$_key); "; if($this->street_view_dom_id!=""){ $_script .= " panorama".$this->street_view_dom_id."$_key = new google.maps.StreetViewPanorama(document.getElementById('".$this->street_view_dom_id."')); map$_key.setStreetView(panorama".$this->street_view_dom_id."$_key); "; if(!empty($this->_markers)){ //Add markers to the street view if($this->street_view_dom_id!=""){ $_script .= $this->getAddMarkersJS($this->map_id, $pano=true); } //set center to last marker $last_id = count($this->_markers)-1; $_script .= " panorama".$this->street_view_dom_id."$_key.setPosition(new google.maps.LatLng( ".$this->_markers[$last_id]["lat"].", ".$this->_markers[$last_id]["lon"]." )); panorama".$this->street_view_dom_id."$_key.setVisible(true); "; } } if(!empty($this->_directions)){ $_script .= $this->getAddDirectionsJS(); } //$_output .= "map.addMapType(G_SATELLITE_3D_MAP);\n"; // zoom so that all markers are in the viewport if($this->zoom_encompass && (count($this->_markers) > 1 || count($this->_polylines) >= 1 || count($this->_overlays) >= 1)) { // increase bounds by fudge factor to keep // markers away from the edges $_len_lon = $this->_max_lon - $this->_min_lon; $_len_lat = $this->_max_lat - $this->_min_lat; $this->_min_lon -= $_len_lon * $this->bounds_fudge; $this->_max_lon += $_len_lon * $this->bounds_fudge; $this->_min_lat -= $_len_lat * $this->bounds_fudge; $this->_max_lat += $_len_lat * $this->bounds_fudge; //unscrew this for our European brethern--Javascript thinks commas separate parameters! $minlat = str_replace(',','.',(string) $this->_min_lat); $maxlat = str_replace(',','.',(string) $this->_max_lat); $minlon = str_replace(',','.',(string) $this->_min_lon); $maxlon = str_replace(',','.',(string) $this->_max_lon); $_script .= "var bds$_key = new google.maps.LatLngBounds(new google.maps.LatLng($minlat, $minlon), new google.maps.LatLng($maxlat, $maxlon));\n"; $_script .= 'map'.$_key.'.fitBounds(bds'.$_key.');' . "\n"; } /* * default V3 functionality caters control display according to the * device that's accessing the page, as well as the specified width * and height of the map itself. if($this->map_controls) { if($this->control_size == 'large') $_output .= 'map.addControl(new GLargeMapControl(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10,10)));' . "\n"; else $_output .= 'map.addControl(new GSmallMapControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,60)));' . "\n"; } if($this->type_controls) { $_output .= 'map.addControl(new GMapTypeControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10)));' . "\n"; } if($this->scale_control) { if($this->control_size == 'large'){ $_output .= 'map.addControl(new GScaleControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(35,190)));' . "\n"; }else { $_output .= 'map.addControl(new GScaleControl(), new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(190,10)));' . "\n"; } } if($this->overview_control) { $_output .= 'map.addControl(new GOverviewMapControl());' . "\n"; } if($this->ads_manager){ $_output .= 'var adsManager = new GAdsManager(map, "'.$this->ads_pub_id.'",{channel:"'.$this->ads_channel.'",maxAdsOnMap:"'.$this->ads_max.'"}); adsManager.enable();'."\n"; } if($this->local_search){ $_output .= "\n map.enableGoogleBar(); "; } */ if($this->traffic_overlay){ $_script .= " var trafficLayer = new google.maps.TrafficLayer(); trafficLayer.setMap(map$_key); "; } if($this->biking_overlay){ $_script .= " var bikingLayer = new google.maps.BicyclingLayer(); bikingLayer.setMap(map$_key); "; } $_script .= $this->getAddMarkersJS(); $_script .= $this->getPolylineJS(); $_script .= $this->getAddOverlayJS(); if($this->_kml_overlays!==""){ foreach($this->_kml_overlays as $_kml_key=>$_kml_file){ $_script .= " kml_overlays$_key[$_kml_key]= new google.maps.KmlLayer('$_kml_file'); kml_overlays$_key[$_kml_key].setMap(map$_key); "; } $_script .= " "; } //end JS if mapObj != "undefined" block $_script .= '}' . "\n"; }//end if $this->display_map==true if(!empty($this->browser_alert)) { // $_output .= '} else {' . "\n"; // $_output .= 'alert("' . str_replace('"','\"',$this->browser_alert) . '");' . "\n"; // $_output .= '}' . "\n"; } if($this->onload) { $_script .= '}' . "\n"; } $_script .= $this->getMapFunctions(); if($this->_minify_js && class_exists("JSMin")){ $_script = JSMin::minify($_script); } //Append script to output $_output .= $_script; $_output .= '//]]>' . "\n"; $_output .= '</script>' . "\n"; return $_output; } /** * function to render utility functions for use on the page */ function getMapFunctions(){ $_script = ""; if($this->_display_js_functions===true){ $_script = $this->getUtilityFunctions(); } return $_script; } function getUtilityFunctions(){ $_script = ""; if(!empty($this->_markers)) $_script .= $this->getCreateMarkerJS(); if(!empty($this->_overlays)) $_script .= $this->getCreateOverlayJS(); if(!empty($this->_elevation_polylines)||(!empty($this->_directions)&&$this->elevation_directions)) $_script .= $this->getPlotElevationJS(); // Utility functions used to distinguish between tabbed and non-tabbed info windows $_script .= 'function isArray(a) {return isObject(a) && a.constructor == Array;}' . "\n"; $_script .= 'function isObject(a) {return (a && typeof a == \'object\') || isFunction(a);}' . "\n"; $_script .= 'function isFunction(a) {return typeof a == \'function\';}' . "\n"; $_script .= 'function isEmpty(obj) { for(var i in obj) { return false; } return true; }'."\n"; return $_script; } /** * overridable function for generating js to add markers */ function getAddMarkersJS($map_id = "", $pano= false) { //defaults if($map_id == ""){ $map_id = $this->map_id; } if($pano==false){ $_prefix = "map"; }else{ $_prefix = "panorama".$this->street_view_dom_id; } $_output = ''; foreach($this->_markers as $_marker) { $iw_html = str_replace('"','\"',str_replace(array("\n", "\r"), "", $_marker['html'])); // replace commas with periods so we can pass parameters! $lat = str_replace(',', '.', $_marker['lat']); $lon = str_replace(',', '.', $_marker['lon']); $_output .= "var point = new google.maps.LatLng(".$lat.",".$lon.");\n"; $_output .= sprintf('%s.push(createMarker(%s%s, point,"%s","%s", %s, %s, "%s", %s ));', (($pano==true)?$_prefix:"")."markers".$map_id, $_prefix, $map_id, str_replace('"','\"',$_marker['title']), str_replace('/','\/',$iw_html), (isset($_marker["icon_key"]))?"icon".$map_id."['".$_marker["icon_key"]."'].image":"''", (isset($_marker["icon_key"])&&isset($_marker["shadow_icon"]))?"icon".$map_id."['".$_marker["icon_key"]."'].shadow":"''", (($this->sidebar)?$this->sidebar_id:""), ((isset($_marker["openers"])&&count($_marker["openers"])>0)?json_encode($_marker["openers"]):"''") ) . "\n"; } if($this->marker_clusterer && $pano==false){//only do marker clusterer for map, not streetview $_output .= " markerClusterer".$map_id." = new MarkerClusterer(".$_prefix.$map_id.", markers".$map_id.", { maxZoom: ".$this->marker_clusterer_options["maxZoom"].", gridSize: ".$this->marker_clusterer_options["gridSize"].", styles: ".$this->marker_clusterer_options["styles"]." }); "; } return $_output; } /** * overridable function to generate polyline js - for now can only be used on a map, not a streetview */ function getPolylineJS() { $_output = ''; foreach($this->_polylines as $polyline_id =>$_polyline) { $_coords_output = ""; foreach($_polyline["coords"] as $_coords){ if($_coords_output != ""){$_coords_output.=",";} $_coords_output .= " new google.maps.LatLng(".$_coords["lat"].", ".$_coords["long"].") "; } $_output .= " polylineCoords".$this->map_id."[$polyline_id] = [".$_coords_output."]; polylines".$this->map_id."[$polyline_id] = new google.maps.Polyline({ path: polylineCoords".$this->map_id."[$polyline_id] ".(($_polyline['color']!="")?", strokeColor: '".$_polyline['color']."'":"")." ".(($_polyline['opacity']!=0)?", strokeOpacity: ".$_polyline['opacity']."":"")." ".(($_polyline['weight']!=0)?", strokeWeight: ".$_polyline['weight']."":"")." }); polylines".$this->map_id."[$polyline_id].setMap(map".$this->map_id."); "; //Elevation profiles if(!empty($this->_elevation_polylines) && isset($this->_elevation_polylines[$polyline_id])){ $elevation_dom_id=$this->_elevation_polylines[$polyline_id]["dom_id"]; $width = $this->_elevation_polylines[$polyline_id]["width"]; $height = $this->_elevation_polylines[$polyline_id]["height"]; $samples = $this->_elevation_polylines[$polyline_id]["samples"]; $focus_color = $this->_elevation_polylines[$polyline_id]["focus_color"]; $_output .= " elevationPolylines".$this->map_id."[$polyline_id] = { 'selector':'$elevation_dom_id', 'chart': new google.visualization.ColumnChart(document.getElementById('$elevation_dom_id')), 'service': new google.maps.ElevationService(), 'width':$width, 'height':$height, 'focusColor':'$focus_color', 'marker':null }; elevationPolylines".$this->map_id."[$polyline_id]['service'].getElevationAlongPath({ path: polylineCoords".$this->map_id."[$polyline_id], samples: $samples }, function(results,status){plotElevation(results,status, elevationPolylines".$this->map_id."[$polyline_id], map".$this->map_id.", elevationCharts".$this->map_id.");}); "; } } return $_output; } /** * function to render proper calls for directions - for now can only be used on a map, not a streetview */ function getAddDirectionsJS(){ $_output = ""; foreach($this->_directions as $directions){ $dom_id = $directions["dom_id"]; $travelModeParams = array(); $directionsParams = ""; if($this->walking_directions==TRUE) $directionsParams .= ", \n travelMode:google.maps.DirectionsTravelMode.WALKING"; else if($this->biking_directions==TRUE) $directionsParams .= ", \n travelMode:google.maps.DirectionsTravelMode.BICYCLING"; else $directionsParams .= ", \n travelMode:google.maps.DirectionsTravelMode.DRIVING"; if($this->avoid_highways==TRUE) $directionsParams .= ", \n avoidHighways: true"; if($this->avoid_tollways==TRUE) $directionsParams .= ", \n avoidTolls: true"; $_output .= " directions".$this->map_id."['$dom_id'] = { displayRenderer:new google.maps.DirectionsRenderer(), directionService:new google.maps.DirectionsService(), request:{ origin: '".$directions["start"]."', destination: '".$directions["dest"]."' $directionsParams } ".(($this->elevation_directions)?", selector: '".$directions["elevation_dom_id"]."', chart: new google.visualization.ColumnChart(document.getElementById('".$directions["elevation_dom_id"]."')), service: new google.maps.ElevationService(), width:".$directions["width"].", height:".$directions["height"].", focusColor:'#00FF00', marker:null ":"")." }; directions".$this->map_id."['$dom_id'].displayRenderer.setMap(map".$this->map_id."); directions".$this->map_id."['$dom_id'].displayRenderer.setPanel(document.getElementById('$dom_id')); directions".$this->map_id."['$dom_id'].directionService.route(directions".$this->map_id."['$dom_id'].request, function(response, status) { if (status == google.maps.DirectionsStatus.OK) { directions".$this->map_id."['$dom_id'].displayRenderer.setDirections(response); ".(($this->elevation_directions)?" directions".$this->map_id."['$dom_id'].service.getElevationAlongPath({ path: response.routes[0].overview_path, samples: ".$directions["elevation_samples"]." }, function(results,status){plotElevation(results,status, directions".$this->map_id."['$dom_id'], map".$this->map_id.", elevationCharts".$this->map_id.");}); ":"")." } }); "; } return $_output; } /** * function to get overlay creation JS. */ function getAddOverlayJS(){ $_output = ""; foreach($this->_overlays as $_key=>$_overlay){ $_output .= " var bounds = new google.maps.LatLngBounds(new google.maps.LatLng(".$_overlay["bounds"]["ne"]["lat"].", ".$_overlay["bounds"]["ne"]["long"]."), new google.maps.LatLng(".$_overlay["bounds"]["sw"]["lat"].", ".$_overlay["bounds"]["sw"]["long"].")); var image = '".$_overlay["img"]."'; overlays".$this->map_id."[$_key] = new CustomOverlay(bounds, image, map".$this->map_id.", ".$_overlay["opacity"]."); "; } return $_output; } /** * overridable function to generate the js for the js function for creating a marker. */ function getCreateMarkerJS() { $_output = " function createMarker(map, point, title, html, icon, icon_shadow, sidebar_id, openers){ var marker_options = { position: point, map: map, title: title}; if(icon!=''){marker_options.icon = icon;} if(icon_shadow!=''){marker_options.icon_shadow = icon_shadow;} //create marker var new_marker = new google.maps.Marker(marker_options); if(html!=''){ ".(($this->info_window)?" var infowindow = new google.maps.InfoWindow({content: html}); google.maps.event.addListener(new_marker, '".$this->window_trigger."', function() { infowindow.open(map,new_marker); }); if(openers != ''&&!isEmpty(openers)){ for(var i in openers){ var opener = document.getElementById(openers[i]); opener.on".$this->window_trigger." = function(){infowindow.open(map,new_marker); return false}; } } ":"")." if(sidebar_id != ''){ var sidebar = document.getElementById(sidebar_id); if(sidebar!=null && sidebar!=undefined && title!=null && title!=''){ var newlink = document.createElement('a'); ".(($this->info_window)?" newlink.onclick=function(){infowindow.open(map,new_marker); return false}; ":" newlink.onclick=function(){map.setCenter(point); return false}; ")." newlink.innerHTML = title; sidebar.appendChild(newlink); } } } return new_marker; } "; return $_output; } /** * Get create overlay js */ function getCreateOverlayJS(){ $_output = " CustomOverlay.prototype = new google.maps.OverlayView(); function CustomOverlay(bounds, image, map, opacity){ this.bounds_ = bounds; this.image_ = image; this.map_ = map; this.div_ = null; this.opacity = (opacity!='')?opacity:10; this.setMap(map); } CustomOverlay.prototype.onAdd = function() { var div = document.createElement('DIV'); div.style.borderStyle = 'none'; div.style.borderWidth = '0px'; div.style.position = 'absolute'; var img = document.createElement('img'); img.src = this.image_; img.style.width = '100%'; img.style.height = '100%'; img.style.opacity = this.opacity/10; img.style.filter = 'alpha(opacity='+this.opacity*10+')'; div.appendChild(img); this.div_ = div; var panes = this.getPanes(); panes.overlayImage.appendChild(div); } CustomOverlay.prototype.draw = function() { var overlayProjection = this.getProjection(); var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest()); var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast()); var div = this.div_; div.style.left = sw.x + 'px'; div.style.top = ne.y + 'px'; div.style.width = (ne.x - sw.x) + 'px'; div.style.height = (sw.y - ne.y) + 'px'; } CustomOverlay.prototype.onRemove = function() { this.div_.parentNode.removeChild(this.div_); this.div_ = null; } "; return $_output; } /** * print helper function to draw elevation results as a chart */ function getPlotElevationJS(){ $_output = " function plotElevation(results, status, elevation_data, map, charts_array) { charts_array[elevation_data.selector] = { results:results, data:new google.visualization.DataTable() }; charts_array[elevation_data.selector].data.addColumn('string', 'Sample'); charts_array[elevation_data.selector].data.addColumn('number', 'Elevation'); for (var i = 0; i < charts_array[elevation_data.selector].results.length; i++) { charts_array[elevation_data.selector].data.addRow(['', charts_array[elevation_data.selector].results[i].elevation]); } document.getElementById(elevation_data.selector).style.display = 'block'; elevation_data.chart.draw(charts_array[elevation_data.selector].data, { width: elevation_data.width, height: elevation_data.height, legend: 'none', titleY: 'Elevation (m)', focusBorderColor: elevation_data.focusColor }); "; if($this->elevation_markers){ $_output .= $this->getElevationMarkerJS(); } $_output .= "}"; return $_output; } /** * create JS that is inside of JS plot elevation function */ function getElevationMarkerJS(){ $_output = " google.visualization.events.addListener(elevation_data.chart, 'onmouseover', function(e) { if(elevation_data.marker==null){ elevation_data.marker = new google.maps.Marker({ position: charts_array[elevation_data.selector].results[e.row].location, map: map, icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png' }); }else{ elevation_data.marker.setPosition(charts_array[elevation_data.selector].results[e.row].location); } map.setCenter(charts_array[elevation_data.selector].results[e.row].location); }); document.getElementById(elevation_data.selector).onmouseout = function(){ elevation_data.marker = clearElevationMarker(elevation_data.marker); }; function clearElevationMarker(marker){ if(marker!=null){ marker.setMap(null); return null; } } "; return $_output; } /** * print map (put at location map will appear) * */ function printMap() { echo $this->getMap(); } /** * return map * */ function getMap() { $_output = '<script type="text/javascript" charset="utf-8">' . "\n" . '//<![CDATA[' . "\n"; //$_output .= 'if (GBrowserIsCompatible()) {' . "\n"; if(strlen($this->width) > 0 && strlen($this->height) > 0) { $_output .= sprintf('document.write(\'<div id="%s" style="width: %s; height: %s; position:relative;"><\/div>\');',$this->map_id,$this->width,$this->height) . "\n"; } else { $_output .= sprintf('document.write(\'<div id="%s" style="position:relative;"><\/div>\');',$this->map_id) . "\n"; } //$_output .= '}'; //if(!empty($this->js_alert)) { // $_output .= ' else {' . "\n"; // $_output .= sprintf('document.write(\'%s\');', str_replace('/','\/',$this->js_alert)) . "\n"; // $_output .= '}' . "\n"; //} $_output .= '//]]>' . "\n" . '</script>' . "\n"; if(!empty($this->js_alert)) { $_output .= '<noscript>' . $this->js_alert . '</noscript>' . "\n"; } return $_output; } /** * print sidebar (put at location sidebar will appear) * */ function printSidebar() { echo $this->getSidebar(); } /** * return sidebar html * */ function getSidebar() { return sprintf('<div id="%s" class="'.$this->sidebar_id.'"></div>',$this->sidebar_id) . "\n"; } /** * get the geocode lat/lon points from given address * look in cache first, otherwise get from Yahoo * * @param string $address * @return array GeoCode information */ function getGeocode($address) { if(empty($address)) return false; $_geocode = false; if(($_geocode = $this->getCache($address)) === false) { if(($_geocode = $this->geoGetCoords($address)) !== false) { $this->putCache($address, $_geocode['lon'], $_geocode['lat']); } } return $_geocode; } /** * get the geocode lat/lon points from cache for given address * * @param string $address * @return bool|array False if no cache, array of data if has cache */ function getCache($address) { if(!isset($this->dsn)) return false; $_ret = array(); // PEAR DB require_once('DB.php'); $_db =& DB::connect($this->dsn); if (PEAR::isError($_db)) { die($_db->getMessage()); } $_res =& $_db->query("SELECT lon,lat FROM {$this->_db_cache_table} where address = ?", $address); if (PEAR::isError($_res)) { die($_res->getMessage()); } if($_row = $_res->fetchRow()) { $_ret['lon'] = $_row[0]; $_ret['lat'] = $_row[1]; } $_db->disconnect(); return !empty($_ret) ? $_ret : false; } /** * put the geocode lat/lon points into cache for given address * * @param string $address * @param string $lon the map latitude (horizontal) * @param string $lat the map latitude (vertical) * @return bool Status of put cache request */ function putCache($address, $lon, $lat) { if(!isset($this->dsn) || (strlen($address) == 0 || strlen($lon) == 0 || strlen($lat) == 0)) return false; // PEAR DB require_once('DB.php'); $_db =& DB::connect($this->dsn); if (PEAR::isError($_db)) { die($_db->getMessage()); } $_res =& $_db->query('insert into '.$this->_db_cache_table.' values (?, ?, ?)', array($address, $lon, $lat)); if (PEAR::isError($_res)) { die($_res->getMessage()); } $_db->disconnect(); return true; } /** * get geocode lat/lon points for given address from Yahoo * * @param string $address * @return bool|array false if can't be geocoded, array or geocdoes if successful */ function geoGetCoords($address,$depth=0) { switch($this->lookup_service) { case 'GOOGLE': $_url = sprintf('http://%s/maps/api/geocode/json?sensor=%s&address=%s',$this->lookup_server['GOOGLE'], $this->mobile==true?"true":"false", rawurlencode($address)); $_result = false; if($_result = $this->fetchURL($_url)) { $_result_parts = json_decode($_result); if($_result_parts->status!="OK"){ return false; } $_coords['lat'] = $_result_parts->results[0]->geometry->location->lat; $_coords['lon'] = $_result_parts->results[0]->geometry->location->lng; } break; case 'YAHOO': default: $_url = 'http://%s/MapsService/V1/geocode'; $_url .= sprintf('?appid=%s&location=%s',$this->lookup_server['YAHOO'],$this->app_id,rawurlencode($address)); $_result = false; if($_result = $this->fetchURL($_url)) { preg_match('!<Latitude>(.*)</Latitude><Longitude>(.*)</Longitude>!U', $_result, $_match); $_coords['lon'] = $_match[2]; $_coords['lat'] = $_match[1]; } break; } return $_coords; } /** * get full geocode information for given address from Google * NOTE: This does not use the getCache function as there is * a lot of data in a full geocode response to cache. * * @param string $address * @return bool|array false if can't be geocoded, array or geocdoes if successful */ function geoGetCoordsFull($address,$depth=0) { switch($this->lookup_service) { case 'GOOGLE': $_url = sprintf('http://%s/maps/api/geocode/json?sensor=%s&address=%s',$this->lookup_server['GOOGLE'], $this->mobile==true?"true":"false", rawurlencode($address)); $_result = false; if($_result = $this->fetchURL($_url)) { return json_decode($_result); } break; case 'YAHOO': default: $_url = 'http://%s/MapsService/V1/geocode'; $_url .= sprintf('?appid=%s&location=%s',$this->lookup_server['YAHOO'],$this->app_id,rawurlencode($address)); $_result = false; if($_result = $this->fetchURL($_url)) { return $_match; } break; } } /** * fetch a URL. Override this method to change the way URLs are fetched. * * @param string $url */ function fetchURL($url) { return file_get_contents($url); } /** * get distance between to geocoords using great circle distance formula * * @param float $lat1 * @param float $lat2 * @param float $lon1 * @param float $lon2 * @param float $unit M=miles, K=kilometers, N=nautical miles, I=inches, F=feet * @return float */ function geoGetDistance($lat1,$lon1,$lat2,$lon2,$unit='M') { // calculate miles $M = 69.09 * rad2deg(acos(sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($lon1 - $lon2)))); switch(strtoupper($unit)) { case 'K': // kilometers return $M * 1.609344; break; case 'N': // nautical miles return $M * 0.868976242; break; case 'F': // feet return $M * 5280; break; case 'I': // inches return $M * 63360; break; case 'M': default: // miles return $M; break; } } } ?>
jewsroch/sf-photos
zp-core/zp-extensions/GoogleMap/GoogleMap.php
PHP
gpl-2.0
84,178
/* * Copyright (C) 2015 Iasc CHEN * * 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 me.iasc.microduino.blueledpad.db; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.io.ByteArrayOutputStream; public class ImgUtility { // convert from bitmap to byte array public static byte[] getBytes(Bitmap bitmap) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream); return stream.toByteArray(); } // convert from byte array to bitmap public static Bitmap getPhoto(byte[] image) { return BitmapFactory.decodeByteArray(image, 0, image.length); } }
huran2014/huran.github.io
LEDdisplay/ble-8x8ledpad/Android/app/src/main/java/me/iasc/microduino/blueledpad/db/ImgUtility.java
Java
gpl-2.0
1,217
package com.homeCenter.service; import java.util.UUID; import com.almworks.sqlite4java.SQLiteConnection; import com.almworks.sqlite4java.SQLiteException; import com.almworks.sqlite4java.SQLiteJob; import com.almworks.sqlite4java.SQLiteStatement; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.homeCenter.Entity; import com.homeCenter.EntityType; import com.homeCenter.Forecast; import com.homeCenter.Notification; import com.homeCenter.User; import com.homeCenter.common.Log; import com.homeCenter.db.Database; import com.homeCenter.db.DatabaseEqualizer; import com.homeCenter.db.DatabaseVersion; public class VisualizationDashboard extends Entity { public static final String TABLE = "dashboard"; public static final String HOME_SCREEN_ID = "HOMESCREEN"; protected JsonArray tiles; public VisualizationDashboard(Database db, User user) { super(db, user, EntityType.DASHBOARD); } public VisualizationDashboard(Database db, User user, final String id) { super(db, user, EntityType.DASHBOARD, id); } public JsonArray getTiles() { if(this.tiles == null) return new JsonArray(); return this.tiles; } public void setTiles(JsonArray tiles) { this.tiles = tiles; } public void setId(String id) { this.id = id; } @Override public void load(final String id) { super.load(id); this.tiles = (JsonArray) db.addJob(new SQLiteJob<Object>() { protected Object job(SQLiteConnection connection) throws SQLiteException { SQLiteStatement stmt = null; JsonArray result = new JsonArray(); try { stmt = connection.prepare("SELECT tiles FROM " + VisualizationDashboard.TABLE + " WHERE id = ?"); stmt.bind(1, id); if(stmt.step()) { JsonParser jsonParser = new JsonParser(); byte[] data = stmt.columnBlob(0); result = (JsonArray) jsonParser.parse(new String(data)); } } catch(SQLiteException e) { Log.error(e); } finally { stmt.dispose(); } return result; } }); this.enrichTiles(this.tiles); } public void save() { super.save(); final VisualizationDashboard self = this; this.db.addJob(new SQLiteJob<Object>() { protected Object job(SQLiteConnection connection) throws SQLiteException { SQLiteStatement stmt = null; try { stmt = connection.prepare("INSERT OR REPLACE INTO " + VisualizationDashboard.TABLE + " ('id','tiles') VALUES (?,?)"); stmt.bind(1, self.getId()); stmt.bind(2, self.getTiles().toString().getBytes()); stmt.step(); } catch(SQLiteException e) { Log.error(e); } finally { stmt.dispose(); } return null; } }); } public JsonObject toJson() { JsonObject result = super.toJson(); result.add("tiles", this.getTiles()); return result; } protected void enrichTiles(JsonArray tiles) { for(int i = 0; i < tiles.size(); ++i) { final JsonObject tile = tiles.get(i).getAsJsonObject(); if(tile.has("type") && tile.get("type").getAsString().equalsIgnoreCase("SYSTEM_TILE")) { Gson gson = new Gson(); Notification notification = new Notification(this.db); tile.add("payload", gson.toJsonTree(notification.getList()).getAsJsonArray()); } if(tile.has("type") && tile.get("type").getAsString().equalsIgnoreCase("FORECAST_TILE")) { Forecast forecast = new Forecast(this.db); tile.add("payload", forecast.processQuery(new String[] {"forecast", "all"}, null)); } if(tile.has("type") && tile.get("type").getAsString().equalsIgnoreCase("VISUALIZATION_TILE")) { StatisticService service = new StatisticService(this.db); tile.add("payload", service.query(tile.get("value").getAsJsonObject().get("query").getAsJsonObject()).toJson()); } } } public static void createTable(DatabaseEqualizer db) throws SQLiteException { db.addQuery(DatabaseVersion.VIS_DASHBOARD, "CREATE TABLE IF NOT EXISTS " + VisualizationDashboard.TABLE + " (" + "id varchar(255) NOT NULL," + "tiles BLOB NULL," + "PRIMARY KEY (id)" + ");"); db.addQuery(DatabaseVersion.VIS_DASHBOARD, "CREATE UNIQUE INDEX index_" + VisualizationDashboard.TABLE + " ON " + VisualizationDashboard.TABLE + " (id)"); db.execute(); } public void pin(Visualization item) { int row = 0; JsonArray tiles = this.getTiles(); for(int i = 0; i < tiles.size(); ++i) { JsonObject tile = tiles.get(i).getAsJsonObject(); row = Math.max(row, tile.get("row").getAsInt() + tile.get("height").getAsInt()); } JsonObject tileFrame = new JsonObject(); tileFrame.addProperty("key", UUID.randomUUID().toString()); tileFrame.addProperty("relationKey", item.getId()); tileFrame.addProperty("title", item.getName()); tileFrame.addProperty("column", 1); tileFrame.addProperty("row", row+1); tileFrame.addProperty("width", 2); tileFrame.addProperty("height", 2); tileFrame.addProperty("resizeable", true); tileFrame.addProperty("type", "VISUALIZATION_TILE"); tileFrame.add("value", item.toJson()); tiles.add(tileFrame); } }
NukulaPoncho/homeCenter
src/com/homeCenter/service/VisualizationDashboard.java
Java
gpl-2.0
5,123
<?php require_once('constants.php'); require_once('lib_annot.php'); require_once('lib_history.php'); require_once('lib_xml.php'); require_once('lib_morph_pools.php'); require_once('Lexeme.php'); // GENERAL function get_dict_stats() { $out = array(); $r = sql_fetch_array(sql_query("SELECT COUNT(*) AS cnt_g FROM `gram`")); $out['cnt_g'] = $r['cnt_g']; $r = sql_fetch_array(sql_query("SELECT COUNT(*) AS cnt_l FROM `dict_lemmata` WHERE deleted=0")); $out['cnt_l'] = $r['cnt_l']; $r = sql_fetch_array(sql_query("SELECT COUNT(*) AS cnt_f FROM `form2lemma`")); $out['cnt_f'] = $r['cnt_f']; $r = sql_fetch_array(sql_query("SELECT COUNT(*) AS cnt_r FROM `dict_revisions` WHERE f2l_check=0")); $out['cnt_r'] = $r['cnt_r']; $r = sql_fetch_array(sql_query("SELECT COUNT(*) AS cnt_v FROM `dict_revisions` WHERE dict_check=0")); $out['cnt_v'] = $r['cnt_v']; return $out; } function get_dict_search_results($search_lemma, $search_form=false) { $out = array(); $find_pos = sql_prepare("SELECT SUBSTR(grammems, 7, 4) AS gr FROM form2lemma WHERE lemma_id = ? LIMIT 1"); if ($search_lemma) { $res = sql_pe("SELECT lemma_id, deleted FROM `dict_lemmata` WHERE `lemma_text`= ?", array($search_lemma)); $count = sizeof($res); $out['lemma']['count'] = $count; if ($count == 0) return $out; foreach ($res as $r) { sql_execute($find_pos, array($r['lemma_id'])); $r1 = sql_fetch_array($find_pos); $out['lemma']['found'][] = array( 'id' => $r['lemma_id'], 'text' => $search_lemma, 'pos' => $r1['gr'], 'is_deleted' => $r['deleted'] ); } } elseif ($search_form) { $res = sql_pe("SELECT DISTINCT dl.lemma_id, dl.lemma_text FROM `form2lemma` fl LEFT JOIN `dict_lemmata` dl ON (fl.lemma_id=dl.lemma_id) WHERE fl.`form_text`= ?", array($search_form)); $count = sizeof($res); $out['form']['count'] = $count; if ($count == 0) return $out; foreach ($res as $r) { sql_execute($find_pos, array($r['lemma_id'])); $r1 = sql_fetch_array($find_pos); $out['form']['found'][] = array('id' => $r['lemma_id'], 'text' => $r['lemma_text'], 'pos' => $r1['gr']); } } return $out; } function get_all_forms_by_lemma_id($lid) { $res = sql_pe("SELECT rev_text FROM dict_revisions WHERE lemma_id=? AND is_last=1 LIMIT 1", array($lid)); $lex = new Lexeme($res[0]['rev_text']); return array_unique($lex->get_all_forms_texts()); } function get_all_forms_by_lemma_text($lemma) { $lemmata = get_dict_search_results($lemma); $forms = array($lemma); foreach ($lemmata['lemma']['found'] as $l) $forms = array_merge($forms, get_all_forms_by_lemma_id($l['id'])); return array_unique($forms); } function dict_get_select_gram() { $res = sql_query("SELECT `gram_id`, `inner_id` FROM `gram` ORDER by `inner_id`"); $out = array(); while ($r = sql_fetch_array($res)) { $out[$r['gram_id']] = $r['inner_id']; } return $out; } function get_link_types() { $res = sql_query("SELECT * FROM dict_links_types ORDER BY link_name"); $out = array(); while ($r = sql_fetch_array($res)) { $out[$r['link_id']] = $r['link_name']; } return $out; } function get_link_type_info($type_id) { $res = sql_pe("SELECT COUNT(*) AS cnt FROM dict_links WHERE link_type = ?", array($type_id)); $data = array('total' => $res[0]['cnt'], 'samples' => array()); $res = sql_pe("SELECT link_name FROM dict_links_types WHERE link_id = ? LIMIT 1", array($type_id)); $data['name'] = $res[0]['link_name']; $res = sql_pe(" SELECT lemma1_id, lemma2_id, lm1.lemma_text AS lemma1_text, lm2.lemma_text AS lemma2_text FROM dict_links lk LEFT JOIN dict_lemmata lm1 ON (lk.lemma1_id = lm1.lemma_id) LEFT JOIN dict_lemmata lm2 ON (lk.lemma2_id = lm2.lemma_id) WHERE link_type = ? LIMIT 100 ", array($type_id)); foreach ($res as $row) { $data['samples'][] = array( 'lemma1' => [$row['lemma1_id'], $row['lemma1_text']], 'lemma2' => [$row['lemma2_id'], $row['lemma2_text']] ); } return $data; } function get_word_paradigm($lemma) { $res = sql_pe("SELECT rev_text FROM dict_revisions LEFT JOIN dict_lemmata USING (lemma_id) WHERE deleted=0 AND lemma_text=? AND is_last=1 LIMIT 1", array($lemma)); if (sizeof($res) == 0) return false; $r = $res[0]; $lex = new Lexeme($r['rev_text']); $out = array( 'lemma_gram' => $lex->lemma->grammemes, 'forms' => array() ); $pseudo_stem = $lex->lemma->text; foreach ($lex->get_all_forms_texts() as $form) { $pseudo_stem = get_common_prefix($form, $pseudo_stem); } $out['lemma_suffix_len'] = mb_strlen($lex->lemma->text) - mb_strlen($pseudo_stem); foreach ($lex->forms as $form) { $suffix_len = mb_strlen($form->text) - mb_strlen($pseudo_stem); $out['forms'][] = array( 'suffix' => $suffix_len ? mb_substr($form->text, -$suffix_len, $suffix_len) : '', 'grm' => $form->grammemes ); } return $out; } function get_common_prefix($word1, $word2) { if ($word1 == $word2) return $word1; $len1 = mb_strlen($word1); $len2 = mb_strlen($word2); $prefix = ''; for ($i = 0; $i < min($len1, $len2); ++$i) { $char1 = mb_substr($word1, $i, 1); $char2 = mb_substr($word2, $i, 1); if ($char1 == $char2) $prefix .= $char1; else break; } return $prefix; } function form_exists($f) { $f = mb_strtolower($f); if (!preg_match('/^[а-яё]/u', $f)) { return -1; } $res = sql_pe("SELECT lemma_id FROM form2lemma WHERE form_text=? LIMIT 1", array($f)); return sizeof($res); } function get_pending_updates($skip=0, $limit=500) { check_permission(PERM_DISAMB); $out = array('revisions' => array(), 'header' => array()); $r = sql_fetch_array(sql_query("SELECT COUNT(*) cnt FROM updated_tokens")); $out['cnt_tokens'] = $r['cnt']; $r = sql_fetch_array(sql_query("SELECT COUNT(*) cnt FROM updated_forms")); $out['cnt_forms'] = $r['cnt']; $res = sql_query("SELECT rev_id FROM dict_revisions WHERE f2l_check=0 LIMIT 1"); $out['outdated_f2l'] = sql_num_rows($res); // header $res = sql_query(" SELECT dict_revision, lemma_id, lemma_text, COUNT(token_id) AS cnt FROM updated_tokens ut LEFT JOIN dict_revisions dr ON (ut.dict_revision = dr.rev_id) LEFT JOIN dict_lemmata dl USING (lemma_id) GROUP BY dict_revision ORDER BY dict_revision "); $sum = 0; // to count pages while ($r = sql_fetch_array($res)) { $out['header'][] = array( 'lemma' => $r['lemma_text'], 'lemma_id' => $r['lemma_id'], 'revision' => $r['dict_revision'], 'count' => $r['cnt'], 'skip' => $sum ); $sum += $r['cnt']; } // main table $res = sql_pe(" SELECT token_id, tf_text, sent_id, dict_revision, lemma_id, dr.set_id, tfr.rev_text AS token_rev_text FROM updated_tokens ut LEFT JOIN dict_revisions dr ON (ut.dict_revision = dr.rev_id) LEFT JOIN tokens tf ON (ut.token_id = tf.tf_id) LEFT JOIN tf_revisions tfr USING (tf_id) WHERE tfr.is_last = 1 ORDER BY dict_revision, token_id LIMIT ?, ? ", array($skip, $limit)); $out['pages'] = array( 'active' => $limit ? floor($skip / $limit) : 0, 'total' => $limit ? ($out['cnt_tokens'] / $limit) : 1 ); $t = array(); $last = NULL; foreach ($res as $r) { if ($last && $last['dict_revision'] != $r['dict_revision']) { $out['revisions'][] = array( 'tokens' => $t, 'id' => $last['dict_revision'], 'diff' => dict_diff($last['lemma_id'], $last['set_id']) ); $t = array(); } $context = get_context_for_word($r['token_id'], 4); $context['context'][$context['mainword']] = '<b>'.htmlspecialchars($context['context'][$context['mainword']]).'</b>'; $t[] = array( 'id' => $r['token_id'], 'text' => $r['tf_text'], 'sentence_id' => $r['sent_id'], 'context' => join(' ', $context['context']), 'is_unkn' => preg_match('/v="UNKN"/', $r['token_rev_text']), 'human_edits' => check_for_human_edits($r['token_id']) ); $last = $r; } if (sizeof($t)) $out['revisions'][] = array( 'tokens' => $t, 'id' => $last['dict_revision'], 'diff' => dict_diff($last['lemma_id'], $last['set_id']) ); return $out; } function check_for_human_edits($token_id) { $res = sql_pe(" SELECT rev_id FROM tf_revisions LEFT JOIN rev_sets USING (set_id) WHERE tf_id = ? AND ((user_id > 0 AND comment != 'Update tokens from dictionary') OR (user_id = 0 AND comment LIKE '%annotation pool #%')) LIMIT 2 ", array($token_id)); return sizeof($res) > 1; } function check_safe_token_update($token_id, $rev_id) { // forbid updating if form2lemma is outdated $res = sql_query("SELECT rev_id FROM dict_revisions WHERE f2l_check=0 LIMIT 1"); if (sql_num_rows($res) > 0) return false; // forbid updating if revision of the CURRENT TOKEN'S FORM is not latest $res = sql_pe(" SELECT * FROM updated_tokens WHERE token_id = ? AND dict_revision > ? LIMIT 1 ", array($token_id, $rev_id)); return sizeof($res) == 0; } function forget_pending_tokens($rev_id) { check_permission(PERM_DISAMB); sql_pe("DELETE FROM updated_tokens WHERE dict_revision=?", array($rev_id)); } function forget_pending_token($token_id, $rev_id) { check_permission(PERM_DISAMB); sql_pe("DELETE FROM updated_tokens WHERE token_id=? AND dict_revision=?", array($token_id, $rev_id)); } function update_pending_tokens($rev_id, $smart=false) { check_permission(PERM_DISAMB); $res = sql_pe("SELECT token_id FROM updated_tokens WHERE dict_revision=?", array($rev_id)); sql_begin(); current_revset("Update tokens from dictionary"); // create revset foreach ($res as $r) update_pending_token($r['token_id'], $rev_id, $smart); sql_commit(); } function can_smart_update($deleted_forms, $added_forms_texts) { return sizeof($deleted_forms) == 0 || sizeof($added_forms_texts) == 0; } function discard_yo($form) { return array('text' => strtr($form->text, array('ё' => 'е')), 'grm' => $form->grammemes); } function discard_yo_all($forms) { $ret = array(); foreach ($forms as $form) { $ret[] = discard_yo($form); } return $ret; } function get_added_and_deleted_forms($prev_forms, $new_forms) { $deleted_forms = array(); foreach ($prev_forms as $pf) { if (!in_array(discard_yo($pf), discard_yo_all($new_forms))) $deleted_forms[] = $pf; } $added_forms_texts = array(); foreach ($new_forms as $nf) { if (!in_array(discard_yo($nf), discard_yo_all($prev_forms))) { $added_forms_texts[] = $nf->text; } } return array($added_forms_texts, $deleted_forms); } function smart_update_pending_token(MorphParseSet $parse_set, $rev_id) { // currently works only for // - deleted lemma // - added lemma (only this lemma's forms are added) // - lemma text change (with optional form e/yo changes) // - lemma gramset change // - added form(s): adds all forms of this lemma homonymous to the added one(s) // - deleted form(s): deletes all forms of this lemma HOMONYMOUS to the deleted one(s) $res = sql_pe("SELECT lemma_id, rev_text FROM dict_revisions WHERE rev_id=? LIMIT 1", array($rev_id)); if (!sizeof($res)) throw new Exception(); $rev_text = $res[0]['rev_text']; $lemma_id = $res[0]['lemma_id']; if (!$rev_text) { // the revision deletes a lemma $parse_set->filter_by_lemma($lemma_id, false); return; } // get previous revision $res = sql_pe("SELECT rev_text FROM dict_revisions WHERE lemma_id=? AND rev_id<? ORDER BY rev_id DESC LIMIT 1", array($lemma_id, $rev_id)); if (!sizeof($res)) { // the revision adds a lemma $new_parses = new MorphParseSet(false, $parse_set->token_text, false, false, $lemma_id); $parse_set->merge_from($new_parses); return; } $prev_rev_text = $res[0]['rev_text']; $lex_prev = new Lexeme($prev_rev_text); $lex_new = new Lexeme($rev_text); // cannot work if smth changed in the paradigm, not lemma // unless the change is addition/deletion of new forms and/or pure text changes list($added_forms_texts, $deleted_forms) = get_added_and_deleted_forms($lex_prev->forms, $lex_new->forms); if (!can_smart_update($deleted_forms, $added_forms_texts)) { throw new Exception("Smart mode unavailable"); } foreach (array_unique($added_forms_texts) as $ftext) { if ($ftext == $parse_set->token_text) { $new_parses = new MorphParseSet(false, $ftext, false, false, $lemma_id); $parse_set->merge_from($new_parses); } } foreach ($deleted_forms as $df) { $parse_set->remove_parse($lemma_id, array_merge($lex_prev->lemma->grammemes, $df->grammemes)); } // process lemma changes $parse_set->set_lemma_text($lemma_id, $lex_new->lemma->text); $parse_set->replace_gram_subset($lemma_id, $lex_prev->lemma->grammemes, $lex_new->lemma->grammemes); } function update_pending_token($token_id, $rev_id, $smart=false) { check_permission(PERM_DISAMB); if (!check_safe_token_update($token_id, $rev_id)) throw new Exception("Update forbidden"); // ok, now we can safely update $res = sql_pe("SELECT tf_text FROM tokens WHERE tf_id=? LIMIT 1", array($token_id)); $token_text = $res[0]['tf_text']; $res = sql_pe("SELECT rev_text FROM tf_revisions WHERE tf_id=? AND is_last=1 LIMIT 1", array($token_id)); $previous_rev = $res[0]['rev_text']; if ($smart) { $parse = new MorphParseSet($previous_rev); smart_update_pending_token($parse, $rev_id); } else $parse = new MorphParseSet(false, $token_text); $new_rev = $parse->to_xml(); // do nothing if nothing changed if ($previous_rev == $new_rev) { forget_pending_token($token_id, $rev_id); return true; } sql_begin(); $revset_id = current_revset("Update tokens from dictionary"); create_tf_revision($revset_id, $token_id, $new_rev); forget_pending_token($token_id, $rev_id); delete_samples_by_token_id($token_id); sql_commit(); } function get_top_absent_words() { $out = array(); $res = sql_query(" SELECT LOWER(tf_text) AS word, COUNT(tf_id) AS cnt FROM tokens LEFT JOIN tf_revisions USING (tf_id) WHERE is_last = 1 AND LENGTH(tf_text) > 2 AND rev_text LIKE '%\"UNKN\"%' GROUP BY LOWER(tf_text) ORDER BY COUNT(tf_id) DESC LIMIT 500 "); while ($r = sql_fetch_array($res)) $out[] = array('word' => $r['word'], 'count' => $r['cnt']); return $out; } // DICTIONARY EDITOR function get_lemma_editor($id) { $out = array('lemma' => array('id' => $id), 'errata' => array()); if ($id == -1) return $out; $res = sql_pe(" SELECT l.`lemma_text`, l.deleted, d.`rev_id`, d.`rev_text` FROM `dict_lemmata` l LEFT JOIN `dict_revisions` d USING (lemma_id) WHERE l.`lemma_id`=? AND d.is_last=1 LIMIT 1 ", array($id)); $lex = new Lexeme($res[0]['rev_text']); $out['deleted'] = $res[0]['deleted']; $out['lemma']['text'] = $res[0]['lemma_text']; $out['lemma']['grms'] = implode(', ', $lex->lemma->grammemes); $out['lemma']['grms_raw'] = $lex->lemma->grammemes; foreach ($lex->forms as $form) { $out['forms'][] = array('text' => $form->text, 'grms' => implode(', ', $form->grammemes), 'grms_raw' => $form->grammemes); } //links $res = sql_pe(" (SELECT lemma1_id lemma_id, lemma_text, link_name, l.link_id, 1 AS target FROM dict_links l LEFT JOIN dict_links_types t ON (l.link_type=t.link_id) LEFT JOIN dict_lemmata lm ON (l.lemma1_id=lm.lemma_id) WHERE lemma2_id=?) UNION (SELECT lemma2_id lemma_id, lemma_text, link_name, l.link_id, 0 AS target FROM dict_links l LEFT JOIN dict_links_types t ON (l.link_type=t.link_id) LEFT JOIN dict_lemmata lm ON (l.lemma2_id=lm.lemma_id) WHERE lemma1_id=?) ", array($id, $id)); foreach ($res as $r) { $out['links'][] = array('lemma_id' => $r['lemma_id'], 'lemma_text' => $r['lemma_text'], 'name' => $r['link_name'], 'id' => $r['link_id'], 'is_target' => (bool)$r['target']); } //errata $res = sql_pe("SELECT e.*, x.item_id, x.timestamp exc_time, x.comment exc_comment, u.user_shown_name AS user_name FROM dict_errata e LEFT JOIN dict_errata_exceptions x ON (e.error_type=x.error_type AND e.error_descr=x.error_descr) LEFT JOIN users u ON (x.author_id = u.user_id) WHERE e.rev_id = (SELECT rev_id FROM dict_revisions WHERE lemma_id=? AND is_last=1 LIMIT 1) ", array($id)); foreach ($res as $r) { $out['errata'][] = array( 'id' => $r['error_id'], 'type' => $r['error_type'], 'descr' => $r['error_descr'], 'is_ok' => ($r['item_id'] > 0 ? 1 : 0), 'author_name' => $r['user_name'], 'exc_time' => $r['exc_time'], 'comment' => $r['exc_comment'] ); } return $out; } function calculate_updated_forms(Lexeme $old_lex, Lexeme $new_lex) { $upd_forms = array(); $old_lemma_text = $old_lex->lemma->text; $old_lemma_gram = implode(', ', $old_lex->lemma->grammemes); $old_paradigm = array(); foreach ($old_lex->forms as $form) { array_push($old_paradigm, array($form->text, implode(', ', $form->grammemes))); } $new_lemma_text = $new_lex->lemma->text; $new_lemma_gram = implode(', ', $new_lex->lemma->grammemes); $new_paradigm = array(); foreach ($new_lex->forms as $form) { array_push($new_paradigm, array($form->text, implode(', ', $form->grammemes))); } //if lemma's grammems or lemma text have changed then all forms have changed if ($new_lemma_gram != $old_lemma_gram || $new_lemma_text != $old_lemma_text) { foreach ($old_paradigm as $farr) { array_push($upd_forms, $farr[0]); } foreach ($new_paradigm as $farr) { array_push($upd_forms, $farr[0]); } } else { $int = paradigm_diff($old_paradigm, $new_paradigm); //..and insert them into `updated_forms` foreach ($int as $int_form) { array_push($upd_forms, $int_form[0]); } } return $upd_forms; } function dict_save($lemma_id, $lemma_text, $lemma_gram, $form_text, $form_gram, $comment) { $do_save = user_has_permission(PERM_DICT); $rev_id = 0; $updated_forms = array(); if (!$lemma_text) throw new UnexpectedValueException(); $lex = new Lexeme; $lex->set_lemma($lemma_text, $lemma_gram); $lex->set_paradigm($form_text, $form_gram); $new_xml = $lex->to_xml(); sql_begin(); //it may be a totally new lemma if ($lemma_id == -1) { if ($do_save) { sql_pe("INSERT INTO dict_lemmata VALUES(NULL, ?, 0)", array(mb_strtolower($lemma_text))); $lemma_id = sql_insert_id(); } else { $lemma_id = 0; } $rev_id = new_dict_rev($lemma_id, $new_xml, $comment, !$do_save); $updated_forms = $lex->get_all_forms_texts(); } else { // lemma might have been deleted, it is not editable then $r = sql_fetch_array(sql_query("SELECT deleted FROM dict_lemmata WHERE lemma_id = $lemma_id LIMIT 1")); if ($r['deleted']) throw new Exception("This lemma is not editable"); $r = sql_fetch_array(sql_query("SELECT rev_text FROM dict_revisions WHERE lemma_id=$lemma_id AND is_last=1 LIMIT 1")); $old_lex = new Lexeme($old_xml = $r['rev_text']); $old_lemma_text = $old_lex->lemma->text; if ($lemma_text == $old_lemma_text && $new_xml == $old_xml) { // nothing changed return $lemma_id; } if ($do_save && $lemma_text != $old_lemma_text) { sql_pe( "UPDATE dict_lemmata SET lemma_text=? WHERE lemma_id=?", array($lemma_text, $lemma_id) ); } $rev_id = new_dict_rev($lemma_id, $new_xml, $comment, !$do_save); $updated_forms = calculate_updated_forms($old_lex, new Lexeme($new_xml)); } if ($do_save && sizeof($updated_forms) > 0) { enqueue_updated_forms($updated_forms, $rev_id); } sql_commit(); return $lemma_id; } function enqueue_updated_forms($forms, $revision_id) { $ins = sql_prepare("INSERT INTO `updated_forms` VALUES (?, ?)"); foreach (array_unique($forms) as $upd_form) sql_execute($ins, array($upd_form, $revision_id)); } function new_dict_rev($lemma_id, $new_xml, $comment = '', $pending = false) { if (!$new_xml) throw new UnexpectedValueException(); sql_begin(); $new_id = -1; if ($pending) { sql_pe( "INSERT INTO dict_revisions_ugc SET user_id = ?, lemma_id = ?, rev_text = ?, comment = ?", array($_SESSION['user_id'], $lemma_id, $new_xml, $comment) ); } else { if (!$lemma_id) throw new UnexpectedValueException(); $revset_id = current_revset($comment); sql_pe("UPDATE dict_revisions SET is_last=0 WHERE lemma_id=?", array($lemma_id)); sql_pe("INSERT INTO `dict_revisions` VALUES(NULL, ?, ?, ?, 0, 0, 1, 0)", array($revset_id, $lemma_id, $new_xml)); $new_id = sql_insert_id(); } sql_commit(); return $new_id; } function paradigm_diff($array1, $array2) { $diff = array(); foreach ($array1 as $form_array) { if (!in_array($form_array, $array2)) array_push($diff, $form_array); } foreach ($array2 as $form_array) { if (!in_array($form_array, $array1)) array_push($diff, $form_array); } return $diff; } function del_lemma($id) { check_permission(PERM_DICT); //delete links (but preserve history) $res = sql_pe("SELECT link_id FROM dict_links WHERE lemma1_id=? OR lemma2_id=?", array($id, $id)); sql_begin(); $revset_id = current_revset("Delete lemma $id"); foreach ($res as $r) del_link($r['link_id']); // create empty revision sql_pe("UPDATE dict_revisions SET is_last=0 WHERE lemma_id=?", array($id)); sql_pe("INSERT INTO dict_revisions VALUES (NULL, ?, ?, '', 1, 1, 1, 0)", array($revset_id, $id)); $rev_id = sql_insert_id(); //update `updated_forms` $res = sql_pe("SELECT rev_text FROM dict_revisions WHERE lemma_id=? ORDER BY `rev_id` DESC LIMIT 1, 1", array($id)); $lex = new Lexeme($res[0]['rev_text']); enqueue_updated_forms($lex->get_all_forms_texts(), $rev_id); //delete forms from form2lemma sql_pe("DELETE FROM `form2lemma` WHERE lemma_id=?", array($id)); //delete lemma sql_pe("UPDATE dict_lemmata SET deleted=1 WHERE lemma_id=? LIMIT 1", array($id)); sql_commit(); } function get_pending_dict_edits() { $res = sql_fetchall(sql_query(" SELECT ugc.rev_id, ugc.user_id, u.user_shown_name AS user_name, created_ts, lemma_id, ugc.rev_text AS rev_text_new, dr.rev_text AS rev_text_old, comment FROM dict_revisions_ugc AS ugc LEFT JOIN dict_revisions dr USING (lemma_id) LEFT JOIN users u USING (user_id) WHERE ugc.status = 0 AND (dr.is_last = 1 OR lemma_id = 0) ORDER BY ugc.rev_id ")); foreach ($res as &$r) { $r['diff'] = php_diff(format_xml($r['rev_text_old']), format_xml($r['rev_text_new'])); } return $res; } function dict_approve_edit($rev_id) { check_permission(PERM_DICT); $res = sql_pe(" SELECT lemma_id, rev_text, status, comment FROM dict_revisions_ugc WHERE rev_id = ? LIMIT 1 ", array($rev_id)); if (!sizeof($res) || $res[0]['status'] != DICT_UGC_PENDING) throw new Exception(); $row = $res[0]; sql_begin(); $lemma_id = $row['lemma_id']; $lex = new Lexeme($row['rev_text']); $updated_forms = []; if ($lemma_id == 0) { sql_pe("INSERT INTO dict_lemmata VALUES(NULL, ?, 0)", array(mb_strtolower($lex->lemma->text))); $lemma_id = sql_insert_id(); $updated_forms = $lex->get_all_forms_texts(); } else { $r = sql_fetch_array(sql_query("SELECT rev_text FROM dict_revisions WHERE lemma_id=$lemma_id AND is_last=1 LIMIT 1")); $old_lex = new Lexeme($r['rev_text']); $updated_forms = calculate_updated_forms($old_lex, $lex); } $new_rev_id = new_dict_rev($lemma_id, $row['rev_text'], "Merge edit #$rev_id", false); if (sizeof($updated_forms) > 0) { enqueue_updated_forms($updated_forms, $new_rev_id); } sql_pe("UPDATE dict_revisions_ugc SET status = ".DICT_UGC_APPROVED.", moder_id = ? WHERE rev_id = ? LIMIT 1", array($_SESSION['user_id'], $rev_id)); sql_pe("UPDATE dict_revisions SET ugc_rev_id = ? WHERE rev_id = ? LIMIT 1", array($rev_id, $new_rev_id)); sql_commit(); } function dict_reject_edit($rev_id) { check_permission(PERM_DICT); $res = sql_pe(" SELECT status FROM dict_revisions_ugc WHERE rev_id = ? LIMIT 1 ", array($rev_id)); if (!sizeof($res) || $res[0]['status'] != DICT_UGC_PENDING) throw new Exception(); sql_pe("UPDATE dict_revisions_ugc SET status = ".DICT_UGC_REJECTED.", moder_id = ? WHERE rev_id = ? LIMIT 1", array($_SESSION['user_id'], $rev_id)); } function del_link($link_id) { check_permission(PERM_DICT); $res = sql_pe("SELECT * FROM dict_links WHERE link_id=? LIMIT 1", array($link_id)); if (!sizeof($res)) throw new UnexpectedValueException(); sql_begin(); $revset_id = current_revset(); sql_query("INSERT INTO dict_links_revisions VALUES(NULL, '$revset_id', '".$res[0]['lemma1_id']."', '".$res[0]['lemma2_id']."', '".$res[0]['link_type']."', '0')"); sql_pe("DELETE FROM dict_links WHERE link_id=? LIMIT 1", array($link_id)); sql_commit(); } function add_link($from_id, $to_id, $link_type) { check_permission(PERM_DICT); if ($from_id <= 0 || $to_id <= 0 || !$link_type) throw new UnexpectedValueException(); sql_begin(); $revset_id = current_revset(); sql_pe("INSERT INTO dict_links VALUES(NULL, ?, ?, ?)", array($from_id, $to_id, $link_type)); sql_pe("INSERT INTO dict_links_revisions VALUES(NULL, ?, ?, ?, ?, 1)", array($revset_id, $from_id, $to_id, $link_type)); sql_commit(); } function change_link_direction($link_id) { check_permission(PERM_DICT); if (!$link_id) throw new UnexpectedValueException(); sql_begin(); $res = sql_pe("SELECT * FROM dict_links WHERE link_id=? LIMIT 1", array($link_id)); del_link($link_id); add_link($res[0]['lemma2_id'], $res[0]['lemma1_id'], $res[0]['link_type']); sql_commit(); } // GRAMMEM EDITOR function get_grammem_editor($order) { $out = array(); $orderby = $order == 'id' ? 'inner_id' : ($order == 'outer' ? 'outer_id' : 'orderby'); $res = sql_query("SELECT g1.`gram_id`, g1.`parent_id`, g1.`inner_id`, g1.`outer_id`, g1.`gram_descr`, g1.`orderby`, g2.`inner_id` AS `parent_name` FROM `gram` g1 LEFT JOIN `gram` g2 ON (g1.parent_id=g2.gram_id) ORDER BY g1.`$orderby`"); while ($r = sql_fetch_array($res)) { $class = strlen($r['inner_id']) != 4 ? 'gramed_bad' : (preg_match('/^[A-Z0-9-]+$/', $r['inner_id']) ? 'gramed_pos' : (preg_match('/[A-Z0-9][A-Z0-9][a-z0-9-][a-z0-9-]/', $r['inner_id']) ? 'gramed_group' : (preg_match('/[A-Z][a-z0-9-][a-z0-9-][a-z0-9-]/', $r['inner_id']) ? 'gramed_label' : ''))); $out[] = array( 'order' => $r['orderby'], 'id' => $r['gram_id'], 'name' => $r['inner_id'], 'outer_id' => $r['outer_id'], 'description' => htmlspecialchars($r['gram_descr']), 'parent_name' => $r['parent_name'], 'css_class' => $class ); } return $out; } function add_grammem($inner_id, $group, $outer_id, $descr) { check_permission(PERM_DICT); if (!$inner_id) throw new UnexpectedValueException(); $r = sql_fetch_array(sql_query("SELECT MAX(`orderby`) AS `m` FROM `gram`")); sql_pe("INSERT INTO `gram` VALUES(NULL, ?, ?, ?, ?, ?)", array($group, $inner_id, $outer_id, $descr, $r['m']+1)); } function del_grammem($grm_id) { check_permission(PERM_DICT); sql_pe("DELETE FROM `gram` WHERE `gram_id`=? LIMIT 1", array($grm_id)); } function edit_grammem($id, $inner_id, $outer_id, $descr) { check_permission(PERM_DICT); if (!$id || !$inner_id) throw new UnexpectedValueException(); sql_pe( "UPDATE `gram` SET `inner_id`=?, `outer_id`=?, `gram_descr`=? WHERE `gram_id`=? LIMIT 1", array($inner_id, $outer_id, $descr, $id) ); } //ERRATA function get_dict_errata($all, $rand) { $r = sql_fetch_array(sql_query("SELECT COUNT(*) AS cnt_v FROM `dict_revisions` WHERE dict_check=0")); $out = array('lag' => $r['cnt_v']); $r = sql_fetch_array(sql_query("SELECT COUNT(*) AS cnt_t FROM `dict_errata`")); $out['total'] = $r['cnt_t']; $res = sql_query("SELECT e.*, r.lemma_id, r.set_id, x.item_id, x.timestamp exc_time, x.comment exc_comment, u.user_shown_name AS user_name FROM dict_errata e LEFT JOIN dict_errata_exceptions x ON (e.error_type=x.error_type AND e.error_descr=x.error_descr) LEFT JOIN users u ON (x.author_id = u.user_id) LEFT JOIN dict_revisions r ON (e.rev_id=r.rev_id) ORDER BY ".($rand?'RAND()':'error_id').($all?'':' LIMIT 200')); while ($r = sql_fetch_array($res)) { $out['errors'][] = array( 'id' => $r['error_id'], 'timestamp' => $r['timestamp'], 'revision' => $r['rev_id'], 'type' => $r['error_type'], 'description' => preg_replace('/<([^>]+)>/', '<a href="?act=edit&amp;id='.$r['lemma_id'].'">$1</a>', $r['error_descr']), 'lemma_id' => $r['lemma_id'], 'set_id' => $r['set_id'], 'is_ok' => ($r['item_id'] > 0 ? 1 : 0), 'author_name' => $r['user_name'], 'exc_time' => $r['exc_time'], 'comment' => $r['exc_comment'] ); } return $out; } function clear_dict_errata($old) { check_permission(PERM_DICT); $q = "UPDATE dict_revisions SET dict_check=0"; if (!$old) { $q .= " WHERE is_last=1"; } sql_query($q); } function mark_dict_error_ok($id, $comment) { check_permission(PERM_DICT); if (!$id) throw new UnexpectedValueException(); sql_pe("INSERT INTO dict_errata_exceptions VALUES( NULL, (SELECT error_type FROM dict_errata WHERE error_id=? LIMIT 1), (SELECT error_descr FROM dict_errata WHERE error_id=? LIMIT 1), ?, ?, ? )", array($id, $id, $_SESSION['user_id'], time(), $comment)); } function get_gram_restrictions($hide_auto) { $res = sql_query("SELECT r.restr_id, r.obj_type, r.restr_type, r.auto, g1.inner_id `if`, g2.inner_id `then` FROM gram_restrictions r LEFT JOIN gram g1 ON (r.if_id=g1.gram_id) LEFT JOIN gram g2 ON (r.then_id=g2.gram_id)". ($hide_auto ? " WHERE `auto`=0" : "") ." ORDER BY r.restr_id"); $out = array('gram_options' => ''); while ($r = sql_fetch_array($res)) { $out['list'][] = array( 'id' => $r['restr_id'], 'if_id' => $r['if'], 'then_id' => $r['then'], 'type' => $r['restr_type'], 'obj_type' => $r['obj_type'], 'auto' => $r['auto'] ); } $res = sql_query("SELECT gram_id, inner_id FROM gram order by inner_id"); while ($r = sql_fetch_array($res)) { $out['gram_options'][$r['gram_id']] = $r['inner_id']; } return $out; } function add_dict_restriction($if, $then, $rtype, $if_type, $then_type) { check_permission(PERM_DICT); sql_begin(); sql_pe(" INSERT INTO gram_restrictions VALUES(NULL, ?, ?, ?, ?, 0) ", array($if, $then, $rtype, $if_type + $then_type)); calculate_gram_restrictions(); sql_commit(); } function del_dict_restriction($id) { check_permission(PERM_DICT); sql_begin(); sql_pe("DELETE FROM gram_restrictions WHERE restr_id=? LIMIT 1", array($id)); calculate_gram_restrictions(); sql_commit(); } function calculate_gram_restrictions() { check_permission(PERM_DICT); sql_begin(); sql_query("DELETE FROM gram_restrictions WHERE `auto`=1"); $restr = array(); $res = sql_query("SELECT r.if_id, r.then_id, r.obj_type, r.restr_type, g1.gram_id gram1, g2.gram_id gram2 FROM gram_restrictions r LEFT JOIN gram g1 ON (r.then_id = g1.parent_id) LEFT JOIN gram g2 ON (g1.gram_id = g2.parent_id) WHERE r.restr_type>0"); while ($r = sql_fetch_array($res)) { $restr[] = $r['if_id'].'#'.$r['then_id'].'#'.$r['obj_type'].'#'.$r['restr_type']; if ($r['gram1']) $restr[] = $r['if_id'].'#'.$r['gram1'].'#'.$r['obj_type'].'#'.$r['restr_type']; if ($r['gram2']) $restr[] = $r['if_id'].'#'.$r['gram2'].'#'.$r['obj_type'].'#'.$r['restr_type']; } $restr = array_unique($restr); foreach ($restr as $quad) { list($if, $then, $type, $w0) = explode('#', $quad); $w = ($w0 == 1 ? 0 : 2); if (sql_num_rows(sql_query("SELECT restr_id FROM gram_restrictions WHERE if_id=$if AND then_id=$then AND obj_type=$type AND restr_type=$w")) == 0) sql_query("INSERT INTO gram_restrictions VALUES(NULL, '$if', '$then', '$w', '$type', '1')"); } sql_commit(); } ?>
OpenCorpora/opencorpora
lib/lib_dict.php
PHP
gpl-2.0
34,646
<?php /** * @package HikaShop for Joomla! * @version 2.4.0 * @author hikashop.com * @copyright (C) 2010-2015 HIKARI SOFTWARE. All rights reserved. * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ defined('_JEXEC') or die('Restricted access'); ?><?php class hikashopProductsyncType{ function load(){ $this->values = array(); $this->values[] = JHTML::_('select.option', 2,JText::_('RELATED_PRODUCTS')); $this->values[] = JHTML::_('select.option', 1,JText::_('IN_SAME_CATEGORIES')); $this->values[] = JHTML::_('select.option', 3,JText::_('FROM_SAME_MANUFACTURER')); $this->values[] = JHTML::_('select.option', 0,JText::_('IN_MODULE_PARENT_CATEGORY')); if(JRequest::getCmd('from_display',false) == false) $this->values[] = JHTML::_('select.option', 4,JText::_('HIKA_INHERIT')); } function display($map,$value){ $this->load(); return JHTML::_('select.genericlist', $this->values, $map, 'class="inputbox" size="1"', 'value', 'text', (int)$value ); } }
metalwork/anphates
administrator/components/com_hikashop/types/productsync.php
PHP
gpl-2.0
993
/**************************************************************************** * * This file is part of the ustk software. * Copyright (C) 2016 - 2017 by Inria. All rights reserved. * * This software is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * ("GPL") version 2 as published by the Free Software Foundation. * See the file LICENSE.txt at the root directory of this source * distribution for additional information about the GNU GPL. * * For using ustk with software that can not be combined with the GNU * GPL, please contact Inria about acquiring a ViSP Professional * Edition License. * * This software was developed at: * Inria Rennes - Bretagne Atlantique * Campus Universitaire de Beaulieu * 35042 Rennes Cedex * France * * If you have questions regarding the use of this file, please contact * Inria at ustk@inria.fr * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * Authors: * Pierre Chatelain * Alexandre Krupa * *****************************************************************************/ #include <visp3/core/vpImageFilter.h> #include <visp3/ustk_needle_detection/usNeedleTrackerSIR2D.h> usNeedleTrackerSIR2D::usNeedleTrackerSIR2D() { m_needleModel = NULL; m_particles = NULL; m_weights = NULL; m_noise.setSigmaMean(1.0, 0.0); m_noise.seed(42); m_sample = vpUniRand(42); m_sigma.eye(2); } usNeedleTrackerSIR2D::~usNeedleTrackerSIR2D() { if (m_needleModel) { delete m_needleModel; m_needleModel = NULL; } if (m_particles) { for (unsigned int i = 0; i < m_nParticles; ++i) { if (m_particles[i]) { delete m_particles[i]; m_particles[i] = NULL; } } delete[] m_particles; m_particles = NULL; } if (m_weights) { delete[] m_weights; m_weights = NULL; } } void usNeedleTrackerSIR2D::init(unsigned int dims[2], unsigned int nPoints, unsigned int nParticles, const usPolynomialCurve2D &needle) { m_dims[0] = dims[0]; m_dims[1] = dims[1]; m_nPoints = nPoints; m_nPointsCurrent = needle.getOrder() + 1; m_nParticles = nParticles; m_needleModel = new usPolynomialCurve2D(needle); m_particles = new usPolynomialCurve2D *[m_nParticles]; for (unsigned int i = 0; i < m_nParticles; ++i) m_particles[i] = new usPolynomialCurve2D(needle); m_weights = new double[m_nParticles]; for (unsigned int i = 0; i < m_nParticles; ++i) m_weights[i] = 1.0 / m_nParticles; m_lengthThreshold = 50.0; } void usNeedleTrackerSIR2D::init(const vpImage<unsigned char> &I, unsigned int nPoints, unsigned int nParticles, const usPolynomialCurve2D &needle) { unsigned int dims[2]; dims[0] = I.getHeight(); dims[1] = I.getWidth(); m_fgMean = 0.0; vpColVector point; unsigned int c = 0; double length = needle.getLength(); for (double t = 0; t <= 1.0; t += 1.0 / length) { point = needle.getPoint(t); unsigned int x = vpMath::round(point[0]); unsigned int y = vpMath::round(point[1]); if ((3 <= x) && (x < dims[0] - 3) && (3 <= y) && (y < dims[1] - 3)) { m_fgMean += vpImageFilter::gaussianFilter(I, x, y); } ++c; } m_fgMean /= c; m_bgMean = I.getSum() / I.getSize(); init(dims, nPoints, nParticles, needle); } usPolynomialCurve2D *usNeedleTrackerSIR2D::getNeedle() { return m_needleModel; } usPolynomialCurve2D *usNeedleTrackerSIR2D::getParticle(unsigned int i) { if (i >= m_nParticles) { std::cerr << "Error: in usNeedleTrackerSIR2D::getParticle(): " << "Particle index is out of range." << std::endl; exit(EXIT_FAILURE); } return m_particles[i]; } double usNeedleTrackerSIR2D::getWeight(unsigned int i) { if (i >= m_nParticles) { std::cerr << "Error: in usNeedleTrackerSIR2D::getWeight(): " << "Particle index is out of range." << std::endl; exit(EXIT_FAILURE); } return m_weights[i]; } void usNeedleTrackerSIR2D::setSigma(double s) { m_noise.setSigmaMean(s, 0.0); } void usNeedleTrackerSIR2D::setSigma1(double s) { m_sigma[0][0] = s; } void usNeedleTrackerSIR2D::setSigma2(double s) { m_sigma[1][1] = s; } void usNeedleTrackerSIR2D::run(vpImage<unsigned char> &I, double v) { vpMatrix controlPoints; vpMatrix meanControlPoints; vpColVector direction; vpMatrix S_noise_tip; vpMatrix S_noise_inter; vpColVector noise(2); vpMatrix U(2, 2); // Sample particles for (unsigned int i = 0; i < m_nParticles; ++i) { controlPoints = m_particles[i]->getControlPoints(); // Get needle direction direction = m_particles[i]->getTangent(1.0); direction /= direction.frobeniusNorm(); // Compute eigen vectors for (unsigned int j = 0; j < 2; ++j) U[j][0] = direction[j]; U[0][1] = -direction[1]; U[1][1] = direction[0]; // Compute noise covariance S_noise_tip = U * m_sigma * U.t(); S_noise_inter.eye(2); S_noise_inter *= m_sigma[1][1]; // Compute tip velocity vector direction *= v; // Entry point // controlPoints[0][0] += m_noise(); // controlPoints[1][0] += m_noise(); // Intermediate control points for (unsigned int j = 1; j < m_nPointsCurrent - 1; ++j) { // Generate noise for (unsigned int k = 0; k < 2; ++k) noise[k] = m_noise(); noise = S_noise_inter * noise; // Update control points for (unsigned int k = 0; k < 2; ++k) controlPoints[k][j] += direction[k] / (m_nPointsCurrent - 1) + noise[k] / 4.0; } // Tip // Generate noise for (unsigned int k = 0; k < 2; ++k) noise[k] = m_noise(); noise = S_noise_tip * noise; // Update control points for (unsigned int k = 0; k < 2; ++k) controlPoints[k][m_nPointsCurrent - 1] += direction[k] + noise[k]; m_particles[i]->setControlPoints(controlPoints); } // Compute weights double sumWeights = 0.0; for (unsigned int i = 0; i < m_nParticles; ++i) { m_weights[i] *= computeLikelihood(*(m_particles[i]), I); sumWeights += m_weights[i]; } // Normalize the weights and estimate the effective number of particles double sumSquare = 0.0; for (unsigned int i = 0; i < m_nParticles; ++i) { m_weights[i] /= sumWeights; sumSquare += vpMath::sqr(m_weights[i]); } double n_eff = 1.0 / sumSquare; // std::cout << "Neff = " << n_eff << std::endl; // Resampling if (n_eff < m_nParticles / 2.0) { resample(); } // Compute mean meanControlPoints.resize(2, m_nPointsCurrent); meanControlPoints = 0.0; for (unsigned int i = 0; i < m_nParticles; ++i) { meanControlPoints += m_weights[i] * m_particles[i]->getControlPoints(); } m_needleModel->setControlPoints(meanControlPoints); if ((m_needleModel->getLength()) > m_lengthThreshold && (m_nPoints != m_nPointsCurrent)) { std::cout << "Changing polynomial order from " << m_nPointsCurrent - 1 << " to " << m_nPointsCurrent << std::endl; usPolynomialCurve2D *newModel = new usPolynomialCurve2D(m_needleModel->getNewOrderPolynomialCurve(m_nPointsCurrent)); delete m_needleModel; m_needleModel = newModel; for (unsigned int i = 0; i < m_nParticles; ++i) { usPolynomialCurve2D *newModel = new usPolynomialCurve2D(m_particles[i]->getNewOrderPolynomialCurve(m_nPointsCurrent)); delete m_particles[i]; m_particles[i] = newModel; } m_lengthThreshold *= 2.0; } } double usNeedleTrackerSIR2D::computeLikelihood(const usPolynomialCurve2D &model, const vpImage<unsigned char> &I) { double l = 0.0; vpColVector point; unsigned int c = 0; double length = model.getLength(); double intensity; for (double t = 0; t <= 1.0; t += 1.0 / length) { point = model.getPoint(t); unsigned int x = vpMath::round(point[0]); unsigned int y = vpMath::round(point[1]); if ((3 <= x) && (x < m_dims[0] - 3) && (3 <= y) && (y < m_dims[1] - 3)) { ++c; intensity = vpImageFilter::gaussianFilter(I, x, y); l += intensity; } } if (c == 0) return 0.0; l /= c; point = model.getPoint(1.0); unsigned int x = vpMath::round(point[0]); unsigned int y = vpMath::round(point[1]); if ((3 <= x) && (x < m_dims[0] - 3) && (3 <= y) && (y < m_dims[1] - 3)) { intensity = vpImageFilter::gaussianFilter(I, x, y); l += intensity; } point = model.getPoint(1.0 + 1.0 / length); x = vpMath::round(point[0]); y = vpMath::round(point[1]); if ((3 <= x) && (x < m_dims[0] - 3) && (3 <= y) && (y < m_dims[1] - 3)) { intensity = vpImageFilter::gaussianFilter(I, x, y); l -= intensity; } return l; } void usNeedleTrackerSIR2D::resample() { // std::cout << "Resampling..." << std::endl; int *idx = new int[m_nParticles]; for (unsigned int i = 0; i < m_nParticles; ++i) { double x = m_sample(); double sumWeights = 0.0; for (unsigned int j = 0; j < m_nParticles; ++j) { if (x < sumWeights + m_weights[j]) { idx[i] = j; break; } sumWeights += m_weights[j]; } } usPolynomialCurve2D **oldParticles = new usPolynomialCurve2D *[m_nParticles]; for (unsigned int i = 0; i < m_nParticles; ++i) { oldParticles[i] = new usPolynomialCurve2D(*m_particles[i]); } for (unsigned int i = 0; i < m_nParticles; ++i) { delete m_particles[i]; m_particles[i] = new usPolynomialCurve2D(*oldParticles[idx[i]]); } for (unsigned int i = 0; i < m_nParticles; ++i) { delete oldParticles[i]; oldParticles[i] = NULL; } delete[] oldParticles; delete[] idx; for (unsigned int i = 0; i < m_nParticles; ++i) { m_weights[i] = 1.0 / m_nParticles; } }
lagadic/ustk
modules/ustk_image_processing/ustk_needle_detection/src/usNeedleTrackerSIR2D.cpp
C++
gpl-3.0
9,747
class RestaurantsController < ApplicationController before_action :set_restaurant, only: [:show, :edit, :update, :destroy] # GET /restaurants # GET /restaurants.json def index @restaurants = Restaurant.all end # GET /restaurants/1 # GET /restaurants/1.json def show end # GET /restaurants/new def new @restaurant = Restaurant.new end # GET /restaurants/1/edit def edit end # POST /restaurants # POST /restaurants.json def create @restaurant = Restaurant.new(restaurant_params) @restaurant.map_icon = params[:map_icon] respond_to do |format| if @restaurant.save format.html { redirect_to @restaurant, notice: 'Restaurant was successfully created.' } format.json { render :show, status: :created, location: @restaurant } else format.html { render :new } format.json { render json: @restaurant.errors, status: :unprocessable_entity } end end end # PATCH/PUT /restaurants/1 # PATCH/PUT /restaurants/1.json def update respond_to do |format| if @restaurant.update(restaurant_params) format.html { redirect_to @restaurant, notice: 'Restaurant was successfully updated.' } format.json { render :show, status: :ok, location: @restaurant } else format.html { render :edit } format.json { render json: @restaurant.errors, status: :unprocessable_entity } end end end # DELETE /restaurants/1 # DELETE /restaurants/1.json def destroy @restaurant.destroy respond_to do |format| format.html { redirect_to restaurants_url, notice: 'Restaurant was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_restaurant @restaurant = Restaurant.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def restaurant_params params.require(:restaurant).permit(:name, :latitude, :longitude, :map_icon) end end
CeutecIngDeSoftware/LeBaleada
app/controllers/restaurants_controller.rb
Ruby
gpl-3.0
2,091
#include "preorder_adl.hpp" #include "simple_table_collection.hpp" #include <fwdpp/ts/marginal_tree_functions/nodes.hpp> #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(test_adl) BOOST_FIXTURE_TEST_CASE(test_preoder, simple_table_collection) { auto n = fwdpp::ts::get_nodes(tv.tree(), nodes_preorder_test()); auto n2 = fwdpp::ts::get_nodes(tv.tree(), fwdpp::ts::nodes_preorder()); BOOST_REQUIRE(n == n2); } BOOST_AUTO_TEST_SUITE_END()
molpopgen/fwdpp
testsuite/tree_sequences/test_node_traversal_order_adl.cc
C++
gpl-3.0
461