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 |
|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FEFTwiddler.GUI.UnitViewer
{
[Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))]
public partial class DragonVein : UserControl
{
private Model.Unit _unit;
public DragonVein()
{
InitializeComponent();
InitializeControls();
}
public void LoadUnit(Model.Unit unit)
{
_unit = unit;
PopulateControls();
}
private void InitializeControls()
{
}
private void PopulateControls()
{
var characterData = Data.Database.Characters.GetByID(_unit.CharacterID);
if (characterData != null)
{
var isDefault = characterData.CanUseDragonVein;
chkDragonVein.Checked = _unit.Trait_CanUseDragonVein || isDefault;
chkDragonVein.Enabled = !isDefault;
}
else
{
chkDragonVein.Checked = _unit.Trait_CanUseDragonVein;
}
}
private void chkDragonVein_CheckedChanged(object sender, EventArgs e)
{
var characterData = Data.Database.Characters.GetByID(_unit.CharacterID);
// If a character can't use Dragon Vein by default
if (chkDragonVein.Checked && characterData != null && !characterData.CanUseDragonVein)
_unit.Trait_CanUseDragonVein = true;
else
_unit.Trait_CanUseDragonVein = false;
}
}
}
| Soaprman/FEFTwiddler | FEFTwiddler/GUI/UnitViewer/DragonVein.cs | C# | gpl-3.0 | 1,798 |
using UnityEngine;
using System.Collections;
using System;
namespace Frontiers.World.WIScripts
{
public class Key : WIScript
{
public override void OnInitialized ()
{
if (!worlditem.Is <QuestItem> ()) {
worlditem.Props.Name.DisplayName = State.KeyName;
}
}
public KeyState State = new KeyState ();
}
[Serializable]
public class KeyState
{
public bool DisappearFromInventory = true;
public string KeyType = "SimpleKey";
public string KeyTag = "Master";
public string KeyName = "Key";
}
}
| SignpostMarv/FRONTIERS | Assets/Scripts/GameWorld/WIScripts/Machines/Key.cs | C# | gpl-3.0 | 523 |
define(
"dojo/cldr/nls/nb/gregorian", //begin v1.x content
{
"dateFormatItem-Ehm": "E h.mm a",
"days-standAlone-short": [
"sø.",
"ma.",
"ti.",
"on.",
"to.",
"fr.",
"lø."
],
"months-format-narrow": [
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D"
],
"field-second-relative+0": "nå",
"quarters-standAlone-narrow": [
"1",
"2",
"3",
"4"
],
"field-weekday": "Ukedag",
"dateFormatItem-yQQQ": "QQQ y",
"dateFormatItem-yMEd": "E d.MM.y",
"field-wed-relative+0": "onsdag denne uken",
"dateFormatItem-GyMMMEd": "E d. MMM y G",
"dateFormatItem-MMMEd": "E d. MMM",
"field-wed-relative+1": "onsdag neste uke",
"eraNarrow": [
"f.Kr.",
"fvt.",
"e.Kr.",
"vt"
],
"dateFormatItem-yMM": "MM.y",
"field-tue-relative+-1": "tirsdag sist uke",
"days-format-short": [
"sø.",
"ma.",
"ti.",
"on.",
"to.",
"fr.",
"lø."
],
"dateFormat-long": "d. MMMM y",
"field-fri-relative+-1": "fredag sist uke",
"field-wed-relative+-1": "onsdag sist uke",
"months-format-wide": [
"januar",
"februar",
"mars",
"april",
"mai",
"juni",
"juli",
"august",
"september",
"oktober",
"november",
"desember"
],
"dateTimeFormat-medium": "{1}, {0}",
"dayPeriods-format-wide-pm": "p.m.",
"dateFormat-full": "EEEE d. MMMM y",
"field-thu-relative+-1": "torsdag sist uke",
"dateFormatItem-Md": "d.M.",
"dayPeriods-format-abbr-am": "a.m.",
"dateFormatItem-yMd": "d.M.y",
"dateFormatItem-yM": "M.y",
"field-era": "Tidsalder",
"months-standAlone-wide": [
"januar",
"februar",
"mars",
"april",
"mai",
"juni",
"juli",
"august",
"september",
"oktober",
"november",
"desember"
],
"timeFormat-short": "HH.mm",
"quarters-format-wide": [
"1. kvartal",
"2. kvartal",
"3. kvartal",
"4. kvartal"
],
"timeFormat-long": "HH.mm.ss z",
"dateFormatItem-yMMM": "MMM y",
"dateFormatItem-yQQQQ": "QQQQ y",
"field-year": "År",
"dateFormatItem-MMdd": "d.M.",
"field-hour": "Time",
"months-format-abbr": [
"jan.",
"feb.",
"mar.",
"apr.",
"mai",
"jun.",
"jul.",
"aug.",
"sep.",
"okt.",
"nov.",
"des."
],
"field-sat-relative+0": "lørdag denne uken",
"field-sat-relative+1": "lørdag neste uke",
"timeFormat-full": "HH.mm.ss zzzz",
"field-day-relative+0": "i dag",
"field-day-relative+1": "i morgen",
"field-thu-relative+0": "torsdag denne uken",
"dateFormatItem-GyMMMd": "d. MMM y G",
"field-day-relative+2": "i overmorgen",
"field-thu-relative+1": "torsdag neste uke",
"dateFormatItem-H": "HH",
"months-standAlone-abbr": [
"jan",
"feb",
"mar",
"apr",
"mai",
"jun",
"jul",
"aug",
"sep",
"okt",
"nov",
"des"
],
"quarters-format-abbr": [
"K1",
"K2",
"K3",
"K4"
],
"quarters-standAlone-wide": [
"1. kvartal",
"2. kvartal",
"3. kvartal",
"4. kvartal"
],
"dateFormatItem-Gy": "y G",
"dateFormatItem-M": "L.",
"days-standAlone-wide": [
"søndag",
"mandag",
"tirsdag",
"onsdag",
"torsdag",
"fredag",
"lørdag"
],
"timeFormat-medium": "HH.mm.ss",
"field-sun-relative+0": "søndag denne uken",
"dateFormatItem-Hm": "HH.mm",
"quarters-standAlone-abbr": [
"K1",
"K2",
"K3",
"K4"
],
"field-sun-relative+1": "søndag neste uke",
"eraAbbr": [
"f.Kr.",
"e.Kr."
],
"field-minute": "Minutt",
"field-dayperiod": "AM/PM",
"days-standAlone-abbr": [
"sø.",
"ma.",
"ti.",
"on.",
"to.",
"fr.",
"lø."
],
"dateFormatItem-d": "d.",
"dateFormatItem-ms": "mm.ss",
"quarters-format-narrow": [
"1",
"2",
"3",
"4"
],
"field-day-relative+-1": "i går",
"dateFormatItem-h": "h a",
"dateTimeFormat-long": "{1} 'kl.' {0}",
"dayPeriods-format-narrow-am": "a",
"field-day-relative+-2": "i forgårs",
"dateFormatItem-MMMd": "d. MMM",
"dateFormatItem-MEd": "E d.M",
"dateTimeFormat-full": "{1} {0}",
"field-fri-relative+0": "fredag denne uken",
"dateFormatItem-yMMMM": "MMMM y",
"field-fri-relative+1": "fredag neste uke",
"field-day": "Dag",
"days-format-wide": [
"søndag",
"mandag",
"tirsdag",
"onsdag",
"torsdag",
"fredag",
"lørdag"
],
"field-zone": "Tidssone",
"dateFormatItem-y": "y",
"months-standAlone-narrow": [
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D"
],
"field-year-relative+-1": "i fjor",
"field-month-relative+-1": "forrige måned",
"dateFormatItem-hm": "h.mm a",
"dayPeriods-format-abbr-pm": "p.m.",
"days-format-abbr": [
"søn.",
"man.",
"tir.",
"ons.",
"tor.",
"fre.",
"lør."
],
"eraNames": [
"f.Kr.",
"e.Kr."
],
"dateFormatItem-yMMMd": "d. MMM y",
"days-format-narrow": [
"S",
"M",
"T",
"O",
"T",
"F",
"L"
],
"days-standAlone-narrow": [
"S",
"M",
"T",
"O",
"T",
"F",
"L"
],
"dateFormatItem-MMM": "LLL",
"field-month": "Måned",
"field-tue-relative+0": "tirsdag denne uken",
"field-tue-relative+1": "tirsdag neste uke",
"dayPeriods-format-wide-am": "a.m.",
"dateFormatItem-EHm": "E HH.mm",
"field-mon-relative+0": "mandag denne uken",
"field-mon-relative+1": "mandag neste uke",
"dateFormat-short": "dd.MM.y",
"dateFormatItem-EHms": "E HH.mm.ss",
"dateFormatItem-Ehms": "E h.mm.ss a",
"field-second": "Sekund",
"field-sat-relative+-1": "lørdag sist uke",
"dateFormatItem-yMMMEd": "E d. MMM y",
"field-sun-relative+-1": "søndag sist uke",
"field-month-relative+0": "denne måneden",
"field-month-relative+1": "neste måned",
"dateFormatItem-Ed": "E d.",
"dateTimeFormats-appendItem-Timezone": "{0} {1}",
"field-week": "Uke",
"dateFormat-medium": "d. MMM y",
"field-year-relative+0": "i år",
"field-week-relative+-1": "forrige uke",
"field-year-relative+1": "neste år",
"dayPeriods-format-narrow-pm": "p",
"dateTimeFormat-short": "{1}, {0}",
"dateFormatItem-Hms": "HH.mm.ss",
"dateFormatItem-hms": "h.mm.ss a",
"dateFormatItem-GyMMM": "MMM y G",
"field-mon-relative+-1": "mandag sist uke",
"field-week-relative+0": "denne uken",
"field-week-relative+1": "neste uke"
}
//end v1.x content
); | AnthonyARM/javascript | rowing/dojo-release-1.13.0/dojo/cldr/nls/nb/gregorian.js.uncompressed.js | JavaScript | gpl-3.0 | 5,993 |
import Ember from 'ember';
export default Ember.Component.extend({
classNames: ['button-content'],
audio: Ember.inject.service(),
soundName: null,
rate: 1,
preloadSounds: function() {
this.get('audio');
}.on('init'),
actions: {
play() {
this.get('audio').play(this.get('soundName'), this.get('rate'));
}
}
});
| hugoruscitti/huayra-procesing | app/components/p5-play-button.js | JavaScript | gpl-3.0 | 347 |
/*
* CPAchecker is a tool for configurable software verification.
* This file is part of CPAchecker.
*
* Copyright (C) 2007-2014 Dirk Beyer
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* CPAchecker web page:
* http://cpachecker.sosy-lab.org
*/
package org.sosy_lab.cpachecker.cfa.model;
import org.sosy_lab.cpachecker.cfa.ast.FileLocation;
import org.sosy_lab.cpachecker.cfa.ast.ADeclaration;
import com.google.common.base.Optional;
public class ADeclarationEdge extends AbstractCFAEdge {
protected final ADeclaration declaration;
protected ADeclarationEdge(final String pRawSignature, final FileLocation pFileLocation,
final CFANode pPredecessor, final CFANode pSuccessor, final ADeclaration pDeclaration) {
super(pRawSignature, pFileLocation, pPredecessor, pSuccessor);
declaration = pDeclaration;
}
@Override
public CFAEdgeType getEdgeType() {
return CFAEdgeType.DeclarationEdge;
}
public ADeclaration getDeclaration() {
return declaration;
}
@Override
public Optional<? extends ADeclaration> getRawAST() {
return Optional.of(declaration);
}
@Override
public String getCode() {
return declaration.toASTString();
}
}
| nishanttotla/predator | cpachecker/src/org/sosy_lab/cpachecker/cfa/model/ADeclarationEdge.java | Java | gpl-3.0 | 1,757 |
<?php
// Copyright (C) <2015> <it-novum GmbH>
//
// This file is dual licensed
//
// 1.
// 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 3 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, see <http://www.gnu.org/licenses/>.
//
// 2.
// If you purchased an openITCOCKPIT Enterprise Edition you can use this file
// under the terms of the openITCOCKPIT Enterprise Edition license agreement.
// License agreement and license key will be shipped with the order
// confirmation.
?>
<div class="row">
<div class="col-xs-12 col-md-2 text-muted">
<center><span id="selectionCount"></span></center>
</div>
<div class="col-xs-12 col-md-2 "><span id="selectAllDowntimes" class="pointer"><i
class="fa fa-lg fa-check-square-o"></i> <?php echo __('Select all'); ?></span></div>
<div class="col-xs-12 col-md-2"><span id="untickAllDowntimes" class="pointer"><i
class="fa fa-lg fa-square-o"></i> <?php echo __('Undo selection'); ?></span></div>
<div class="col-xs-12 col-md-2">
<?php if ($this->Acl->hasPermission('delete', 'Services', '')): ?>
<a href="javascript:void(0);" id="deleteAllServiceDowntimes" class="txt-color-red"
style="text-decoration: none;"> <i
class="fa fa-lg fa-trash-o"></i> <?php echo __('Delete'); ?></a>
<?php endif; ?>
</div>
</div> | it-novum/openITCOCKPIT | src/Template/element/downtimes_mass_service_delete.php | PHP | gpl-3.0 | 1,842 |
<?php
/* Copyright (C) 2012 Regis Houssin <regis.houssin@capnetworks.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
$languages = array(
'CHARSET' => 'UTF-8',
'Language_ar_AR' => 'Arabia',
'Language_ar_SA' => 'Arabic',
'Language_bg_BG' => 'Bulgarian',
'Language_ca_ES' => 'Katalaani',
'Language_da_DA' => 'Tanska',
'Language_da_DK' => 'Tanska',
'Language_de_DE' => 'Saksa',
'Language_de_AT' => 'Saksa (Itävalta)',
'Language_el_GR' => 'Kreikkalainen',
'Language_en_AU' => 'Englanti (Australia)',
'Language_en_GB' => 'Englanti (Yhdistynyt kuningaskunta)',
'Language_en_IN' => 'Englanti (Intia)',
'Language_en_NZ' => 'Englanti (Uusi-Seelanti)',
'Language_en_US' => 'Englanti (Yhdysvallat)',
'Language_es_ES' => 'Espanjalainen',
'Language_es_AR' => 'Espanja (Argentiina)',
'Language_es_HN' => 'Espanja (Honduras)',
'Language_es_MX' => 'Espanja (Meksiko)',
'Language_es_PR' => 'Espanja (Puerto Rico)',
'Language_et_EE' => 'Estonian',
'Language_fa_IR' => 'Persialainen',
'Language_fi_FI' => 'Fins',
'Language_fr_BE' => 'Ranska (Belgia)',
'Language_fr_CA' => 'Ranska (Kanada)',
'Language_fr_CH' => 'Ranska (Sveitsi)',
'Language_fr_FR' => 'Ranskalainen',
'Language_he_IL' => 'Hebrew',
'Language_hu_HU' => 'Unkari',
'Language_is_IS' => 'Islannin',
'Language_it_IT' => 'Italialainen',
'Language_ja_JP' => 'Japanin kieli',
'Language_nb_NO' => 'Norja (bokmål)',
'Language_nl_BE' => 'Hollanti (Belgia)',
'Language_nl_NL' => 'Hollanti (Alankomaat)',
'Language_pl_PL' => 'Puola',
'Language_pt_BR' => 'Portugali (Brasilia)',
'Language_pt_PT' => 'Portugali',
'Language_ro_RO' => 'Romanialainen',
'Language_ru_RU' => 'Venäläinen',
'Language_ru_UA' => 'Venäjä (Ukraina)',
'Language_tr_TR' => 'Turkki',
'Language_sl_SI' => 'Slovenian',
'Language_sv_SV' => 'Ruotsi',
'Language_sv_SE' => 'Ruotsi',
'Language_zh_CN' => 'Kiinalainen',
'Language_is_IS' => 'Islannin'
);
?> | woakes070048/crm-php | htdocs/langs/fi_FI/languages.lang.php | PHP | gpl-3.0 | 2,557 |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ExtentTest.cs" company="Allors bvba">
// Copyright 2002-2012 Allors bvba.
//
// Dual Licensed under
// a) the Lesser General Public Licence v3 (LGPL)
// b) the Allors License
//
// The LGPL License is included in the file lgpl.txt.
// The Allors License is an addendum to your contract.
//
// Allors Platform 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.
//
// For more information visit http://www.allors.com/legal
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Allors.Adapters.Object.SqlClient
{
using System.Linq;
using Allors;
using Allors.Domain;
using Allors.Meta;
using Xunit;
public abstract class ExtentTest : Adapters.ExtentTest
{
[Fact]
public override void SortOne()
{
foreach (var init in this.Inits)
{
foreach (var marker in this.Markers)
{
init();
this.Populate();
this.Session.Commit();
this.c1B.C1AllorsString = "3";
this.c1C.C1AllorsString = "1";
this.c1D.C1AllorsString = "2";
this.Session.Commit();
marker();
var extent = this.Session.Extent(MetaC1.Instance.ObjectType);
extent.AddSort(MetaC1.Instance.C1AllorsString);
var sortedObjects = (C1[])extent.ToArray(typeof(C1));
Assert.Equal(4, sortedObjects.Length);
Assert.Equal(this.c1A, sortedObjects[0]);
Assert.Equal(this.c1C, sortedObjects[1]);
Assert.Equal(this.c1D, sortedObjects[2]);
Assert.Equal(this.c1B, sortedObjects[3]);
marker();
extent = this.Session.Extent(MetaC1.Instance.ObjectType);
extent.AddSort(MetaC1.Instance.C1AllorsString, SortDirection.Ascending);
sortedObjects = (C1[])extent.ToArray(typeof(C1));
Assert.Equal(4, sortedObjects.Length);
Assert.Equal(this.c1A, sortedObjects[0]);
Assert.Equal(this.c1C, sortedObjects[1]);
Assert.Equal(this.c1D, sortedObjects[2]);
Assert.Equal(this.c1B, sortedObjects[3]);
marker();
extent = this.Session.Extent(MetaC1.Instance.ObjectType);
extent.AddSort(MetaC1.Instance.C1AllorsString, SortDirection.Ascending);
sortedObjects = (C1[])extent.ToArray(typeof(C1));
Assert.Equal(4, sortedObjects.Length);
Assert.Equal(this.c1A, sortedObjects[0]);
Assert.Equal(this.c1C, sortedObjects[1]);
Assert.Equal(this.c1D, sortedObjects[2]);
Assert.Equal(this.c1B, sortedObjects[3]);
marker();
extent = this.Session.Extent(MetaC1.Instance.ObjectType);
extent.AddSort(MetaC1.Instance.C1AllorsString, SortDirection.Descending);
sortedObjects = (C1[])extent.ToArray(typeof(C1));
Assert.Equal(4, sortedObjects.Length);
Assert.Equal(this.c1B, sortedObjects[0]);
Assert.Equal(this.c1D, sortedObjects[1]);
Assert.Equal(this.c1C, sortedObjects[2]);
Assert.Equal(this.c1A, sortedObjects[3]);
marker();
extent = this.Session.Extent(MetaC1.Instance.ObjectType);
extent.AddSort(MetaC1.Instance.C1AllorsString, SortDirection.Descending);
sortedObjects = (C1[])extent.ToArray(typeof(C1));
Assert.Equal(4, sortedObjects.Length);
Assert.Equal(this.c1B, sortedObjects[0]);
Assert.Equal(this.c1D, sortedObjects[1]);
Assert.Equal(this.c1C, sortedObjects[2]);
Assert.Equal(this.c1A, sortedObjects[3]);
foreach (var useOperator in this.UseOperator)
{
if (useOperator)
{
marker();
var firstExtent = this.Session.Extent(MetaC1.Instance.ObjectType);
firstExtent.Filter.AddLike(MetaC1.Instance.C1AllorsString, "1");
var secondExtent = this.Session.Extent(MetaC1.Instance.ObjectType);
extent = this.Session.Union(firstExtent, secondExtent);
secondExtent.Filter.AddLike(MetaC1.Instance.C1AllorsString, "3");
extent.AddSort(MetaC1.Instance.C1AllorsString);
sortedObjects = (C1[])extent.ToArray(typeof(C1));
Assert.Equal(2, sortedObjects.Length);
Assert.Equal(this.c1C, sortedObjects[0]);
Assert.Equal(this.c1B, sortedObjects[1]);
}
}
}
}
}
[Fact]
public override void SortTwo()
{
foreach (var init in this.Inits)
{
init();
this.Populate();
this.c1B.C1AllorsString = "a";
this.c1C.C1AllorsString = "b";
this.c1D.C1AllorsString = "a";
this.c1B.C1AllorsInteger = 2;
this.c1C.C1AllorsInteger = 1;
this.c1D.C1AllorsInteger = 0;
this.Session.Commit();
var extent = this.Session.Extent(MetaC1.Instance.ObjectType);
extent.AddSort(MetaC1.Instance.C1AllorsString);
extent.AddSort(MetaC1.Instance.C1AllorsInteger);
var sortedObjects = (C1[])extent.ToArray(typeof(C1));
Assert.Equal(4, sortedObjects.Length);
Assert.Equal(this.c1A, sortedObjects[0]);
Assert.Equal(this.c1D, sortedObjects[1]);
Assert.Equal(this.c1B, sortedObjects[2]);
Assert.Equal(this.c1C, sortedObjects[3]);
extent = this.Session.Extent(MetaC1.Instance.ObjectType);
extent.AddSort(MetaC1.Instance.C1AllorsString);
extent.AddSort(MetaC1.Instance.C1AllorsInteger, SortDirection.Ascending);
sortedObjects = (C1[])extent.ToArray(typeof(C1));
Assert.Equal(4, sortedObjects.Length);
Assert.Equal(this.c1A, sortedObjects[0]);
Assert.Equal(this.c1D, sortedObjects[1]);
Assert.Equal(this.c1B, sortedObjects[2]);
Assert.Equal(this.c1C, sortedObjects[3]);
extent = this.Session.Extent(MetaC1.Instance.ObjectType);
extent.AddSort(MetaC1.Instance.C1AllorsString);
extent.AddSort(MetaC1.Instance.C1AllorsInteger, SortDirection.Descending);
sortedObjects = (C1[])extent.ToArray(typeof(C1));
Assert.Equal(4, sortedObjects.Length);
Assert.Equal(this.c1A, sortedObjects[0]);
Assert.Equal(this.c1B, sortedObjects[1]);
Assert.Equal(this.c1D, sortedObjects[2]);
Assert.Equal(this.c1C, sortedObjects[3]);
extent = this.Session.Extent(MetaC1.Instance.ObjectType);
extent.AddSort(MetaC1.Instance.C1AllorsString, SortDirection.Descending);
extent.AddSort(MetaC1.Instance.C1AllorsInteger, SortDirection.Descending);
sortedObjects = (C1[])extent.ToArray(typeof(C1));
Assert.Equal(4, sortedObjects.Length);
Assert.Equal(this.c1C, sortedObjects[0]);
Assert.Equal(this.c1B, sortedObjects[1]);
Assert.Equal(this.c1D, sortedObjects[2]);
Assert.Equal(this.c1A, sortedObjects[3]);
}
}
[Fact]
public override void SortDifferentSession()
{
foreach (var init in this.Inits)
{
init();
var c1A = C1.Create(this.Session);
var c1B = C1.Create(this.Session);
var c1C = C1.Create(this.Session);
var c1D = C1.Create(this.Session);
c1A.C1AllorsString = "2";
c1B.C1AllorsString = "1";
c1C.C1AllorsString = "3";
var extent = this.Session.Extent(M.C1.Class);
extent.AddSort(M.C1.C1AllorsString, SortDirection.Ascending);
var sortedObjects = (C1[])extent.ToArray(typeof(C1));
var names = sortedObjects.Select(v => v.C1AllorsString).ToArray();
Assert.Equal(4, sortedObjects.Length);
Assert.Equal(c1D, sortedObjects[0]);
Assert.Equal(c1B, sortedObjects[1]);
Assert.Equal(c1A, sortedObjects[2]);
Assert.Equal(c1C, sortedObjects[3]);
var c1AId = c1A.Id;
this.Session.Commit();
using (var session2 = this.CreateSession())
{
c1A = (C1)session2.Instantiate(c1AId);
extent = session2.Extent(M.C1.Class);
extent.AddSort(M.C1.C1AllorsString, SortDirection.Ascending);
sortedObjects = (C1[])extent.ToArray(typeof(C1));
names = sortedObjects.Select(v => v.C1AllorsString).ToArray();
Assert.Equal(4, sortedObjects.Length);
Assert.Equal(c1D, sortedObjects[0]);
Assert.Equal(c1B, sortedObjects[1]);
Assert.Equal(c1A, sortedObjects[2]);
Assert.Equal(c1C, sortedObjects[3]);
}
}
}
}
} | Allors/allors | Platform/Database/Adapters/Tests.Static/Static/object/sqlclient/ExtentTest.cs | C# | gpl-3.0 | 10,380 |
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\App\Test\Unit\View\Asset\MaterializationStrategy;
use \Magento\Framework\App\View\Asset\MaterializationStrategy\Factory;
use Magento\Framework\ObjectManagerInterface;
class FactoryTest extends \PHPUnit_Framework_TestCase
{
/**
* @var ObjectManagerInterface | \PHPUnit_Framework_MockObject_MockObject
*/
private $objectManager;
protected function setUp()
{
$this->objectManager = $this->getMockBuilder('Magento\Framework\ObjectManagerInterface')
->setMethods([])
->getMock();
}
public function testCreateEmptyStrategies()
{
$asset = $this->getAsset();
$copyStrategy = $this->getMockBuilder('Magento\Framework\App\View\Asset\MaterializationStrategy\Copy')
->setMethods([])
->getMock();
$copyStrategy->expects($this->once())
->method('isSupported')
->with($asset)
->willReturn(true);
$this->objectManager->expects($this->once())
->method('get')
->with(Factory::DEFAULT_STRATEGY)
->willReturn($copyStrategy);
$factory = new Factory($this->objectManager, []);
$this->assertSame($copyStrategy, $factory->create($asset));
}
public function testCreateSupported()
{
$asset = $this->getAsset();
$copyStrategy = $this->getMockBuilder('Magento\Framework\App\View\Asset\MaterializationStrategy\Copy')
->setMethods([])
->getMock();
$copyStrategy->expects($this->once())
->method('isSupported')
->with($asset)
->willReturn(false);
$supportedStrategy = $this->getMockBuilder(
'Magento\Framework\App\View\Asset\MaterializationStrategy\StrategyInterface'
)
->setMethods([])
->getMock();
$supportedStrategy->expects($this->once())
->method('isSupported')
->with($asset)
->willReturn(true);
$factory = new Factory($this->objectManager, [$copyStrategy, $supportedStrategy]);
$this->assertSame($supportedStrategy, $factory->create($asset));
}
public function testCreateException()
{
$asset = $this->getAsset();
$copyStrategy = $this->getMockBuilder('Magento\Framework\App\View\Asset\MaterializationStrategy\Copy')
->setMethods([])
->getMock();
$copyStrategy->expects($this->once())
->method('isSupported')
->with($asset)
->willReturn(false);
$this->objectManager->expects($this->once())
->method('get')
->with(Factory::DEFAULT_STRATEGY)
->willReturn($copyStrategy);
$factory = new Factory($this->objectManager, []);
$this->setExpectedException('LogicException', 'No materialization strategy is supported');
$factory->create($asset);
}
/**
* @return \Magento\Framework\View\Asset\LocalInterface | \PHPUnit_Framework_MockObject_MockObject
*/
private function getAsset()
{
return $this->getMockBuilder('Magento\Framework\View\Asset\LocalInterface')
->setMethods([])
->getMock();
}
}
| rajmahesh/magento2-master | vendor/magento/framework/App/Test/Unit/View/Asset/MaterializationStrategy/FactoryTest.php | PHP | gpl-3.0 | 3,355 |
#coding=gbk
"""Convert HTML page to Word 97 document
This script is used during the build process of "Dive Into Python"
(http://diveintopython.org/) to create the downloadable Word 97 version
of the book (http://diveintopython.org/diveintopython.doc)
Looks for 2 arguments on the command line. The first argument is the input (HTML)
file; the second argument is the output (.doc) file.
Only runs on Windows. Requires Microsoft Word 2000.
Safe to run on the same file(s) more than once. The output file will be
silently overwritten if it already exists.
The script has been modified by xiaq (xiaqqaix@gmail.com) to fit Simplified Chinese version of Microsoft Word.
"""
__author__ = "Mark Pilgrim (mark@diveintopython.org)"
__version__ = "$Revision: 1.2 $"
__date__ = "$Date: 2004/05/05 21:57:19 $"
__copyright__ = "Copyright (c) 2001 Mark Pilgrim"
__license__ = "Python"
import sys, os
from win32com.client import gencache, constants
def makeRealWordDoc(infile, outfile):
word = gencache.EnsureDispatch("Word.Application")
try:
worddoc = word.Documents.Open(FileName=infile)
try:
worddoc.TablesOfContents.Add(Range=word.ActiveWindow.Selection.Range, \
RightAlignPageNumbers=1, \
UseHeadingStyles=1, \
UpperHeadingLevel=1, \
LowerHeadingLevel=2, \
IncludePageNumbers=1, \
AddedStyles='', \
UseHyperlinks=1, \
HidePageNumbersInWeb=1)
worddoc.TablesOfContents(1).TabLeader = constants.wdTabLeaderDots
worddoc.TablesOfContents.Format = constants.wdIndexIndent
word.ActiveWindow.ActivePane.View.SeekView = constants.wdSeekCurrentPageHeader
word.Selection.TypeText(Text="Dive Into Python\t\thttp://diveintopython.org/")
word.ActiveWindow.ActivePane.View.SeekView = constants.wdSeekCurrentPageFooter
word.NormalTemplate.AutoTextEntries("- Ò³Âë -").Insert(Where=word.ActiveWindow.Selection.Range)
word.ActiveWindow.View.Type = constants.wdPrintView
worddoc.TablesOfContents(1).Update()
worddoc.SaveAs(FileName=outfile, \
FileFormat=constants.wdFormatDocument)
finally:
worddoc.Close(0)
del worddoc
finally:
word.Quit()
del word
if __name__ == "__main__":
infile = os.path.normpath(os.path.join(os.getcwd(), sys.argv[1]))
outfile = os.path.normpath(os.path.join(os.getcwd(), sys.argv[2]))
makeRealWordDoc(infile, outfile)
| qilicun/python | python2/diveintopythonzh-cn-5.4b/zh_cn/makerealworddoc.py | Python | gpl-3.0 | 2,374 |
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Tax\Test\Unit\Model;
class TaxRateManagementTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \Magento\Tax\Model\TaxRateManagement
*/
protected $model;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $searchCriteriaBuilderMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $filterBuilderMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $taxRuleRepositoryMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $taxRateRepositoryMock;
protected function setUp()
{
$this->filterBuilderMock = $this->getMock('\Magento\Framework\Api\FilterBuilder', [], [], '', false);
$this->taxRuleRepositoryMock = $this->getMock('\Magento\Tax\Api\TaxRuleRepositoryInterface', [], [], '', false);
$this->taxRateRepositoryMock = $this->getMock('\Magento\Tax\Api\TaxRateRepositoryInterface', [], [], '', false);
$this->searchCriteriaBuilderMock = $this->getMock(
'\Magento\Framework\Api\SearchCriteriaBuilder',
[],
[],
'',
false
);
$this->model = new \Magento\Tax\Model\TaxRateManagement(
$this->taxRuleRepositoryMock,
$this->taxRateRepositoryMock,
$this->filterBuilderMock,
$this->searchCriteriaBuilderMock
);
}
public function testGetRatesByCustomerAndProductTaxClassId()
{
$customerTaxClassId = 4;
$productTaxClassId = 42;
$rateIds = [10];
$productFilterMock = $this->getMock('\Magento\Framework\Api\Filter', [], [], '', false);
$customerFilterMock = $this->getMock('\Magento\Framework\Api\Filter', [], [], '', false);
$searchCriteriaMock = $this->getMock('\Magento\Framework\Api\SearchCriteria', [], [], '', false);
$searchResultsMock = $this->getMock('\Magento\Tax\Api\Data\TaxRuleSearchResultsInterface', [], [], '', false);
$taxRuleMock = $this->getMock('\Magento\Tax\Api\Data\TaxRuleInterface', [], [], '', false);
$taxRateMock = $this->getMock('\Magento\Tax\Api\Data\TaxRateInterface', [], [], '', false);
$this->filterBuilderMock->expects($this->exactly(2))->method('setField')->withConsecutive(
['customer_tax_class_ids'],
['product_tax_class_ids']
)->willReturnSelf();
$this->filterBuilderMock->expects($this->exactly(2))->method('setValue')->withConsecutive(
[$this->equalTo([$customerTaxClassId])],
[$this->equalTo([$productTaxClassId])]
)->willReturnSelf();
$this->filterBuilderMock->expects($this->exactly(2))->method('create')->willReturnOnConsecutiveCalls(
$customerFilterMock,
$productFilterMock
);
$this->searchCriteriaBuilderMock->expects($this->exactly(2))->method('addFilters')->withConsecutive(
[[$customerFilterMock]],
[[$productFilterMock]]
);
$this->searchCriteriaBuilderMock->expects($this->once())->method('create')->willReturn($searchCriteriaMock);
$this->taxRuleRepositoryMock->expects($this->once())->method('getList')->with($searchCriteriaMock)
->willReturn($searchResultsMock);
$searchResultsMock->expects($this->once())->method('getItems')->willReturn([$taxRuleMock]);
$taxRuleMock->expects($this->once())->method('getTaxRateIds')->willReturn($rateIds);
$this->taxRateRepositoryMock->expects($this->once())->method('get')->with($rateIds[0])
->willReturn($taxRateMock);
$this->assertEquals(
[$taxRateMock],
$this->model->getRatesByCustomerAndProductTaxClassId($customerTaxClassId, $productTaxClassId)
);
}
}
| rajmahesh/magento2-master | vendor/magento/module-tax/Test/Unit/Model/TaxRateManagementTest.php | PHP | gpl-3.0 | 3,944 |
/*
* log_ft_data.cpp
*
* Created on: Jul 9, 2010
* Author: dc
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <syslog.h>
#include <signal.h>
#include <unistd.h>
#include <native/task.h>
#include <native/timer.h>
#include <boost/thread.hpp>
#include <boost/ref.hpp>
#include <boost/tuple/tuple.hpp>
#include <barrett/detail/stacktrace.h>
#include <barrett/detail/stl_utils.h>
#include <barrett/units.h>
#include <barrett/log.h>
#include <barrett/products/product_manager.h>
using namespace barrett;
using detail::waitForEnter;
BARRETT_UNITS_FIXED_SIZE_TYPEDEFS;
typedef boost::tuple<double, cf_type, ct_type> tuple_type;
bool g_Going = true; // Global
void stopThreads(int sig) {
g_Going = false;
}
void warnOnSwitchToSecondaryMode(int)
{
syslog(LOG_ERR, "WARNING: Switched out of RealTime. Stack-trace:");
detail::syslog_stacktrace();
std::cerr << "WARNING: Switched out of RealTime. Stack-trace in syslog.\n";
}
void ftThreadEntryPoint(bool* going, double T_s, ForceTorqueSensor& fts, log::RealTimeWriter<tuple_type>* lw, int windowSize, int* numSamples, tuple_type* sum) {
tuple_type t;
rt_task_shadow(new RT_TASK, NULL, 10, 0);
rt_task_set_mode(0, T_PRIMARY | T_WARNSW, NULL);
rt_task_set_periodic(NULL, TM_NOW, T_s * 1e9);
RTIME now = rt_timer_read();
RTIME lastUpdate = now;
while (*going) {
rt_task_wait_period(NULL);
now = rt_timer_read();
fts.update(true); // Do a realtime update (no sleeping while waiting for messages)
boost::get<0>(t) = ((double) now - lastUpdate) * 1e-9;
boost::get<1>(t) = fts.getForce();
boost::get<2>(t) = fts.getTorque();
if (lw != NULL) {
lw->putRecord(t);
} else {
if (*numSamples == 0) {
boost::get<1>(*sum).setZero();
boost::get<2>(*sum).setZero();
}
if (*numSamples < windowSize) {
boost::get<1>(*sum) += boost::get<1>(t);
boost::get<2>(*sum) += boost::get<2>(t);
++(*numSamples);
}
}
lastUpdate = now;
}
rt_task_set_mode(T_WARNSW, 0, NULL);
}
void showUsageAndExit(const char* programName) {
printf("Usage: %s {-f <fileName> | -a <windowSize>} [<samplePeriodInSeconds>]\n", programName);
printf(" -f <fileName> Log data to a file\n");
printf(" -a <windowSize> Print statistics on segments of data\n");
exit(0);
}
int main(int argc, char** argv) {
char* outFile = NULL;
double T_s = 0.002; // Default: 500Hz
bool fileMode = false;
int windowSize = 0;
if (argc == 4) {
T_s = std::atof(argv[3]);
} else if (argc != 3) {
showUsageAndExit(argv[0]);
}
printf("Sample period: %fs\n", T_s);
if (strcmp(argv[1], "-f") == 0) {
fileMode = true;
outFile = argv[2];
printf("Output file: %s\n", outFile);
} else if (strcmp(argv[1], "-a") == 0) {
fileMode = false;
windowSize = atoi(argv[2]);
printf("Window size: %d\n", windowSize);
} else {
showUsageAndExit(argv[0]);
}
printf("\n");
signal(SIGXCPU, &warnOnSwitchToSecondaryMode);
char tmpFile[] = "/tmp/btXXXXXX";
log::RealTimeWriter<tuple_type>* lw = NULL;
if (fileMode) {
signal(SIGINT, &stopThreads);
if (mkstemp(tmpFile) == -1) {
printf("ERROR: Couldn't create temporary file!\n");
return 1;
}
lw = new barrett::log::RealTimeWriter<tuple_type>(tmpFile, T_s);
}
int numSamples = windowSize, numSets = 0;
tuple_type sum;
ProductManager pm;
if ( !pm.foundForceTorqueSensor() ) {
printf("ERROR: No Force-Torque Sensor found!\n");
return 1;
}
boost::thread ftThread(ftThreadEntryPoint, &g_Going, T_s, boost::ref(*pm.getForceTorqueSensor()), lw, windowSize, &numSamples, &sum);
if (fileMode) {
printf(">>> Logging data. Press [Ctrl-C] to exit.\n");
} else {
printf(">>> Press [Enter] to start a new sample. Press [Ctrl-C] to exit.\n\n");
printf("ID,FX,FY,FZ,TX,TY,TZ");
while (g_Going) {
waitForEnter();
numSamples = 0;
while (numSamples != windowSize) {
usleep(100000);
}
boost::get<1>(sum) /= windowSize;
boost::get<2>(sum) /= windowSize;
printf("%d,%f,%f,%f,%f,%f,%f", ++numSets, boost::get<1>(sum)[0], boost::get<1>(sum)[1], boost::get<1>(sum)[2], boost::get<2>(sum)[0], boost::get<2>(sum)[1], boost::get<2>(sum)[2]);
}
}
ftThread.join();
printf("\n");
if (fileMode) {
delete lw;
log::Reader<tuple_type> lr(tmpFile);
lr.exportCSV(outFile);
printf("Output written to %s.\n", outFile);
std::remove(tmpFile);
}
return 0;
}
| jhu-lcsr-forks/barrett | sandbox/log_ft_data.cpp | C++ | gpl-3.0 | 4,369 |
/*
Lehrstuhl fuer Energietransport und -speicherung
UNIVERSITAET DUISBURG-ESSEN
ef.Ruhr E-DeMa AP-2
Wissenschaftlicher Mitarbeiter:
Dipl.-Ing. Holger Kellerbauer
Das Linklayer-Paket "powerline" umfasst eine Sammlung von Modulen, die zur Simulation von Powerline-
Uebertragungsstrecken in intelligenten Energieverteilsystemen programmiert worden sind.
Dieser Quellcode wurde erstellt von Dipl.-Ing. Holger Kellerbauer - er basiert auf dem INET Framework-Modul
"Linklayer/Ethernet" von Andras Varga (c) 2003. Er ist gesitiges Eigentum des Lehrstuhles fuer Energietransport
und -speicherung der Universitaet Duisburg-Essen, und darf ohne Genehmigung weder weitergegeben, noch verwendet
werden.
*/
#include <stdio.h>
#include <string.h>
#include <omnetpp.h>
#include "Adapter_PLC_Base.h"
#include "IPassiveQueue.h"
#include "IInterfaceTable.h"
#include "InterfaceTableAccess.h"
//static const double SPEED_OF_LIGHT = 200000000.0; // TODO: Changed by Ramon; already defined in INETDefs.h
Adapter_PLC_Base::Adapter_PLC_Base()
{
nb = NULL;
queueModule = NULL;
interfaceEntry = NULL;
endTxMsg = endIFGMsg = endPauseMsg = NULL;
}
Adapter_PLC_Base::~Adapter_PLC_Base()
{
cancelAndDelete(endTxMsg);
cancelAndDelete(endIFGMsg);
cancelAndDelete(endPauseMsg);
}
void Adapter_PLC_Base::initialize()
{
physOutGate = gate("phys$o");
initializeFlags();
initializeTxrate();
WATCH(txrate);
initializeMACAddress();
initializeQueueModule();
initializeNotificationBoard();
initializeStatistics();
/*
The adapter has no higher layer!
*/
// registerInterface(txrate); // needs MAC address
// initialize queue
txQueue.setName("txQueue");
// initialize self messages
endTxMsg = new cMessage("EndTransmission", ENDTRANSMISSION);
endIFGMsg = new cMessage("EndIFG", ENDIFG);
endPauseMsg = new cMessage("EndPause", ENDPAUSE);
// initialize states
transmitState = TX_IDLE_STATE;
receiveState = RX_IDLE_STATE;
WATCH(transmitState);
WATCH(receiveState);
// initalize pause
pauseUnitsRequested = 0;
WATCH(pauseUnitsRequested);
// initialize queue limit
txQueueLimit = par("txQueueLimit");
WATCH(txQueueLimit);
}
void Adapter_PLC_Base::initializeQueueModule()
{
if (par("queueModule").stringValue()[0])
{
cModule *module = getParentModule()->getSubmodule(par("queueModule").stringValue());
queueModule = check_and_cast<IPassiveQueue *>(module);
if (COMMENTS_ON) EV << "Requesting first frame from queue module\n";
queueModule->requestPacket();
}
}
void Adapter_PLC_Base::initializeMACAddress()
{
const char *addrstr = par("address");
if (!strcmp(addrstr,"auto"))
{
// assign automatic address
address = MACAddress::generateAutoAddress();
// change module parameter from "auto" to concrete address
par("address").setStringValue(address.str().c_str());
}
else
{
address.setAddress(addrstr);
}
}
void Adapter_PLC_Base::initializeNotificationBoard()
{
hasSubscribers = false;
if (interfaceEntry) {
nb = NotificationBoardAccess().getIfExists();
notifDetails.setInterfaceEntry(interfaceEntry);
nb->subscribe(this, NF_SUBSCRIBERLIST_CHANGED);
updateHasSubcribers();
}
}
void Adapter_PLC_Base::initializeFlags()
{
// initialize connected flag
connected = physOutGate->getPathEndGate()->isConnected();
if (!connected)
if (COMMENTS_ON) EV << "MAC not connected to a network.\n";
WATCH(connected);
// TODO: this should be settable from the gui
// initialize disabled flag
// Note: it is currently not supported to enable a disabled MAC at runtime.
// Difficulties: (1) autoconfig (2) how to pick up channel state (free, tx, collision etc)
disabled = false;
WATCH(disabled);
// initialize promiscuous flag
promiscuous = par("promiscuous");
WATCH(promiscuous);
}
void Adapter_PLC_Base::initializeStatistics()
{
framesSentInBurst = 0;
bytesSentInBurst = 0;
numFramesSent = numFramesReceivedOK = numBytesSent = numBytesReceivedOK = 0;
numFramesPassedToHL = numDroppedBitError = numDroppedNotForUs = 0;
numFramesFromHL = numDroppedIfaceDown = 0;
numPauseFramesRcvd = numPauseFramesSent = 0;
WATCH(framesSentInBurst);
WATCH(bytesSentInBurst);
WATCH(numFramesSent);
WATCH(numFramesReceivedOK);
WATCH(numBytesSent);
WATCH(numBytesReceivedOK);
WATCH(numFramesFromHL);
WATCH(numDroppedIfaceDown);
WATCH(numDroppedBitError);
WATCH(numDroppedNotForUs);
WATCH(numFramesPassedToHL);
WATCH(numPauseFramesRcvd);
WATCH(numPauseFramesSent);
/*
numFramesSentVector.setName("framesSent");
numFramesReceivedOKVector.setName("framesReceivedOK");
numBytesSentVector.setName("bytesSent");
numBytesReceivedOKVector.setName("bytesReceivedOK");
numDroppedIfaceDownVector.setName("framesDroppedIfaceDown");
numDroppedBitErrorVector.setName("framesDroppedBitError");
numDroppedNotForUsVector.setName("framesDroppedNotForUs");
numFramesPassedToHLVector.setName("framesPassedToHL");
numPauseFramesRcvdVector.setName("pauseFramesRcvd");
numPauseFramesSentVector.setName("pauseFramesSent");
*/
}
void Adapter_PLC_Base::registerInterface(double txrate)
{
IInterfaceTable *ift = InterfaceTableAccess().getIfExists();
if (!ift)
return;
// interfaceEntry = new InterfaceEntry();
interfaceEntry = new InterfaceEntry(NULL); // TODO: Changed by Ramon
// interface name: our module name without special characters ([])
char *interfaceName = new char[strlen(getParentModule()->getFullName())+1];
char *d=interfaceName;
for (const char *s=getParentModule()->getFullName(); *s; s++)
if (isalnum(*s))
*d++ = *s;
*d = '\0';
interfaceEntry->setName(interfaceName);
delete [] interfaceName;
// data rate
interfaceEntry->setDatarate(txrate);
// generate a link-layer address to be used as interface token for IPv6
interfaceEntry->setMACAddress(address);
interfaceEntry->setInterfaceToken(address.formInterfaceIdentifier());
//InterfaceToken token(0, simulation.getUniqueNumber(), 64);
//interfaceEntry->setInterfaceToken(token);
// MTU: typical values are 576 (Internet de facto), 1500 (PLC-friendly),
// 4000 (on some point-to-point links), 4470 (Cisco routers default, FDDI compatible)
interfaceEntry->setMtu(par("mtu"));
// capabilities
interfaceEntry->setMulticast(true);
interfaceEntry->setBroadcast(true);
// add
// ift->addInterface(interfaceEntry, this);
ift->addInterface(interfaceEntry); // TODO: Changed by Ramon
}
bool Adapter_PLC_Base::checkDestinationAddress(PlcFrame *frame)
{
/*
// If not set to promiscuous = on, then checks if received frame contains destination MAC address
// matching port's MAC address, also checks if broadcast bit is set
if (!promiscuous && !frame->getDest().isBroadcast() && !frame->getDest().equals(address))
{
if (COMMENTS_ON) EV << "Frame `" << frame->getName() <<"' not destined to us, discarding\n";
numDroppedNotForUs++;
numDroppedNotForUsVector.record(numDroppedNotForUs);
delete frame;
return false;
}
*/
if (COMMENTS_ON) EV << "Since I'm an adapter, I will pass through every frame!" << endl;
return true;
}
void Adapter_PLC_Base::calculateParameters()
{
if (disabled || !connected)
{
bitTime = slotTime = interFrameGap = jamDuration = shortestFrameDuration = 0;
carrierExtension = frameBursting = false;
return;
}
// CHANGE ---------------------------------------------------------------------------------------
/*
Diesen Abschnitt mus man ausblenden, da er die Uebertragungsraten auf wenige, zulaessige
reduziert, was fuer Powerline absolut nicht zutreffend ist.
if (txrate != PLC_TXRATE && txrate != FAST_PLC_TXRATE &&
txrate != GIGABIT_PLC_TXRATE && txrate != FAST_GIGABIT_PLC_TXRATE)
{
error("nonstandard transmission rate %g, must be %g, %g, %g or %g bit/sec",
txrate, PLC_TXRATE, FAST_PLC_TXRATE, GIGABIT_PLC_TXRATE, FAST_GIGABIT_PLC_TXRATE);
}
*/
double temp = ROBO_DATARATE * 1000000;
if (txrate <= temp)
{
if (COMMENTS_ON) EV << "Measured datarate is estimated below ROBO datarate." << endl;
if (COMMENTS_ON) EV << "ROBO datarate is the lowest datarate possible." << endl;
if (COMMENTS_ON) EV << "TX rate will be set to ROBO datarate." << endl;
txrate = ROBO_DATARATE * 1000000;
}
if (txrate <= ROBO_DATARATE || txrate >= 1000000000) txrate = ROBO_DATARATE;
bitTime = 1/(double)txrate;
if (COMMENTS_ON) EV << endl << "Bit time is calculated to " << bitTime << "s." << endl;
/*
Dieser Abschnitt muss ausgeblendet werden, da die Berechnung der Parameter fuer
Powerline-Uebertragungen etwas anders von Statten gehen muss.
// set slot time
if (txrate==PLC_TXRATE || txrate==FAST_PLC_TXRATE)
slotTime = SLOT_TIME;
else
slotTime = GIGABIT_SLOT_TIME;
// only if Gigabit PLC
frameBursting = (txrate==GIGABIT_PLC_TXRATE || txrate==FAST_GIGABIT_PLC_TXRATE);
carrierExtension = (slotTime == GIGABIT_SLOT_TIME && !duplexMode);
interFrameGap = INTERFRAME_GAP_BITS/(double)txrate;
jamDuration = 8*JAM_SIGNAL_BYTES*bitTime;
shortestFrameDuration = carrierExtension ? GIGABIT_MIN_FRAME_WITH_EXT : MIN_PLC_FRAME;
*/
// set slot time
slotTime = 512/txrate;
if (COMMENTS_ON) EV << "Slot time is set to " << slotTime << "s." << endl;
// only if fast PLC
// Ein Burst darf nicht laenger als 5000 usec sein. 4 x MaxFramedauer < 5000 usec => FrameBursting = true!
simtime_t k = 0.005; /* s */
simtime_t x = (simtime_t)(bitTime * (MAX_PLC_FRAME * 8 /* bytes */) * 4);
if (COMMENTS_ON) EV << "Calculation for frame bursting resulted in " << x << " sec." << endl;
if (COMMENTS_ON) EV << "Threshold for frame bursting is " << k << " sec." << endl;
if (x < k)
{
frameBursting = true;
}
else
{
frameBursting = false;
}
if (COMMENTS_ON) EV << "Frame bursting is at " << frameBursting << "." << endl;
carrierExtension = false; // not available for PLC
if (frameBursting)
{
interFrameGap = /* INTERFRAME_GAP_BITS/(double)txrate; */ CIFS / 1000000;
}
else
{
interFrameGap = /* INTERFRAME_GAP_BITS/(double)txrate; */ RIFS / 1000000;
}
if (COMMENTS_ON) EV << "Inter frame gap is at " << interFrameGap << "s." << endl;
jamDuration = 8*JAM_SIGNAL_BYTES*bitTime;
if (COMMENTS_ON) EV << "Jam duration is at " << jamDuration << "s." << endl;
shortestFrameDuration = MIN_PLC_FRAME;
// ----------------------------------------------------------------------------------------------
}
void Adapter_PLC_Base::printParameters()
{
// Dump parameters
if (COMMENTS_ON) EV << "MAC address: " << address << (promiscuous ? ", promiscuous mode" : "") << endl;
if (COMMENTS_ON) EV << "txrate: " << txrate << ", " << (duplexMode ? "duplex" : "half-duplex") << endl;
#if 0
EV << "bitTime: " << bitTime << endl;
EV << "carrierExtension: " << carrierExtension << endl;
EV << "frameBursting: " << frameBursting << endl;
EV << "slotTime: " << slotTime << endl;
EV << "interFrameGap: " << interFrameGap << endl;
EV << endl;
#endif
}
void Adapter_PLC_Base::processFrameFromUpperLayer(PlcFrame *frame)
{
if (COMMENTS_ON) EV << "Received frame from upper layer: " << frame << endl;
if (frame->getDest().equals(address))
{
error("logic error: frame %s from higher layer has local MAC address as dest (%s)",
frame->getFullName(), frame->getDest().str().c_str());
}
if (frame->getByteLength() > MAX_PLC_FRAME)
error("packet from higher layer (%d bytes) exceeds maximum PLC frame size (%d)", frame->getByteLength(), MAX_PLC_FRAME);
// must be PlcFrame (or PlcPauseFrame) from upper layer
bool isPauseFrame = (dynamic_cast<PlcPauseFrame*>(frame)!=NULL);
if (!isPauseFrame)
{
numFramesFromHL++;
if (txQueueLimit && txQueue.length()>txQueueLimit)
error("txQueue length exceeds %d -- this is probably due to "
"a bogus app model generating excessive traffic "
"(or if this is normal, increase txQueueLimit!)",
txQueueLimit);
// fill in src address if not set
if (frame->getSrc().isUnspecified())
frame->setSrc(address);
// store frame and possibly begin transmitting
if (COMMENTS_ON) EV << "Packet " << frame << " arrived from higher layers, enqueueing\n";
txQueue.insert(frame);
}
else
{
if (COMMENTS_ON) EV << "PAUSE received from higher layer\n";
// PAUSE frames enjoy priority -- they're transmitted before all other frames queued up
if (!txQueue.empty())
txQueue.insertBefore(txQueue.front(), frame); // front() frame is probably being transmitted
else
txQueue.insert(frame);
}
}
void Adapter_PLC_Base::processMsgFromNetwork(cPacket *frame)
{
if (COMMENTS_ON) EV << "Received frame from network: " << frame << endl;
// frame must be PlcFrame or PlcJam
if (dynamic_cast<PlcFrame*>(frame)==NULL && dynamic_cast<PlcJam*>(frame)==NULL)
error("message with unexpected message class '%s' arrived from network (name='%s')",
frame->getClassName(), frame->getFullName());
// detect cable length violation in half-duplex mode
if (!duplexMode && simTime()-frame->getSendingTime()>=shortestFrameDuration)
error("very long frame propagation time detected, maybe cable exceeds maximum allowed length? "
"(%lgs corresponds to an approx. %lgm cable)",
SIMTIME_STR(simTime() - frame->getSendingTime()),
SIMTIME_STR((simTime() - frame->getSendingTime())*SPEED_OF_LIGHT));
}
void Adapter_PLC_Base::frameReceptionComplete(PlcFrame *frame)
{
int pauseUnits;
PlcPauseFrame *pauseFrame;
if ((pauseFrame=dynamic_cast<PlcPauseFrame*>(frame))!=NULL)
{
pauseUnits = pauseFrame->getPauseTime();
delete frame;
numPauseFramesRcvd++;
// numPauseFramesRcvdVector.record(numPauseFramesRcvd);
processPauseCommand(pauseUnits);
}
else
{
processReceivedDataFrame((PlcFrame *)frame);
}
}
void Adapter_PLC_Base::processReceivedDataFrame(PlcFrame *frame)
{
// bit errors
if (frame->hasBitError())
{
numDroppedBitError++;
// numDroppedBitErrorVector.record(numDroppedBitError);
delete frame;
return;
}
// strip preamble and SFD
frame->addByteLength(-PREAMBLE_BYTES-SFD_BYTES);
// statistics
numFramesReceivedOK++;
numBytesReceivedOK += frame->getByteLength();
// numFramesReceivedOKVector.record(numFramesReceivedOK);
// numBytesReceivedOKVector.record(numBytesReceivedOK);
if (!checkDestinationAddress(frame))
return;
numFramesPassedToHL++;
// numFramesPassedToHLVector.record(numFramesPassedToHL);
// pass up to upper layer
send(frame, "upperLayerOut");
}
void Adapter_PLC_Base::processPauseCommand(int pauseUnits)
{
if (transmitState==TX_IDLE_STATE)
{
if (COMMENTS_ON) EV << "PAUSE frame received, pausing for " << pauseUnitsRequested << " time units\n";
if (pauseUnits>0)
scheduleEndPausePeriod(pauseUnits);
}
else if (transmitState==PAUSE_STATE)
{
if (COMMENTS_ON) EV << "PAUSE frame received, pausing for " << pauseUnitsRequested << " more time units from now\n";
cancelEvent(endPauseMsg);
if (pauseUnits>0)
scheduleEndPausePeriod(pauseUnits);
}
else
{
// transmitter busy -- wait until it finishes with current frame (endTx)
// and then it'll go to PAUSE state
if (COMMENTS_ON) EV << "PAUSE frame received, storing pause request\n";
pauseUnitsRequested = pauseUnits;
}
}
void Adapter_PLC_Base::handleEndIFGPeriod()
{
if (transmitState!=WAIT_IFG_STATE)
error("Not in WAIT_IFG_STATE at the end of IFG period");
if (txQueue.empty())
error("End of IFG and no frame to transmit");
// End of IFG period, okay to transmit, if Rx idle OR duplexMode
cPacket *frame = (cPacket *)txQueue.front();
if (COMMENTS_ON) EV << "IFG elapsed, now begin transmission of frame " << frame << endl;
// CHANGE ----------------------------------------------------------------------------
// We skip carrier extension, because there is no for plc communications
/*
// Perform carrier extension if in Gigabit PLC
if (carrierExtension && frame->getByteLength() < GIGABIT_MIN_FRAME_WITH_EXT)
{
EV << "Performing carrier extension of small frame\n";
frame->setByteLength(GIGABIT_MIN_FRAME_WITH_EXT);
}
*/
// -----------------------------------------------------------------------------------
// start frame burst, if enabled
if (frameBursting)
{
if (COMMENTS_ON) EV << "Starting frame burst\n";
framesSentInBurst = 0;
bytesSentInBurst = 0;
}
}
void Adapter_PLC_Base::handleEndTxPeriod()
{
// we only get here if transmission has finished successfully, without collision
if (transmitState!=TRANSMITTING_STATE || (!duplexMode && receiveState!=RX_IDLE_STATE))
error("End of transmission, and incorrect state detected");
if (txQueue.empty())
error("Frame under transmission cannot be found");
// get frame from buffer
cPacket *frame = (cPacket *)txQueue.pop();
numFramesSent++;
numBytesSent += frame->getByteLength();
// numFramesSentVector.record(numFramesSent);
// numBytesSentVector.record(numBytesSent);
if (dynamic_cast<PlcPauseFrame*>(frame)!=NULL)
{
numPauseFramesSent++;
// numPauseFramesSentVector.record(numPauseFramesSent);
}
if (COMMENTS_ON) EV << "Transmission of " << frame << " successfully completed\n";
delete frame;
}
void Adapter_PLC_Base::handleEndPausePeriod()
{
if (transmitState != PAUSE_STATE)
error("At end of PAUSE not in PAUSE_STATE!");
if (COMMENTS_ON) EV << "Pause finished, resuming transmissions\n";
beginSendFrames();
}
void Adapter_PLC_Base::processMessageWhenNotConnected(cMessage *msg)
{
if (COMMENTS_ON) EV << "Interface is not connected -- dropping packet " << msg << endl;
delete msg;
numDroppedIfaceDown++;
}
void Adapter_PLC_Base::processMessageWhenDisabled(cMessage *msg)
{
if (COMMENTS_ON) EV << "MAC is disabled -- dropping message " << msg << endl;
delete msg;
}
void Adapter_PLC_Base::scheduleEndIFGPeriod()
{
// CHANGE ------------------------------------------------------------------------------
/*
Anders als bei CSMA/CD (Ethernet) wird bei PLC CSMA/CA angewendet. Hierzu wird zu der
"normalen" Wartezeit nach der Feststellung, dass das Medium nicht belegt ist, eine
zufaellige zusaetzliche Wartezeit addiert, die ein Vielfaches von 1.28 us ist (dieser
Wert konnte beim Modemhersteller devolo erfragt werden).
Hierdurch werden Kollisionen noch unwahrscheinlicher, da nach Freigabe nicht alle
Modems mit Sendewunsch gleichzeitig versuchen, das Medium zu belegen.
*/
// For CSMA/CA, we have to add a random selected additional wait time
int gap = CSMA_CA_MAX_ADDITIONAL_WAIT_TIME;
int x = rand()%10;
x = x * gap;
simtime_t additional_wait_time = (simtime_t) x/1000;
if (COMMENTS_ON) EV << "End of IFG period is scheduled at t=" << simTime()+interFrameGap +additional_wait_time << "." << endl;
// -------------------------------------------------------------------------------------
scheduleAt(simTime()+interFrameGap +additional_wait_time, endIFGMsg);
transmitState = WAIT_IFG_STATE;
}
// CHANGE ------------------------------------------------------------------------------
void Adapter_PLC_Base::scheduleEndIFGPeriod(int priority)
/*
Um trotz des durch CSMA/CA etwas zufaelligerem Mediumzugriff noch zu gewaehrleisten, das
wichtige Informationen zur Aufrechterhaltung der Verbindungen gegenueber einfachem
Datenverkehr bevorzugt werden, gibt es nach jeder Mediumsfreigabe die "Priority resolution
period". In vier Stufen erhalten zunaechst die Modems mit wichtigen Frames den Vorzug.
Die Periode wird dazu in 4 Teilabschnitte geteilt, und die durch CSMA/CA erweiterte
Wartezeit wird innerhalb der Fenster aufgeloest.
[----------------------------- Priority resolution period ------------------------------------]
t-> [Window 1 - Priority 4] [Window 2 - Priority 3] [Window 3 - Priority 2] [Window 4 - Priority 1]
*/
{
if (COMMENTS_ON) EV << "Scheduling end of IFG period ..." << endl;
if (COMMENTS_ON) EV << "Priority based traffic detected. Priority is " << priority << "." << endl;
// the higher the priority, the faster the channel access
double whole_period = PRIORITY_RESOLUTION_PERIOD;
if (COMMENTS_ON) EV << "Whole priority resolution period: " << whole_period << " micro sec" << endl;
double quarter_period = whole_period/4;
if (COMMENTS_ON) EV << "Quarter of the priority resolution period: " << quarter_period << " micro sec" << endl;
double basic_priority_period = whole_period - (priority * quarter_period);
if (COMMENTS_ON) EV << "Basic priority period for a priority of " << priority << " is: " << basic_priority_period << " micro sec" << endl;
double fluctuation = quarter_period * 0.9; // 16,12 us
if (COMMENTS_ON) EV << "The fluctuations are at maximum: " << fluctuation << " micro sec" << endl;
// For CSMA/CA, we have to add a random selected additional wait time
int gap = CSMA_CA_MAX_ADDITIONAL_WAIT_TIME;
int int_k = rand()%11; // 0 us to 14,08 us
if (COMMENTS_ON) EV << "Diceroll resulted in " << int_k << "." << endl;
double m = fluctuation - (int_k * gap);
double x = (m+basic_priority_period)/1000000;
simtime_t priority_wait_time = (simtime_t) x; // us
if (COMMENTS_ON) EV << "This time, the priority based additional wait time is calculated to: " << priority_wait_time * 1000000 << " micro sec" << endl;
simtime_t complete_wait_time = interFrameGap+priority_wait_time;
if (COMMENTS_ON) EV << "End of IFG period is scheduled at t=" << simTime()+complete_wait_time << " micro sec." << endl << endl;
scheduleAt(simTime()+complete_wait_time, endIFGMsg);
transmitState = WAIT_IFG_STATE;
}
// -------------------------------------------------------------------------------------
void Adapter_PLC_Base::scheduleEndTxPeriod(cPacket *frame)
{
scheduleAt(simTime()+frame->getBitLength()*bitTime, endTxMsg);
transmitState = TRANSMITTING_STATE;
}
void Adapter_PLC_Base::scheduleEndPausePeriod(int pauseUnits)
{
// length is interpreted as 512-bit-time units
simtime_t pausePeriod = pauseUnits*PAUSE_BITTIME*bitTime;
scheduleAt(simTime()+pausePeriod, endPauseMsg);
transmitState = PAUSE_STATE;
}
bool Adapter_PLC_Base::checkAndScheduleEndPausePeriod()
{
if (pauseUnitsRequested>0)
{
// if we received a PAUSE frame recently, go into PAUSE state
if (COMMENTS_ON) EV << "Going to PAUSE mode for " << pauseUnitsRequested << " time units\n";
scheduleEndPausePeriod(pauseUnitsRequested);
pauseUnitsRequested = 0;
return true;
}
return false;
}
void Adapter_PLC_Base::beginSendFrames()
{
if (!txQueue.empty())
{
// Other frames are queued, therefore wait IFG period and transmit next frame
if (COMMENTS_ON) EV << "Transmit next frame in output queue, after IFG period\n";
scheduleEndIFGPeriod();
}
else
{
transmitState = TX_IDLE_STATE;
if (queueModule)
{
// tell queue module that we've become idle
if (COMMENTS_ON) EV << "Requesting another frame from queue module\n";
queueModule->requestPacket();
}
else
{
// No more frames set transmitter to idle
if (COMMENTS_ON) EV << "No more frames to send, transmitter set to idle\n";
}
}
}
void Adapter_PLC_Base::fireChangeNotification(int type, cPacket *msg)
{
if (nb) {
notifDetails.setPacket(msg);
nb->fireChangeNotification(type, ¬ifDetails);
}
}
void Adapter_PLC_Base::finish()
{
/*
if (!disabled)
{
simtime_t t = simTime();
recordScalar("simulated time", t);
recordScalar("txrate (Mb)", txrate/1000000);
recordScalar("full duplex", duplexMode);
recordScalar("frames sent", numFramesSent);
recordScalar("frames rcvd", numFramesReceivedOK);
recordScalar("bytes sent", numBytesSent);
recordScalar("bytes rcvd", numBytesReceivedOK);
recordScalar("frames from higher layer", numFramesFromHL);
recordScalar("frames from higher layer dropped (iface down)", numDroppedIfaceDown);
recordScalar("frames dropped (bit error)", numDroppedBitError);
recordScalar("frames dropped (not for us)", numDroppedNotForUs);
recordScalar("frames passed up to HL", numFramesPassedToHL);
recordScalar("PAUSE frames sent", numPauseFramesSent);
recordScalar("PAUSE frames rcvd", numPauseFramesRcvd);
if (t>0)
{
recordScalar("frames/sec sent", numFramesSent/t);
recordScalar("frames/sec rcvd", numFramesReceivedOK/t);
recordScalar("bits/sec sent", 8*numBytesSent/t);
recordScalar("bits/sec rcvd", 8*numBytesReceivedOK/t);
}
}
*/
}
void Adapter_PLC_Base::updateDisplayString()
{
// icon coloring
const char *color;
if (receiveState==RX_COLLISION_STATE)
color = "red";
else if (transmitState==TRANSMITTING_STATE)
color = "yellow";
else if (transmitState==JAMMING_STATE)
color = "red";
else if (receiveState==RECEIVING_STATE)
color = "#4040ff";
else if (transmitState==BACKOFF_STATE)
color = "white";
else if (transmitState==PAUSE_STATE)
color = "gray";
else
color = "";
getDisplayString().setTagArg("i",1,color);
if (!strcmp(getParentModule()->getClassName(),"PLCInterface"))
getParentModule()->getDisplayString().setTagArg("i",1,color);
// connection coloring
updateConnectionColor(transmitState);
#if 0
// this code works but didn't turn out to be very useful
const char *txStateName;
switch (transmitState) {
case TX_IDLE_STATE: txStateName="IDLE"; break;
case WAIT_IFG_STATE: txStateName="WAIT_IFG"; break;
case TRANSMITTING_STATE: txStateName="TX"; break;
case JAMMING_STATE: txStateName="JAM"; break;
case BACKOFF_STATE: txStateName="BACKOFF"; break;
case PAUSE_STATE: txStateName="PAUSE"; break;
default: error("wrong tx state");
}
const char *rxStateName;
switch (receiveState) {
case RX_IDLE_STATE: rxStateName="IDLE"; break;
case RECEIVING_STATE: rxStateName="RX"; break;
case RX_COLLISION_STATE: rxStateName="COLL"; break;
default: error("wrong rx state");
}
char buf[80];
sprintf(buf, "tx:%s rx: %s\n#boff:%d #cTx:%d",
txStateName, rxStateName, backoffs, numConcurrentTransmissions);
getDisplayString().setTagArg("t",0,buf);
#endif
}
void Adapter_PLC_Base::updateConnectionColor(int txState)
{
const char *color;
if (txState==TRANSMITTING_STATE)
color = "yellow";
else if (txState==JAMMING_STATE || txState==BACKOFF_STATE)
color = "red";
else
color = "";
cGate *g = physOutGate;
while (g && g->getType()==cGate::OUTPUT)
{
g->getDisplayString().setTagArg("o",0,color);
g->getDisplayString().setTagArg("o",1, color[0] ? "3" : "1");
g = g->getNextGate();
}
}
void Adapter_PLC_Base::receiveChangeNotification(int category, const cPolymorphic *)
{
if (category==NF_SUBSCRIBERLIST_CHANGED)
updateHasSubcribers();
}
| hoferr/SG_OMNeTpp | plc/src/Adapter_PLC_Base.cc | C++ | gpl-3.0 | 28,190 |
<?php
/*
##########################################################################
# #
# Version 4 / / / #
# -----------__---/__---__------__----__---/---/- #
# | /| / /___) / ) (_ ` / ) /___) / / #
# _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ #
# Free Content / Management System #
# / #
# #
# #
# Copyright 2005-2015 by webspell.org #
# #
# visit webSPELL.org, webspell.info to get webSPELL for free #
# - Script runs under the GNU GENERAL PUBLIC LICENSE #
# - It's NOT allowed to remove this copyright-tag #
# -- http://www.fsf.org/licensing/licenses/gpl.html #
# #
# Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), #
# Far Development by Development Team - webspell.org #
# #
# visit webspell.org #
# #
##########################################################################
*/
$language_array = Array(
/* do not edit above this line */
'access_denied'=>'Hyrja e Ndaluar',
'add_rank'=>'shtoni Renditjen',
'actions'=>'Veprimet',
'delete'=>'fshij',
'edit_rank'=>'edito Renditjen',
'information_incomplete'=>'Disa të dhëna mungojnë.',
'max_posts'=>'max. Postimet',
'min_posts'=>'min. Postimet',
'new_rank'=>'Renditja e re',
'rank_icon'=>'Renditja Ikon-ave',
'rank_name'=>'Renditja Emri',
'really_delete'=>'Vërtet e fshini këtë Lidhje?',
'transaction_invalid'=>'ID e tranzaksionit e pavlefshme',
'update'=>'përditësim',
'user_ranks'=>'Renditja Përdoruesve'
);
| nerdiabet/webSPELL | languages/sq/admin/ranks.php | PHP | gpl-3.0 | 2,358 |
/**
* Copyright (C) 2015 Envidatec GmbH <info@envidatec.com>
*
* This file is part of JECommons.
*
* JECommons 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 in version 3.
*
* JECommons 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
* JECommons. If not, see <http://www.gnu.org/licenses/>.
*
* JECommons is part of the OpenJEVis project, further project information are
* published at <http://www.OpenJEVis.org/>.
*/
package org.jevis.commons.dataprocessing.v2;
import java.util.List;
/**
*
* @author Florian Simon
*/
public interface Task {
void setDataProcessor(Function dp);
Function getDataProcessor();
void setDependency(List<Task> dps);
List<Task> getDependency();
Result getResult();
}
| AIT-JEVis/JECommons | src/main/java/org/jevis/commons/dataprocessing/v2/Task.java | Java | gpl-3.0 | 1,111 |
## roster_nb.py
## based on roster.py
##
## Copyright (C) 2003-2005 Alexey "Snake" Nezhdanov
## modified by Dimitur Kirov <dkirov@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, 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.
# $Id: roster.py,v 1.17 2005/05/02 08:38:49 snakeru Exp $
"""
Simple roster implementation. Can be used though for different tasks like
mass-renaming of contacts.
"""
from protocol import JID, Iq, Presence, Node, NodeProcessed, NS_MUC_USER, NS_ROSTER
from plugin import PlugIn
import logging
log = logging.getLogger('nbxmpp.roster_nb')
class NonBlockingRoster(PlugIn):
"""
Defines a plenty of methods that will allow you to manage roster. Also
automatically track presences from remote JIDs taking into account that
every JID can have multiple resources connected. Does not currently support
'error' presences. You can also use mapping interface for access to the
internal representation of contacts in roster
"""
def __init__(self, version=None):
"""
Init internal variables
"""
PlugIn.__init__(self)
self.version = version
self._data = {}
self._set=None
self._exported_methods=[self.getRoster]
self.received_from_server = False
def Request(self, force=0):
"""
Request roster from server if it were not yet requested (or if the
'force' argument is set)
"""
if self._set is None:
self._set = 0
elif not force:
return
iq = Iq('get', NS_ROSTER)
if self.version is not None:
iq.setTagAttr('query', 'ver', self.version)
id_ = self._owner.getAnID()
iq.setID(id_)
self._owner.send(iq)
log.info('Roster requested from server')
return id_
def RosterIqHandler(self, dis, stanza):
"""
Subscription tracker. Used internally for setting items state in internal
roster representation
"""
sender = stanza.getAttr('from')
if not sender is None and not sender.bareMatch(
self._owner.User + '@' + self._owner.Server):
return
query = stanza.getTag('query')
if query:
self.received_from_server = True
self.version = stanza.getTagAttr('query', 'ver')
if self.version is None:
self.version = ''
for item in query.getTags('item'):
jid=item.getAttr('jid')
if item.getAttr('subscription')=='remove':
if self._data.has_key(jid): del self._data[jid]
# Looks like we have a workaround
# raise NodeProcessed # a MUST
log.info('Setting roster item %s...' % jid)
if not self._data.has_key(jid): self._data[jid]={}
self._data[jid]['name']=item.getAttr('name')
self._data[jid]['ask']=item.getAttr('ask')
self._data[jid]['subscription']=item.getAttr('subscription')
self._data[jid]['groups']=[]
if not self._data[jid].has_key('resources'): self._data[jid]['resources']={}
for group in item.getTags('group'):
if group.getData() not in self._data[jid]['groups']:
self._data[jid]['groups'].append(group.getData())
self._data[self._owner.User+'@'+self._owner.Server]={'resources': {}, 'name': None, 'ask': None, 'subscription': None, 'groups': None,}
self._set=1
# Looks like we have a workaround
# raise NodeProcessed # a MUST. Otherwise you'll get back an <iq type='error'/>
def PresenceHandler(self, dis, pres):
"""
Presence tracker. Used internally for setting items' resources state in
internal roster representation
"""
if pres.getTag('x', namespace=NS_MUC_USER):
return
jid=pres.getFrom()
if not jid:
# If no from attribue, it's from server
jid=self._owner.Server
jid=JID(jid)
if not self._data.has_key(jid.getStripped()): self._data[jid.getStripped()]={'name':None,'ask':None,'subscription':'none','groups':['Not in roster'],'resources':{}}
if type(self._data[jid.getStripped()]['resources'])!=type(dict()):
self._data[jid.getStripped()]['resources']={}
item=self._data[jid.getStripped()]
typ=pres.getType()
if not typ:
log.info('Setting roster item %s for resource %s...'%(jid.getStripped(), jid.getResource()))
item['resources'][jid.getResource()]=res={'show':None,'status':None,'priority':'0','timestamp':None}
if pres.getTag('show'): res['show']=pres.getShow()
if pres.getTag('status'): res['status']=pres.getStatus()
if pres.getTag('priority'): res['priority']=pres.getPriority()
if not pres.getTimestamp(): pres.setTimestamp()
res['timestamp']=pres.getTimestamp()
elif typ=='unavailable' and item['resources'].has_key(jid.getResource()): del item['resources'][jid.getResource()]
# Need to handle type='error' also
def _getItemData(self, jid, dataname):
"""
Return specific jid's representation in internal format. Used internally
"""
jid = jid[:(jid+'/').find('/')]
return self._data[jid][dataname]
def _getResourceData(self, jid, dataname):
"""
Return specific jid's resource representation in internal format. Used
internally
"""
if jid.find('/') + 1:
jid, resource = jid.split('/', 1)
if self._data[jid]['resources'].has_key(resource):
return self._data[jid]['resources'][resource][dataname]
elif self._data[jid]['resources'].keys():
lastpri = -129
for r in self._data[jid]['resources'].keys():
if int(self._data[jid]['resources'][r]['priority']) > lastpri:
resource, lastpri=r, int(self._data[jid]['resources'][r]['priority'])
return self._data[jid]['resources'][resource][dataname]
def delItem(self, jid):
"""
Delete contact 'jid' from roster
"""
self._owner.send(Iq('set', NS_ROSTER, payload=[Node('item', {'jid': jid, 'subscription': 'remove'})]))
def getAsk(self, jid):
"""
Return 'ask' value of contact 'jid'
"""
return self._getItemData(jid, 'ask')
def getGroups(self, jid):
"""
Return groups list that contact 'jid' belongs to
"""
return self._getItemData(jid, 'groups')
def getName(self, jid):
"""
Return name of contact 'jid'
"""
return self._getItemData(jid, 'name')
def getPriority(self, jid):
"""
Return priority of contact 'jid'. 'jid' should be a full (not bare) JID
"""
return self._getResourceData(jid, 'priority')
def getRawRoster(self):
"""
Return roster representation in internal format
"""
return self._data
def getRawItem(self, jid):
"""
Return roster item 'jid' representation in internal format
"""
return self._data[jid[:(jid+'/').find('/')]]
def getShow(self, jid):
"""
Return 'show' value of contact 'jid'. 'jid' should be a full (not bare)
JID
"""
return self._getResourceData(jid, 'show')
def getStatus(self, jid):
"""
Return 'status' value of contact 'jid'. 'jid' should be a full (not bare)
JID
"""
return self._getResourceData(jid, 'status')
def getSubscription(self, jid):
"""
Return 'subscription' value of contact 'jid'
"""
return self._getItemData(jid, 'subscription')
def getResources(self, jid):
"""
Return list of connected resources of contact 'jid'
"""
return self._data[jid[:(jid+'/').find('/')]]['resources'].keys()
def setItem(self, jid, name=None, groups=[]):
"""
Rename contact 'jid' and sets the groups list that it now belongs to
"""
iq = Iq('set', NS_ROSTER)
query = iq.getTag('query')
attrs = {'jid': jid}
if name:
attrs['name'] = name
item = query.setTag('item', attrs)
for group in groups:
item.addChild(node=Node('group', payload=[group]))
self._owner.send(iq)
def setItemMulti(self, items):
"""
Rename multiple contacts and sets their group lists
"""
iq = Iq('set', NS_ROSTER)
query = iq.getTag('query')
for i in items:
attrs = {'jid': i['jid']}
if i['name']:
attrs['name'] = i['name']
item = query.setTag('item', attrs)
for group in i['groups']:
item.addChild(node=Node('group', payload=[group]))
self._owner.send(iq)
def getItems(self):
"""
Return list of all [bare] JIDs that the roster is currently tracks
"""
return self._data.keys()
def keys(self):
"""
Same as getItems. Provided for the sake of dictionary interface
"""
return self._data.keys()
def __getitem__(self, item):
"""
Get the contact in the internal format. Raises KeyError if JID 'item' is
not in roster
"""
return self._data[item]
def getItem(self, item):
"""
Get the contact in the internal format (or None if JID 'item' is not in
roster)
"""
if self._data.has_key(item):
return self._data[item]
def Subscribe(self, jid):
"""
Send subscription request to JID 'jid'
"""
self._owner.send(Presence(jid, 'subscribe'))
def Unsubscribe(self, jid):
"""
Ask for removing our subscription for JID 'jid'
"""
self._owner.send(Presence(jid, 'unsubscribe'))
def Authorize(self, jid):
"""
Authorize JID 'jid'. Works only if these JID requested auth previously
"""
self._owner.send(Presence(jid, 'subscribed'))
def Unauthorize(self, jid):
"""
Unauthorise JID 'jid'. Use for declining authorisation request or for
removing existing authorization
"""
self._owner.send(Presence(jid, 'unsubscribed'))
def getRaw(self):
"""
Return the internal data representation of the roster
"""
return self._data
def setRaw(self, data):
"""
Return the internal data representation of the roster
"""
self._data = data
self._data[self._owner.User + '@' + self._owner.Server] = {
'resources': {},
'name': None,
'ask': None,
'subscription': None,
'groups': None
}
self._set = 1
def plugin(self, owner, request=1):
"""
Register presence and subscription trackers in the owner's dispatcher.
Also request roster from server if the 'request' argument is set. Used
internally
"""
self._owner.RegisterHandler('iq', self.RosterIqHandler, 'result', NS_ROSTER, makefirst = 1)
self._owner.RegisterHandler('iq', self.RosterIqHandler, 'set', NS_ROSTER)
self._owner.RegisterHandler('presence', self.PresenceHandler)
if request:
return self.Request()
def _on_roster_set(self, data):
if data:
self._owner.Dispatcher.ProcessNonBlocking(data)
if not self._set:
return
if not hasattr(self, '_owner') or not self._owner:
# Connection has been closed by receiving a <stream:error> for ex,
return
self._owner.onreceive(None)
if self.on_ready:
self.on_ready(self)
self.on_ready = None
return True
def getRoster(self, on_ready=None, force=False):
"""
Request roster from server if neccessary and returns self
"""
return_self = True
if not self._set:
self.on_ready = on_ready
self._owner.onreceive(self._on_roster_set)
return_self = False
elif on_ready:
on_ready(self)
return_self = False
if return_self or force:
return self
return None
| 9thSenseRobotics/bosh_server | nbxmpp-0.1/nbxmpp/roster_nb.py | Python | gpl-3.0 | 13,001 |
using System.IO;
using System.Text;
using Microsoft.WindowsAzure.Storage.Blob;
namespace ScrewTurn.Wiki.Plugins.AzureStorage
{
/// <summary>
///
/// </summary>
public static class CloudBlobExtensions
{
/// <summary>
/// Uploads a string of text to a block blob.
/// </summary>
/// <param name="blob"></param>
/// <param name="content">The text to upload, encoded as a UTF-8 string.</param>
public static void UploadText(this ICloudBlob blob, string content)
{
UploadText(blob, content, Encoding.UTF8, null);
}
/// <summary>
/// Uploads a string of text to a block blob.
/// </summary>
/// <param name="blob"></param>
/// <param name="content">The text to upload.</param>
/// <param name="encoding">An object that indicates the text encoding to use.</param>
/// <param name="options">An object that specifies any additional options for the request.</param>
public static void UploadText(this ICloudBlob blob, string content, Encoding encoding, BlobRequestOptions options)
{
UploadByteArray(blob, encoding.GetBytes(content), options);
}
/// <summary>
/// Uploads a file from the file system to a block blob.
/// </summary>
/// <param name="blob"></param>
/// <param name="fileName">The path and file name of the file to upload.</param>
public static void UploadFile(this ICloudBlob blob, string fileName)
{
UploadFile(blob, fileName, null);
}
/// <summary>
/// Uploads a file from the file system to a block blob.
/// </summary>
/// <param name="blob"></param>
/// <param name="fileName">The path and file name of the file to upload.</param>
/// <param name="options">An object that specifies any additional options for the request.</param>
public static void UploadFile(this ICloudBlob blob, string fileName, BlobRequestOptions options)
{
using (var data = File.OpenRead(fileName))
{
blob.UploadFromStream(data, null, options);
}
}
/// <summary>
/// Uploads an array of bytes to a block blob.
/// </summary>
/// <param name="blob"></param>
/// <param name="content">The array of bytes to upload.</param>
public static void UploadByteArray(this ICloudBlob blob, byte[] content)
{
UploadByteArray(blob, content, null);
}
/// <summary>
/// Uploads an array of bytes to a blob.
/// </summary>
/// <param name="blob"></param>
/// <param name="content">The array of bytes to upload.</param>
/// <param name="options">An object that specifies any additional options for the request.</param>
public static void UploadByteArray(this ICloudBlob blob, byte[] content, BlobRequestOptions options)
{
using (var data = new MemoryStream(content))
{
blob.UploadFromStream(data, null, options);
}
}
/// <summary>
/// Downloads the blob's contents.
/// </summary>
/// <returns>The contents of the blob, as a string.</returns>
public static string DownloadText(this ICloudBlob blob)
{
return DownloadText(blob, null);
}
/// <summary>
/// Downloads the blob's contents.
/// </summary>
/// <param name="blob"></param>
/// <param name="options">An object that specifies any additional options for the request.</param>
/// <returns>The contents of the blob, as a string.</returns>
public static string DownloadText(this ICloudBlob blob, BlobRequestOptions options)
{
Encoding encoding = GetDefaultEncoding();
byte[] array = DownloadByteArray(blob, options);
return encoding.GetString(array);
}
/// <summary>
/// Downloads the blob's contents to a file.
/// </summary>
/// <param name="blob"></param>
/// <param name="fileName">The path and file name of the target file.</param>
public static void DownloadToFile(this ICloudBlob blob, string fileName)
{
DownloadToFile(blob, fileName, null);
}
/// <summary>
/// Downloads the blob's contents to a file.
/// </summary>
/// <param name="blob"></param>
/// <param name="fileName">The path and file name of the target file.</param>
/// <param name="options">An object that specifies any additional options for the request.</param>
public static void DownloadToFile(this ICloudBlob blob, string fileName, BlobRequestOptions options)
{
using (var fileStream = File.Create(fileName))
{
blob.DownloadToStream(fileStream, null, options);
}
}
/// <summary>
/// Downloads the blob's contents as an array of bytes.
/// </summary>
/// <returns>The contents of the blob, as an array of bytes.</returns>
public static byte[] DownloadByteArray(this ICloudBlob blob)
{
return DownloadByteArray(blob, null);
}
/// <summary>
/// Downloads the blob's contents as an array of bytes.
/// </summary>
/// <param name="blob"></param>
/// <param name="options">An object that specifies any additional options for the request.</param>
/// <returns>The contents of the blob, as an array of bytes.</returns>
public static byte[] DownloadByteArray(this ICloudBlob blob, BlobRequestOptions options)
{
using (var memoryStream = new MemoryStream())
{
blob.DownloadToStream(memoryStream, null, options);
return memoryStream.ToArray();
}
}
/// <summary>
/// Gets the default encoding for the blob, which is UTF-8.
/// </summary>
/// <returns>The default <see cref="Encoding"/> object.</returns>
private static Encoding GetDefaultEncoding()
{
Encoding encoding = Encoding.UTF8;
return encoding;
}
}
}
| Askanio/STW6 | ScrewTurnWiki.AzureStorageProviders/CloudBlobExtensions.cs | C# | gpl-3.0 | 6,370 |
<?php
/**
* The view model to store the state of an ajax request/response in JSON objects.
*
* @author Jeremie Litzler
* @copyright Copyright (c) 2015
* @licence http://opensource.org/licenses/gpl-license.php GNU Public License
* @link https://github.com/WebDevJL/EasyMvc
* @since Version 1.0.0
* @package BaseJsonVm
*/
namespace Library\ViewModels;
if (!FrameworkConstants_ExecutionAccessRestriction) {
exit('No direct script access allowed');
}
class BaseJsonVm extends BaseVm {
/**
*
* @var mixed The response to use by the JavaScript Client
*/
protected $Response;
/**
* Getter for $Response member.
*
* @return mixed
* @see $Response member
*/
public function Response() {
return $this->Response;
}
}
| WebDevJL/EasyMVC | Library/ViewModels/BaseJsonVm.php | PHP | gpl-3.0 | 766 |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using ACE.Web.Models.Account;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
namespace ACE.Web.Controllers
{
public class AccountController : Controller
{
[HttpGet]
public ActionResult Login()
{
return View(new LoginModel());
}
[HttpPost]
public ActionResult Login(LoginModel model)
{
if (!ModelState.IsValid)
return View(model);
RestClient authClient = new RestClient(ConfigurationManager.AppSettings["Ace.Api"]);
var authRequest = new RestRequest("/Account/Authenticate", Method.POST);
authRequest.AddJsonBody(new { model.Username, model.Password });
var authResponse = authClient.Execute(authRequest);
if (authResponse.StatusCode == HttpStatusCode.Unauthorized)
{
model.ErrorMessage = "Incorrect Username or Password";
return View(model);
}
else if (authResponse.StatusCode != HttpStatusCode.OK)
{
model.ErrorMessage = "Error connecting to API";
return View(model);
}
// else we got an OK response
JObject response = JObject.Parse(authResponse.Content);
var authToken = (string)response.SelectToken("authToken");
if (!string.IsNullOrWhiteSpace(authToken))
{
JwtCookieManager.SetCookie(authToken);
return RedirectToAction("Index", "Home", null);
}
return View(model);
}
[HttpGet]
public ActionResult LogOff()
{
JwtCookieManager.SignOut();
return RedirectToAction("Index", "Home", null);
}
[HttpGet]
public ActionResult Register()
{
return View(new RegisterModel());
}
[HttpPost]
public ActionResult Register(RegisterModel model)
{
// create the user
return View();
}
}
} | fantoms/ACE | Source/ACE.Web/Controllers/AccountController.cs | C# | gpl-3.0 | 2,291 |
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils.translation import ugettext as _
from .models import AbuseReport, SearchTermRecord
admin.site.register(AbuseReport)
class SearchTermAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'ip_address', 'get_user_full_name', )
search_fields = ('term', )
def get_user_full_name(self, obj):
if obj.user is None:
return "(%s)" % _(u"None")
return obj.user.get_full_name()
get_user_full_name.short_description = "user"
admin.site.register(SearchTermRecord, SearchTermAdmin)
| piotrek-golda/CivilHubIndependantCopy | places_core/admin.py | Python | gpl-3.0 | 596 |
"""
================================================================================
Logscaled Histogram
================================================================================
| Calculates a logarithmically spaced histogram for a data map.
| Written By: Matthew Stadelman
| Date Written: 2016/03/07
| Last Modifed: 2016/10/20
"""
import scipy as sp
from .histogram import Histogram
class HistogramLogscale(Histogram):
r"""
Performs a histogram where the bin limits are logarithmically spaced
based on the supplied scale factor. If there are negative values then
the first bin contains everything below 0, the next bin will contain
everything between 0 and 1.
kwargs include:
scale_fact - numeric value to generate axis scale for bins. A
scale fact of 10 creates bins: 0-1, 1-10, 10-100, etc.
"""
def __init__(self, field, **kwargs):
super().__init__(field)
self.args.update(kwargs)
self.output_key = 'hist_logscale'
self.action = 'histogram_logscale'
@classmethod
def _add_subparser(cls, subparsers, parent):
r"""
Adds a specific action based sub-parser to the supplied arg_parser
instance.
"""
parser = subparsers.add_parser(cls.__name__,
aliases=['histlog'],
parents=[parent],
help=cls.__doc__)
#
parser.add_argument('scale_fact', type=float, nargs='?', default=10.0,
help='base to generate logscale from')
parser.set_defaults(func=cls)
def define_bins(self, **kwargs):
r"""
This defines the bins for a logscaled histogram
"""
self.data_vector.sort()
sf = self.args['scale_fact']
num_bins = int(sp.logn(sf, self.data_vector[-1]) + 1)
#
# generating initial bins from 1 - sf**num_bins
low = list(sp.logspace(0, num_bins, num_bins + 1, base=sf))[:-1]
high = list(sp.logspace(0, num_bins, num_bins + 1, base=sf))[1:]
#
# Adding "catch all" bins for anything between 0 - 1 and less than 0
if self.data_vector[0] < 1.0:
low.insert(0, 0.0)
high.insert(0, 1.0)
if self.data_vector[0] < 0.0:
low.insert(0, self.data_vector[0])
high.insert(0, 0.0)
#
self.bins = [bin_ for bin_ in zip(low, high)]
| stadelmanma/netl-ap-map-flow | apmapflow/data_processing/histogram_logscale.py | Python | gpl-3.0 | 2,486 |
#region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.ClearCanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source 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 3 of the
// License, or (at your option) any later version.
//
// The ClearCanvas RIS/PACS open source project 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
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
namespace Macro.Desktop.View.WinForms
{
/// <summary>
/// Enumeration for specifying the style of check boxes displayed on a <see cref="BindingTreeView"/> control.
/// </summary>
public enum CheckBoxStyle
{
/// <summary>
/// Indicates that no check boxes should be displayed at all.
/// </summary>
None,
/// <summary>
/// Indicates that standard true/false check boxes should be displayed.
/// </summary>
Standard,
/// <summary>
/// Indicates that tri-state (true/false/unknown) check boxes should be displayed.
/// </summary>
TriState
}
} | mayioit/MacroMedicalSystem | Desktop/View/WinForms/CheckBoxStyle.cs | C# | gpl-3.0 | 1,515 |
package org.ovirt.engine.core.bll.transport;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.ovirt.engine.core.bll.Backend;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VdsProtocol;
import org.ovirt.engine.core.common.businessentities.VdsStatic;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.interfaces.FutureVDSCall;
import org.ovirt.engine.core.common.vdscommands.FutureVDSCommandType;
import org.ovirt.engine.core.common.vdscommands.TimeBoundPollVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSReturnValue;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.utils.transaction.TransactionMethod;
import org.ovirt.engine.core.utils.transaction.TransactionSupport;
import org.ovirt.engine.core.vdsbroker.ResourceManager;
/**
* We need to detect whether vdsm supports jsonrpc or only xmlrpc. It is confusing to users
* when they have cluster 3.5+ and connect to vdsm <3.5 which supports only xmlrpc.
* In order to present version information in such situation we need fallback to xmlrpc.
*
*/
public class ProtocolDetector {
private Integer connectionTimeout = null;
private Integer retryAttempts = null;
private VDS vds;
public ProtocolDetector(VDS vds) {
this.vds = vds;
this.retryAttempts = Config.<Integer> getValue(ConfigValues.ProtocolFallbackRetries);
this.connectionTimeout = Config.<Integer> getValue(ConfigValues.ProtocolFallbackTimeoutInMilliSeconds);
}
/**
* Attempts to connect to vdsm using a proxy from {@code VdsManager} for a host.
* There are 3 attempts to connect.
*
* @return <code>true</code> if connected or <code>false</code> if connection failed.
*/
public boolean attemptConnection() {
boolean connected = false;
try {
for (int i = 0; i < this.retryAttempts; i++) {
long timeout = Config.<Integer> getValue(ConfigValues.SetupNetworksPollingTimeout);
FutureVDSCall<VDSReturnValue> task =
Backend.getInstance().getResourceManager().runFutureVdsCommand(FutureVDSCommandType.TimeBoundPoll,
new TimeBoundPollVDSCommandParameters(vds.getId(), timeout, TimeUnit.SECONDS));
VDSReturnValue returnValue =
task.get(timeout, TimeUnit.SECONDS);
connected = returnValue.getSucceeded();
if (connected) {
break;
}
Thread.sleep(this.connectionTimeout);
}
} catch (TimeoutException | InterruptedException ignored) {
}
return connected;
}
/**
* Stops {@code VdsManager} for a host.
*/
public void stopConnection() {
ResourceManager.getInstance().RemoveVds(this.vds.getId());
}
/**
* Fall back the protocol and attempts the connection {@link ProtocolDetector#attemptConnection()}.
*
* @return <code>true</code> if connected or <code>false</code> if connection failed.
*/
public boolean attemptFallbackProtocol() {
vds.setProtocol(VdsProtocol.XML);
ResourceManager.getInstance().AddVds(vds, false);
return attemptConnection();
}
/**
* Updates DB with fall back protocol (xmlrpc).
*/
public void setFallbackProtocol() {
final VdsStatic vdsStatic = this.vds.getStaticData();
vdsStatic.setProtocol(VdsProtocol.XML);
TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() {
@Override
public Void runInTransaction() {
DbFacade.getInstance().getVdsStaticDao().update(vdsStatic);
return null;
}
});
}
}
| jtux270/translate | ovirt/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/transport/ProtocolDetector.java | Java | gpl-3.0 | 3,963 |
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Dashboard</div>
<div class="panel-body">
Hello {{Auth::guard('user')->user()->name}}
You are logged in!
{{ Auth()->guard('user')->user()->email }}
</div>
</div>
</div>
</div>
</div>
@endsection
| aneeshsudhakaran/laravel5.3demo | resources/views/frontend/dashboard.blade.php | PHP | gpl-3.0 | 602 |
/*
* This file is part of eduVPN.
*
* eduVPN 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.
*
* eduVPN 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 eduVPN. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.eduvpn.app.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import nl.eduvpn.app.R;
import nl.eduvpn.app.adapter.viewholder.MessageViewHolder;
import nl.eduvpn.app.entity.message.Maintenance;
import nl.eduvpn.app.entity.message.Message;
import nl.eduvpn.app.entity.message.Notification;
import nl.eduvpn.app.utils.FormattingUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Adapter for serving the message views inside a list.
* Created by Daniel Zolnai on 2016-10-19.
*/
public class MessagesAdapter extends RecyclerView.Adapter<MessageViewHolder> {
private List<Message> _userMessages;
private List<Message> _systemMessages;
private List<Message> _mergedList = new ArrayList<>();
private LayoutInflater _layoutInflater;
public void setUserMessages(List<Message> userMessages) {
_userMessages = userMessages;
_regenerateList();
}
public void setSystemMessages(List<Message> systemMessages) {
_systemMessages = systemMessages;
_regenerateList();
}
private void _regenerateList() {
_mergedList.clear();
if (_userMessages != null) {
_mergedList.addAll(_userMessages);
}
if (_systemMessages != null) {
_mergedList.addAll(_systemMessages);
}
Collections.sort(_mergedList);
notifyDataSetChanged();
}
@Override
public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (_layoutInflater == null) {
_layoutInflater = LayoutInflater.from(parent.getContext());
}
return new MessageViewHolder(_layoutInflater.inflate(R.layout.list_item_message, parent, false));
}
@Override
public void onBindViewHolder(MessageViewHolder holder, int position) {
Message message = _mergedList.get(position);
if (message instanceof Maintenance) {
holder.messageIcon.setVisibility(View.VISIBLE);
Context context = holder.messageText.getContext();
String maintenanceText = FormattingUtils.getMaintenanceText(context, (Maintenance)message);
holder.messageText.setText(maintenanceText);
} else if (message instanceof Notification) {
holder.messageIcon.setVisibility(View.GONE);
holder.messageText.setText(((Notification)message).getContent());
} else {
throw new RuntimeException("Unexpected message type!");
}
}
@Override
public int getItemCount() {
return _mergedList.size();
}
}
| dzolnai/android | app/src/main/java/nl/eduvpn/app/adapter/MessagesAdapter.java | Java | gpl-3.0 | 3,444 |
/* This file is part of Jellyfish.
Jellyfish 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.
Jellyfish 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 Jellyfish. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __JELLYFISH_PARSE_DNA_HPP__
#define __JELLYFISH_PARSE_DNA_HPP__
#include <iostream>
#include <vector>
#include <jellyfish/double_fifo_input.hpp>
#include <jellyfish/atomic_gcc.hpp>
#include <jellyfish/misc.hpp>
#include <jellyfish/sequence_parser.hpp>
#include <jellyfish/allocators_mmap.hpp>
#include <jellyfish/dna_codes.hpp>
#include <jellyfish/seedmod/seedmod.hpp>
namespace jellyfish {
class parse_dna : public double_fifo_input<sequence_parser::sequence_t> {
typedef std::vector<const char *> fary_t;
uint_t mer_len;
size_t buffer_size;
const fary_t files;
fary_t::const_iterator current_file;
bool have_seam;
char *seam;
allocators::mmap buffer_data;
bool canonical;
sequence_parser *fparser;
const char *Spaced_seed_cstr;
public:
/* Action to take for a given letter in fasta file:
* A, C, G, T: map to 0, 1, 2, 3. Append to kmer
* Other nucleic acid code: map to -1. reset kmer
* '\n': map to -2. ignore
* Other ASCII: map to -3. Report error.
*/
static uint64_t mer_string_to_binary(const char *in, uint_t klen) {
uint64_t res = 0;
for(uint_t i = 0; i < klen; i++) {
const uint_t c = dna_codes[(uint_t)*in++];
if(c & CODE_NOT_DNA)
return 0;
res = (res << 2) | c;
}
return res;
}
static void mer_binary_to_string(uint64_t mer, uint_t klen, char *out) {
static const char table[4] = { 'A', 'C', 'G', 'T' };
for(unsigned int i = 0 ; i < klen; i++) {
out[klen-1-i] = table[mer & (uint64_t)0x3];
mer >>= 2;
}
out[klen] = '\0';
}
static uint64_t reverse_complement(uint64_t v, uint_t length) {
v = ((v >> 2) & 0x3333333333333333UL) | ((v & 0x3333333333333333UL) << 2);
v = ((v >> 4) & 0x0F0F0F0F0F0F0F0FUL) | ((v & 0x0F0F0F0F0F0F0F0FUL) << 4);
v = ((v >> 8) & 0x00FF00FF00FF00FFUL) | ((v & 0x00FF00FF00FF00FFUL) << 8);
v = ((v >> 16) & 0x0000FFFF0000FFFFUL) | ((v & 0x0000FFFF0000FFFFUL) << 16);
v = ( v >> 32 ) | ( v << 32);
return (((uint64_t)-1) - v) >> (bsizeof(v) - (length << 1));
}
template<typename T>
parse_dna(T _files_start, T _files_end, uint_t _mer_len,
unsigned int nb_buffers, size_t _buffer_size,
const char * seed_cstr);
~parse_dna() {
delete [] seam;
}
void set_canonical(bool v = true) { canonical = v; }
virtual void fill();
class thread {
parse_dna *parser;
bucket_t *sequence;
const uint_t mer_len, lshift;
__uint128_t kmer, rkmer;
const __uint128_t masq;
uint64_t ret_mer;
uint_t cmlen;
const bool canonical;
uint64_t distinct, total;
typedef void (*error_reporter)(std::string& err);
error_reporter error_report;
public:
explicit thread(parse_dna *_parser) :
parser(_parser), sequence(0),
mer_len(_parser->mer_len), lshift(2 * (mer_len - 1)),
kmer(0), rkmer(0), ret_mer(0), masq((~(__uint128_t)(0))^((~(__uint128_t)(0))<<(2*mer_len))),
cmlen(0), canonical(parser->canonical),
distinct(0), total(0), error_report(0) {}
uint64_t get_uniq() const { return 0; }
uint64_t get_distinct() const { return distinct; }
uint64_t get_total() const { return total; }
template<typename T>
void parse(T &counter) {
cmlen = kmer = rkmer = ret_mer = 0;
while((sequence = parser->next())) {
const char *start = sequence->start;
const char * const end = sequence->end;
while(start < end) {
const uint_t c = dna_codes[(uint_t)*start++];
switch(c) {
case CODE_IGNORE: break;
case CODE_COMMENT:
report_bad_input(*(start-1));
// Fall through
case CODE_RESET:
cmlen = kmer = rkmer = 0;
break;
default:
kmer = ((kmer << 2) & masq) | c;
//rkmer = (rkmer >> 2) | ((0x3 - c) << lshift);
if(++cmlen >= mer_len) {
cmlen = mer_len;
ret_mer = 0;
kraken::squash_kmer_for_index(parser->Spaced_seed_cstr, mer_len,
kmer,ret_mer);
typename T::val_type oval;
if(canonical){
//counter->add(kmer < rkmer ? kmer : rkmer, 1, &oval);
std::cerr<<"Jellyfish with SpacedSeeds does not support canonical kmers."
<<std::endl;
exit(-1);
}else{
counter->add(ret_mer, 1, &oval);
//DEBUG
//std::cerr<<kraken::kmer_to_str(mer_len,kmer)<<" <--> "
// <<kraken::kmer_to_str(mer_len,ret_mer)
// <<std::endl;
}
distinct += oval == (typename T::val_type)0;
++total;
}
}
}
// Buffer exhausted. Get a new one
cmlen = kmer = rkmer = 0;
parser->release(sequence);
}
}
void set_error_reporter(error_reporter e) {
error_report = e;
}
private:
void report_bad_input(char c) {
if(!error_report)
return;
std::string err("Bad character in sequence: ");
err += c;
error_report(err);
}
};
friend class thread;
thread new_thread() { return thread(this); }
};
}
template<typename T>
jellyfish::parse_dna::parse_dna(T _files_start, T _files_end,
uint_t _mer_len,
unsigned int nb_buffers, size_t _buffer_size,
const char * seed_cstr) :
double_fifo_input<sequence_parser::sequence_t>(nb_buffers), mer_len(_mer_len),
buffer_size(allocators::mmap::round_to_page(_buffer_size)),
files(_files_start, _files_end), current_file(files.begin()),
have_seam(false), buffer_data(buffer_size * nb_buffers), canonical(false),
Spaced_seed_cstr(seed_cstr)
{
seam = new char[mer_len];
memset(seam, 'A', mer_len);
unsigned long i = 0;
for(bucket_iterator it = bucket_begin();
it != bucket_end(); ++it, ++i) {
it->end = it->start = (char *)buffer_data.get_ptr() + i * buffer_size;
}
assert(i == nb_buffers);
fparser = sequence_parser::new_parser(*current_file);
}
#endif
| macieksk/Jellyfish | jellyfish/parse_dna.hpp | C++ | gpl-3.0 | 7,390 |
<?php
use Alchemy\Phrasea\Model\Serializer\CaptionSerializer;
use Symfony\Component\Yaml\Yaml;
/**
* @group functional
* @group legacy
*/
class caption_recordTest extends \PhraseanetTestCase
{
/**
* @var caption_record
*/
protected $object;
public function setUp()
{
parent::setUp();
$this->object = new caption_record(self::$DI['app'], self::$DI['record_1'], self::$DI['record_1']->get_databox());
}
/**
* @covers \caption_record::serializeXML
*/
public function testSerializeXML()
{
foreach (self::$DI['record_1']->get_databox()->get_meta_structure() as $databox_field) {
$n = $databox_field->is_multi() ? 3 : 1;
for ($i = 0; $i < $n; $i ++) {
\caption_Field_Value::create(self::$DI['app'], $databox_field, self::$DI['record_1'], self::$DI['app']['random.low']->generateString(8));
}
}
$xml = self::$DI['app']['serializer.caption']->serialize($this->object, CaptionSerializer::SERIALIZE_XML);
$sxe = simplexml_load_string($xml);
$this->assertInstanceOf('SimpleXMLElement', $sxe);
foreach (self::$DI['record_1']->get_caption()->get_fields() as $field) {
if ($field->get_databox_field()->is_multi()) {
$tagname = $field->get_name();
$retrieved = [];
foreach ($sxe->description->$tagname as $value) {
$retrieved[] = (string) $value;
}
$values = $field->get_values();
$this->assertEquals(count($values), count($retrieved));
foreach ($values as $val) {
$this->assertTrue(in_array($val->getValue(), $retrieved));
}
} else {
$tagname = $field->get_name();
$data = $field->get_values();
$value = array_pop($data);
$this->assertEquals($value->getValue(), (string) $sxe->description->$tagname);
}
}
}
public function testSerializeJSON()
{
foreach (self::$DI['record_1']->get_databox()->get_meta_structure() as $databox_field) {
$n = $databox_field->is_multi() ? 3 : 1;
for ($i = 0; $i < $n; $i ++) {
\caption_Field_Value::create(self::$DI['app'], $databox_field, self::$DI['record_1'], self::$DI['app']['random.low']->generateString(8));
}
}
$json = json_decode(self::$DI['app']['serializer.caption']->serialize($this->object, CaptionSerializer::SERIALIZE_JSON), true);
foreach (self::$DI['record_1']->get_caption()->get_fields() as $field) {
if ($field->get_databox_field()->is_multi()) {
$tagname = $field->get_name();
$retrieved = [];
foreach ($json["record"]["description"][$tagname] as $value) {
$retrieved[] = $value;
}
$values = $field->get_values();
$this->assertEquals(count($values), count($retrieved));
foreach ($values as $val) {
$this->assertTrue(in_array($val->getValue(), $retrieved));
}
} else {
$tagname = $field->get_name();
$data = $field->get_values();
$value = array_pop($data);
$this->assertEquals($value->getValue(), $json["record"]["description"][$tagname]);
}
}
}
/**
* @covers \caption_record::serializeYAML
*/
public function testSerializeYAML()
{
foreach (self::$DI['record_1']->get_databox()->get_meta_structure() as $databox_field) {
$n = $databox_field->is_multi() ? 3 : 1;
for ($i = 0; $i < $n; $i ++) {
\caption_Field_Value::create(self::$DI['app'], $databox_field, self::$DI['record_1'], self::$DI['app']['random.low']->generateString(8));
}
}
$parser = new Yaml();
$yaml = $parser->parse(self::$DI['app']['serializer.caption']->serialize($this->object, CaptionSerializer::SERIALIZE_YAML));
foreach (self::$DI['record_1']->get_caption()->get_fields() as $field) {
if ($field->get_databox_field()->is_multi()) {
$tagname = $field->get_name();
$retrieved = [];
foreach ($yaml["record"]["description"][$tagname] as $value) {
$retrieved[] = (string) $value;
}
$values = $field->get_values();
$this->assertEquals(count($values), count($retrieved));
foreach ($values as $val) {
$this->assertTrue(in_array($val->getValue(), $retrieved));
}
} else {
$tagname = $field->get_name();
$data = $field->get_values();
$value = array_pop($data);
$this->assertEquals($value->getValue(), (string) $yaml["record"]["description"][$tagname]);
}
}
}
/**
* @covers \caption_record::get_fields
* @todo Implement testGet_fields().
*/
public function testGet_fields()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}
/**
* @covers \caption_record::get_field
* @todo Implement testGet_field().
*/
public function testGet_field()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}
/**
* @covers \caption_record::get_dc_field
* @todo Implement testGet_dc_field().
*/
public function testGet_dc_field()
{
$field = null;
foreach (self::$DI['app']->getDataboxes() as $databox) {
foreach ($databox->get_meta_structure() as $meta) {
$meta->set_dces_element(new databox_Field_DCES_Contributor());
$field = $meta;
$set = true;
break;
}
break;
}
if (!$field) {
$this->markTestSkipped('Unable to set a DC field');
}
$captionField = self::$DI['record_1']->get_caption()->get_field($field->get_name());
if (!$captionField) {
self::$DI['record_1']->set_metadatas([
[
'meta_id' => null,
'meta_struct_id' => $field->get_id(),
'value' => ['HELLO MO !'],
]
]);
$value = 'HELLO MO !';
} else {
$value = $captionField->get_serialized_values();
}
$this->assertEquals($value, self::$DI['record_1']->get_caption()->get_dc_field(databox_Field_DCESAbstract::Contributor)->get_serialized_values());
}
/**
* @covers \caption_record::get_highlight_fields
* @todo Implement testGet_highlight_fields().
*/
public function testGet_highlight_fields()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}
/**
* @covers \caption_record::get_cache_key
* @todo Implement testGet_cache_key().
*/
public function testGet_cache_key()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}
/**
* @covers \caption_record::get_data_from_cache
* @todo Implement testGet_data_from_cache().
*/
public function testGet_data_from_cache()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}
/**
* @covers \caption_record::set_data_to_cache
* @todo Implement testSet_data_to_cache().
*/
public function testSet_data_to_cache()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}
/**
* @covers \caption_record::delete_data_from_cache
* @todo Implement testDelete_data_from_cache().
*/
public function testDelete_data_from_cache()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}
}
| bburnichon/Phraseanet | tests/classes/caption/recordTest.php | PHP | gpl-3.0 | 8,719 |
from ..daltools.util.full import init
Z = [8., 1., 1.]
Rc = init([0.00000000, 0.00000000, 0.48860959])
Dtot = [0, 0, -0.76539388]
Daa = init([
[ 0.00000000, 0.00000000, -0.28357300],
[ 0.15342658, 0.00000000, 0.12734703],
[-0.15342658, 0.00000000, 0.12734703],
])
QUc = init([-7.31176220, 0., 0., -5.43243232, 0., -6.36258665])
QUN = init([4.38968295, 0., 0., 0., 0., 1.75400326])
QUaa = init([
[-3.29253618, 0.00000000, 0.00000000, -4.54316657, 0.00000000, -4.00465380],
[-0.13213704, 0.00000000, 0.24980518, -0.44463288, 0.00000000, -0.26059139],
[-0.13213704, 0.00000000,-0.24980518, -0.44463288, 0.00000000, -0.26059139]
])
Fab = init([
[-0.11E-03, 0.55E-04, 0.55E-04],
[ 0.55E-04, -0.55E-04, 0.16E-30],
[ 0.55E-04, 0.16E-30, -0.55E-04]
])
Lab = init([
[0.11E-03, 0.28E-03, 0.28E-03],
[0.28E-03, 0.17E-03, 0.22E-03],
[0.28E-03, 0.22E-03, 0.17E-03]
])
la = init([
[0.0392366,-27.2474016 , 27.2081650],
[0.0358964, 27.2214515 ,-27.2573479],
[0.01211180, -0.04775576, 0.03564396],
[0.01210615, -0.00594030, -0.00616584],
[10.69975088, -5.34987556, -5.34987532],
[-10.6565582, 5.3282791 , 5.3282791]
])
O = [
0.76145382,
-0.00001648, 1.75278523,
-0.00007538, 0.00035773, 1.39756345
]
H1O = [
3.11619527,
0.00019911, 1.25132346,
2.11363325, 0.00111442, 2.12790474
]
H1 = [
0.57935224,
0.00018083, 0.43312326,
0.11495546, 0.00004222, 0.45770123
]
H2O = [
3.11568759,
0.00019821, 1.25132443,
-2.11327482, -0.00142746, 2.12790473
]
H2H1 = [
0.04078206,
-0.00008380, -0.01712262,
-0.00000098, 0.00000084, -0.00200285
]
H2 = [
0.57930522,
0.00018221, 0.43312149,
-0.11493635, -0.00016407, 0.45770123
]
Aab = init([O, H1O, H1, H2O, H2H1, H2])
Aa = init([
[ 3.87739525, 0.00018217, 3.00410918, 0.00010384, 0.00020122, 3.52546819 ],
[ 2.15784091, 0.00023848, 1.05022368, 1.17177159, 0.00059985, 1.52065218 ],
[ 2.15754005, 0.00023941, 1.05022240, -1.17157425, -0.00087738, 1.52065217 ]
])
ff = 0.001
rMP = init([
#O
[
[-8.70343886, 0.00000000, 0.00000000, -0.39827574, -3.68114747, 0.00000000, 0.00000000, -4.58632761, 0.00000000, -4.24741556],
[-8.70343235, 0.00076124, 0.00000000, -0.39827535, -3.68114147, 0.00000000, 0.00193493, -4.58631888, 0.00000000, -4.24741290],
[-8.70343291,-0.00076166, 0.00000000, -0.39827505, -3.68114128, 0.00000000, -0.00193603, -4.58631789, 0.00000000, -4.24741229],
[-8.70343685,-0.00000006, 0.00175241, -0.39827457, -3.68114516, 0.00000000, 0.00000161, -4.58632717, 0.00053363, -4.24741642],
[-8.70343685, 0.00000000, -0.00175316, -0.39827456, -3.68114514, 0.00000000, 0.00000000, -4.58632711, -0.00053592, -4.24741639],
[-8.70166502, 0.00000000, 0.00000144, -0.39688042, -3.67884999, 0.00000000, 0.00000000, -4.58395384, 0.00000080, -4.24349307],
[-8.70520554, 0.00000000, 0.00000000, -0.39967554, -3.68344246, 0.00000000, 0.00000000, -4.58868836, 0.00000000, -4.25134640],
],
#H1O
[
[ 0.00000000, 0.10023328, 0.00000000, 0.11470275, 0.53710687, 0.00000000, 0.43066796, 0.04316104, 0.00000000, 0.36285790],
[ 0.00150789, 0.10111974, 0.00000000, 0.11541803, 0.53753360, 0.00000000, 0.43120945, 0.04333774, 0.00000000, 0.36314215],
[-0.00150230, 0.09934695, 0.00000000, 0.11398581, 0.53667861, 0.00000000, 0.43012612, 0.04298361, 0.00000000, 0.36257249],
[ 0.00000331, 0.10023328, 0.00125017, 0.11470067, 0.53710812, -0.00006107, 0.43066944, 0.04316020, 0.00015952, 0.36285848],
[ 0.00000100, 0.10023249, -0.00125247, 0.11470042, 0.53710716, 0.00006135, 0.43066837, 0.04316018, -0.00015966, 0.36285788],
[ 0.00088692, 0.10059268, -0.00000064, 0.11590322, 0.53754715, -0.00000006, 0.43071206, 0.04334198, -0.00000015, 0.36330053],
[-0.00088334, 0.09987383, 0.00000000, 0.11350091, 0.53666602, 0.00000000, 0.43062352, 0.04297910, 0.00000000, 0.36241326],
],
#H1
[
[-0.64828057, 0.10330994, 0.00000000, 0.07188960, -0.47568174, 0.00000000, -0.03144252, -0.46920879, 0.00000000, -0.50818752],
[-0.64978846, 0.10389186, 0.00000000, 0.07204462, -0.47729337, 0.00000000, -0.03154159, -0.47074619, 0.00000000, -0.50963693],
[-0.64677827, 0.10273316, 0.00000000, 0.07173584, -0.47408263, 0.00000000, -0.03134407, -0.46768337, 0.00000000, -0.50674873],
[-0.64828388, 0.10331167, 0.00043314, 0.07189029, -0.47568875, -0.00023642, -0.03144270, -0.46921635, -0.00021728, -0.50819386],
[-0.64828157, 0.10331095, -0.00043311, 0.07188988, -0.47568608, 0.00023641, -0.03144256, -0.46921346, 0.00021729, -0.50819095],
[-0.64916749, 0.10338629, -0.00000024, 0.07234862, -0.47634698, 0.00000013, -0.03159569, -0.47003679, 0.00000011, -0.50936853],
[-0.64739723, 0.10323524, 0.00000000, 0.07143322, -0.47502412, 0.00000000, -0.03129003, -0.46838912, 0.00000000, -0.50701656],
],
#H2O
[
[ 0.00000000,-0.10023328, 0.00000000, 0.11470275, 0.53710687, 0.00000000, -0.43066796, 0.04316104, 0.00000000, 0.36285790],
[-0.00150139,-0.09934749, 0.00000000, 0.11398482, 0.53667874, 0.00000000, -0.43012670, 0.04298387, 0.00000000, 0.36257240],
[ 0.00150826,-0.10112008, 0.00000000, 0.11541676, 0.53753350, 0.00000000, -0.43120982, 0.04333795, 0.00000000, 0.36314186],
[-0.00000130,-0.10023170, 0.00125018, 0.11470018, 0.53710620, 0.00006107, -0.43066732, 0.04316017, 0.00015952, 0.36285728],
[ 0.00000101,-0.10023249, -0.00125247, 0.11470042, 0.53710716, -0.00006135, -0.43066838, 0.04316018, -0.00015966, 0.36285788],
[ 0.00088692,-0.10059268, -0.00000064, 0.11590322, 0.53754715, 0.00000006, -0.43071206, 0.04334198, -0.00000015, 0.36330053],
[-0.00088334,-0.09987383, 0.00000000, 0.11350091, 0.53666602, 0.00000000, -0.43062352, 0.04297910, 0.00000000, 0.36241326],
],
#H2H1
[
[ 0.00000000, 0.00000000, 0.00000000, -0.00378789, 0.00148694, 0.00000000, 0.00000000, 0.00599079, 0.00000000, 0.01223822],
[ 0.00000000, 0.00004089, 0.00000000, -0.00378786, 0.00148338, 0.00000000, -0.00004858, 0.00599281, 0.00000000, 0.01224094],
[ 0.00000000,-0.00004067, 0.00000000, -0.00378785, 0.00148341, 0.00000000, 0.00004861, 0.00599277, 0.00000000, 0.01224093],
[ 0.00000000,-0.00000033, -0.00001707, -0.00378763, 0.00149017, 0.00000000, 0.00000001, 0.00599114, -0.00001229, 0.01223979],
[ 0.00000000, 0.00000000, 0.00001717, -0.00378763, 0.00149019, 0.00000000, 0.00000000, 0.00599114, 0.00001242, 0.01223980],
[ 0.00000000, 0.00000000, 0.00000000, -0.00378978, 0.00141897, 0.00000000, 0.00000000, 0.00590445, 0.00000002, 0.01210376],
[ 0.00000000, 0.00000000, 0.00000000, -0.00378577, 0.00155694, 0.00000000, 0.00000000, 0.00607799, 0.00000000, 0.01237393],
],
#H2
[
[-0.64828057,-0.10330994, 0.00000000, 0.07188960, -0.47568174, 0.00000000, 0.03144252, -0.46920879, 0.00000000, -0.50818752],
[-0.64677918,-0.10273369, 0.00000000, 0.07173576, -0.47408411, 0.00000000, 0.03134408, -0.46768486, 0.00000000, -0.50674986],
[-0.64978883,-0.10389230, 0.00000000, 0.07204446, -0.47729439, 0.00000000, 0.03154159, -0.47074717, 0.00000000, -0.50963754],
[-0.64827927,-0.10331022, 0.00043313, 0.07188947, -0.47568340, 0.00023642, 0.03144242, -0.46921057, -0.00021727, -0.50818804],
[-0.64828158,-0.10331095, -0.00043311, 0.07188988, -0.47568609, -0.00023641, 0.03144256, -0.46921348, 0.00021729, -0.50819097],
[-0.64916749,-0.10338629, -0.00000024, 0.07234862, -0.47634698, -0.00000013, 0.03159569, -0.47003679, 0.00000011, -0.50936853],
[-0.64739723,-0.10323524, 0.00000000, 0.07143322, -0.47502412, 0.00000000, 0.03129003, -0.46838912, 0.00000000, -0.50701656]
]
])
Am = init([
[8.186766009140, 0., 0.],
[0., 5.102747935447, 0.],
[0., 0., 6.565131856389]
])
Amw = init([
[11.98694996213, 0., 0.],
[0., 4.403583657738, 0.],
[0., 0., 2.835142058626]
])
R = [
[ 0.00000, 0.00000, 0.69801],
[-1.48150, 0.00000, -0.34901],
[ 1.48150, 0.00000, -0.34901]
]
Qtot = -10.0
Q = rMP[0, 0, (0, 2, 5)]
D = rMP[1:4, 0, :]
QU = rMP[4:, 0, :]
dQa = rMP[0, :, (0,2,5)]
dQab = rMP[0, :, (1, 3, 4)]
#These are string data for testing potential file
PAn0 = """AU
3 -1 0 1
1 0.000 0.000 0.698
1 -1.481 0.000 -0.349
1 1.481 0.000 -0.349
"""
PA00 = """AU
3 0 0 1
1 0.000 0.000 0.698 -0.703
1 -1.481 0.000 -0.349 0.352
1 1.481 0.000 -0.349 0.352
"""
PA10 = """AU
3 1 0 1
1 0.000 0.000 0.698 -0.703 -0.000 0.000 -0.284
1 -1.481 0.000 -0.349 0.352 0.153 0.000 0.127
1 1.481 0.000 -0.349 0.352 -0.153 0.000 0.127
"""
PA20 = """AU
3 2 0 1
1 0.000 0.000 0.698 -0.703 -0.000 0.000 -0.284 -3.293 0.000 -0.000 -4.543 -0.000 -4.005
1 -1.481 0.000 -0.349 0.352 0.153 0.000 0.127 -0.132 0.000 0.250 -0.445 0.000 -0.261
1 1.481 0.000 -0.349 0.352 -0.153 0.000 0.127 -0.132 -0.000 -0.250 -0.445 0.000 -0.261
"""
PA21 = """AU
3 2 1 1
1 0.000 0.000 0.698 -0.703 -0.000 0.000 -0.284 -3.293 0.000 -0.000 -4.543 -0.000 -4.005 3.466
1 -1.481 0.000 -0.349 0.352 0.153 0.000 0.127 -0.132 0.000 0.250 -0.445 0.000 -0.261 1.576
1 1.481 0.000 -0.349 0.352 -0.153 0.000 0.127 -0.132 -0.000 -0.250 -0.445 0.000 -0.261 1.576
"""
PA22 = """AU
3 2 2 1
1 0.000 0.000 0.698 -0.703 -0.000 0.000 -0.284 -3.293 0.000 -0.000 -4.543 -0.000 -4.005 3.875 -0.000 -0.000 3.000 -0.000 3.524
1 -1.481 0.000 -0.349 0.352 0.153 0.000 0.127 -0.132 0.000 0.250 -0.445 0.000 -0.261 2.156 -0.000 1.106 1.051 -0.000 1.520
1 1.481 0.000 -0.349 0.352 -0.153 0.000 0.127 -0.132 -0.000 -0.250 -0.445 0.000 -0.261 2.156 -0.000 -1.106 1.051 -0.000 1.520
"""
OUTPUT_n0_1 = """\
---------------
Atomic domain 1
---------------
Domain center: 0.00000 0.00000 0.69801
"""
OUTPUT_00_1 = OUTPUT_n0_1 + """\
Nuclear charge: 8.00000
Electronic charge: -8.70344
Total charge: -0.70344
"""
OUTPUT_10_1 = OUTPUT_00_1 + """\
Electronic dipole -0.00000 0.00000 -0.28357
"""
OUTPUT_20_1 = OUTPUT_10_1 + """\
Electronic quadrupole -3.29254 0.00000 -0.00000 -4.54317 0.00000 -4.00466
"""
OUTPUT_01_1 = OUTPUT_00_1 + """\
Isotropic polarizablity (w=0) 3.46639
"""
OUTPUT_02_1 = OUTPUT_00_1 + """\
Electronic polarizability (w=0) 3.87468 -0.00000 3.00027 -0.00000 -0.00000 3.52422
"""
| fishstamp82/loprop | test/h2o_data.py | Python | gpl-3.0 | 11,431 |
/***************************************************************
* This source files comes from the xLights project
* https://www.xlights.org
* https://github.com/smeighan/xLights
* See the github commit history for a record of contributing
* developers.
* Copyright claimed based on commit dates recorded in Github
* License: https://github.com/smeighan/xLights/blob/master/License.txt
**************************************************************/
#include "PlayListItemAudioPanel.h"
#include "PlayListItemAudio.h"
#include "PlayListDialog.h"
#include "PlayListSimpleDialog.h"
//(*InternalHeaders(PlayListItemAudioPanel)
#include <wx/intl.h>
#include <wx/string.h>
//*)
//(*IdInit(PlayListItemAudioPanel)
const long PlayListItemAudioPanel::ID_STATICTEXT2 = wxNewId();
const long PlayListItemAudioPanel::ID_FILEPICKERCTRL2 = wxNewId();
const long PlayListItemAudioPanel::ID_CHECKBOX2 = wxNewId();
const long PlayListItemAudioPanel::ID_SLIDER1 = wxNewId();
const long PlayListItemAudioPanel::ID_CHECKBOX1 = wxNewId();
const long PlayListItemAudioPanel::ID_STATICTEXT4 = wxNewId();
const long PlayListItemAudioPanel::ID_SPINCTRL1 = wxNewId();
const long PlayListItemAudioPanel::ID_STATICTEXT3 = wxNewId();
const long PlayListItemAudioPanel::ID_TEXTCTRL1 = wxNewId();
//*)
BEGIN_EVENT_TABLE(PlayListItemAudioPanel,wxPanel)
//(*EventTable(PlayListItemAudioPanel)
//*)
END_EVENT_TABLE()
class AudioFilePickerCtrl : public wxFilePickerCtrl
{
public:
AudioFilePickerCtrl(wxWindow *parent,
wxWindowID id,
const wxString& path = wxEmptyString,
const wxString& message = wxFileSelectorPromptStr,
const wxString& wildcard = wxFileSelectorDefaultWildcardStr,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = wxFLP_DEFAULT_STYLE,
const wxValidator& validator = wxDefaultValidator,
const wxString& name = wxFilePickerCtrlNameStr) :
wxFilePickerCtrl(parent, id, path, message, AUDIOFILES, pos, size, style, validator, name)
{}
virtual ~AudioFilePickerCtrl() {}
};
PlayListItemAudioPanel::PlayListItemAudioPanel(wxWindow* parent, PlayListItemAudio* audio, wxWindowID id,const wxPoint& pos,const wxSize& size)
{
_audio = audio;
//(*Initialize(PlayListItemAudioPanel)
wxFlexGridSizer* FlexGridSizer1;
Create(parent, id, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("id"));
FlexGridSizer1 = new wxFlexGridSizer(0, 2, 0, 0);
FlexGridSizer1->AddGrowableCol(1);
StaticText2 = new wxStaticText(this, ID_STATICTEXT2, _("Audio File:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT2"));
FlexGridSizer1->Add(StaticText2, 1, wxALL|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
FilePickerCtrl_AudioFile = new AudioFilePickerCtrl(this, ID_FILEPICKERCTRL2, wxEmptyString, _("Audio File"), wxEmptyString, wxDefaultPosition, wxDefaultSize, wxFLP_FILE_MUST_EXIST|wxFLP_OPEN|wxFLP_USE_TEXTCTRL, wxDefaultValidator, _T("ID_FILEPICKERCTRL2"));
FlexGridSizer1->Add(FilePickerCtrl_AudioFile, 1, wxALL|wxEXPAND, 5);
FlexGridSizer1->Add(-1,-1,1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
CheckBox_OverrideVolume = new wxCheckBox(this, ID_CHECKBOX2, _("Override Volume"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX2"));
CheckBox_OverrideVolume->SetValue(false);
FlexGridSizer1->Add(CheckBox_OverrideVolume, 1, wxALL|wxEXPAND, 5);
FlexGridSizer1->Add(-1,-1,1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
Slider1 = new wxSlider(this, ID_SLIDER1, 100, 0, 100, wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_SLIDER1"));
FlexGridSizer1->Add(Slider1, 1, wxALL|wxEXPAND, 5);
FlexGridSizer1->Add(-1,-1,1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
CheckBox_FastStartAudio = new wxCheckBox(this, ID_CHECKBOX1, _("Fast Start Audio"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX1"));
CheckBox_FastStartAudio->SetValue(false);
FlexGridSizer1->Add(CheckBox_FastStartAudio, 1, wxALL|wxEXPAND, 5);
StaticText4 = new wxStaticText(this, ID_STATICTEXT4, _("Priority:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT4"));
FlexGridSizer1->Add(StaticText4, 1, wxALL|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
SpinCtrl_Priority = new wxSpinCtrl(this, ID_SPINCTRL1, _T("5"), wxDefaultPosition, wxDefaultSize, 0, 1, 10, 5, _T("ID_SPINCTRL1"));
SpinCtrl_Priority->SetValue(_T("5"));
FlexGridSizer1->Add(SpinCtrl_Priority, 1, wxALL|wxEXPAND, 5);
StaticText3 = new wxStaticText(this, ID_STATICTEXT3, _("Delay:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT3"));
FlexGridSizer1->Add(StaticText3, 1, wxALL|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5);
TextCtrl_Delay = new wxTextCtrl(this, ID_TEXTCTRL1, _("0.000"), wxDefaultPosition, wxDefaultSize, wxTE_RIGHT, wxDefaultValidator, _T("ID_TEXTCTRL1"));
FlexGridSizer1->Add(TextCtrl_Delay, 1, wxALL|wxEXPAND, 5);
SetSizer(FlexGridSizer1);
FlexGridSizer1->Fit(this);
FlexGridSizer1->SetSizeHints(this);
Connect(ID_FILEPICKERCTRL2,wxEVT_COMMAND_FILEPICKER_CHANGED,(wxObjectEventFunction)&PlayListItemAudioPanel::OnFilePickerCtrl2FileChanged);
Connect(ID_CHECKBOX2,wxEVT_COMMAND_CHECKBOX_CLICKED,(wxObjectEventFunction)&PlayListItemAudioPanel::OnCheckBox_OverrideVolumeClick);
//*)
FilePickerCtrl_AudioFile->SetFileName(wxFileName(audio->GetAudioFile()));
TextCtrl_Delay->SetValue(wxString::Format(wxT("%.3f"), (float)audio->GetDelay() / 1000.0));
CheckBox_FastStartAudio->SetValue(audio->GetFastStartAudio());
if (audio->GetVolume() != -1)
{
CheckBox_OverrideVolume->SetValue(true);
Slider1->SetValue(audio->GetVolume());
}
else
{
CheckBox_OverrideVolume->SetValue(false);
}
ValidateWindow();
}
PlayListItemAudioPanel::~PlayListItemAudioPanel()
{
//(*Destroy(PlayListItemAudioPanel)
//*)
_audio->SetDelay(wxAtof(TextCtrl_Delay->GetValue()) * 1000);
_audio->SetFastStartAudio(CheckBox_FastStartAudio->GetValue());
if (CheckBox_OverrideVolume->GetValue())
{
_audio->SetVolume(Slider1->GetValue());
}
else
{
_audio->SetVolume(-1);
}
_audio->SetAudioFile(FilePickerCtrl_AudioFile->GetFileName().GetFullPath().ToStdString());
}
void PlayListItemAudioPanel::OnTextCtrl_DelayText(wxCommandEvent& event)
{
}
void PlayListItemAudioPanel::OnFilePickerCtrl2FileChanged(wxFileDirPickerEvent& event)
{
_audio->SetAudioFile(FilePickerCtrl_AudioFile->GetFileName().GetFullPath().ToStdString());
wxCommandEvent e(EVT_UPDATEITEMNAME);
wxPostEvent(GetParent()->GetParent()->GetParent()->GetParent(), e);
}
void PlayListItemAudioPanel::ValidateWindow()
{
if (CheckBox_OverrideVolume->GetValue())
{
Slider1->Enable();
}
else
{
Slider1->Enable(false);
}
}
void PlayListItemAudioPanel::OnCheckBox_OverrideVolumeClick(wxCommandEvent& event)
{
ValidateWindow();
}
| smeighan/xLights | xSchedule/PlayList/PlayListItemAudioPanel.cpp | C++ | gpl-3.0 | 6,948 |
from __future__ import absolute_import, print_function, division
from mitmproxy import exceptions
import pprint
def _get_name(itm):
return getattr(itm, "name", itm.__class__.__name__)
class Addons(object):
def __init__(self, master):
self.chain = []
self.master = master
master.options.changed.connect(self.options_update)
def options_update(self, options, updated):
for i in self.chain:
with self.master.handlecontext():
i.configure(options, updated)
def add(self, options, *addons):
if not addons:
raise ValueError("No addons specified.")
self.chain.extend(addons)
for i in addons:
self.invoke_with_context(i, "start")
self.invoke_with_context(
i,
"configure",
self.master.options,
self.master.options.keys()
)
def remove(self, addon):
self.chain = [i for i in self.chain if i is not addon]
self.invoke_with_context(addon, "done")
def done(self):
for i in self.chain:
self.invoke_with_context(i, "done")
def has_addon(self, name):
"""
Is an addon with this name registered?
"""
for i in self.chain:
if _get_name(i) == name:
return True
def __len__(self):
return len(self.chain)
def __str__(self):
return pprint.pformat([str(i) for i in self.chain])
def invoke_with_context(self, addon, name, *args, **kwargs):
with self.master.handlecontext():
self.invoke(addon, name, *args, **kwargs)
def invoke(self, addon, name, *args, **kwargs):
func = getattr(addon, name, None)
if func:
if not callable(func):
raise exceptions.AddonError(
"Addon handler %s not callable" % name
)
func(*args, **kwargs)
def __call__(self, name, *args, **kwargs):
for i in self.chain:
self.invoke(i, name, *args, **kwargs)
| x2Ident/x2Ident_test | mitmproxy/mitmproxy/addons.py | Python | gpl-3.0 | 2,173 |
#! /usr/bin/env python
#################################################################################################
#
# Script Name: bip.py
# Script Usage: This script is the menu system and runs everything else. Do not use other
# files unless you are comfortable with the code.
#
# It has the following:
# 1.
# 2.
# 3.
# 4.
#
# You will probably want to do the following:
# 1. Make sure the info in bip_config.py is correct.
# 2. Make sure GAM (Google Apps Manager) is installed and the path is correct.
# 3. Make sure the AD scripts in toos/ are present on the DC running run.ps1.
#
# Script Updates:
# 201709191243 - rdegennaro@sscps.org - copied boilerplate.
#
#################################################################################################
import os # os.system for clearing screen and simple gam calls
import subprocess # subprocess.Popen is to capture gam output (needed for user info in particular)
import MySQLdb # MySQLdb is to get data from relevant tables
import csv # CSV is used to read output of drive commands that supply data in CSV form
import bip_config # declare installation specific variables
# setup for MySQLdb connection
varMySQLHost = bip_config.mysqlconfig['host']
varMySQLUser = bip_config.mysqlconfig['user']
varMySQLPassword = bip_config.mysqlconfig['password']
varMySQLDB = bip_config.mysqlconfig['db']
# setup to find GAM
varCommandGam = bip_config.gamconfig['fullpath']
#################################################################################################
#
#################################################################################################
| SSCPS/bip-gam-v1 | bip.py | Python | gpl-3.0 | 1,835 |
/*
* Copyright (c) 2013 The Interedition Development Group.
*
* This file is part of CollateX.
*
* CollateX 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.
*
* CollateX 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 CollateX. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.interedition.text.xml;
import com.google.common.base.Objects;
import javax.xml.XMLConstants;
import javax.xml.stream.XMLStreamReader;
import java.util.Stack;
/**
* @author <a href="http://gregor.middell.net/" title="Homepage">Gregor Middell</a>
*/
public class WhitespaceCompressor extends ConversionFilter {
private final Stack<Boolean> spacePreservationContext = new Stack<Boolean>();
private final WhitespaceStrippingContext whitespaceStrippingContext;
private char lastChar = ' ';
public WhitespaceCompressor(WhitespaceStrippingContext whitespaceStrippingContext) {
this.whitespaceStrippingContext = whitespaceStrippingContext;
}
@Override
public void start() {
spacePreservationContext.clear();
whitespaceStrippingContext.reset();
lastChar = ' ';
}
@Override
protected void onXMLEvent(XMLStreamReader reader) {
whitespaceStrippingContext.onXMLEvent(reader);
if (reader.isStartElement()) {
spacePreservationContext.push(spacePreservationContext.isEmpty() ? false : spacePreservationContext.peek());
final Object xmlSpace = reader.getAttributeValue(XMLConstants.XML_NS_URI, "space");
if (xmlSpace != null) {
spacePreservationContext.pop();
spacePreservationContext.push("preserve".equalsIgnoreCase(xmlSpace.toString()));
}
} else if (reader.isEndElement()) {
spacePreservationContext.pop();
}
}
String compress(String text) {
final StringBuilder compressed = new StringBuilder();
final boolean preserveSpace = Objects.firstNonNull(spacePreservationContext.peek(), false);
for (int cc = 0, length = text.length(); cc < length; cc++) {
char currentChar = text.charAt(cc);
if (!preserveSpace && Character.isWhitespace(currentChar) && (Character.isWhitespace(lastChar) || whitespaceStrippingContext.isInContainerElement())) {
continue;
}
if (currentChar == '\n' || currentChar == '\r') {
currentChar = ' ';
}
compressed.append(lastChar = currentChar);
}
return compressed.toString();
}
}
| faustedition/text | text-core/src/main/java/eu/interedition/text/xml/WhitespaceCompressor.java | Java | gpl-3.0 | 3,002 |
/*
* Copyright (C) 2016-2021 David Rubio Escares / Kodehawa
*
* Mantaro 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.
* Mantaro 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 Mantaro. If not, see http://www.gnu.org/licenses/
*/
package net.kodehawa.mantarobot.commands.currency.profile;
import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class BadgeUtils {
public static byte[] applyBadge(byte[] avatarBytes, byte[] badgeBytes, int startX, int startY, boolean allWhite) {
BufferedImage avatar;
BufferedImage badge;
try {
avatar = ImageIO.read(new ByteArrayInputStream(avatarBytes));
badge = ImageIO.read(new ByteArrayInputStream(badgeBytes));
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
WritableRaster raster = badge.getRaster();
if (allWhite) {
for (int xx = 0, width = badge.getWidth(); xx < width; xx++) {
for (int yy = 0, height = badge.getHeight(); yy < height; yy++) {
int[] pixels = raster.getPixel(xx, yy, (int[]) null);
pixels[0] = 255;
pixels[1] = 255;
pixels[2] = 255;
pixels[3] = pixels[3] == 255 ? 165 : 0;
raster.setPixel(xx, yy, pixels);
}
}
}
BufferedImage res = new BufferedImage(128, 128, BufferedImage.TYPE_INT_ARGB);
int circleCenterX = 88, circleCenterY = 88;
int width = 32, height = 32;
int circleRadius = 40;
Graphics2D g2d = res.createGraphics();
g2d.drawImage(avatar, 0, 0, 128, 128, null);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(new Color(0, 0, 165, 165));
g2d.fillOval(circleCenterX, circleCenterY, circleRadius, circleRadius);
g2d.drawImage(badge, startX, startY, width, height, null);
g2d.dispose();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(res, "png", baos);
} catch (IOException e) {
throw new AssertionError(e);
}
return baos.toByteArray();
}
}
| Mantaro/MantaroBot | src/main/java/net/kodehawa/mantarobot/commands/currency/profile/BadgeUtils.java | Java | gpl-3.0 | 2,976 |
# Copyright (C) 2012,2013
# Max Planck Institute for Polymer Research
# Copyright (C) 2008,2009,2010,2011
# Max-Planck-Institute for Polymer Research & Fraunhofer SCAI
#
# This file is part of ESPResSo++.
#
# ESPResSo++ 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.
#
# ESPResSo++ 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/>.
r"""
********************************************
**espressopp.integrator.LangevinThermostat**
********************************************
.. function:: espressopp.integrator.LangevinThermostat(system)
:param system:
:type system:
"""
from espressopp.esutil import cxxinit
from espressopp import pmi
from espressopp.integrator.Extension import *
from _espressopp import integrator_LangevinThermostat
class LangevinThermostatLocal(ExtensionLocal, integrator_LangevinThermostat):
def __init__(self, system):
if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup():
cxxinit(self, integrator_LangevinThermostat, system)
#def enableAdress(self):
# if pmi.workerIsActive():
# self.cxxclass.enableAdress(self);
if pmi.isController :
class LangevinThermostat(Extension):
__metaclass__ = pmi.Proxy
pmiproxydefs = dict(
cls = 'espressopp.integrator.LangevinThermostatLocal',
pmiproperty = [ 'gamma', 'temperature', 'adress' ]
)
| capoe/espressopp.soap | src/integrator/LangevinThermostat.py | Python | gpl-3.0 | 1,956 |
asm(1000){
var a = 1;
};
| soliton4/promiseLand-website | release/client/promiseland/playground/asmsyntax.js | JavaScript | gpl-3.0 | 27 |
<?php
/**
* Modify layout using filter
*/
/**
* Available actions (by ref)
* dynamic_block_{block_name}_before where block_name is name of block e.g. header. action can have two arguments "block" and "block_settings" as array
* dynamic_block_{block_name}_before_block_items
* dynamic_block_{block_name}_after where block_name is name of block e.g. header. action can have two arguments "block" and "block_settings" as array
* If you want to disable certain block base on certain condition(s), you can add hide key to $block
* You can override render callback of block items by writing a function theme_block_item_{block_item_id} where block_item_id is id of block item e.g. widget, shortcode, post_loop etc.
*/
/**
* Manipulate block items at runtime.
* Add logos dynamically without providing any control to user.
*
* @since 1.0.0.0
*
* @param ref array $block_items list of block items in a block
* @return void
*/
function le_theme_filter_header_block_items(&$block_items)
{
if(!empty($block_items))
{
$blocks_new = array();
$blocks_new[] = array(
'id' => 'theme_logo',
'name' => 'Runtime Logos',
'title' => '',
'columns' => 3,
'runtime_id' => 'o7r7ot',
'args' => array()
);
foreach($block_items as $item)
$blocks_new[] = $item;
$block_items = $blocks_new;
}
}
add_action('dynamic_block_header_before_block_items', 'le_theme_filter_header_block_items')
?> | simpleux/le-twentyeleven | extensions/hard_coded_filters.php | PHP | gpl-3.0 | 1,457 |
package monitor;
public interface RunnableWithResult<T> {
public T run() ;
}
| erseco/ugr_sistemas_concurrentes_distribuidos | Practica_02_monitores/monitor/RunnableWithResult.java | Java | gpl-3.0 | 84 |
/*
Copyright (C) 2013 Hong Jen Yee (PCMan) <pcman.tw@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "filepropsdialog.h"
#include "ui_file-props.h"
#include "icontheme.h"
#include "utilities.h"
#include "fileoperation.h"
#include <QStringBuilder>
#include <QStringListModel>
#include <QMessageBox>
#include <qdial.h>
#include <sys/types.h>
#include <time.h>
#define DIFFERENT_UIDS ((uid)-1)
#define DIFFERENT_GIDS ((gid)-1)
#define DIFFERENT_PERMS ((mode_t)-1)
using namespace Fm;
enum {
ACCESS_NO_CHANGE = 0,
ACCESS_READ_ONLY,
ACCESS_READ_WRITE,
ACCESS_FORBID
};
FilePropsDialog::FilePropsDialog(FmFileInfoList* files, QWidget* parent, Qt::WindowFlags f):
QDialog(parent, f),
fileInfos_(fm_file_info_list_ref(files)),
singleType(fm_file_info_list_is_same_type(files)),
singleFile(fm_file_info_list_get_length(files) == 1 ? true:false),
fileInfo(fm_file_info_list_peek_head(files)),
mimeType(NULL) {
setAttribute(Qt::WA_DeleteOnClose);
ui = new Ui::FilePropsDialog();
ui->setupUi(this);
if(singleType) {
mimeType = fm_mime_type_ref(fm_file_info_get_mime_type(fileInfo));
}
FmPathList* paths = fm_path_list_new_from_file_info_list(files);
deepCountJob = fm_deep_count_job_new(paths, FM_DC_JOB_DEFAULT);
fm_path_list_unref(paths);
initGeneralPage();
initPermissionsPage();
}
FilePropsDialog::~FilePropsDialog() {
delete ui;
if(fileInfos_)
fm_file_info_list_unref(fileInfos_);
if(deepCountJob)
g_object_unref(deepCountJob);
if(fileSizeTimer) {
fileSizeTimer->stop();
delete fileSizeTimer;
fileSizeTimer = NULL;
}
}
void FilePropsDialog::initApplications() {
if(singleType && mimeType && !fm_file_info_is_dir(fileInfo)) {
ui->openWith->setMimeType(mimeType);
}
else {
ui->openWith->hide();
ui->openWithLabel->hide();
}
}
void FilePropsDialog::initPermissionsPage() {
// ownership handling
// get owner/group and mode of the first file in the list
uid = fm_file_info_get_uid(fileInfo);
gid = fm_file_info_get_gid(fileInfo);
mode_t mode = fm_file_info_get_mode(fileInfo);
ownerPerm = (mode & (S_IRUSR|S_IWUSR|S_IXUSR));
groupPerm = (mode & (S_IRGRP|S_IWGRP|S_IXGRP));
otherPerm = (mode & (S_IROTH|S_IWOTH|S_IXOTH));
execPerm = (mode & (S_IXUSR|S_IXGRP|S_IXOTH));
allNative = fm_file_info_is_native(fileInfo);
hasDir = S_ISDIR(mode);
// check if all selected files belongs to the same owner/group or have the same mode
// at the same time, check if all files are on native unix filesystems
GList* l;
for(l = fm_file_info_list_peek_head_link(fileInfos_)->next; l; l = l->next) {
FmFileInfo* fi = FM_FILE_INFO(l->data);
if(allNative && !fm_file_info_is_native(fi))
allNative = false; // not all of the files are native
mode_t fi_mode = fm_file_info_get_mode(fi);
if(S_ISDIR(fi_mode))
hasDir = true; // the files list contains dir(s)
if(uid != DIFFERENT_UIDS && uid != fm_file_info_get_uid(fi))
uid = DIFFERENT_UIDS; // not all files have the same owner
if(gid != DIFFERENT_GIDS && gid != fm_file_info_get_gid(fi))
gid = DIFFERENT_GIDS; // not all files have the same owner group
if(ownerPerm != DIFFERENT_PERMS && ownerPerm != (fi_mode & (S_IRUSR|S_IWUSR|S_IXUSR)))
ownerPerm = DIFFERENT_PERMS; // not all files have the same permission for owner
if(groupPerm != DIFFERENT_PERMS && groupPerm != (fi_mode & (S_IRGRP|S_IWGRP|S_IXGRP)))
groupPerm = DIFFERENT_PERMS; // not all files have the same permission for grop
if(otherPerm != DIFFERENT_PERMS && otherPerm != (fi_mode & (S_IROTH|S_IWOTH|S_IXOTH)))
otherPerm = DIFFERENT_PERMS; // not all files have the same permission for other
if(execPerm != DIFFERENT_PERMS && execPerm != (fi_mode & (S_IXUSR|S_IXGRP|S_IXOTH)))
execPerm = DIFFERENT_PERMS; // not all files have the same executable permission
}
// init owner/group
initOwner();
// if all files are of the same type, and some of them are dirs => all of the items are dirs
// rwx values have different meanings for dirs
// Let's make it clear for the users
// init combo boxes for file permissions here
QStringList comboItems;
comboItems.append("---"); // no change
if(singleType && hasDir) { // all files are dirs
comboItems.append(tr("View folder content"));
comboItems.append(tr("View and modify folder content"));
ui->executable->hide();
}
else { //not all of the files are dirs
comboItems.append(tr("Read"));
comboItems.append(tr("Read and write"));
}
comboItems.append(tr("Forbidden"));
QStringListModel* comboModel = new QStringListModel(comboItems, this);
ui->ownerPerm->setModel(comboModel);
ui->groupPerm->setModel(comboModel);
ui->otherPerm->setModel(comboModel);
// owner
ownerPermSel = ACCESS_NO_CHANGE;
if(ownerPerm != DIFFERENT_PERMS) { // permissions for owner are the same among all files
if(ownerPerm & S_IRUSR) { // can read
if(ownerPerm & S_IWUSR) // can write
ownerPermSel = ACCESS_READ_WRITE;
else
ownerPermSel = ACCESS_READ_ONLY;
}
else {
if((ownerPerm & S_IWUSR) == 0) // cannot read or write
ownerPermSel = ACCESS_FORBID;
}
}
ui->ownerPerm->setCurrentIndex(ownerPermSel);
// owner and group
groupPermSel = ACCESS_NO_CHANGE;
if(groupPerm != DIFFERENT_PERMS) { // permissions for owner are the same among all files
if(groupPerm & S_IRGRP) { // can read
if(groupPerm & S_IWGRP) // can write
groupPermSel = ACCESS_READ_WRITE;
else
groupPermSel = ACCESS_READ_ONLY;
}
else {
if((groupPerm & S_IWGRP) == 0) // cannot read or write
groupPermSel = ACCESS_FORBID;
}
}
ui->groupPerm->setCurrentIndex(groupPermSel);
// other
otherPermSel = ACCESS_NO_CHANGE;
if(otherPerm != DIFFERENT_PERMS) { // permissions for owner are the same among all files
if(otherPerm & S_IROTH) { // can read
if(otherPerm & S_IWOTH) // can write
otherPermSel = ACCESS_READ_WRITE;
else
otherPermSel = ACCESS_READ_ONLY;
}
else {
if((otherPerm & S_IWOTH) == 0) // cannot read or write
otherPermSel = ACCESS_FORBID;
}
}
ui->otherPerm->setCurrentIndex(otherPermSel);
// set the checkbox to partially checked state
// when owner, group, and other have different executable flags set.
// some of them have exec, and others do not have.
execCheckState = Qt::PartiallyChecked;
if(execPerm != DIFFERENT_PERMS) { // if all files have the same executable permission
// check if the files are all executable
if((mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == (S_IXUSR|S_IXGRP|S_IXOTH)) {
// owner, group, and other all have exec permission.
execCheckState = Qt::Checked;
}
else if((mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
// owner, group, and other all have no exec permission
execCheckState = Qt::Unchecked;
}
}
ui->executable->setCheckState(execCheckState);
}
void FilePropsDialog::initGeneralPage() {
// update UI
if(singleType) { // all files are of the same mime-type
FmIcon* icon = NULL;
// FIXME: handle custom icons for some files
// FIXME: display special property pages for special files or
// some specified mime-types.
if(singleFile) { // only one file is selected.
icon = fm_file_info_get_icon(fileInfo);
}
if(mimeType) {
if(!icon) // get an icon from mime type if needed
icon = fm_mime_type_get_icon(mimeType);
ui->fileType->setText(QString::fromUtf8(fm_mime_type_get_desc(mimeType)));
ui->mimeType->setText(QString::fromUtf8(fm_mime_type_get_type(mimeType)));
}
if(icon) {
ui->iconButton->setIcon(IconTheme::icon(icon));
}
if(singleFile && fm_file_info_is_symlink(fileInfo)) {
ui->target->setText(QString::fromUtf8(fm_file_info_get_target(fileInfo)));
}
else {
ui->target->hide();
ui->targetLabel->hide();
}
} // end if(singleType)
else { // not singleType, multiple files are selected at the same time
ui->fileType->setText(tr("Files of different types"));
ui->target->hide();
ui->targetLabel->hide();
}
// FIXME: check if all files has the same parent dir, mtime, or atime
if(singleFile) { // only one file is selected
FmPath* parent_path = fm_path_get_parent(fm_file_info_get_path(fileInfo));
char* parent_str = parent_path ? fm_path_display_name(parent_path, true) : NULL;
ui->fileName->setText(QString::fromUtf8(fm_file_info_get_disp_name(fileInfo)));
if(parent_str) {
ui->location->setText(QString::fromUtf8(parent_str));
g_free(parent_str);
}
else
ui->location->clear();
ui->lastModified->setText(QString::fromUtf8(fm_file_info_get_disp_mtime(fileInfo)));
// FIXME: need to encapsulate this in an libfm API.
time_t atime;
struct tm tm;
atime = fm_file_info_get_atime(fileInfo);
localtime_r(&atime, &tm);
char buf[128];
strftime(buf, sizeof(buf), "%x %R", &tm);
ui->lastAccessed->setText(QString::fromUtf8(buf));
}
else {
ui->fileName->setText(tr("Multiple Files"));
ui->fileName->setEnabled(false);
}
initApplications(); // init applications combo box
// calculate total file sizes
fileSizeTimer = new QTimer(this);
connect(fileSizeTimer, SIGNAL(timeout()), SLOT(onFileSizeTimerTimeout()));
fileSizeTimer->start(600);
g_signal_connect(deepCountJob, "finished", G_CALLBACK(onDeepCountJobFinished), this);
fm_job_run_async(FM_JOB(deepCountJob));
}
/*static */ void FilePropsDialog::onDeepCountJobFinished(FmDeepCountJob* job, FilePropsDialog* pThis) {
pThis->onFileSizeTimerTimeout(); // update file size display
// free the job
g_object_unref(pThis->deepCountJob);
pThis->deepCountJob = NULL;
// stop the timer
if(pThis->fileSizeTimer) {
pThis->fileSizeTimer->stop();
delete pThis->fileSizeTimer;
pThis->fileSizeTimer = NULL;
}
}
void FilePropsDialog::onFileSizeTimerTimeout() {
if(deepCountJob && !fm_job_is_cancelled(FM_JOB(deepCountJob))) {
char size_str[128];
fm_file_size_to_str(size_str, sizeof(size_str), deepCountJob->total_size,
fm_config->si_unit);
// FIXME:
// OMG! It's really unbelievable that Qt developers only implement
// QObject::tr(... int n). GNU gettext developers are smarter and
// they use unsigned long instead of int.
// We cannot use Qt here to handle plural forms. So sad. :-(
QString str = QString::fromUtf8(size_str) %
QString(" (%1 B)").arg(deepCountJob->total_size);
// tr(" (%n) byte(s)", "", deepCountJob->total_size);
ui->fileSize->setText(str);
fm_file_size_to_str(size_str, sizeof(size_str), deepCountJob->total_ondisk_size,
fm_config->si_unit);
str = QString::fromUtf8(size_str) %
QString(" (%1 B)").arg(deepCountJob->total_ondisk_size);
// tr(" (%n) byte(s)", "", deepCountJob->total_ondisk_size);
ui->onDiskSize->setText(str);
}
}
void FilePropsDialog::accept() {
// applications
if(mimeType && ui->openWith->isChanged()) {
GAppInfo* currentApp = ui->openWith->selectedApp();
g_app_info_set_as_default_for_type(currentApp, fm_mime_type_get_type(mimeType), NULL);
}
// check if chown or chmod is needed
guint32 newUid = uidFromName(ui->owner->text());
guint32 newGid = gidFromName(ui->ownerGroup->text());
bool needChown = (newUid != uid || newGid != gid);
int newOwnerPermSel = ui->ownerPerm->currentIndex();
int newGroupPermSel = ui->groupPerm->currentIndex();
int newOtherPermSel = ui->otherPerm->currentIndex();
Qt::CheckState newExecCheckState = ui->executable->checkState();
bool needChmod = ((newOwnerPermSel != ownerPermSel) ||
(newGroupPermSel != groupPermSel) ||
(newOtherPermSel != otherPermSel) ||
(newExecCheckState != execCheckState));
if(needChmod || needChown) {
FmPathList* paths = fm_path_list_new_from_file_info_list(fileInfos_);
FileOperation* op = new FileOperation(FileOperation::ChangeAttr, paths);
fm_path_list_unref(paths);
if(needChown) {
// don't do chown if new uid/gid and the original ones are actually the same.
if(newUid == uid)
newUid = -1;
if(newGid == gid)
newGid = -1;
op->setChown(newUid, newGid);
}
if(needChmod) {
mode_t newMode = 0;
mode_t newModeMask = 0;
// FIXME: we need to make sure that folders with "r" permission also have "x"
// at the same time. Otherwise, it's not able to browse the folder later.
if(newOwnerPermSel != ownerPermSel && newOwnerPermSel != ACCESS_NO_CHANGE) {
// owner permission changed
newModeMask |= (S_IRUSR|S_IWUSR); // affect user bits
if(newOwnerPermSel == ACCESS_READ_ONLY)
newMode |= S_IRUSR;
else if(newOwnerPermSel == ACCESS_READ_WRITE)
newMode |= (S_IRUSR|S_IWUSR);
}
if(newGroupPermSel != groupPermSel && newGroupPermSel != ACCESS_NO_CHANGE) {
qDebug("newGroupPermSel: %d", newGroupPermSel);
// group permission changed
newModeMask |= (S_IRGRP|S_IWGRP); // affect group bits
if(newGroupPermSel == ACCESS_READ_ONLY)
newMode |= S_IRGRP;
else if(newGroupPermSel == ACCESS_READ_WRITE)
newMode |= (S_IRGRP|S_IWGRP);
}
if(newOtherPermSel != otherPermSel && newOtherPermSel != ACCESS_NO_CHANGE) {
// other permission changed
newModeMask |= (S_IROTH|S_IWOTH); // affect other bits
if(newOtherPermSel == ACCESS_READ_ONLY)
newMode |= S_IROTH;
else if(newOtherPermSel == ACCESS_READ_WRITE)
newMode |= (S_IROTH|S_IWOTH);
}
if(newExecCheckState != execCheckState && newExecCheckState != Qt::PartiallyChecked) {
// executable state changed
newModeMask |= (S_IXUSR|S_IXGRP|S_IXOTH);
if(newExecCheckState == Qt::Checked)
newMode |= (S_IXUSR|S_IXGRP|S_IXOTH);
}
op->setChmod(newMode, newModeMask);
if(hasDir) { // if there are some dirs in our selected files
QMessageBox::StandardButton r = QMessageBox::question(this,
tr("Apply changes"),
tr("Do you want to recursively apply these changes to all files and sub-folders?"),
QMessageBox::Yes|QMessageBox::No);
if(r == QMessageBox::Yes)
op->setRecursiveChattr(true);
}
}
op->setAutoDestroy(true);
op->run();
}
QDialog::accept();
}
void FilePropsDialog::initOwner() {
if(allNative) {
if(uid != DIFFERENT_UIDS)
ui->owner->setText(uidToName(uid));
if(gid != DIFFERENT_GIDS)
ui->ownerGroup->setText(gidToName(gid));
if(geteuid() != 0) { // on local filesystems, only root can do chown.
ui->owner->setEnabled(false);
ui->ownerGroup->setEnabled(false);
}
}
}
| MoonLightDE/MoonLightDE | src/file-manager/libfm-qt/filepropsdialog.cpp | C++ | gpl-3.0 | 15,744 |
/************************************************************************
Extended WPF Toolkit
Copyright (C) 2010-2012 Xceed Software Inc.
This program is provided to you under the terms of the Microsoft Public
License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license
This program can be provided to you by Xceed Software Inc. under a
proprietary commercial license agreement for use in non-Open Source
projects. The commercial version of Extended WPF Toolkit also includes
priority technical support, commercial updates, and many additional
useful WPF controls if you license Xceed Business Suite for WPF.
Visit http://xceed.com and follow @datagrid on Twitter.
**********************************************************************/
using System;
using System.Windows.Data;
using System.Windows.Media;
namespace Xceed.Wpf.Toolkit.Core.Converters
{
public class ColorToSolidColorBrushConverter : IValueConverter
{
#region IValueConverter Members
/// <summary>
/// Converts a Color to a SolidColorBrush.
/// </summary>
/// <param name="value">The Color produced by the binding source.</param>
/// <param name="targetType">The type of the binding target property.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
/// <returns>
/// A converted SolidColorBrush. If the method returns null, the valid null value is used.
/// </returns>
public object Convert( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
{
if( value != null )
return new SolidColorBrush( ( Color )value );
return value;
}
/// <summary>
/// Converts a SolidColorBrush to a Color.
/// </summary>
/// <remarks>Currently not used in toolkit, but provided for developer use in their own projects</remarks>
/// <param name="value">The SolidColorBrush that is produced by the binding target.</param>
/// <param name="targetType">The type to convert to.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
/// <returns>
/// A converted value. If the method returns null, the valid null value is used.
/// </returns>
public object ConvertBack( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
{
if( value != null )
return ( ( SolidColorBrush )value ).Color;
return value;
}
#endregion
}
}
| Emudofus/BehaviorIsManaged | Librairies/WPFToolkit.Extended/Core/Converters/ColorToSolidColorBrushConverter.cs | C# | gpl-3.0 | 2,652 |
package handling.handlers;
import java.awt.Point;
import client.MapleClient;
import handling.PacketHandler;
import handling.RecvPacketOpcode;
import server.MaplePortal;
import tools.data.LittleEndianAccessor;
public class UseInnerPortalHandler {
@PacketHandler(opcode = RecvPacketOpcode.USE_INNER_PORTAL)
public static void handle(MapleClient c, LittleEndianAccessor lea) {
lea.skip(1);
if (c.getPlayer() == null || c.getPlayer().getMap() == null) {
return;
}
String portalName = lea.readMapleAsciiString();
MaplePortal portal = c.getPlayer().getMap().getPortal(portalName);
if (portal == null) {
return;
}
//That "22500" should not be hard coded in this manner
if (portal.getPosition().distanceSq(c.getPlayer().getTruePosition()) > 22500.0D && !c.getPlayer().isGM()) {
return;
}
int toX = lea.readShort();
int toY = lea.readShort();
//Are there not suppose to be checks here? Can players not just PE any x and y value they want?
c.getPlayer().getMap().movePlayer(c.getPlayer(), new Point(toX, toY));
c.getPlayer().checkFollow();
}
}
| Maxcloud/Mushy | src/handling/handlers/UseInnerPortalHandler.java | Java | gpl-3.0 | 1,090 |
// This file is part of Hermes2D.
//
// Hermes2D 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.
//
// Hermes2D 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 Hermes2D. If not, see <http://www.gnu.org/licenses/>.
#include "curved.h"
#include <algorithm>
#include "global.h"
#include "shapeset/shapeset_h1_all.h"
#include "shapeset/shapeset_common.h"
#include "shapeset/precalc.h"
#include "mesh.h"
#include "quad_all.h"
#include "matrix.h"
#include "algebra/dense_matrix_operations.h"
using namespace Hermes::Algebra::DenseMatrixOperations;
namespace Hermes
{
namespace Hermes2D
{
HERMES_API Quad1DStd g_quad_1d_std;
HERMES_API Quad2DStd g_quad_2d_std;
H1ShapesetJacobi ref_map_shapeset;
PrecalcShapesetAssembling ref_map_pss_static(&ref_map_shapeset);
CurvMapStatic::CurvMapStatic()
{
int order = ref_map_shapeset.get_max_order();
this->edge_proj_matrix_size = order - 1;
// Edges.
this->edge_proj_matrix = new_matrix<double>(edge_proj_matrix_size, edge_proj_matrix_size);
edge_p = malloc_with_check<double>(edge_proj_matrix_size);
// Bubbles - triangles.
this->tri_bubble_np = ref_map_shapeset.get_num_bubbles(order, HERMES_MODE_TRIANGLE);
bubble_proj_matrix_tri = new_matrix<double>(tri_bubble_np, tri_bubble_np);
bubble_tri_p = malloc_with_check<double>(tri_bubble_np);
// Bubbles - quads.
order = H2D_MAKE_QUAD_ORDER(order, order);
this->quad_bubble_np = ref_map_shapeset.get_num_bubbles(order, HERMES_MODE_QUAD);
bubble_proj_matrix_quad = new_matrix<double>(quad_bubble_np, quad_bubble_np);
bubble_quad_p = malloc_with_check<double>(quad_bubble_np);
this->precalculate_cholesky_projection_matrices_bubble();
this->precalculate_cholesky_projection_matrix_edge();
}
CurvMapStatic::~CurvMapStatic()
{
free_with_check(edge_proj_matrix, true);
free_with_check(bubble_proj_matrix_tri, true);
free_with_check(bubble_proj_matrix_quad, true);
free_with_check(edge_p);
free_with_check(bubble_tri_p);
free_with_check(bubble_quad_p);
}
double** CurvMapStatic::calculate_bubble_projection_matrix(short* indices, ElementMode2D mode)
{
unsigned short nb;
double** mat;
if (mode == HERMES_MODE_TRIANGLE)
{
mat = this->bubble_proj_matrix_tri;
nb = this->tri_bubble_np;
}
else
{
mat = this->bubble_proj_matrix_quad;
nb = this->quad_bubble_np;
}
PrecalcShapesetAssembling ref_map_pss_static_temp(&ref_map_shapeset);
ref_map_pss_static_temp.set_active_element(ref_map_pss_static.get_active_element());
for (unsigned short i = 0; i < nb; i++)
{
for (unsigned short j = i; j < nb; j++)
{
short ii = indices[i], ij = indices[j];
unsigned short o = ref_map_shapeset.get_order(ii, mode) + ref_map_shapeset.get_order(ij, mode);
o = std::max(H2D_GET_V_ORDER(o), H2D_GET_H_ORDER(o));
ref_map_pss_static.set_active_shape(ii);
ref_map_pss_static.set_quad_order(o, H2D_FN_VAL);
const double* fni = ref_map_pss_static.get_fn_values();
ref_map_pss_static_temp.set_active_shape(ij);
ref_map_pss_static_temp.set_quad_order(o, H2D_FN_VAL);
const double* fnj = ref_map_pss_static_temp.get_fn_values();
double3* pt = g_quad_2d_std.get_points(o, mode);
double val = 0.0;
for (unsigned short k = 0; k < g_quad_2d_std.get_num_points(o, mode); k++)
val += pt[k][2] * (fni[k] * fnj[k]);
mat[i][j] = mat[j][i] = val;
}
}
return mat;
}
void CurvMapStatic::precalculate_cholesky_projection_matrices_bubble()
{
// *** triangles ***
// calculate projection matrix of maximum order
{
Element e;
e.nvert = 3;
e.cm = nullptr;
e.id = -1;
ref_map_pss_static.set_active_element(&e);
short* indices = ref_map_shapeset.get_bubble_indices(ref_map_shapeset.get_max_order(), HERMES_MODE_TRIANGLE);
curvMapStatic.bubble_proj_matrix_tri = calculate_bubble_projection_matrix(indices, HERMES_MODE_TRIANGLE);
// cholesky factorization of the matrix
choldc(curvMapStatic.bubble_proj_matrix_tri, this->tri_bubble_np, curvMapStatic.bubble_tri_p);
}
// *** quads ***
// calculate projection matrix of maximum order
{
Element e;
e.nvert = 4;
e.cm = nullptr;
e.id = -1;
ref_map_pss_static.set_active_element(&e);
short *indices = ref_map_shapeset.get_bubble_indices(H2D_MAKE_QUAD_ORDER(ref_map_shapeset.get_max_order(), ref_map_shapeset.get_max_order()), HERMES_MODE_QUAD);
curvMapStatic.bubble_proj_matrix_quad = calculate_bubble_projection_matrix(indices, HERMES_MODE_QUAD);
// cholesky factorization of the matrix
choldc(curvMapStatic.bubble_proj_matrix_quad, this->quad_bubble_np, curvMapStatic.bubble_quad_p);
}
}
void CurvMapStatic::precalculate_cholesky_projection_matrix_edge()
{
// calculate projection matrix of maximum order
for (int i = 0; i < this->edge_proj_matrix_size; i++)
{
for (int j = i; j < this->edge_proj_matrix_size; j++)
{
int o = i + j + 4;
double2* pt = g_quad_1d_std.get_points(o);
double val = 0.0;
for (int k = 0; k < g_quad_1d_std.get_num_points(o); k++)
{
double fi = 0;
double fj = 0;
double x = pt[k][0];
switch (i + 2)
{
case 0:
fi = l0(x);
break;
case 1:
fi = l1(x);
break;
case 2:
fi = l2(x);
break;
case 3:
fi = l3(x);
break;
case 4:
fi = l4(x);
break;
case 5:
fi = l5(x);
break;
case 6:
fi = l6(x);
break;
case 7:
fi = l7(x);
break;
case 8:
fi = l8(x);
break;
case 9:
fi = l9(x);
break;
case 10:
fi = l10(x);
break;
case 11:
fi = l11(x);
break;
}
switch (j + 2)
{
case 0:
fj = l0(x);
break;
case 1:
fj = l1(x);
break;
case 2:
fj = l2(x);
break;
case 3:
fj = l3(x);
break;
case 4:
fj = l4(x);
break;
case 5:
fj = l5(x);
break;
case 6:
fj = l6(x);
break;
case 7:
fj = l7(x);
break;
case 8:
fj = l8(x);
break;
case 9:
fj = l9(x);
break;
case 10:
fj = l10(x);
break;
case 11:
fj = l11(x);
break;
}
val += pt[k][1] * (fi * fj);
}
this->edge_proj_matrix[i][j] = this->edge_proj_matrix[j][i] = val;
}
}
// Cholesky factorization of the matrix
choldc(this->edge_proj_matrix, this->edge_proj_matrix_size, this->edge_p);
}
CurvMapStatic curvMapStatic;
Curve::Curve(CurvType type) : type(type)
{
}
Curve::~Curve()
{
}
Arc::Arc() : Curve(ArcType)
{
kv[0] = kv[1] = kv[2] = 0;
kv[3] = kv[4] = kv[5] = 1;
}
Arc::Arc(double angle) : Curve(ArcType), angle(angle)
{
kv[0] = kv[1] = kv[2] = 0;
kv[3] = kv[4] = kv[5] = 1;
}
Arc::Arc(const Arc* other) : Curve(ArcType)
{
this->angle = other->angle;
memcpy(this->kv, other->kv, 6 * sizeof(double));
memcpy(this->pt, other->pt, 3 * sizeof(double3));
}
Nurbs::Nurbs() : Curve(NurbsType)
{
pt = nullptr;
kv = nullptr;
};
Nurbs::~Nurbs()
{
free_with_check(pt);
free_with_check(kv);
};
Nurbs::Nurbs(const Nurbs* other) : Curve(NurbsType)
{
this->degree = other->degree;
this->nk = other->nk;
this->np = other->np;
this->kv = malloc_with_check<double>(nk);
this->pt = malloc_with_check<double3>(np);
}
static double lambda_0(double x, double y)
{
return -0.5 * (x + y);
}
static double lambda_1(double x, double y)
{
return 0.5 * (x + 1);
}
static double lambda_2(double x, double y)
{
return 0.5 * (y + 1);
}
CurvMap::CurvMap() : ref_map_pss(&ref_map_shapeset)
{
coeffs = nullptr;
ctm = nullptr;
memset(curves, 0, sizeof(Curve*)* H2D_MAX_NUMBER_EDGES);
this->parent = nullptr;
this->sub_idx = 0;
}
CurvMap::CurvMap(const CurvMap* cm) : ref_map_pss(&ref_map_shapeset)
{
this->nc = cm->nc;
this->order = cm->order;
/// \todo Find out if this is safe.
this->ctm = cm->ctm;
this->coeffs = malloc_with_check<double2>(nc, true);
memcpy(coeffs, cm->coeffs, sizeof(double2)* nc);
this->toplevel = cm->toplevel;
if (this->toplevel)
{
for (int i = 0; i < 4; i++)
{
if (cm->curves[i])
{
if (cm->curves[i]->type == NurbsType)
this->curves[i] = new Nurbs((Nurbs*)cm->curves[i]);
else
this->curves[i] = new Arc((Arc*)cm->curves[i]);
}
else
this->curves[i] = nullptr;
}
this->parent = nullptr;
this->sub_idx = 0;
}
else
{
memset(curves, 0, sizeof(Curve*)* H2D_MAX_NUMBER_EDGES);
this->parent = cm->parent;
this->sub_idx = cm->sub_idx;
}
}
CurvMap::~CurvMap()
{
this->free();
}
void CurvMap::free()
{
free_with_check(this->coeffs, true);
if (toplevel)
{
for (int i = 0; i < 4; i++)
if (curves[i])
{
delete curves[i];
curves[i] = nullptr;
}
}
}
double CurvMap::nurbs_basis_fn(unsigned short i, unsigned short k, double t, double* knot)
{
if (k == 0)
{
return (t >= knot[i] && t <= knot[i + 1] && knot[i] < knot[i + 1]) ? 1.0 : 0.0;
}
else
{
double N1 = nurbs_basis_fn(i, k - 1, t, knot);
double N2 = nurbs_basis_fn(i + 1, k - 1, t, knot);
if ((N1 > HermesEpsilon) || (N2 > HermesEpsilon))
{
double result = 0.0;
if ((N1 > HermesEpsilon) && knot[i + k] != knot[i])
result += ((t - knot[i]) / (knot[i + k] - knot[i])) * N1;
if ((N2 > HermesEpsilon) && knot[i + k + 1] != knot[i + 1])
result += ((knot[i + k + 1] - t) / (knot[i + k + 1] - knot[i + 1])) * N2;
return result;
}
else
return 0.0;
}
}
void CurvMap::nurbs_edge(Element* e, Curve* curve, int edge, double t, double& x,
double& y)
{
// Nurbs curves are parametrized from 0 to 1.
t = (t + 1.0) / 2.0;
// Start point A, end point B.
double2 A = { e->vn[edge]->x, e->vn[edge]->y };
double2 B = { e->vn[e->next_vert(edge)]->x, e->vn[e->next_vert(edge)]->y };
// Vector pointing from A to B.
double2 v = { B[0] - A[0], B[1] - A[1] };
// Straight line.
if (!curve)
{
x = A[0] + t * v[0];
y = A[1] + t * v[1];
}
else
{
double3* cp;
int degree, np;
double* kv;
if (curve->type == ArcType)
{
cp = ((Arc*)curve)->pt;
np = ((Arc*)curve)->np;
degree = ((Arc*)curve)->degree;
kv = ((Arc*)curve)->kv;
}
else
{
cp = ((Nurbs*)curve)->pt;
np = ((Nurbs*)curve)->np;
degree = ((Nurbs*)curve)->degree;
kv = ((Nurbs*)curve)->kv;
}
// sum of basis fns and weights
double sum = 0.0;
x = y = 0.0;
for (int i = 0; i < np; i++)
{
double basis = nurbs_basis_fn(i, degree, t, kv);
sum += cp[i][2] * basis;
double x_i = cp[i][0];
double y_i = cp[i][1];
double w_i = cp[i][2];
x += w_i * basis * x_i;
y += w_i * basis * y_i;
}
x /= sum;
y /= sum;
}
}
const double2 CurvMap::ref_vert[2][H2D_MAX_NUMBER_VERTICES] =
{
{ { -1.0, -1.0 }, { 1.0, -1.0 }, { -1.0, 1.0 }, { 0.0, 0.0 } },
{ { -1.0, -1.0 }, { 1.0, -1.0 }, { 1.0, 1.0 }, { -1.0, 1.0 } }
};
void CurvMap::nurbs_edge_0(Element* e, Curve* curve, unsigned short edge, double t, double& x, double& y, double& n_x, double& n_y, double& t_x, double& t_y)
{
unsigned short va = edge;
unsigned short vb = e->next_vert(edge);
nurbs_edge(e, curve, edge, t, x, y);
x -= 0.5 * ((1 - t) * (e->vn[va]->x) + (1 + t) * (e->vn[vb]->x));
y -= 0.5 * ((1 - t) * (e->vn[va]->y) + (1 + t) * (e->vn[vb]->y));
double k = 4.0 / ((1 - t) * (1 + t));
x *= k;
y *= k;
}
void CurvMap::calc_ref_map_tri(Element* e, Curve** curve, double xi_1, double xi_2, double& x, double& y)
{
double fx, fy;
x = y = 0.0;
double l[3] = { lambda_0(xi_1, xi_2), lambda_1(xi_1, xi_2), lambda_2(xi_1, xi_2) };
for (unsigned char j = 0; j < e->get_nvert(); j++)
{
int va = j;
int vb = e->next_vert(j);
double la = l[va];
double lb = l[vb];
// vertex part
x += e->vn[j]->x * la;
y += e->vn[j]->y * la;
if (!(((ref_vert[0][va][0] == xi_1) && (ref_vert[0][va][1] == xi_2)) || ((ref_vert[0][vb][0] == xi_1) && (ref_vert[0][vb][1] == xi_2))))
{
// edge part
double t = lb - la;
double n_x, n_y, t_x, t_y;
nurbs_edge_0(e, curve[j], j, t, fx, fy, n_x, n_y, t_x, t_y);
x += fx * lb * la;
y += fy * lb * la;
}
}
}
void CurvMap::calc_ref_map_quad(Element* e, Curve** curve, double xi_1, double xi_2,
double& x, double& y)
{
double ex[H2D_MAX_NUMBER_EDGES], ey[H2D_MAX_NUMBER_EDGES];
nurbs_edge(e, curve[0], 0, xi_1, ex[0], ey[0]);
nurbs_edge(e, curve[1], 1, xi_2, ex[1], ey[1]);
nurbs_edge(e, curve[2], 2, -xi_1, ex[2], ey[2]);
nurbs_edge(e, curve[3], 3, -xi_2, ex[3], ey[3]);
x = (1 - xi_2) / 2.0 * ex[0] + (1 + xi_1) / 2.0 * ex[1] +
(1 + xi_2) / 2.0 * ex[2] + (1 - xi_1) / 2.0 * ex[3] -
(1 - xi_1)*(1 - xi_2) / 4.0 * e->vn[0]->x - (1 + xi_1)*(1 - xi_2) / 4.0 * e->vn[1]->x -
(1 + xi_1)*(1 + xi_2) / 4.0 * e->vn[2]->x - (1 - xi_1)*(1 + xi_2) / 4.0 * e->vn[3]->x;
y = (1 - xi_2) / 2.0 * ey[0] + (1 + xi_1) / 2.0 * ey[1] +
(1 + xi_2) / 2.0 * ey[2] + (1 - xi_1) / 2.0 * ey[3] -
(1 - xi_1)*(1 - xi_2) / 4.0 * e->vn[0]->y - (1 + xi_1)*(1 - xi_2) / 4.0 * e->vn[1]->y -
(1 + xi_1)*(1 + xi_2) / 4.0 * e->vn[2]->y - (1 - xi_1)*(1 + xi_2) / 4.0 * e->vn[3]->y;
}
void CurvMap::calc_ref_map(Element* e, Curve** curve, double xi_1, double xi_2, double2& f)
{
if (e->get_mode() == HERMES_MODE_QUAD)
calc_ref_map_quad(e, curve, xi_1, xi_2, f[0], f[1]);
else
calc_ref_map_tri(e, curve, xi_1, xi_2, f[0], f[1]);
}
void CurvMap::edge_coord(Element* e, unsigned short edge, double t, double2& x) const
{
unsigned short mode = e->get_mode();
double2 a, b;
a[0] = ctm->m[0] * ref_vert[mode][edge][0] + ctm->t[0];
a[1] = ctm->m[1] * ref_vert[mode][edge][1] + ctm->t[1];
b[0] = ctm->m[0] * ref_vert[mode][e->next_vert(edge)][0] + ctm->t[0];
b[1] = ctm->m[1] * ref_vert[mode][e->next_vert(edge)][1] + ctm->t[1];
for (int i = 0; i < 2; i++)
{
x[i] = a[i] + (t + 1.0) / 2.0 * (b[i] - a[i]);
}
}
void CurvMap::calc_edge_projection(Element* e, unsigned short edge, Curve** nurbs, unsigned short order, double2* proj) const
{
unsigned short i, j, k;
unsigned short mo1 = g_quad_1d_std.get_max_order();
unsigned char np = g_quad_1d_std.get_num_points(mo1);
unsigned short ne = order - 1;
unsigned short mode = e->get_mode();
assert(np <= 15 && ne <= 10);
double2 fn[15];
double rhside[2][10];
memset(rhside[0], 0, sizeof(double)* ne);
memset(rhside[1], 0, sizeof(double)* ne);
double a_1, a_2, b_1, b_2;
a_1 = ctm->m[0] * ref_vert[mode][edge][0] + ctm->t[0];
a_2 = ctm->m[1] * ref_vert[mode][edge][1] + ctm->t[1];
b_1 = ctm->m[0] * ref_vert[mode][e->next_vert(edge)][0] + ctm->t[0];
b_2 = ctm->m[1] * ref_vert[mode][e->next_vert(edge)][1] + ctm->t[1];
// values of nonpolynomial function in two vertices
double2 fa, fb;
calc_ref_map(e, nurbs, a_1, a_2, fa);
calc_ref_map(e, nurbs, b_1, b_2, fb);
double2* pt = g_quad_1d_std.get_points(mo1);
// over all integration points
for (j = 0; j < np; j++)
{
double2 x;
double t = pt[j][0];
edge_coord(e, edge, t, x);
calc_ref_map(e, nurbs, x[0], x[1], fn[j]);
for (k = 0; k < 2; k++)
fn[j][k] = fn[j][k] - (fa[k] + (t + 1) / 2.0 * (fb[k] - fa[k]));
}
double2* result = proj + e->get_nvert() + edge * (order - 1);
for (k = 0; k < 2; k++)
{
for (i = 0; i < ne; i++)
{
for (j = 0; j < np; j++)
{
double t = pt[j][0];
double fi = 0;
switch (i + 2)
{
case 0:
fi = l0(t);
break;
case 1:
fi = l1(t);
break;
case 2:
fi = l2(t);
break;
case 3:
fi = l3(t);
break;
case 4:
fi = l4(t);
break;
case 5:
fi = l5(t);
break;
case 6:
fi = l6(t);
break;
case 7:
fi = l7(t);
break;
case 8:
fi = l8(t);
break;
case 9:
fi = l9(t);
break;
case 10:
fi = l10(t);
break;
case 11:
fi = l11(t);
break;
}
rhside[k][i] += pt[j][1] * (fi * fn[j][k]);
}
}
// solve
cholsl(curvMapStatic.edge_proj_matrix, ne, curvMapStatic.edge_p, rhside[k], rhside[k]);
for (i = 0; i < ne; i++)
result[i][k] = rhside[k][i];
}
}
void CurvMap::old_projection(Element* e, unsigned short order, double2* proj, double* old[2])
{
unsigned short mo2 = g_quad_2d_std.get_max_order(e->get_mode());
unsigned char np = g_quad_2d_std.get_num_points(mo2, e->get_mode());
unsigned short nvert = e->get_nvert();
for (unsigned int k = 0; k < nvert; k++) // loop over vertices
{
// vertex basis functions in all integration points
int index_v = ref_map_shapeset.get_vertex_index(k, e->get_mode());
ref_map_pss.set_active_shape(index_v);
ref_map_pss.set_quad_order(mo2, H2D_FN_VAL_0);
const double* vd = ref_map_pss.get_fn_values();
for (int m = 0; m < 2; m++) // part 0 or 1
for (int j = 0; j < np; j++)
old[m][j] += proj[k][m] * vd[j];
for (int ii = 0; ii < order - 1; ii++)
{
// edge basis functions in all integration points
int index_e = ref_map_shapeset.get_edge_index(k, 0, ii + 2, e->get_mode());
ref_map_pss.set_active_shape(index_e);
ref_map_pss.set_quad_order(mo2, H2D_FN_VAL_0);
const double* ed = ref_map_pss.get_fn_values();
for (int m = 0; m < 2; m++) //part 0 or 1
for (int j = 0; j < np; j++)
old[m][j] += proj[nvert + k * (order - 1) + ii][m] * ed[j];
}
}
}
void CurvMap::calc_bubble_projection(Element* e, Curve** curve, unsigned short order, double2* proj)
{
ref_map_pss.set_active_element(e);
unsigned short i, j, k;
unsigned short mo2 = g_quad_2d_std.get_max_order(e->get_mode());
unsigned char np = g_quad_2d_std.get_num_points(mo2, e->get_mode());
unsigned short qo = e->is_quad() ? H2D_MAKE_QUAD_ORDER(order, order) : order;
unsigned short nb = ref_map_shapeset.get_num_bubbles(qo, e->get_mode());
double2* fn = new double2[np];
memset(fn, 0, np * sizeof(double2));
double* rhside[2];
double* old[2];
for (i = 0; i < 2; i++)
{
rhside[i] = new double[nb];
old[i] = new double[np];
memset(rhside[i], 0, sizeof(double)* nb);
memset(old[i], 0, sizeof(double)* np);
}
// compute known part of projection (vertex and edge part)
old_projection(e, order, proj, old);
// fn values of both components of nonpolynomial function
double3* pt = g_quad_2d_std.get_points(mo2, e->get_mode());
for (j = 0; j < np; j++) // over all integration points
{
double2 a;
a[0] = ctm->m[0] * pt[j][0] + ctm->t[0];
a[1] = ctm->m[1] * pt[j][1] + ctm->t[1];
calc_ref_map(e, curve, a[0], a[1], fn[j]);
}
double2* result = proj + e->get_nvert() + e->get_nvert() * (order - 1);
for (k = 0; k < 2; k++)
{
for (i = 0; i < nb; i++) // loop over bubble basis functions
{
// bubble basis functions in all integration points
int index_i = ref_map_shapeset.get_bubble_indices(qo, e->get_mode())[i];
ref_map_pss.set_active_shape(index_i);
ref_map_pss.set_quad_order(mo2, H2D_FN_VAL_0);
const double *bfn = ref_map_pss.get_fn_values();
for (j = 0; j < np; j++) // over all integration points
rhside[k][i] += pt[j][2] * (bfn[j] * (fn[j][k] - old[k][j]));
}
// solve
if (e->get_mode() == HERMES_MODE_TRIANGLE)
cholsl(curvMapStatic.bubble_proj_matrix_tri, nb, curvMapStatic.bubble_tri_p, rhside[k], rhside[k]);
else
cholsl(curvMapStatic.bubble_proj_matrix_quad, nb, curvMapStatic.bubble_quad_p, rhside[k], rhside[k]);
for (i = 0; i < nb; i++)
result[i][k] = rhside[k][i];
}
for (i = 0; i < 2; i++)
{
delete[] rhside[i];
delete[] old[i];
}
delete[] fn;
}
void CurvMap::update_refmap_coeffs(Element* e)
{
ref_map_pss.set_quad_2d(&g_quad_2d_std);
ref_map_pss.set_active_element(e);
// allocate projection coefficients
unsigned char nvert = e->get_nvert();
unsigned char ne = order - 1;
unsigned short qo = e->is_quad() ? H2D_MAKE_QUAD_ORDER(order, order) : order;
unsigned short nb = ref_map_shapeset.get_num_bubbles(qo, e->get_mode());
this->nc = nvert + nvert*ne + nb;
this->coeffs = realloc_with_check<double2>(this->coeffs, nc);
// WARNING: do not change the format of the array 'coeffs'. If it changes,
// RefMap::set_active_element() has to be changed too.
Curve** curves;
if (toplevel == false)
{
ref_map_pss.set_active_element(e);
ref_map_pss.set_transform(this->sub_idx);
curves = parent->cm->curves;
}
else
{
ref_map_pss.reset_transform();
curves = e->cm->curves;
}
ctm = ref_map_pss.get_ctm();
// calculation of new_ projection coefficients
// vertex part
for (unsigned char i = 0; i < nvert; i++)
{
coeffs[i][0] = e->vn[i]->x;
coeffs[i][1] = e->vn[i]->y;
}
if (!e->cm->toplevel)
e = e->cm->parent;
// edge part
for (unsigned char edge = 0; edge < nvert; edge++)
calc_edge_projection(e, edge, curves, order, coeffs);
//bubble part
calc_bubble_projection(e, curves, order, coeffs);
}
void CurvMap::get_mid_edge_points(Element* e, double2* pt, unsigned short n)
{
Curve** curves = this->curves;
Transformable tran;
tran.set_active_element(e);
if (toplevel == false)
{
tran.set_transform(this->sub_idx);
e = e->cm->parent;
curves = e->cm->curves;
}
ctm = tran.get_ctm();
double xi_1, xi_2;
for (unsigned short i = 0; i < n; i++)
{
xi_1 = ctm->m[0] * pt[i][0] + ctm->t[0];
xi_2 = ctm->m[1] * pt[i][1] + ctm->t[1];
calc_ref_map(e, curves, xi_1, xi_2, pt[i]);
}
}
CurvMap* CurvMap::create_son_curv_map(Element* e, int son)
{
// if the top three bits of part are nonzero, we would overflow
// -- make the element non-curvilinear
if (e->cm->sub_idx & 0xe000000000000000ULL)
return nullptr;
// if the parent element is already almost straight-edged,
// the son will be even more straight-edged
if (e->iro_cache == 0)
return nullptr;
CurvMap* cm = new CurvMap;
if (e->cm->toplevel == false)
{
cm->parent = e->cm->parent;
cm->sub_idx = (e->cm->sub_idx << 3) + son + 1;
}
else
{
cm->parent = e;
cm->sub_idx = (son + 1);
}
cm->toplevel = false;
cm->order = 4;
return cm;
}
}
} | filipr/hermes | hermes2d/src/mesh/curved.cpp | C++ | gpl-3.0 | 26,263 |
// MonoGame - Copyright (C) The MonoGame Team
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
namespace Microsoft.Xna.Framework.Content.Pipeline.Graphics
{
/// <summary>
/// Provides properties for managing a bone weight.
/// </summary>
public struct BoneWeight
{
string boneName;
float weight;
/// <summary>
/// Gets the name of the bone.
/// </summary>
public string BoneName
{
get
{
return boneName;
}
}
/// <summary>
/// Gets the amount of bone influence, ranging from zero to one. The complete set of weights in a BoneWeightCollection should sum to one.
/// </summary>
public float Weight
{
get
{
return weight;
}
internal set
{
weight = value;
}
}
/// <summary>
/// Initializes a new instance of BoneWeight with the specified name and weight.
/// </summary>
/// <param name="boneName">Name of the bone.</param>
/// <param name="weight">Amount of influence, ranging from zero to one.</param>
public BoneWeight(string boneName, float weight)
{
this.boneName = boneName;
this.weight = weight;
}
}
}
| Blucky87/Otiose2D | src/libs/MonoGame/MonoGame.Framework.Content.Pipeline/Graphics/BoneWeight.cs | C# | gpl-3.0 | 1,470 |
using WowPacketParser.Enums;
using WowPacketParser.Hotfix;
namespace WowPacketParserModule.V8_0_1_27101.Hotfix
{
[HotfixStructure(DB2Hash.WorldEffect, HasIndexInData = false)]
public class WorldEffectEntry
{
public uint QuestFeedbackEffectID { get; set; }
public byte WhenToDisplay { get; set; }
public sbyte TargetType { get; set; }
public int TargetAsset { get; set; }
public uint PlayerConditionID { get; set; }
public ushort CombatConditionID { get; set; }
}
}
| TrinityCore/WowPacketParser | WowPacketParserModule.V8_0_1_27101/Hotfix/WorldEffectEntry.cs | C# | gpl-3.0 | 530 |
<?php
namespace TYPO3\Neos\Routing;
/*
* This file is part of the TYPO3.Neos package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use TYPO3\Flow\Annotations as Flow;
/**
* A route part handler for finding nodes specifically in the website's frontend.
*
* @Flow\Scope("singleton")
*/
class BackendModuleArgumentsRoutePartHandler extends \TYPO3\Flow\Mvc\Routing\DynamicRoutePart
{
/**
* @Flow\Inject
* @var \TYPO3\Flow\Persistence\PersistenceManagerInterface
*/
protected $persistenceManager;
/**
* Iterate through the configured modules, find the matching module and set
* the route path accordingly
*
* @param array $value (contains action, controller and package of the module controller)
* @return boolean
*/
protected function resolveValue($value)
{
if (is_array($value)) {
$this->value = isset($value['@action']) && $value['@action'] !== 'index' ? $value['@action'] : '';
if ($this->value !== '' && isset($value['@format'])) {
$this->value .= '.' . $value['@format'];
}
$exceedingArguments = array();
foreach ($value as $argumentKey => $argumentValue) {
if (substr($argumentKey, 0, 1) !== '@' && substr($argumentKey, 0, 2) !== '__') {
$exceedingArguments[$argumentKey] = $argumentValue;
}
}
if ($exceedingArguments !== array()) {
$exceedingArguments = \TYPO3\Flow\Utility\Arrays::removeEmptyElementsRecursively($exceedingArguments);
$exceedingArguments = $this->persistenceManager->convertObjectsToIdentityArrays($exceedingArguments);
$queryString = http_build_query(array($this->name => $exceedingArguments), null, '&');
if ($queryString !== '') {
$this->value .= '?' . $queryString;
}
}
}
return true;
}
}
| dimaip/neos-development-collection | TYPO3.Neos/Classes/TYPO3/Neos/Routing/BackendModuleArgumentsRoutePartHandler.php | PHP | gpl-3.0 | 2,168 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 1991-2010 OpenCFD Ltd.
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "meshSearch.H"
#include "polyMesh.H"
#include "indexedOctree.H"
#include "DynamicList.H"
#include "demandDrivenData.H"
#include "treeDataCell.H"
#include "treeDataFace.H"
#include "treeDataPoint.H"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
defineTypeNameAndDebug(Foam::meshSearch, 0);
Foam::scalar Foam::meshSearch::tol_ = 1E-3;
// * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * //
bool Foam::meshSearch::findNearer
(
const point& sample,
const pointField& points,
label& nearestI,
scalar& nearestDistSqr
)
{
bool nearer = false;
forAll(points, pointI)
{
scalar distSqr = magSqr(points[pointI] - sample);
if (distSqr < nearestDistSqr)
{
nearestDistSqr = distSqr;
nearestI = pointI;
nearer = true;
}
}
return nearer;
}
bool Foam::meshSearch::findNearer
(
const point& sample,
const pointField& points,
const labelList& indices,
label& nearestI,
scalar& nearestDistSqr
)
{
bool nearer = false;
forAll(indices, i)
{
label pointI = indices[i];
scalar distSqr = magSqr(points[pointI] - sample);
if (distSqr < nearestDistSqr)
{
nearestDistSqr = distSqr;
nearestI = pointI;
nearer = true;
}
}
return nearer;
}
// tree based searching
Foam::label Foam::meshSearch::findNearestCellTree(const point& location) const
{
const indexedOctree<treeDataPoint>& tree = cellCentreTree();
scalar span = tree.bb().mag();
pointIndexHit info = tree.findNearest(location, Foam::sqr(span));
if (!info.hit())
{
info = tree.findNearest(location, Foam::sqr(GREAT));
}
return info.index();
}
// linear searching
Foam::label Foam::meshSearch::findNearestCellLinear(const point& location) const
{
const vectorField& centres = mesh_.cellCentres();
label nearestIndex = 0;
scalar minProximity = magSqr(centres[nearestIndex] - location);
findNearer
(
location,
centres,
nearestIndex,
minProximity
);
return nearestIndex;
}
// walking from seed
Foam::label Foam::meshSearch::findNearestCellWalk
(
const point& location,
const label seedCellI
) const
{
if (seedCellI < 0)
{
FatalErrorIn
(
"meshSearch::findNearestCellWalk(const point&, const label)"
) << "illegal seedCell:" << seedCellI << exit(FatalError);
}
// Walk in direction of face that decreases distance
label curCellI = seedCellI;
scalar distanceSqr = magSqr(mesh_.cellCentres()[curCellI] - location);
bool closer;
do
{
// Try neighbours of curCellI
closer = findNearer
(
location,
mesh_.cellCentres(),
mesh_.cellCells()[curCellI],
curCellI,
distanceSqr
);
} while (closer);
return curCellI;
}
// tree based searching
Foam::label Foam::meshSearch::findNearestFaceTree(const point& location) const
{
// Search nearest cell centre.
const indexedOctree<treeDataPoint>& tree = cellCentreTree();
scalar span = tree.bb().mag();
// Search with decent span
pointIndexHit info = tree.findNearest(location, Foam::sqr(span));
if (!info.hit())
{
// Search with desparate span
info = tree.findNearest(location, Foam::sqr(GREAT));
}
// Now check any of the faces of the nearest cell
const vectorField& centres = mesh_.faceCentres();
const cell& ownFaces = mesh_.cells()[info.index()];
label nearestFaceI = ownFaces[0];
scalar minProximity = magSqr(centres[nearestFaceI] - location);
findNearer
(
location,
centres,
ownFaces,
nearestFaceI,
minProximity
);
return nearestFaceI;
}
// linear searching
Foam::label Foam::meshSearch::findNearestFaceLinear(const point& location) const
{
const vectorField& centres = mesh_.faceCentres();
label nearestFaceI = 0;
scalar minProximity = magSqr(centres[nearestFaceI] - location);
findNearer
(
location,
centres,
nearestFaceI,
minProximity
);
return nearestFaceI;
}
// walking from seed
Foam::label Foam::meshSearch::findNearestFaceWalk
(
const point& location,
const label seedFaceI
) const
{
if (seedFaceI < 0)
{
FatalErrorIn
(
"meshSearch::findNearestFaceWalk(const point&, const label)"
) << "illegal seedFace:" << seedFaceI << exit(FatalError);
}
const vectorField& centres = mesh_.faceCentres();
// Walk in direction of face that decreases distance
label curFaceI = seedFaceI;
scalar distanceSqr = magSqr(centres[curFaceI] - location);
while (true)
{
label betterFaceI = curFaceI;
findNearer
(
location,
centres,
mesh_.cells()[mesh_.faceOwner()[curFaceI]],
betterFaceI,
distanceSqr
);
if (mesh_.isInternalFace(curFaceI))
{
findNearer
(
location,
centres,
mesh_.cells()[mesh_.faceNeighbour()[curFaceI]],
betterFaceI,
distanceSqr
);
}
if (betterFaceI == curFaceI)
{
break;
}
curFaceI = betterFaceI;
}
return curFaceI;
}
Foam::label Foam::meshSearch::findCellLinear(const point& location) const
{
bool cellFound = false;
label n = 0;
label cellI = -1;
while ((!cellFound) && (n < mesh_.nCells()))
{
if (pointInCell(location, n))
{
cellFound = true;
cellI = n;
}
else
{
n++;
}
}
if (cellFound)
{
return cellI;
}
else
{
return -1;
}
}
Foam::label Foam::meshSearch::findNearestBoundaryFaceWalk
(
const point& location,
const label seedFaceI
) const
{
if (seedFaceI < 0)
{
FatalErrorIn
(
"meshSearch::findNearestBoundaryFaceWalk"
"(const point&, const label)"
) << "illegal seedFace:" << seedFaceI << exit(FatalError);
}
// Start off from seedFaceI
label curFaceI = seedFaceI;
const face& f = mesh_.faces()[curFaceI];
scalar minDist = f.nearestPoint
(
location,
mesh_.points()
).distance();
bool closer;
do
{
closer = false;
// Search through all neighbouring boundary faces by going
// across edges
label lastFaceI = curFaceI;
const labelList& myEdges = mesh_.faceEdges()[curFaceI];
forAll (myEdges, myEdgeI)
{
const labelList& neighbours = mesh_.edgeFaces()[myEdges[myEdgeI]];
// Check any face which uses edge, is boundary face and
// is not curFaceI itself.
forAll(neighbours, nI)
{
label faceI = neighbours[nI];
if
(
(faceI >= mesh_.nInternalFaces())
&& (faceI != lastFaceI)
)
{
const face& f = mesh_.faces()[faceI];
pointHit curHit = f.nearestPoint
(
location,
mesh_.points()
);
// If the face is closer, reset current face and distance
if (curHit.distance() < minDist)
{
minDist = curHit.distance();
curFaceI = faceI;
closer = true; // a closer neighbour has been found
}
}
}
}
} while (closer);
return curFaceI;
}
Foam::vector Foam::meshSearch::offset
(
const point& bPoint,
const label bFaceI,
const vector& dir
) const
{
// Get the neighbouring cell
label ownerCellI = mesh_.faceOwner()[bFaceI];
const point& c = mesh_.cellCentres()[ownerCellI];
// Typical dimension: distance from point on face to cell centre
scalar typDim = mag(c - bPoint);
return tol_*typDim*dir;
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
// Construct from components
Foam::meshSearch::meshSearch(const polyMesh& mesh, const bool faceDecomp)
:
mesh_(mesh),
faceDecomp_(faceDecomp),
cloud_(mesh_, IDLList<passiveParticle>()),
boundaryTreePtr_(NULL),
cellTreePtr_(NULL),
cellCentreTreePtr_(NULL)
{}
// * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * //
Foam::meshSearch::~meshSearch()
{
clearOut();
}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
const Foam::indexedOctree<Foam::treeDataFace>& Foam::meshSearch::boundaryTree()
const
{
if (!boundaryTreePtr_)
{
//
// Construct tree
//
// all boundary faces (not just walls)
labelList bndFaces(mesh_.nFaces()-mesh_.nInternalFaces());
forAll(bndFaces, i)
{
bndFaces[i] = mesh_.nInternalFaces() + i;
}
treeBoundBox overallBb(mesh_.points());
Random rndGen(123456);
overallBb = overallBb.extend(rndGen, 1E-4);
overallBb.min() -= point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL);
overallBb.max() += point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL);
boundaryTreePtr_ = new indexedOctree<treeDataFace>
(
treeDataFace // all information needed to search faces
(
false, // do not cache bb
mesh_,
bndFaces // boundary faces only
),
overallBb, // overall search domain
8, // maxLevel
10, // leafsize
3.0 // duplicity
);
}
return *boundaryTreePtr_;
}
const Foam::indexedOctree<Foam::treeDataCell>& Foam::meshSearch::cellTree()
const
{
if (!cellTreePtr_)
{
//
// Construct tree
//
treeBoundBox overallBb(mesh_.points());
Random rndGen(123456);
overallBb = overallBb.extend(rndGen, 1E-4);
overallBb.min() -= point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL);
overallBb.max() += point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL);
cellTreePtr_ = new indexedOctree<treeDataCell>
(
treeDataCell
(
false, // not cache bb
mesh_
),
overallBb, // overall search domain
8, // maxLevel
10, // leafsize
3.0 // duplicity
);
}
return *cellTreePtr_;
}
const Foam::indexedOctree<Foam::treeDataPoint>&
Foam::meshSearch::cellCentreTree() const
{
if (!cellCentreTreePtr_)
{
//
// Construct tree
//
treeBoundBox overallBb(mesh_.cellCentres());
Random rndGen(123456);
overallBb = overallBb.extend(rndGen, 1E-4);
overallBb.min() -= point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL);
overallBb.max() += point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL);
cellCentreTreePtr_ = new indexedOctree<treeDataPoint>
(
treeDataPoint(mesh_.cellCentres()),
overallBb, // overall search domain
10, // max levels
10.0, // maximum ratio of cubes v.s. cells
100.0 // max. duplicity; n/a since no bounding boxes.
);
}
return *cellCentreTreePtr_;
}
// Is the point in the cell
// Works by checking if there is a face inbetween the point and the cell
// centre.
// Check for internal uses proper face decomposition or just average normal.
bool Foam::meshSearch::pointInCell(const point& p, label cellI) const
{
if (faceDecomp_)
{
const point& ctr = mesh_.cellCentres()[cellI];
vector dir(p - ctr);
scalar magDir = mag(dir);
// Check if any faces are hit by ray from cell centre to p.
// If none -> p is in cell.
const labelList& cFaces = mesh_.cells()[cellI];
// Make sure half_ray does not pick up any faces on the wrong
// side of the ray.
scalar oldTol = intersection::setPlanarTol(0.0);
forAll(cFaces, i)
{
label faceI = cFaces[i];
pointHit inter = mesh_.faces()[faceI].ray
(
ctr,
dir,
mesh_.points(),
intersection::HALF_RAY,
intersection::VECTOR
);
if (inter.hit())
{
scalar dist = inter.distance();
if (dist < magDir)
{
// Valid hit. Hit face so point is not in cell.
intersection::setPlanarTol(oldTol);
return false;
}
}
}
intersection::setPlanarTol(oldTol);
// No face inbetween point and cell centre so point is inside.
return true;
}
else
{
const labelList& f = mesh_.cells()[cellI];
const labelList& owner = mesh_.faceOwner();
const vectorField& cf = mesh_.faceCentres();
const vectorField& Sf = mesh_.faceAreas();
forAll(f, facei)
{
label nFace = f[facei];
vector proj = p - cf[nFace];
vector normal = Sf[nFace];
if (owner[nFace] == cellI)
{
if ((normal & proj) > 0)
{
return false;
}
}
else
{
if ((normal & proj) < 0)
{
return false;
}
}
}
return true;
}
}
Foam::label Foam::meshSearch::findNearestCell
(
const point& location,
const label seedCellI,
const bool useTreeSearch
) const
{
if (seedCellI == -1)
{
if (useTreeSearch)
{
return findNearestCellTree(location);
}
else
{
return findNearestCellLinear(location);
}
}
else
{
return findNearestCellWalk(location, seedCellI);
}
}
Foam::label Foam::meshSearch::findNearestFace
(
const point& location,
const label seedFaceI,
const bool useTreeSearch
) const
{
if (seedFaceI == -1)
{
if (useTreeSearch)
{
return findNearestFaceTree(location);
}
else
{
return findNearestFaceLinear(location);
}
}
else
{
return findNearestFaceWalk(location, seedFaceI);
}
}
Foam::label Foam::meshSearch::findCell
(
const point& location,
const label seedCellI,
const bool useTreeSearch
) const
{
// Find the nearest cell centre to this location
label nearCellI = findNearestCell(location, seedCellI, useTreeSearch);
if (debug)
{
Pout<< "findCell : nearCellI:" << nearCellI
<< " ctr:" << mesh_.cellCentres()[nearCellI]
<< endl;
}
if (pointInCell(location, nearCellI))
{
return nearCellI;
}
else
{
if (useTreeSearch)
{
// Start searching from cell centre of nearCell
point curPoint = mesh_.cellCentres()[nearCellI];
vector edgeVec = location - curPoint;
edgeVec /= mag(edgeVec);
do
{
// Walk neighbours (using tracking) to get closer
passiveParticle tracker(cloud_, curPoint, nearCellI);
if (debug)
{
Pout<< "findCell : tracked from curPoint:" << curPoint
<< " nearCellI:" << nearCellI;
}
tracker.track(location);
if (debug)
{
Pout<< " to " << tracker.position()
<< " need:" << location
<< " onB:" << tracker.onBoundary()
<< " cell:" << tracker.cell()
<< " face:" << tracker.face() << endl;
}
if (!tracker.onBoundary())
{
// stopped not on boundary -> reached location
return tracker.cell();
}
// stopped on boundary face. Compare positions
scalar typDim = sqrt(mag(mesh_.faceAreas()[tracker.face()]));
if ((mag(tracker.position() - location)/typDim) < SMALL)
{
return tracker.cell();
}
// tracking stopped at boundary. Find next boundary
// intersection from current point (shifted out a little bit)
// in the direction of the destination
curPoint =
tracker.position()
+ offset(tracker.position(), tracker.face(), edgeVec);
if (debug)
{
Pout<< "Searching for next boundary from curPoint:"
<< curPoint
<< " to location:" << location << endl;
}
pointIndexHit curHit = intersection(curPoint, location);
if (debug)
{
Pout<< "Returned from line search with ";
curHit.write(Pout);
Pout<< endl;
}
if (!curHit.hit())
{
return -1;
}
else
{
nearCellI = mesh_.faceOwner()[curHit.index()];
curPoint =
curHit.hitPoint()
+ offset(curHit.hitPoint(), curHit.index(), edgeVec);
}
}
while(true);
}
else
{
return findCellLinear(location);
}
}
return -1;
}
Foam::label Foam::meshSearch::findNearestBoundaryFace
(
const point& location,
const label seedFaceI,
const bool useTreeSearch
) const
{
if (seedFaceI == -1)
{
if (useTreeSearch)
{
const indexedOctree<treeDataFace>& tree = boundaryTree();
scalar span = tree.bb().mag();
pointIndexHit info = boundaryTree().findNearest
(
location,
Foam::sqr(span)
);
if (!info.hit())
{
info = boundaryTree().findNearest
(
location,
Foam::sqr(GREAT)
);
}
return tree.shapes().faceLabels()[info.index()];
}
else
{
scalar minDist = GREAT;
label minFaceI = -1;
for
(
label faceI = mesh_.nInternalFaces();
faceI < mesh_.nFaces();
faceI++
)
{
const face& f = mesh_.faces()[faceI];
pointHit curHit =
f.nearestPoint
(
location,
mesh_.points()
);
if (curHit.distance() < minDist)
{
minDist = curHit.distance();
minFaceI = faceI;
}
}
return minFaceI;
}
}
else
{
return findNearestBoundaryFaceWalk(location, seedFaceI);
}
}
Foam::pointIndexHit Foam::meshSearch::intersection
(
const point& pStart,
const point& pEnd
) const
{
pointIndexHit curHit = boundaryTree().findLine(pStart, pEnd);
if (curHit.hit())
{
// Change index into octreeData into face label
curHit.setIndex(boundaryTree().shapes().faceLabels()[curHit.index()]);
}
return curHit;
}
Foam::List<Foam::pointIndexHit> Foam::meshSearch::intersections
(
const point& pStart,
const point& pEnd
) const
{
DynamicList<pointIndexHit> hits;
vector edgeVec = pEnd - pStart;
edgeVec /= mag(edgeVec);
point pt = pStart;
pointIndexHit bHit;
do
{
bHit = intersection(pt, pEnd);
if (bHit.hit())
{
hits.append(bHit);
const vector& area = mesh_.faceAreas()[bHit.index()];
scalar typDim = Foam::sqrt(mag(area));
if ((mag(bHit.hitPoint() - pEnd)/typDim) < SMALL)
{
break;
}
// Restart from hitPoint shifted a little bit in the direction
// of the destination
pt =
bHit.hitPoint()
+ offset(bHit.hitPoint(), bHit.index(), edgeVec);
}
} while(bHit.hit());
hits.shrink();
return hits;
}
bool Foam::meshSearch::isInside(const point& p) const
{
return
boundaryTree().getVolumeType(p)
== indexedOctree<treeDataFace>::INSIDE;
}
// Delete all storage
void Foam::meshSearch::clearOut()
{
deleteDemandDrivenData(boundaryTreePtr_);
deleteDemandDrivenData(cellTreePtr_);
deleteDemandDrivenData(cellCentreTreePtr_);
}
void Foam::meshSearch::correct()
{
clearOut();
}
// ************************************************************************* //
| OpenCFD/OpenFOAM-1.7.x | src/meshTools/meshSearch/meshSearch.C | C++ | gpl-3.0 | 22,990 |
#include "simulation/Elements.h"
//#TPT-Directive ElementClass Element_FRZZ PT_FRZZ 100
Element_FRZZ::Element_FRZZ()
{
Identifier = "DEFAULT_PT_FRZZ";
Name = "FRZZ";
Colour = PIXPACK(0xC0E0FF);
MenuVisible = 1;
MenuSection = SC_POWDERS;
Enabled = 1;
Advection = 0.7f;
AirDrag = 0.01f * CFDS;
AirLoss = 0.96f;
Loss = 0.90f;
Collision = -0.1f;
Gravity = 0.05f;
Diffusion = 0.01f;
HotAir = -0.00005f* CFDS;
Falldown = 1;
Flammable = 0;
Explosive = 0;
Meltable = 0;
Hardness = 20;
Weight = 50;
Temperature = 253.15f;
HeatConduct = 46;
Description = "Freeze powder. When melted, forms ice that always cools. Spreads with regular water.";
State = ST_SOLID;
Properties = TYPE_PART;
LowPressure = IPL;
LowPressureTransition = NT;
HighPressure = 1.8f;
HighPressureTransition = PT_SNOW;
LowTemperature = 50.0f;
LowTemperatureTransition = PT_ICEI;
HighTemperature = 273.15;
HighTemperatureTransition = PT_WATR;
Update = &Element_FRZZ::update;
}
//#TPT-Directive ElementHeader Element_FRZZ static int update(UPDATE_FUNC_ARGS)
int Element_FRZZ::update(UPDATE_FUNC_ARGS)
{
int r, rx, ry;
for (rx=-1; rx<2; rx++)
for (ry=-1; ry<2; ry++)
if (x+rx>=0 && y+ry>0 && x+rx<XRES && y+ry<YRES && (rx || ry))
{
r = pmap[y+ry][x+rx];
if (!r)
continue;
if ((r&0xFF)==PT_WATR&&5>rand()%100)
{
sim->part_change_type(r>>8,x+rx,y+ry,PT_FRZW);
parts[r>>8].life = 100;
parts[i].type = PT_NONE;
}
}
if (parts[i].type==PT_NONE) {
sim->kill_part(i);
return 1;
}
return 0;
}
Element_FRZZ::~Element_FRZZ() {} | jacksonmj/Powder-Toy-Mods | src/simulation/elements/FRZZ.cpp | C++ | gpl-3.0 | 1,712 |
package net.minecraft.inventory;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.util.IIcon;
// CraftBukkit start
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.play.server.S2FPacketSetSlot;
import org.bukkit.craftbukkit.inventory.CraftInventoryCrafting;
import org.bukkit.craftbukkit.inventory.CraftInventoryView;
// CraftBukkit end
public class ContainerPlayer extends Container
{
public InventoryCrafting craftMatrix = new InventoryCrafting(this, 2, 2);
public IInventory craftResult = new InventoryCraftResult();
public boolean isLocalWorld;
private final EntityPlayer thePlayer;
// CraftBukkit start
private CraftInventoryView bukkitEntity = null;
private InventoryPlayer player;
// CraftBukkit end
private static final String __OBFID = "CL_00001754";
public ContainerPlayer(final InventoryPlayer p_i1819_1_, boolean p_i1819_2_, EntityPlayer p_i1819_3_)
{
this.isLocalWorld = p_i1819_2_;
this.thePlayer = p_i1819_3_;
this.craftResult = new InventoryCraftResult(); // CraftBukkit - moved to before InventoryCrafting construction
this.craftMatrix = new InventoryCrafting(this, 2, 2, p_i1819_1_.player); // CraftBukkit - pass player
this.craftMatrix.resultInventory = this.craftResult; // CraftBukkit - let InventoryCrafting know about its result slot
this.player = p_i1819_1_; // CraftBukkit - save player
this.addSlotToContainer(new SlotCrafting(p_i1819_1_.player, this.craftMatrix, this.craftResult, 0, 144, 36));
int i;
int j;
for (i = 0; i < 2; ++i)
{
for (j = 0; j < 2; ++j)
{
this.addSlotToContainer(new Slot(this.craftMatrix, j + i * 2, 88 + j * 18, 26 + i * 18));
}
}
for (i = 0; i < 4; ++i)
{
final int k = i;
this.addSlotToContainer(new Slot(p_i1819_1_, p_i1819_1_.getSizeInventory() - 1 - i, 8, 8 + i * 18)
{
private static final String __OBFID = "CL_00001755";
public int getSlotStackLimit()
{
return 1;
}
public boolean isItemValid(ItemStack p_75214_1_)
{
if (p_75214_1_ == null) return false;
return p_75214_1_.getItem().isValidArmor(p_75214_1_, k, thePlayer);
}
@SideOnly(Side.CLIENT)
public IIcon getBackgroundIconIndex()
{
return ItemArmor.func_94602_b(k);
}
});
}
for (i = 0; i < 3; ++i)
{
for (j = 0; j < 9; ++j)
{
this.addSlotToContainer(new Slot(p_i1819_1_, j + (i + 1) * 9, 8 + j * 18, 84 + i * 18));
}
}
for (i = 0; i < 9; ++i)
{
this.addSlotToContainer(new Slot(p_i1819_1_, i, 8 + i * 18, 142));
}
// this.onCraftMatrixChanged(this.craftMatrix); // CraftBukkit - unneeded since it just sets result slot to empty
}
public void onCraftMatrixChanged(IInventory p_75130_1_)
{
// CraftBukkit start (Note: the following line would cause an error if called during construction)
CraftingManager.getInstance().lastCraftView = getBukkitView();
ItemStack craftResult = CraftingManager.getInstance().findMatchingRecipe(this.craftMatrix, this.thePlayer.worldObj);
this.craftResult.setInventorySlotContents(0, craftResult);
if (super.crafters.size() < 1)
{
return;
}
EntityPlayerMP player = (EntityPlayerMP) super.crafters.get(0); // TODO: Is this _always_ correct? Seems like it.
player.playerNetServerHandler.sendPacket(new S2FPacketSetSlot(player.openContainer.windowId, 0, craftResult));
// CraftBukkit end
}
public void onContainerClosed(EntityPlayer p_75134_1_)
{
super.onContainerClosed(p_75134_1_);
for (int i = 0; i < 4; ++i)
{
ItemStack itemstack = this.craftMatrix.getStackInSlotOnClosing(i);
if (itemstack != null)
{
p_75134_1_.dropPlayerItemWithRandomChoice(itemstack, false);
}
}
this.craftResult.setInventorySlotContents(0, (ItemStack)null);
}
public boolean canInteractWith(EntityPlayer p_75145_1_)
{
return true;
}
public ItemStack transferStackInSlot(EntityPlayer p_82846_1_, int p_82846_2_)
{
ItemStack itemstack = null;
Slot slot = (Slot)this.inventorySlots.get(p_82846_2_);
if (slot != null && slot.getHasStack())
{
ItemStack itemstack1 = slot.getStack();
itemstack = itemstack1.copy();
if (p_82846_2_ == 0)
{
if (!this.mergeItemStack(itemstack1, 9, 45, true))
{
return null;
}
slot.onSlotChange(itemstack1, itemstack);
}
else if (p_82846_2_ >= 1 && p_82846_2_ < 5)
{
if (!this.mergeItemStack(itemstack1, 9, 45, false))
{
return null;
}
}
else if (p_82846_2_ >= 5 && p_82846_2_ < 9)
{
if (!this.mergeItemStack(itemstack1, 9, 45, false))
{
return null;
}
}
else if (itemstack.getItem() instanceof ItemArmor && !((Slot)this.inventorySlots.get(5 + ((ItemArmor)itemstack.getItem()).armorType)).getHasStack())
{
int j = 5 + ((ItemArmor)itemstack.getItem()).armorType;
if (!this.mergeItemStack(itemstack1, j, j + 1, false))
{
return null;
}
}
else if (p_82846_2_ >= 9 && p_82846_2_ < 36)
{
if (!this.mergeItemStack(itemstack1, 36, 45, false))
{
return null;
}
}
else if (p_82846_2_ >= 36 && p_82846_2_ < 45)
{
if (!this.mergeItemStack(itemstack1, 9, 36, false))
{
return null;
}
}
else if (!this.mergeItemStack(itemstack1, 9, 45, false))
{
return null;
}
if (itemstack1.stackSize == 0)
{
slot.putStack((ItemStack)null);
}
else
{
slot.onSlotChanged();
}
if (itemstack1.stackSize == itemstack.stackSize)
{
return null;
}
slot.onPickupFromSlot(p_82846_1_, itemstack1);
}
return itemstack;
}
public boolean func_94530_a(ItemStack p_94530_1_, Slot p_94530_2_)
{
return p_94530_2_.inventory != this.craftResult && super.func_94530_a(p_94530_1_, p_94530_2_);
}
// CraftBukkit start
public CraftInventoryView getBukkitView()
{
if (bukkitEntity != null)
{
return bukkitEntity;
}
CraftInventoryCrafting inventory = new CraftInventoryCrafting(this.craftMatrix, this.craftResult);
bukkitEntity = new CraftInventoryView(this.player.player.getBukkitEntity(), inventory, this);
return bukkitEntity;
}
// CraftBukkit end
} | Scrik/Cauldron-1 | eclipse/cauldron/src/main/java/net/minecraft/inventory/ContainerPlayer.java | Java | gpl-3.0 | 7,916 |
#include "spammer.h"
SpammerType Settings::Spammer::type = SpammerType::SPAMMER_NONE;
bool Settings::Spammer::say_team = false;
bool Settings::Spammer::KillSpammer::enabled = false;
bool Settings::Spammer::KillSpammer::sayTeam = false;
std::vector<std::string> Settings::Spammer::KillSpammer::messages = {
"$nick owned by ELITE4",
"$nick suck's again"
};
bool Settings::Spammer::RadioSpammer::enabled = false;
std::vector<std::string> Settings::Spammer::NormalSpammer::messages = {
"I'AM BAD CODER",
"DON'T LIKE TOMATOES",
"SUPREME HACK",
"ELITE4 OWNS U AND ALL",
"ELITE4LEGIT.TK",
"ELITE4HVH.TK"
};
int Settings::Spammer::PositionSpammer::team = 1;
bool Settings::Spammer::PositionSpammer::showName = true;
bool Settings::Spammer::PositionSpammer::showWeapon = true;
bool Settings::Spammer::PositionSpammer::showRank = true;
bool Settings::Spammer::PositionSpammer::showWins = true;
bool Settings::Spammer::PositionSpammer::showHealth = true;
bool Settings::Spammer::PositionSpammer::showMoney = true;
bool Settings::Spammer::PositionSpammer::showLastplace = true;
std::vector<int> killedPlayerQueue;
void Spammer::BeginFrame(float frameTime)
{
if (!engine->IsInGame())
return;
// Grab the current time in milliseconds
long currentTime_ms = Util::GetEpochTime();
static long timeStamp = currentTime_ms;
if (currentTime_ms - timeStamp < 850)
return;
// Kill spammer
if (Settings::Spammer::KillSpammer::enabled && killedPlayerQueue.size() > 0)
{
IEngineClient::player_info_t playerInfo;
engine->GetPlayerInfo(killedPlayerQueue[0], &playerInfo);
// Prepare dead player's nickname without ';' & '"' characters
// as they might cause user to execute a command.
std::string dead_player_name = std::string(playerInfo.name);
dead_player_name.erase(std::remove(dead_player_name.begin(), dead_player_name.end(), ';'), dead_player_name.end());
dead_player_name.erase(std::remove(dead_player_name.begin(), dead_player_name.end(), '"'), dead_player_name.end());
// Remove end line character
dead_player_name.erase(std::remove(dead_player_name.begin(), dead_player_name.end(), '\n'), dead_player_name.end());
// Construct a command with our message
pstring str;
str << (Settings::Spammer::KillSpammer::sayTeam ? "say_team" : "say");
std::string message = Settings::Spammer::KillSpammer::messages[std::rand() % Settings::Spammer::KillSpammer::messages.size()];
str << " \"" << Util::ReplaceString(message, "$nick", dead_player_name) << "\"";
// Execute our constructed command
engine->ExecuteClientCmd(str.c_str());
// Remove the first element from the vector
killedPlayerQueue.erase(killedPlayerQueue.begin(), killedPlayerQueue.begin() + 1);
return;
}
if (Settings::Spammer::RadioSpammer::enabled)
{
const char* radioCommands[] = {
"coverme",
"takepoint",
"holdpos",
"regroup",
"followme",
"takingfire",
"go",
"fallback",
"sticktog",
"report",
"roger",
"enemyspot",
"needbackup",
"sectorclear",
"inposition",
"reportingin",
"getout",
"negative",
"enemydown",
};
engine->ClientCmd_Unrestricted(radioCommands[std::rand() % IM_ARRAYSIZE(radioCommands)]);
}
if (Settings::Spammer::type == SpammerType::SPAMMER_NORMAL)
{
if (Settings::Spammer::NormalSpammer::messages.empty())
return;
// Grab a random message string
std::string message = Settings::Spammer::NormalSpammer::messages[std::rand() % Settings::Spammer::NormalSpammer::messages.size()];
// Construct a command with our message
pstring str;
str << (Settings::Spammer::say_team ? "say_team" : "say") << " ";
str << message;
// Execute our constructed command
engine->ExecuteClientCmd(str.c_str());
}
else if (Settings::Spammer::type == SpammerType::SPAMMER_POSITIONS)
{
C_BasePlayer* localplayer = (C_BasePlayer*) entityList->GetClientEntity(engine->GetLocalPlayer());
static int lastId = 1;
for (int i = lastId; i < engine->GetMaxClients(); i++)
{
C_BasePlayer* player = (C_BasePlayer*) entityList->GetClientEntity(i);
lastId++;
if (lastId == engine->GetMaxClients())
lastId = 1;
if (!player
|| player->GetDormant()
|| !player->GetAlive())
continue;
if (Settings::Spammer::PositionSpammer::team == 0 && player->GetTeam() != localplayer->GetTeam())
continue;
if (Settings::Spammer::PositionSpammer::team == 1 && player->GetTeam() == localplayer->GetTeam())
continue;
IEngineClient::player_info_t entityInformation;
engine->GetPlayerInfo(i, &entityInformation);
C_BaseCombatWeapon* activeWeapon = (C_BaseCombatWeapon*) entityList->GetClientEntityFromHandle(player->GetActiveWeapon());
// Prepare player's nickname without ';' & '"' characters
// as they might cause user to execute a command.
std::string playerName = std::string(entityInformation.name);
playerName.erase(std::remove(playerName.begin(), playerName.end(), ';'), playerName.end());
playerName.erase(std::remove(playerName.begin(), playerName.end(), '"'), playerName.end());
// Remove end line character
playerName.erase(std::remove(playerName.begin(), playerName.end(), '\n'), playerName.end());
// Construct a command with our message
pstring str;
str << (Settings::Spammer::say_team ? "say_team" : "say") << " \"";
if (Settings::Spammer::PositionSpammer::showName)
str << playerName << " | ";
if (Settings::Spammer::PositionSpammer::showWeapon)
str << Util::Items::GetItemDisplayName(*activeWeapon->GetItemDefinitionIndex()) << " | ";
if (Settings::Spammer::PositionSpammer::showRank)
str << ESP::ranks[*(*csPlayerResource)->GetCompetitiveRanking(i)] << " | ";
if (Settings::Spammer::PositionSpammer::showWins)
str << *(*csPlayerResource)->GetCompetitiveWins(i) << " wins | ";
if (Settings::Spammer::PositionSpammer::showHealth)
str << player->GetHealth() << "HP | ";
if (Settings::Spammer::PositionSpammer::showMoney)
str << "$" << player->GetMoney() << " | ";
if (Settings::Spammer::PositionSpammer::showLastplace)
str << player->GetLastPlaceName();
str << "\"";
// Execute our constructed command
engine->ExecuteClientCmd(str.c_str());
break;
}
}
// Update the time stamp
timeStamp = currentTime_ms;
}
void Spammer::FireGameEvent(IGameEvent* event)
{
if (!Settings::Spammer::KillSpammer::enabled)
return;
if (!engine->IsInGame())
return;
if (strcmp(event->GetName(), "player_death") != 0)
return;
int attacker_id = engine->GetPlayerForUserID(event->GetInt("attacker"));
int deadPlayer_id = engine->GetPlayerForUserID(event->GetInt("userid"));
// Make sure it's not a suicide.x
if (attacker_id == deadPlayer_id)
return;
// Make sure we're the one who killed someone...
if (attacker_id != engine->GetLocalPlayer())
return;
killedPlayerQueue.push_back(deadPlayer_id);
}
| sneakyevilSK/sneakyevil.win | src/Hacks/spammer.cpp | C++ | gpl-3.0 | 6,876 |
package com.app.server.repository;
import com.athena.server.repository.SearchInterface;
import com.athena.annotation.Complexity;
import com.athena.annotation.SourceCodeAuthorClass;
import com.athena.framework.server.exception.repository.SpartanPersistenceException;
import java.util.List;
import com.athena.framework.server.exception.biz.SpartanConstraintViolationException;
@SourceCodeAuthorClass(createdBy = "john.doe", updatedBy = "", versionNumber = "1", comments = "Repository for Title Master table Entity", complexity = Complexity.LOW)
public interface TitleRepository<T> extends SearchInterface {
public List<T> findAll() throws SpartanPersistenceException;
public T save(T entity) throws SpartanPersistenceException;
public List<T> save(List<T> entity) throws SpartanPersistenceException;
public void delete(String id) throws SpartanPersistenceException;
public void update(T entity) throws SpartanConstraintViolationException, SpartanPersistenceException;
public void update(List<T> entity) throws SpartanPersistenceException;
public T findById(String titleId) throws Exception, SpartanPersistenceException;
}
| applifireAlgo/appDemoApps201115 | bloodbank/src/main/java/com/app/server/repository/TitleRepository.java | Java | gpl-3.0 | 1,156 |
<?php
/**
* This file is part of OXID eShop Community Edition.
*
* OXID eShop Community Edition 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.
*
* OXID eShop Community Edition 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 OXID eShop Community Edition. If not, see <http://www.gnu.org/licenses/>.
*
* @link http://www.oxid-esales.com
* @copyright (C) OXID eSales AG 2003-2016
* @version OXID eShop CE
*/
namespace OxidEsales\EshopCommunity\Tests\Integration\Seo;
use OxidEsales\Eshop\Application\Model\Article;
use OxidEsales\Eshop\Application\Model\Category;
use OxidEsales\Eshop\Application\Model\Object2Category;
use OxidEsales\Eshop\Core\DatabaseProvider;
use OxidEsales\Eshop\Core\Field;
/**
* Class PaginationSeoTest
*
* @package OxidEsales\EshopCommunity\Tests\Integration\Seo
*/
class PaginationSeoTest extends \OxidEsales\TestingLibrary\UnitTestCase
{
/** @var string Original theme */
private $origTheme;
/**
* @var string
*/
private $seoUrl = '';
/**
* @var string
*/
private $categoryOxid = '';
/**
* Sets up test
*/
protected function setUp(): void
{
parent::setUp();
$this->origTheme = $this->getConfig()->getConfigParam('sTheme');
$this->activateTheme('azure');
$this->getConfig()->saveShopConfVar('bool', 'blEnableSeoCache', false);
$this->cleanRegistry();
$this->cleanSeoTable();
$facts = new \OxidEsales\Facts\Facts();
$this->seoUrl = ('EE' == $facts->getEdition()) ? 'Party/Bar-Equipment/' : 'Geschenke/';
$this->categoryOxid = ('EE' == $facts->getEdition()) ? '30e44ab8593023055.23928895' : '8a142c3e4143562a5.46426637';
oxNew(\OxidEsales\Eshop\Application\Model\ArticleList::class)->renewPriceUpdateTime();
oxNew(\OxidEsales\Eshop\Core\SystemEventHandler::class)->onShopEnd();
}
/**
* Tear down test.
*/
protected function tearDown(): void
{
//restore theme, do it directly in database as it might be dummy 'basic' theme
$query = "UPDATE `oxconfig` SET `OXVARVALUE` = '" . $this->origTheme . "' WHERE `OXVARNAME` = 'sTheme'";
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute($query);
$this->cleanRegistry();
$this->cleanSeoTable();
$_GET = [];
parent::tearDown();
}
/**
* Call with a seo url that is not yet stored in oxseo table.
* Category etc exists.
* We hit the 404 as no entry for this url exists in oxseo table.
* But when shop shows the 404 page, it creates the main category seo urls.
*/
public function testCallWithSeoUrlNoEntryInTableExists()
{
$this->callCurl('');
$this->callCurl($this->seoUrl);
$this->cleanRegistry();
$this->cleanSeoTable();
$this->clearProxyCache();
$seoUrl = $this->seoUrl;
$checkResponse = '404 Not Found';
//before
$query = "SELECT oxstdurl, oxseourl FROM `oxseo` WHERE `OXSEOURL` like '%" . $seoUrl . "%'" .
" AND oxtype = 'oxcategory'";
$res = \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->getAll($query);
$this->assertEmpty($res);
//check what shop does
$response = $this->callCurl($seoUrl);
$this->assertStringContainsString($checkResponse, $response, "Should get $checkResponse");
}
/**
* Call with a standard url that is not yet stored in oxseo table.
* Category etc exists. No pgNr is provided.
*
*
*/
public function testCallWithStdUrlNoEntryExists()
{
$urlToCall = 'index.php?cl=alist&cnid=' . $this->categoryOxid;
$checkResponse = 'HTTP/1.1 200 OK';
//Check entries in oxseo table for oxtype = 'oxcategory'
$query = "SELECT oxstdurl, oxseourl FROM `oxseo` WHERE `OXSTDURL` like '%" . $this->categoryOxid . "%'" .
" AND oxtype = 'oxcategory'";
$res = \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->getAll($query);
$this->assertEmpty($res);
$response = $this->callCurl($urlToCall);
$this->assertStringContainsString($checkResponse, $response, "Should get $checkResponse");
}
/**
* Call shop with standard url, no matching entry in seo table exists atm.
*/
public function testStandardUrlNoMatchingSeoUrlSavedYet()
{
$requestUrl = 'index.php?cl=alist&cnid=' . $this->categoryOxid;
//No match in oxseo table
$redirectUrl = \OxidEsales\Eshop\Core\Registry::getSeoEncoder()->fetchSeoUrl($requestUrl);
$this->assertFalse($redirectUrl);
$utils = $this->getMock(\OxidEsales\Eshop\Core\Utils::class, array('redirect'));
$utils->expects($this->never())->method('redirect');
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils);
$request = $this->getMock(\OxidEsales\Eshop\Core\Request::class, array('getRequestUrl'));
$request->expects($this->any())->method('getRequestUrl')->will($this->returnValue($requestUrl));
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Request::class, $request);
$controller = oxNew(\OxidEsales\Eshop\Application\Controller\FrontendController::class);
$this->assertEquals(VIEW_INDEXSTATE_INDEX, $controller->noIndex());
$controller->init();
$this->assertEquals(VIEW_INDEXSTATE_NOINDEXFOLLOW, $controller->noIndex());
$this->assertEmpty($this->getCategorySeoEntries());
}
/**
* Call shop with standard url, a matching entry in seo table already exists.
*/
public function testStandardUrlMatchingSeoUrlAvailable()
{
$this->callCurl(''); //call shop start page to have all seo urls for main categories generated
$requestUrl = 'index.php?cl=alist&cnid=' . $this->categoryOxid;
$shopUrl = $this->getConfig()->getCurrentShopUrl();
$redirectUrl = \OxidEsales\Eshop\Core\Registry::getSeoEncoder()->fetchSeoUrl($requestUrl);
$this->assertEquals($this->seoUrl, $redirectUrl);
$utils = $this->getMock(\OxidEsales\Eshop\Core\Utils::class, array('redirect'));
$utils->expects($this->once())->method('redirect')
->with(
$this->equalTo($shopUrl . $redirectUrl),
$this->equalTo(false),
$this->equalTo('301')
);
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils);
$request = $this->getMock(\OxidEsales\Eshop\Core\Request::class, array('getRequestUrl'));
$request->expects($this->any())->method('getRequestUrl')->will($this->returnValue($requestUrl));
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Request::class, $request);
$controller = oxNew(\OxidEsales\Eshop\Application\Controller\FrontendController::class);
$this->assertEquals(VIEW_INDEXSTATE_INDEX, $controller->noIndex());
$controller->init();
$this->assertEquals(VIEW_INDEXSTATE_INDEX, $controller->noIndex());
$this->assertEquals(1, count($this->getCategorySeoEntries()));
}
/**
* Call shop with standard url and append pgNr request parameter.
* Blank seo url already is stored in oxseo table.
* Case that pgNr should exist as there are sufficient items in that category.
*/
public function testSeoUrlWithPgNr()
{
$this->callCurl(''); //call shop start page to have all seo urls for main categories generated
$requestUrl = 'index.php?cl=alist&cnid=' . $this->categoryOxid . '&pgNr=2';
//base seo url is found in database and page part appended
$shopUrl = $this->getConfig()->getCurrentShopUrl();
$redirectUrl = \OxidEsales\Eshop\Core\Registry::getSeoEncoder()->fetchSeoUrl($requestUrl);
$this->assertEquals($this->seoUrl . '?pgNr=2', $redirectUrl);
$utils = $this->getMock(\OxidEsales\Eshop\Core\Utils::class, array('redirect'));
$utils->expects($this->once())->method('redirect')
->with(
$this->equalTo($shopUrl . $redirectUrl),
$this->equalTo(false),
$this->equalTo('301')
);
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils);
$request = $this->getMock(\OxidEsales\Eshop\Core\Request::class, array('getRequestUrl'));
$request->expects($this->any())->method('getRequestUrl')->will($this->returnValue($requestUrl));
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Request::class, $request);
$controller = oxNew(\OxidEsales\Eshop\Application\Controller\FrontendController::class);
$this->assertEquals(VIEW_INDEXSTATE_INDEX, $controller->noIndex());
$controller->init();
$this->assertEquals(VIEW_INDEXSTATE_INDEX, $controller->noIndex());
}
/**
* Test paginated entries. Call with standard url with appended pgNr parameter.
*/
public function testExistingPaginatedSeoEntries()
{
$this->callCurl(''); //call shop start page to have all seo urls for main categories generated
$this->callCurl($this->seoUrl); //call shop seo page, this will create all paginated pages
$this->assertGeneratedPages();
//Call with standard url that has a pgNr parameter attached, paginated seo url will be found in this case.
$shopUrl = $this->getConfig()->getCurrentShopUrl();
$requestUrl = 'index.php?cl=alist&cnid=' . $this->categoryOxid . '&pgNr=1';
$redirectUrl = \OxidEsales\Eshop\Core\Registry::getSeoEncoder()->fetchSeoUrl($requestUrl);
$this->assertEquals($this->seoUrl . '?pgNr=1', $redirectUrl);
$utils = $this->getMock(\OxidEsales\Eshop\Core\Utils::class, array('redirect'));
$utils->expects($this->once())->method('redirect')
->with(
$this->equalTo($shopUrl . $redirectUrl),
$this->equalTo(false),
$this->equalTo('301')
);
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils);
$request = $this->getMock(\OxidEsales\Eshop\Core\Request::class, array('getRequestUrl'));
$request->expects($this->any())->method('getRequestUrl')->will($this->returnValue($requestUrl));
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Request::class, $request);
$controller = oxNew(\OxidEsales\Eshop\Application\Controller\FrontendController::class);
$this->assertEquals(VIEW_INDEXSTATE_INDEX, $controller->noIndex());
$controller->init();
$this->assertEquals(VIEW_INDEXSTATE_INDEX, $controller->noIndex());
}
/**
* Test paginated entries. Call with standard url with appended pgNr parameter.
* Dofference to test case before: call with ot existing page Nr.
*/
public function testNotExistingPaginatedSeoEntries()
{
$this->callCurl(''); //call shop start page to have all seo urls for main categories generated
$this->callCurl($this->seoUrl); //call shop seo page, this will create all paginated pages
$this->assertGeneratedPages();
//Call with standard url that has a pgNr parameter attached, paginated seo url will be found in this case.
$requestUrl = 'index.php?cl=alist&cnid=' . $this->categoryOxid . '&pgNr=20';
//The paginated page url is created on the fly. This seo page would not contain any data.
$redirectUrl = \OxidEsales\Eshop\Core\Registry::getSeoEncoder()->fetchSeoUrl($requestUrl);
$this->assertEquals($this->seoUrl . '?pgNr=20', $redirectUrl);
}
public function providerTestDecodeNewSeoUrl()
{
$facts = new \OxidEsales\Facts\Facts();
$this->seoUrl = ('EE' == $facts->getEdition()) ? 'Party/Bar-Equipment/' : 'Geschenke/';
$this->categoryOxid = ('EE' == $facts->getEdition()) ? '30e44ab8593023055.23928895' : '8a142c3e4143562a5.46426637';
$data = [];
$data['plain_seo_url'] = ['params' => $this->seoUrl,
'expected' => ['cl' => 'alist',
'cnid' => $this->categoryOxid,
'lang' => '0']
];
$data['old_style_paginated_page'] = ['params' => $this->seoUrl . '2/',
'expected' => ['cl' => 'alist',
'cnid' => $this->categoryOxid,
'lang' => '0',
'pgNr' => 1]
];
return $data;
}
/**
* Test decoding seo calls.
*
* @param string $params
* @param array $expected
*
* @dataProvider providerTestDecodeNewSeoUrl
*/
public function testDecodeNewSeoUrl($params, $expected)
{
$this->callCurl(''); //call shop start page to have all seo urls for main categories generated
$this->callCurl($this->seoUrl); //call shop seo page, this will create all paginated pages
$utils = $this->getMock(\OxidEsales\Eshop\Core\Utils::class, array('redirect'));
$utils->expects($this->never())->method('redirect');
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils);
$seoDecoder = oxNew(\OxidEsales\Eshop\Core\SeoDecoder::class);
$decoded = $seoDecoder->decodeUrl($params); //decoded new url
$this->assertEquals($expected, $decoded);
}
public function providerTestProcessingSeoCallNewSeoUrl()
{
$facts = new \OxidEsales\Facts\Facts();
$this->seoUrl = ('EE' == $facts->getEdition()) ? 'Party/Bar-Equipment/' : 'Geschenke/';
$this->categoryOxid = ('EE' == $facts->getEdition()) ? '30e44ab8593023055.23928895' : '8a142c3e4143562a5.46426637';
$data = [];
$data['plain_seo_url'] = ['request' => $this->seoUrl,
'get' => [],
'expected' => ['cl' => 'alist',
'cnid' => $this->categoryOxid,
'lang' => '0']
];
$data['paginated_page'] = ['request' => $this->seoUrl . '2/',
'get' => ['pgNr' => '1'],
'expected' => ['cl' => 'alist',
'cnid' => $this->categoryOxid,
'lang' => '0',
'pgNr' => '1']
];
$data['pgnr_as_get'] = ['params' => $this->seoUrl . '?pgNr=2',
'get' => ['pgNr' => '2'],
'expected' => ['cl' => 'alist',
'cnid' => $this->categoryOxid,
'lang' => '0',
'pgNr' => '2']
];
return $data;
}
/**
* Test decoding seo calls. Call shop with seo main page plus pgNr parameter.
* No additional paginated pages are stored in oxseo table. pgNr parameter
* come in via GET and all other needed parameters for processing the call
* are extracted via decodeUrl.
* To be able to correctly decode an url like 'Geschenke/2/' without having
* a matching entry stored in oxseo table, we need to parse this url into
* 'Geschenke/' plus pgNr parameter.
*
* @param string $params
* @param array $get
* @param array $expected
*
* @dataProvider providerTestProcessingSeoCallNewSeoUrl
*/
public function testProcessingSeoCallNewSeoUrl($request, $get, $expected)
{
$this->callCurl(''); //call shop start page to have all seo urls for main categories generated
$utils = $this->getMock(\OxidEsales\Eshop\Core\Utils::class, array('redirect'));
$utils->expects($this->never())->method('redirect');
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils);
$seoDecoder = oxNew(\OxidEsales\Eshop\Core\SeoDecoder::class);
$_GET = $get;
$seoDecoder->processSeoCall($request, '/');
$this->assertEquals($expected, $_GET);
$this->assertGeneratedPages();
}
/**
* Test SeoEncoderCategory::getCategoryPageUrl()
*/
public function testGetCategoryPageUrl()
{
$shopUrl = $this->getConfig()->getCurrentShopUrl();
$category = oxNew(\OxidEsales\Eshop\Application\Model\Category::class);
$category->load($this->categoryOxid);
$seoEncoderCategory = oxNew(\OxidEsales\Eshop\Application\Model\SeoEncoderCategory::class);
$result = $seoEncoderCategory->getCategoryPageUrl($category, 2);
$this->assertEquals($shopUrl . $this->seoUrl . '?pgNr=2', $result);
//unpaginated seo url is now stored in database and should not be saved again.
$seoEncoderCategory = $this->getMock(\OxidEsales\Eshop\Application\Model\SeoEncoderCategory::class, ['_saveToDb']);
$seoEncoderCategory->expects($this->never())->method('_saveToDb');
$seoEncoderCategory->getCategoryPageUrl($category, 0);
$seoEncoderCategory->getCategoryPageUrl($category, 1);
$seoEncoderCategory->getCategoryPageUrl($category, 2);
}
/**
* Test SeoEncoderVendor::getVendorPageUrl()
*/
public function testGetVendorPageUrl()
{
$facts = new \OxidEsales\Facts\Facts();
if ('EE' != $facts->getEdition()) {
$this->markTestSkipped('missing testdata');
}
$shopUrl = $this->getConfig()->getCurrentShopUrl();
$vendorOxid = 'd2e44d9b31fcce448.08890330';
$seoUrl = 'Nach-Lieferant/Hersteller-1/';
$vendor = oxNew(\OxidEsales\Eshop\Application\Model\Vendor::class);
$vendor->load($vendorOxid);
$seoEncoderVendor = oxNew(\OxidEsales\Eshop\Application\Model\SeoEncoderVendor::class);
$result = $seoEncoderVendor->getVendorPageUrl($vendor, 2);
$this->assertEquals($shopUrl . $seoUrl . '?pgNr=2', $result);
//unpaginated seo url is now stored in database and should not be saved again.
$seoEncoderVendor = $this->getMock(\OxidEsales\Eshop\Application\Model\SeoEncoderVendor::class, ['_saveToDb']);
$seoEncoderVendor->expects($this->never())->method('_saveToDb');
$seoEncoderVendor->getVendorPageUrl($vendor, 0);
$seoEncoderVendor->getVendorPageUrl($vendor, 1);
$seoEncoderVendor->getVendorPageUrl($vendor, 2);
}
/**
* Test SeoEncoderManufacturer::getManufacturerPageUrl()
*/
public function testGetManufacturerPageUrl()
{
$facts = new \OxidEsales\Facts\Facts();
if ('EE' != $facts->getEdition()) {
$this->markTestSkipped('missing testdata');
}
$languageId = 1; //en
$shopUrl = $this->getConfig()->getCurrentShopUrl();
$manufacturerOxid = '2536d76675ebe5cb777411914a2fc8fb';
$seoUrl = 'en/By-manufacturer/Manufacturer-2/';
$manufacturer = oxNew(\OxidEsales\Eshop\Application\Model\Manufacturer::class);
$manufacturer->load($manufacturerOxid);
$seoEncoderManufacturer = oxNew(\OxidEsales\Eshop\Application\Model\SeoEncoderManufacturer::class);
$result = $seoEncoderManufacturer->getManufacturerPageUrl($manufacturer, 2, $languageId);
$this->assertEquals($shopUrl . $seoUrl . '?pgNr=2', $result);
}
/**
* Test SeoEncoderRecomm::getRecommPageUrl()
*/
public function testGetRecommPageUrl()
{
$shopUrl = $this->getConfig()->getCurrentShopUrl();
$seoUrl = 'testTitle/';
$recomm = $this->getMock(\OxidEsales\Eshop\Application\Model\RecommendationList::class, ['getId', 'getBaseStdLink']);
$recomm->expects($this->any())->method('getId')->will($this->returnValue('testRecommId'));
$recomm->expects($this->any())->method('getBaseStdLink')->will($this->returnValue('testStdLink'));
$recomm->oxrecommlists__oxtitle = new \OxidEsales\Eshop\Core\Field('testTitle');
$seoEncoderRecomm = oxNew(\OxidEsales\Eshop\Application\Model\SeoEncoderRecomm::class);
$result = $seoEncoderRecomm->getRecommPageUrl($recomm, 2);
$this->assertEquals($shopUrl . $seoUrl . '?pgNr=2', $result);
//unpaginated seo url is now stored in database and should not be saved again.
$seoEncoderRecomm = $this->getMock(\OxidEsales\Eshop\Application\Model\SeoEncoderRecomm::class, ['_saveToDb']);
$seoEncoderRecomm->expects($this->never())->method('_saveToDb');
$seoEncoderRecomm->getRecommPageUrl($recomm, 0);
$seoEncoderRecomm->getRecommPageUrl($recomm, 1);
$seoEncoderRecomm->getRecommPageUrl($recomm, 2);
}
public function providerCheckSeoUrl()
{
$facts = new \OxidEsales\Facts\Facts();
$oxidLiving = ('EE' != $facts->getEdition()) ? '8a142c3e44ea4e714.31136811' : '30e44ab83b6e585c9.63147165';
$data = [
['Eco-Fashion/', ['HTTP/1.1 200 OK'], ['ROBOTS'], []],
['Eco-Fashion/3/', ['404 Not Found'], [], ['Eco-Fashion/']],
['Eco-Fashion/?pgNr=0', ['HTTP/1.1 200 OK'], ['ROBOTS', 'Location'], []],
['Eco-Fashion/?pgNr=34', ['404 Not Found'],[], []],
['index.php?cl=alist&cnid=oxmore', ['HTTP/1.1 200 OK'], ['Location'], []],
['index.php?cl=alist&cnid=oxmore&pgNr=0', ['HTTP/1.1 200 OK'], ['Location'], []],
['index.php?cl=alist&cnid=oxmore&pgNr=10', ['HTTP/1.1 200 OK'], ['Location'], []],
['index.php?cl=alist&cnid=oxmore&pgNr=20', ['HTTP/1.1 200 OK'], ['Location'], []],
['index.php?cl=alist&cnid=' . $oxidLiving, ['HTTP/1.1 200 OK'], ['ROBOTS'], []],
['index.php?cl=alist&cnid=' . $oxidLiving . '&pgNr=0', ['HTTP/1.1 200 OK'], ['ROBOTS'], []],
['index.php?cl=alist&cnid=' . $oxidLiving . '&pgNr=100', ['HTTP/1.1 302 Found'], [], ['index.php?cl=alist&cnid=' . $oxidLiving]],
['index.php?cl=alist&cnid=' . $oxidLiving . '&pgNr=200', ['HTTP/1.1 302 Found'], [], ['index.php?cl=alist&cnid=' . $oxidLiving]]
];
if (('EE' == $facts->getEdition())) {
$data[] = ['Fuer-Sie/', ['HTTP/1.1 200 OK'], ['ROBOTS'], []];
$data[] = ['Fuer-Sie/45/', ['HTTP/1.1 302 Found', 'Location'], ['ROBOTS'], ['Fuer-Sie/']];
$data[] = ['Fuer-Sie/?pgNr=0', ['HTTP/1.1 200 OK'], [ 'Location', 'ROBOTS'], []];
$data[] = ['Fuer-Sie/?pgNr=34', ['HTTP/1.1 302 Found', 'Location'], ['ROBOTS'], ['Fuer-Sie/']];
} else {
$data[] = ['Geschenke/', ['HTTP/1.1 200 OK'], ['ROBOTS', 'Location'], ['index.php?cl=alist&cnid=' . $oxidLiving]];
$data[] = ['Geschenke/?pgNr=0', ['HTTP/1.1 200 OK'], ['ROBOTS', 'Location'], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/']];
$data[] = ['Geschenke/?pgNr=100', ['HTTP/1.1 302 Found', 'Location'], [], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/']];
$data[] = ['Geschenke/30/', ['HTTP/1.1 302 Found', 'Location'], [], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/']];
$data[] = ['Geschenke/?pgNr=1', ['HTTP/1.1 200 OK', 'ROBOTS', 'NOINDEX'], ['Location'], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/']];
$data[] = ['Geschenke/?pgNr=3', ['HTTP/1.1 200 OK', 'ROBOTS', 'NOINDEX'], ['Location'], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/']];
$data[] = ['Geschenke/?pgNr=4', ['HTTP/1.1 302 Found', 'Location'], [], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/']];
$data[] = ['Geschenke/4/', ['HTTP/1.1 200 OK', 'ROBOTS', 'NOINDEX'], ['Location'], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/', 'Geschenke/?pgNr=0', 'Geschenke/?pgNr=1',]];
$data[] = ['Geschenke/10/', ['HTTP/1.1 302 Found', 'Location'], [], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/', 'Geschenke/?pgNr=0', 'Geschenke/?pgNr=1', 'Geschenke/4/']];
}
return $data;
}
/**
* Calling not existing pagenumbers must not result in additional entries in oxseo table.
*
* @dataProvider providerCheckSeoUrl
*
* @param string $urlToCall Url to call
* @param array $responseContains Curl call response must contain.
* @param array $responseNotContains Curl call response must not contain.
* @param array $prepareUrls To make test cases independent, call this url first.
*/
public function testCheckSeoUrl(
$urlToCall,
$responseContains,
$responseNotContains,
$prepareUrls
) {
$this->initSeoUrlGeneration();
foreach ($prepareUrls as $url) {
$this->callCurl($url);
}
$response = $this->callCurl($urlToCall);
foreach ($responseContains as $checkFor) {
$this->assertStringContainsString($checkFor, $response, "Should get $checkFor");
}
foreach ($responseNotContains as $checkFor) {
$this->assertStringNotContainsString($checkFor, $response, "Should not get $checkFor");
}
}
public function testCreateProductSeoUrlsOnProductListPageRequest()
{
$this->prepareSeoUrlTestData();
$this->initSeoUrlGeneration();
$seoUrl = 'testSeoUrl/';
$productSeoUrlsCountBeforeRequest = $this->getProductSeoUrlsCount($seoUrl);
$this->callCurl($seoUrl . '?pgNr=0');
$this->clearProxyCache();
$this->callCurl($seoUrl . '?pgNr=0');
$productSeoUrlsCountAfterRequest = $this->getProductSeoUrlsCount($seoUrl);
$productsPerPage = 10;
$this->assertEquals(
$productSeoUrlsCountBeforeRequest + $productsPerPage,
$productSeoUrlsCountAfterRequest
);
}
public function testDoNotCreateAnotherCategorySeoUrlsOnProductListPageRequest()
{
$this->prepareSeoUrlTestData();
$seoUrl = 'testSeoUrl/';
$this->callCurl($seoUrl);
$this->assertCount(
1,
$this->getCategorySeoUrls($seoUrl)
);
$this->callCurl($seoUrl . '?pgNr=0');
$this->callCurl($seoUrl . '1');
$this->assertCount(
1,
$this->getCategorySeoUrls($seoUrl)
);
}
private function initSeoUrlGeneration()
{
$this->clearProxyCache();
$this->callCurl(''); //call shop startpage
$this->clearProxyCache();
}
private function getProductSeoUrlsCount($url)
{
$query = "
SELECT
count(*)
FROM
`oxseo`
WHERE
oxseourl LIKE '%" . $url . "%'
AND oxtype = 'oxarticle'
";
return DatabaseProvider::getDb()->getOne($query);
}
private function getCategorySeoUrls($url)
{
$query = "
SELECT
oxseourl
FROM
`oxseo`
WHERE
oxseourl LIKE '%" . $url . "%'
AND oxtype = 'oxcategory'
";
return DatabaseProvider::getDb()->getAll($query);
}
private function prepareSeoUrlTestData()
{
$seoUrl = 'testSeoUrl';
$shopId = $this->getConfig()->getBaseShopId();
$category = oxNew(Category::class);
$category->oxcategories__oxactive = new Field(1, Field::T_RAW);
$category->oxcategories__oxparentid = new Field('oxrootid', Field::T_RAW);
$category->oxcategories__oxshopid = new Field($shopId, Field::T_RAW);
$category->oxcategories__oxtitle = new Field($seoUrl, Field::T_RAW);
$category->save();
for ($i = 1; $i <= 20; $i++) {
$product = oxNew(Article::class);
$product->oxarticles__oxtitle = new Field($seoUrl, Field::T_RAW);
$product->save();
$relation = oxNew(Object2Category::class);
$relation->setCategoryId($category->getId());
$relation->setProductId($product->getId());
$relation->save();
}
}
/**
* Clean oxseo for testing.
*/
private function cleanSeoTable()
{
$query = "DELETE FROM oxseo WHERE oxtype in ('oxcategory', 'oxarticle')";
\OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute($query);
}
/**
* Ensure that whatever mocks were added are removed from Registry.
*/
private function cleanRegistry()
{
$seoEncoder = oxNew(\OxidEsales\Eshop\Core\SeoEncoder::class);
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\SeoEncoder::class, $seoEncoder);
$seoDecoder = oxNew(\OxidEsales\Eshop\Core\SeoDecoder::class);
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\SeoDecoder::class, $seoDecoder);
$utils = oxNew(\OxidEsales\Eshop\Core\Utils::class);
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils);
$request = oxNew(\OxidEsales\Eshop\Core\Request::class);
\OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Request::class, $request);
}
/**
* @param string $fileUrlPart Shop url part to call.
*
* @return string
*/
private function callCurl($fileUrlPart)
{
$url = $this->getConfig()->getShopMainUrl() . $fileUrlPart;
$curl = oxNew(\OxidEsales\Eshop\Core\Curl::class);
$curl->setOption('CURLOPT_HEADER', true);
$curl->setOption('CURLOPT_RETURNTRANSFER', true);
$curl->setUrl($url);
$return = $curl->execute();
sleep(0.5); // for master slave: please wait before checking the results.
return $return;
}
/**
* Test helper to check for paginated seo pages.
*/
private function assertGeneratedPages()
{
$query = "SELECT oxstdurl, oxseourl FROM `oxseo` WHERE `OXSEOURL` LIKE '{$this->seoUrl}'" .
" OR `OXSEOURL` LIKE '{$this->seoUrl}%pgNr%'" .
" OR `OXSEOURL` LIKE '{$this->seoUrl}1/'" .
" OR `OXSEOURL` LIKE '{$this->seoUrl}2/'" .
" OR `OXSEOURL` LIKE '{$this->seoUrl}3/'" .
" OR `OXSEOURL` LIKE '{$this->seoUrl}4/'" .
" OR `OXSEOURL` LIKE '{$this->seoUrl}5/'" .
" AND oxtype = 'oxcategory'";
$res = \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->getAll($query);
$this->assertEquals(1, count($res));
}
/**
* Test helper.
*
* @return array
*/
private function getCategorySeoEntries()
{
$query = "SELECT oxstdurl, oxseourl FROM `oxseo` WHERE `OXSTDURL` like '%" . $this->categoryOxid . "%'" .
" AND oxtype = 'oxcategory'";
return \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->getAll($query);
}
/**
* Test helper.
*/
private function clearProxyCache()
{
$cacheService = oxNew(\OxidEsales\TestingLibrary\Services\Library\Cache::class);
$cacheService->clearReverseProxyCache();
}
}
| flow-control/oxideshop_ce | tests/Integration/Seo/PaginationSeoTest.php | PHP | gpl-3.0 | 31,918 |
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include <vgui/IBorder.h>
#include <vgui/IInputInternal.h>
#include <vgui/IPanel.h>
#include <vgui/IScheme.h>
#include <vgui/IVGui.h>
#include <vgui/KeyCode.h>
#include <KeyValues.h>
#include <vgui/MouseCode.h>
#include <vgui/ISurface.h>
#include <vgui_controls/Button.h>
#include <vgui_controls/Controls.h>
#include <vgui_controls/Label.h>
#include <vgui_controls/PropertySheet.h>
#include <vgui_controls/ComboBox.h>
#include <vgui_controls/Panel.h>
#include <vgui_controls/ToolWindow.h>
#include <vgui_controls/TextImage.h>
#include <vgui_controls/ImagePanel.h>
#include <vgui_controls/PropertyPage.h>
#include "vgui_controls/AnimationController.h"
#include "strtools_local.h" // TODO: temp
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
using namespace vgui2;
namespace vgui2
{
class ContextLabel : public Label
{
DECLARE_CLASS_SIMPLE(ContextLabel, Label);
public:
ContextLabel(Button *parent, char const *panelName, char const *text)
: BaseClass((Panel *)parent, panelName, text),
m_pTabButton(parent)
{
SetBlockDragChaining(true);
}
virtual void OnMousePressed(MouseCode code)
{
if(m_pTabButton)
{
m_pTabButton->FireActionSignal();
}
}
virtual void OnMouseReleased(MouseCode code)
{
BaseClass::OnMouseReleased(code);
if(GetParent())
{
GetParent()->OnCommand("ShowContextMenu");
}
}
virtual void ApplySchemeSettings(IScheme *pScheme)
{
BaseClass::ApplySchemeSettings(pScheme);
HFont marlett = pScheme->GetFont("Marlett");
SetFont(marlett);
SetTextInset(0, 0);
SetContentAlignment(Label::a_northwest);
if(GetParent())
{
SetFgColor(pScheme->GetColor("Button.TextColor", GetParent()->GetFgColor()));
SetBgColor(GetParent()->GetBgColor());
}
}
private:
Button *m_pTabButton;
};
//-----------------------------------------------------------------------------
// Purpose: Helper for drag drop
// Input : msglist -
// Output : static PropertySheet
//-----------------------------------------------------------------------------
static PropertySheet *IsDroppingSheet(CUtlVector<KeyValues *> &msglist)
{
if(msglist.Count() == 0)
return NULL;
KeyValues *data = msglist[0];
PropertySheet *sheet = reinterpret_cast<PropertySheet *>(data->GetPtr("propertysheet"));
if(sheet)
return sheet;
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose: A single tab
//-----------------------------------------------------------------------------
class PageTab : public Button
{
DECLARE_CLASS_SIMPLE(PageTab, Button);
private:
bool _active;
SDK_Color _textColor;
SDK_Color _dimTextColor;
int m_bMaxTabWidth;
IBorder *m_pActiveBorder;
IBorder *m_pNormalBorder;
PropertySheet *m_pParent;
Panel *m_pPage;
ImagePanel *m_pImage;
char *m_pszImageName;
bool m_bShowContextLabel;
ContextLabel *m_pContextLabel;
public:
PageTab(PropertySheet *parent, const char *panelName, const char *text, char const *imageName, int maxTabWidth, Panel *page, bool showContextButton)
: Button((Panel *)parent, panelName, text),
m_pParent(parent),
m_pPage(page),
m_pImage(0),
m_pszImageName(0),
m_bShowContextLabel(showContextButton)
{
SetCommand(new KeyValues("TabPressed"));
_active = false;
m_bMaxTabWidth = maxTabWidth;
SetDropEnabled(true);
SetDragEnabled(m_pParent->IsDraggableTab());
if(imageName)
{
m_pImage = new ImagePanel(this, text);
int buflen = Q_strlen(imageName) + 1;
m_pszImageName = new char[buflen];
Q_strncpy(m_pszImageName, imageName, buflen);
}
SetMouseClickEnabled(MOUSE_RIGHT, true);
m_pContextLabel = m_bShowContextLabel ? new ContextLabel(this, "Context", "9") : NULL;
REGISTER_COLOR_AS_OVERRIDABLE(_textColor, "selectedcolor");
REGISTER_COLOR_AS_OVERRIDABLE(_dimTextColor, "unselectedcolor");
}
~PageTab()
{
delete[] m_pszImageName;
}
virtual void Paint()
{
BaseClass::Paint();
}
virtual bool IsDroppable(CUtlVector<KeyValues *> &msglist)
{
// It's never droppable, but should activate
FireActionSignal();
SetSelected(true);
Repaint();
if(!GetParent())
return false;
PropertySheet *sheet = IsDroppingSheet(msglist);
if(sheet)
{
return GetParent()->IsDroppable(msglist);
}
// Defer to active page...
Panel *active = m_pParent->GetActivePage();
if(!active || !active->IsDroppable(msglist))
return false;
return active->IsDroppable(msglist);
}
virtual void OnDroppablePanelPaint(CUtlVector<KeyValues *> &msglist, CUtlVector<Panel *> &dragPanels)
{
PropertySheet *sheet = IsDroppingSheet(msglist);
if(sheet)
{
Panel *target = GetParent()->GetDropTarget(msglist);
if(target)
{
// Fixme, mouse pos could be wrong...
target->OnDroppablePanelPaint(msglist, dragPanels);
return;
}
}
// Just highlight the tab if dropping onto active page via the tab
BaseClass::OnDroppablePanelPaint(msglist, dragPanels);
}
virtual void OnPanelDropped(CUtlVector<KeyValues *> &msglist)
{
PropertySheet *sheet = IsDroppingSheet(msglist);
if(sheet)
{
Panel *target = GetParent()->GetDropTarget(msglist);
if(target)
{
// Fixme, mouse pos could be wrong...
target->OnPanelDropped(msglist);
}
}
// Defer to active page...
Panel *active = m_pParent->GetActivePage();
if(!active || !active->IsDroppable(msglist))
return;
active->OnPanelDropped(msglist);
}
virtual void OnDragFailed(CUtlVector<KeyValues *> &msglist)
{
PropertySheet *sheet = IsDroppingSheet(msglist);
if(!sheet)
return;
// Create a new property sheet
if(m_pParent->IsDraggableTab())
{
if(msglist.Count() == 1)
{
KeyValues *data = msglist[0];
int screenx = data->GetInt("screenx");
int screeny = data->GetInt("screeny");
// m_pParent->ScreenToLocal( screenx, screeny );
if(!m_pParent->IsWithin(screenx, screeny))
{
Panel *page = reinterpret_cast<Panel *>(data->GetPtr("propertypage"));
PropertySheet *sheet = reinterpret_cast<PropertySheet *>(data->GetPtr("propertysheet"));
char const *title = data->GetString("tabname", "");
if(!page || !sheet)
return;
// Can only create if sheet was part of a ToolWindow derived object
ToolWindow *tw = dynamic_cast<ToolWindow *>(sheet->GetParent());
if(tw)
{
IToolWindowFactory *factory = tw->GetToolWindowFactory();
if(factory)
{
bool hasContextMenu = sheet->PageHasContextMenu(page);
sheet->RemovePage(page);
factory->InstanceToolWindow(tw->GetParent(), sheet->ShouldShowContextButtons(), page, title, hasContextMenu);
if(sheet->GetNumPages() == 0)
{
tw->MarkForDeletion();
}
}
}
}
}
}
}
virtual void OnCreateDragData(KeyValues *msg)
{
Assert(m_pParent->IsDraggableTab());
msg->SetPtr("propertypage", m_pPage);
msg->SetPtr("propertysheet", m_pParent);
char sz[256];
GetText(sz, sizeof(sz));
msg->SetString("tabname", sz);
msg->SetString("text", sz);
}
virtual void ApplySchemeSettings(IScheme *pScheme)
{
// set up the scheme settings
Button::ApplySchemeSettings(pScheme);
_textColor = GetSchemeColor("PropertySheet.SelectedTextColor", GetFgColor(), pScheme);
_dimTextColor = GetSchemeColor("PropertySheet.TextColor", GetFgColor(), pScheme);
m_pActiveBorder = pScheme->GetBorder("TabActiveBorder");
m_pNormalBorder = pScheme->GetBorder("TabBorder");
if(m_pImage)
{
ClearImages();
m_pImage->SetImage(scheme()->GetImage(m_pszImageName, false));
AddImage(m_pImage->GetImage(), 2);
int w, h;
m_pImage->GetSize(w, h);
w += m_pContextLabel ? 10 : 0;
if(m_pContextLabel)
{
m_pImage->SetPos(10, 0);
}
SetSize(w + 4, h + 2);
}
else
{
int wide, tall;
int contentWide, contentTall;
GetSize(wide, tall);
GetContentSize(contentWide, contentTall);
wide = std::max(m_bMaxTabWidth, contentWide + 10); // 10 = 5 pixels margin on each side
wide += m_pContextLabel ? 10 : 0;
SetSize(wide, tall);
}
if(m_pContextLabel)
{
SetTextInset(12, 0);
}
}
virtual void OnCommand(char const *cmd)
{
if(!Q_stricmp(cmd, "ShowContextMenu"))
{
KeyValues *kv = new KeyValues("OpenContextMenu");
kv->SetPtr("page", m_pPage);
kv->SetPtr("contextlabel", m_pContextLabel);
PostActionSignal(kv);
return;
}
BaseClass::OnCommand(cmd);
}
IBorder *GetBorder(bool depressed, bool armed, bool selected, bool keyfocus)
{
if(_active)
{
return m_pActiveBorder;
}
return m_pNormalBorder;
}
virtual SDK_Color GetButtonFgColor()
{
if(_active)
{
return _textColor;
}
else
{
return _dimTextColor;
}
}
virtual void SetActive(bool state)
{
_active = state;
InvalidateLayout();
Repaint();
}
virtual bool CanBeDefaultButton(void)
{
return false;
}
//Fire action signal when mouse is pressed down instead of on release.
virtual void OnMousePressed(MouseCode code)
{
// check for context menu open
if(!IsEnabled())
return;
if(!IsMouseClickEnabled(code))
return;
if(IsUseCaptureMouseEnabled())
{
{
RequestFocus();
FireActionSignal();
SetSelected(true);
Repaint();
}
// lock mouse input to going to this button
input()->SetMouseCapture(GetVPanel());
}
}
virtual void OnMouseReleased(MouseCode code)
{
// ensure mouse capture gets released
if(IsUseCaptureMouseEnabled())
{
input()->SetMouseCapture(NULL_HANDLE);
}
// make sure the button gets unselected
SetSelected(false);
Repaint();
if(code == MOUSE_RIGHT)
{
KeyValues *kv = new KeyValues("OpenContextMenu");
kv->SetPtr("page", m_pPage);
kv->SetPtr("contextlabel", m_pContextLabel);
PostActionSignal(kv);
}
}
virtual void PerformLayout()
{
BaseClass::PerformLayout();
if(m_pContextLabel)
{
int w, h;
GetSize(w, h);
m_pContextLabel->SetBounds(0, 0, 10, h);
}
}
};
}; // namespace vgui2
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
PropertySheet::PropertySheet(
Panel *parent,
const char *panelName,
bool draggableTabs /*= false*/)
: BaseClass(parent, panelName)
{
_activePage = NULL;
_activeTab = NULL;
_tabWidth = 64;
_activeTabIndex = 0;
_showTabs = true;
_combo = NULL;
_tabFocus = false;
m_flPageTransitionEffectTime = 0.0f;
m_bSmallTabs = false;
m_tabFont = 0;
m_bDraggableTabs = draggableTabs;
if(m_bDraggableTabs)
{
SetDropEnabled(true);
}
m_bKBNavigationEnabled = true;
}
//-----------------------------------------------------------------------------
// Purpose: Constructor, associates pages with a combo box
//-----------------------------------------------------------------------------
PropertySheet::PropertySheet(Panel *parent, const char *panelName, ComboBox *combo)
: BaseClass(parent, panelName)
{
_activePage = NULL;
_activeTab = NULL;
_tabWidth = 64;
_activeTabIndex = 0;
_combo = combo;
_combo->AddActionSignalTarget(this);
_showTabs = false;
_tabFocus = false;
m_flPageTransitionEffectTime = 0.0f;
m_bSmallTabs = false;
m_tabFont = 0;
m_bDraggableTabs = false;
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
PropertySheet::~PropertySheet()
{
}
//-----------------------------------------------------------------------------
// Purpose: ToolWindow uses this to drag tools from container to container by dragging the tab
// Input : -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool PropertySheet::IsDraggableTab() const
{
return m_bDraggableTabs;
}
void PropertySheet::SetDraggableTabs(bool state)
{
m_bDraggableTabs = state;
}
//-----------------------------------------------------------------------------
// Purpose: Lower profile tabs
// Input : state -
//-----------------------------------------------------------------------------
void PropertySheet::SetSmallTabs(bool state)
{
m_bSmallTabs = state;
m_tabFont = scheme()->GetIScheme(GetScheme())->GetFont(m_bSmallTabs ? "DefaultVerySmall" : "Default");
int c = m_PageTabs.Count();
for(int i = 0; i < c; ++i)
{
PageTab *tab = m_PageTabs[i];
Assert(tab);
tab->SetFont(m_tabFont);
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool PropertySheet::IsSmallTabs() const
{
return m_bSmallTabs;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : state -
//-----------------------------------------------------------------------------
void PropertySheet::ShowContextButtons(bool state)
{
m_bContextButton = state;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool PropertySheet::ShouldShowContextButtons() const
{
return m_bContextButton;
}
int PropertySheet::FindPage(Panel *page) const
{
int c = m_Pages.Count();
for(int i = 0; i < c; ++i)
{
if(m_Pages[i].page == page)
return i;
}
return m_Pages.InvalidIndex();
}
//-----------------------------------------------------------------------------
// Purpose: adds a page to the sheet
//-----------------------------------------------------------------------------
void PropertySheet::AddPage(Panel *page, const char *title, char const *imageName /*= NULL*/, bool bHasContextMenu /*= false*/)
{
if(!page)
return;
// don't add the page if we already have it
if(FindPage(page) != m_Pages.InvalidIndex())
return;
PageTab *tab = new PageTab(this, "tab", title, imageName, _tabWidth, page, m_bContextButton && bHasContextMenu);
if(m_bDraggableTabs)
{
tab->SetDragEnabled(true);
}
tab->SetFont(m_tabFont);
if(_showTabs)
{
tab->AddActionSignalTarget(this);
}
else if(_combo)
{
_combo->AddItem(title, NULL);
}
m_PageTabs.AddToTail(tab);
Page_t info;
info.page = page;
info.contextMenu = m_bContextButton && bHasContextMenu;
m_Pages.AddToTail(info);
page->SetParent(this);
page->AddActionSignalTarget(this);
PostMessage(page, new KeyValues("ResetData"));
page->SetVisible(false);
InvalidateLayout();
if(!_activePage)
{
// first page becomes the active page
ChangeActiveTab(0);
if(_activePage)
{
_activePage->RequestFocus(0);
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void PropertySheet::SetActivePage(Panel *page)
{
// walk the list looking for this page
int index = FindPage(page);
if(!m_Pages.IsValidIndex(index))
return;
ChangeActiveTab(index);
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void PropertySheet::SetTabWidth(int pixels)
{
_tabWidth = pixels;
InvalidateLayout();
}
//-----------------------------------------------------------------------------
// Purpose: reloads the data in all the property page
//-----------------------------------------------------------------------------
void PropertySheet::ResetAllData()
{
// iterate all the dialogs resetting them
for(int i = 0; i < m_Pages.Count(); i++)
{
ipanel()->SendMessage(m_Pages[i].page->GetVPanel(), new KeyValues("ResetData"), GetVPanel());
}
}
//-----------------------------------------------------------------------------
// Purpose: Applies any changes made by the dialog
//-----------------------------------------------------------------------------
void PropertySheet::ApplyChanges()
{
// iterate all the dialogs resetting them
for(int i = 0; i < m_Pages.Count(); i++)
{
ipanel()->SendMessage(m_Pages[i].page->GetVPanel(), new KeyValues("ApplyChanges"), GetVPanel());
}
}
//-----------------------------------------------------------------------------
// Purpose: gets a pointer to the currently active page
//-----------------------------------------------------------------------------
Panel *PropertySheet::GetActivePage()
{
return _activePage;
}
//-----------------------------------------------------------------------------
// Purpose: gets a pointer to the currently active tab
//-----------------------------------------------------------------------------
Panel *PropertySheet::GetActiveTab()
{
return _activeTab;
}
//-----------------------------------------------------------------------------
// Purpose: returns the number of panels in the sheet
//-----------------------------------------------------------------------------
int PropertySheet::GetNumPages()
{
return m_Pages.Count();
}
//-----------------------------------------------------------------------------
// Purpose: returns the name contained in the active tab
// Input : a text buffer to contain the output
//-----------------------------------------------------------------------------
void PropertySheet::GetActiveTabTitle(char *textOut, int bufferLen)
{
if(_activeTab)
_activeTab->GetText(textOut, bufferLen);
}
//-----------------------------------------------------------------------------
// Purpose: returns the name contained in the active tab
// Input : a text buffer to contain the output
//-----------------------------------------------------------------------------
bool PropertySheet::GetTabTitle(int i, char *textOut, int bufferLen)
{
if(i < 0 && i > m_PageTabs.Count())
{
return false;
}
m_PageTabs[i]->GetText(textOut, bufferLen);
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Returns the index of the currently active page
//-----------------------------------------------------------------------------
int PropertySheet::GetActivePageNum()
{
for(int i = 0; i < m_Pages.Count(); i++)
{
if(m_Pages[i].page == _activePage)
{
return i;
}
}
return -1;
}
//-----------------------------------------------------------------------------
// Purpose: Forwards focus requests to current active page
//-----------------------------------------------------------------------------
void PropertySheet::RequestFocus(int direction)
{
if(direction == -1 || direction == 0)
{
if(_activePage)
{
_activePage->RequestFocus(direction);
_tabFocus = false;
}
}
else
{
if(_showTabs && _activeTab)
{
_activeTab->RequestFocus(direction);
_tabFocus = true;
}
else if(_activePage)
{
_activePage->RequestFocus(direction);
_tabFocus = false;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: moves focus back
//-----------------------------------------------------------------------------
bool PropertySheet::RequestFocusPrev(VPANEL panel)
{
if(_tabFocus || !_showTabs || !_activeTab)
{
_tabFocus = false;
return BaseClass::RequestFocusPrev(panel);
}
else
{
if(GetVParent())
{
PostMessage(GetVParent(), new KeyValues("FindDefaultButton"));
}
_activeTab->RequestFocus(-1);
_tabFocus = true;
return true;
}
}
//-----------------------------------------------------------------------------
// Purpose: moves focus forward
//-----------------------------------------------------------------------------
bool PropertySheet::RequestFocusNext(VPANEL panel)
{
if(!_tabFocus || !_activePage)
{
return BaseClass::RequestFocusNext(panel);
}
else
{
if(!_activeTab)
{
return BaseClass::RequestFocusNext(panel);
}
else
{
_activePage->RequestFocus(1);
_tabFocus = false;
return true;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Gets scheme settings
//-----------------------------------------------------------------------------
void PropertySheet::ApplySchemeSettings(IScheme *pScheme)
{
BaseClass::ApplySchemeSettings(pScheme);
// a little backwards-compatibility with old scheme files
IBorder *pBorder = pScheme->GetBorder("PropertySheetBorder");
if(pBorder == pScheme->GetBorder("Default"))
{
// get the old name
pBorder = pScheme->GetBorder("RaisedBorder");
}
SetBorder(pBorder);
m_flPageTransitionEffectTime = atof(pScheme->GetResourceString("PropertySheet.TransitionEffectTime"));
m_tabFont = pScheme->GetFont(m_bSmallTabs ? "DefaultVerySmall" : "Default");
}
//-----------------------------------------------------------------------------
// Purpose: Paint our border specially, with the tabs in mind
//-----------------------------------------------------------------------------
void PropertySheet::PaintBorder()
{
IBorder *border = GetBorder();
if(!border)
return;
// draw the border, but with a break at the active tab
int px = 0, py = 0, pwide = 0, ptall = 0;
if(_activeTab)
{
_activeTab->GetBounds(px, py, pwide, ptall);
ptall -= 1;
}
// draw the border underneath the buttons, with a break
int wide, tall;
GetSize(wide, tall);
border->Paint(0, py + ptall, wide, tall, IBorder::SIDE_TOP, px + 1, px + pwide - 1);
}
//-----------------------------------------------------------------------------
// Purpose: Lays out the dialog
//-----------------------------------------------------------------------------
void PropertySheet::PerformLayout()
{
BaseClass::PerformLayout();
int x, y, wide, tall;
GetBounds(x, y, wide, tall);
if(_activePage)
{
int tabHeight = IsSmallTabs() ? 14 : 28;
if(_showTabs)
{
_activePage->SetBounds(0, tabHeight, wide, tall - tabHeight);
}
else
{
_activePage->SetBounds(0, 0, wide, tall);
}
_activePage->InvalidateLayout();
}
int xtab;
int limit = m_PageTabs.Count();
xtab = 0;
// draw the visible tabs
if(_showTabs)
{
for(int i = 0; i < limit; i++)
{
int tabHeight = IsSmallTabs() ? 13 : 27;
int width, tall;
m_PageTabs[i]->GetSize(width, tall);
if(m_PageTabs[i] == _activeTab)
{
// active tab is taller
_activeTab->SetBounds(xtab, 2, width, tabHeight);
}
else
{
m_PageTabs[i]->SetBounds(xtab, 4, width, tabHeight - 2);
}
m_PageTabs[i]->SetVisible(true);
xtab += (width + 1);
}
}
else
{
for(int i = 0; i < limit; i++)
{
m_PageTabs[i]->SetVisible(false);
}
}
// ensure draw order (page drawing over all the tabs except one)
if(_activePage)
{
_activePage->MoveToFront();
_activePage->Repaint();
}
if(_activeTab)
{
_activeTab->MoveToFront();
_activeTab->Repaint();
}
}
//-----------------------------------------------------------------------------
// Purpose: Switches the active panel
//-----------------------------------------------------------------------------
void PropertySheet::OnTabPressed(Panel *panel)
{
// look for the tab in the list
for(int i = 0; i < m_PageTabs.Count(); i++)
{
if(m_PageTabs[i] == panel)
{
// flip to the new tab
ChangeActiveTab(i);
return;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: returns the panel associated with index i
// Input : the index of the panel to return
//-----------------------------------------------------------------------------
Panel *PropertySheet::GetPage(int i)
{
if(i < 0 && i > m_Pages.Count())
{
return NULL;
}
return m_Pages[i].page;
}
//-----------------------------------------------------------------------------
// Purpose: disables page by name
//-----------------------------------------------------------------------------
void PropertySheet::DisablePage(const char *title)
{
SetPageEnabled(title, false);
}
//-----------------------------------------------------------------------------
// Purpose: enables page by name
//-----------------------------------------------------------------------------
void PropertySheet::EnablePage(const char *title)
{
SetPageEnabled(title, true);
}
//-----------------------------------------------------------------------------
// Purpose: enabled or disables page by name
//-----------------------------------------------------------------------------
void PropertySheet::SetPageEnabled(const char *title, bool state)
{
for(int i = 0; i < m_PageTabs.Count(); i++)
{
if(_showTabs)
{
char tmp[50];
m_PageTabs[i]->GetText(tmp, 50);
if(!strnicmp(title, tmp, strlen(tmp)))
{
m_PageTabs[i]->SetEnabled(state);
}
}
else
{
_combo->SetItemEnabled(title, state);
}
}
}
void PropertySheet::RemoveAllPages()
{
int c = m_Pages.Count();
for(int i = c - 1; i >= 0; --i)
{
RemovePage(m_Pages[i].page);
}
}
//-----------------------------------------------------------------------------
// Purpose: deletes the page associated with panel
// Input : *panel - the panel of the page to remove
//-----------------------------------------------------------------------------
void PropertySheet::RemovePage(Panel *panel)
{
int location = FindPage(panel);
if(location == m_Pages.InvalidIndex())
return;
// Since it's being deleted, don't animate!!!
m_hPreviouslyActivePage = NULL;
_activeTab = NULL;
// ASSUMPTION = that the number of pages equals number of tabs
if(_showTabs)
{
m_PageTabs[location]->RemoveActionSignalTarget(this);
}
// now remove the tab
PageTab *tab = m_PageTabs[location];
m_PageTabs.Remove(location);
tab->MarkForDeletion();
// Remove from page list
m_Pages.Remove(location);
// Unparent
panel->SetParent((Panel *)NULL);
if(_activePage == panel)
{
_activePage = NULL;
// if this page is currently active, backup to the page before this.
ChangeActiveTab(std::max(location - 1, 0));
}
PerformLayout();
}
//-----------------------------------------------------------------------------
// Purpose: deletes the page associated with panel
// Input : *panel - the panel of the page to remove
//-----------------------------------------------------------------------------
void PropertySheet::DeletePage(Panel *panel)
{
Assert(panel);
RemovePage(panel);
panel->MarkForDeletion();
}
//-----------------------------------------------------------------------------
// Purpose: flips to the new tab, sending out all the right notifications
// flipping to a tab activates the tab.
//-----------------------------------------------------------------------------
void PropertySheet::ChangeActiveTab(int index)
{
if(!m_Pages.IsValidIndex(index))
{
_activeTab = NULL;
if(m_Pages.Count() > 0)
{
_activePage = NULL;
ChangeActiveTab(0);
}
return;
}
if(m_Pages[index].page == _activePage)
{
if(_activeTab)
{
_activeTab->RequestFocus();
}
_tabFocus = true;
return;
}
int c = m_Pages.Count();
for(int i = 0; i < c; ++i)
{
m_Pages[i].page->SetVisible(false);
}
m_hPreviouslyActivePage = _activePage;
// notify old page
if(_activePage)
{
ivgui()->PostMessage(_activePage->GetVPanel(), new KeyValues("PageHide"), GetVPanel());
KeyValues *msg = new KeyValues("PageTabActivated");
msg->SetPtr("panel", (Panel *)NULL);
ivgui()->PostMessage(_activePage->GetVPanel(), msg, GetVPanel());
}
if(_activeTab)
{
//_activeTabIndex=index;
_activeTab->SetActive(false);
// does the old tab have the focus?
_tabFocus = _activeTab->HasFocus();
}
else
{
_tabFocus = false;
}
// flip page
_activePage = m_Pages[index].page;
_activeTab = m_PageTabs[index];
_activeTabIndex = index;
_activePage->SetVisible(true);
_activePage->MoveToFront();
_activeTab->SetVisible(true);
_activeTab->MoveToFront();
_activeTab->SetActive(true);
if(_tabFocus)
{
// if a tab already has focused,give the new tab the focus
_activeTab->RequestFocus();
}
else
{
// otherwise, give the focus to the page
_activePage->RequestFocus();
}
if(!_showTabs)
{
_combo->ActivateItemByRow(index);
}
_activePage->MakeReadyForUse();
// transition effect
if(m_flPageTransitionEffectTime)
{
if(m_hPreviouslyActivePage.Get())
{
// fade out the previous page
GetAnimationController()->RunAnimationCommand(m_hPreviouslyActivePage, "Alpha", 0.0f, 0.0f, m_flPageTransitionEffectTime / 2, AnimationController::INTERPOLATOR_LINEAR);
}
// fade in the new page
_activePage->SetAlpha(0);
GetAnimationController()->RunAnimationCommand(_activePage, "Alpha", 255.0f, m_flPageTransitionEffectTime / 2, m_flPageTransitionEffectTime / 2, AnimationController::INTERPOLATOR_LINEAR);
}
else
{
if(m_hPreviouslyActivePage.Get())
{
// no transition, just hide the previous page
m_hPreviouslyActivePage->SetVisible(false);
}
_activePage->SetAlpha(255);
}
// notify
ivgui()->PostMessage(_activePage->GetVPanel(), new KeyValues("PageShow"), GetVPanel());
KeyValues *msg = new KeyValues("PageTabActivated");
msg->SetPtr("panel", (Panel *)_activeTab);
ivgui()->PostMessage(_activePage->GetVPanel(), msg, GetVPanel());
// tell parent
PostActionSignal(new KeyValues("PageChanged"));
// Repaint
InvalidateLayout();
Repaint();
}
//-----------------------------------------------------------------------------
// Purpose: Gets the panel with the specified hotkey, from the current page
//-----------------------------------------------------------------------------
Panel *PropertySheet::HasHotkey(wchar_t key)
{
if(!_activePage)
return NULL;
for(int i = 0; i < _activePage->GetChildCount(); i++)
{
Panel *hot = _activePage->GetChild(i)->HasHotkey(key);
if(hot)
{
return hot;
}
}
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose: catches the opencontextmenu event
//-----------------------------------------------------------------------------
void PropertySheet::OnOpenContextMenu(KeyValues *params)
{
// tell parent
KeyValues *kv = params->MakeCopy();
PostActionSignal(kv);
Panel *page = reinterpret_cast<Panel *>(params->GetPtr("page"));
if(page)
{
PostMessage(page->GetVPanel(), params->MakeCopy());
}
}
//-----------------------------------------------------------------------------
// Purpose: Handle key presses, through tabs.
//-----------------------------------------------------------------------------
void PropertySheet::OnKeyCodeTyped(KeyCode code)
{
bool shift = (input()->IsKeyDown(KEY_LSHIFT) || input()->IsKeyDown(KEY_RSHIFT));
bool ctrl = (input()->IsKeyDown(KEY_LCONTROL) || input()->IsKeyDown(KEY_RCONTROL));
bool alt = (input()->IsKeyDown(KEY_LALT) || input()->IsKeyDown(KEY_RALT));
if(ctrl && shift && alt && code == KEY_B)
{
// enable build mode
EditablePanel *ep = dynamic_cast<EditablePanel *>(GetActivePage());
if(ep)
{
ep->ActivateBuildMode();
return;
}
}
if(IsKBNavigationEnabled())
{
switch(code)
{
// for now left and right arrows just open or close submenus if they are there.
case KEY_RIGHT:
{
ChangeActiveTab(_activeTabIndex + 1);
break;
}
case KEY_LEFT:
{
ChangeActiveTab(_activeTabIndex - 1);
break;
}
default:
BaseClass::OnKeyCodeTyped(code);
break;
}
}
else
{
BaseClass::OnKeyCodeTyped(code);
}
}
//-----------------------------------------------------------------------------
// Purpose: Called by the associated combo box (if in that mode), changes the current panel
//-----------------------------------------------------------------------------
void PropertySheet::OnTextChanged(Panel *panel, const wchar_t *wszText)
{
if(panel == _combo)
{
wchar_t tabText[30];
for(int i = 0; i < m_PageTabs.Count(); i++)
{
tabText[0] = 0;
m_PageTabs[i]->GetText(tabText, 30);
if(!wcsicmp(wszText, tabText))
{
ChangeActiveTab(i);
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void PropertySheet::OnCommand(const char *command)
{
// propogate the close command to our parent
if(!stricmp(command, "Close") && GetVParent())
{
CallParentFunction(new KeyValues("Command", "command", command));
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void PropertySheet::OnApplyButtonEnable()
{
// tell parent
PostActionSignal(new KeyValues("ApplyButtonEnable"));
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void PropertySheet::OnCurrentDefaultButtonSet(Panel *defaultButton)
{
// forward the message up
if(GetVParent())
{
KeyValues *msg = new KeyValues("CurrentDefaultButtonSet");
msg->SetPtr("button", defaultButton);
PostMessage(GetVParent(), msg);
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void PropertySheet::OnDefaultButtonSet(Panel *defaultButton)
{
// forward the message up
if(GetVParent())
{
KeyValues *msg = new KeyValues("DefaultButtonSet");
msg->SetPtr("button", defaultButton);
PostMessage(GetVParent(), msg);
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void PropertySheet::OnFindDefaultButton()
{
if(GetVParent())
{
PostMessage(GetVParent(), new KeyValues("FindDefaultButton"));
}
}
bool PropertySheet::PageHasContextMenu(Panel *page) const
{
int pageNum = FindPage(page);
if(pageNum == m_Pages.InvalidIndex())
return false;
return m_Pages[pageNum].contextMenu;
}
void PropertySheet::OnPanelDropped(CUtlVector<KeyValues *> &msglist)
{
if(msglist.Count() != 1)
{
return;
}
PropertySheet *sheet = IsDroppingSheet(msglist);
if(!sheet)
{
// Defer to active page
if(_activePage && _activePage->IsDropEnabled())
{
return _activePage->OnPanelDropped(msglist);
}
return;
}
KeyValues *data = msglist[0];
Panel *page = reinterpret_cast<Panel *>(data->GetPtr("propertypage"));
char const *title = data->GetString("tabname", "");
if(!page || !sheet)
return;
// Can only create if sheet was part of a ToolWindow derived object
ToolWindow *tw = dynamic_cast<ToolWindow *>(sheet->GetParent());
if(tw)
{
IToolWindowFactory *factory = tw->GetToolWindowFactory();
if(factory)
{
bool showContext = sheet->PageHasContextMenu(page);
sheet->RemovePage(page);
if(sheet->GetNumPages() == 0)
{
tw->MarkForDeletion();
}
AddPage(page, title, NULL, showContext);
}
}
}
bool PropertySheet::IsDroppable(CUtlVector<KeyValues *> &msglist)
{
if(!m_bDraggableTabs)
return false;
if(msglist.Count() != 1)
{
return false;
}
int mx, my;
input()->GetCursorPos(mx, my);
ScreenToLocal(mx, my);
int tabHeight = IsSmallTabs() ? 14 : 28;
if(my > tabHeight)
return false;
PropertySheet *sheet = IsDroppingSheet(msglist);
if(!sheet)
{
return false;
}
if(sheet == this)
return false;
return true;
}
// Mouse is now over a droppable panel
void PropertySheet::OnDroppablePanelPaint(CUtlVector<KeyValues *> &msglist, CUtlVector<Panel *> &dragPanels)
{
// Convert this panel's bounds to screen space
int x, y, w, h;
GetSize(w, h);
int tabHeight = IsSmallTabs() ? 14 : 28;
h = tabHeight + 4;
x = y = 0;
LocalToScreen(x, y);
surface()->DrawSetColor(GetDropFrameColor());
// Draw 2 pixel frame
surface()->DrawOutlinedRect(x, y, x + w, y + h);
surface()->DrawOutlinedRect(x + 1, y + 1, x + w - 1, y + h - 1);
if(!IsDroppable(msglist))
{
return;
}
if(!_showTabs)
{
return;
}
// Draw a fake new tab...
x = 0;
y = 2;
w = 1;
h = tabHeight;
int last = m_PageTabs.Count();
if(last != 0)
{
m_PageTabs[last - 1]->GetBounds(x, y, w, h);
}
// Compute left edge of "fake" tab
x += (w + 1);
// Compute size of new panel
KeyValues *data = msglist[0];
char const *text = data->GetString("tabname", "");
Assert(text);
PageTab *fakeTab = new PageTab(this, "FakeTab", text, NULL, _tabWidth, NULL, false);
fakeTab->SetBounds(x, 4, w, tabHeight - 4);
fakeTab->SetFont(m_tabFont);
SETUP_PANEL(fakeTab);
fakeTab->Repaint();
surface()->SolveTraverse(fakeTab->GetVPanel(), true);
surface()->PaintTraverse(fakeTab->GetVPanel());
delete fakeTab;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : state -
//-----------------------------------------------------------------------------
void PropertySheet::SetKBNavigationEnabled(bool state)
{
m_bKBNavigationEnabled = state;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool PropertySheet::IsKBNavigationEnabled() const
{
return m_bKBNavigationEnabled;
}
| projectogs/OpenGoldSrc | goldsrc/vgui2/controls/PropertySheet.cpp | C++ | gpl-3.0 | 37,352 |
import gtk
class ExtensionFeatures:
SYSTEM_WIDE = 0
class MountManagerExtension:
"""Base class for mount manager extensions.
Mount manager has only one instance and is created on program startup.
Methods defined in this class are called automatically by the mount manager
so you need to implement them.
"""
# features extension supports
features = ()
def __init__(self, parent, window):
self._parent = parent
self._window = window
self._application = self._parent._application
# create user interface
self._container = gtk.VBox(False, 5)
self._controls = gtk.HBox(False, 5)
separator = gtk.HSeparator()
# pack interface
self._container.pack_end(separator, False, False, 0)
self._container.pack_end(self._controls, False, False, 0)
def can_handle(self, uri):
"""Returns boolean denoting if specified URI can be handled by this extension"""
return False
def get_container(self):
"""Return container widget"""
return self._container
def get_information(self):
"""Returns information about extension"""
icon = None
name = None
return icon, name
def unmount(self, uri):
"""Method called by the mount manager for unmounting the selected URI"""
pass
def focus_object(self):
"""Method called by the mount manager for focusing main object"""
pass
@classmethod
def get_features(cls):
"""Returns set of features supported by extension"""
return cls.features
| Azulinho/sunflower-file-manager-with-tmsu-tagging-support | application/plugin_base/mount_manager_extension.py | Python | gpl-3.0 | 1,433 |
<?php // content="text/plain; charset=utf-8"
require_once ('jpgraph/jpgraph.php');
require_once ('jpgraph/jpgraph_gantt.php');
$graph = new GanttGraph();
$graph->SetBox();
$graph->SetShadow();
// Add title and subtitle
$graph->title->Set("Example of captions");
$graph->title->SetFont(FF_ARIAL,FS_BOLD,12);
$graph->subtitle->Set("(ganttex16.php)");
// Show day, week and month scale
$graph->ShowHeaders(GANTT_HDAY | GANTT_HWEEK | GANTT_HMONTH);
// Set table title
$graph->scale->tableTitle->Set("(Rev: 1.22)");
$graph->scale->tableTitle->SetFont(FF_FONT1,FS_BOLD);
$graph->scale->SetTableTitleBackground("silver");
$graph->scale->tableTitle->Show();
// Use the short name of the month together with a 2 digit year
// on the month scale
$graph->scale->month->SetStyle(MONTHSTYLE_SHORTNAMEYEAR2);
$graph->scale->month->SetFontColor("white");
$graph->scale->month->SetBackgroundColor("blue");
// 0 % vertical label margin
$graph->SetLabelVMarginFactor(1);
// Format the bar for the first activity
// ($row,$title,$startdate,$enddate)
$activity = new GanttBar(0,"Project","2001-12-21","2002-01-07","[50%]");
// Yellow diagonal line pattern on a red background
$activity->SetPattern(BAND_RDIAG,"yellow");
$activity->SetFillColor("red");
// Set absolute height
$activity->SetHeight(10);
// Specify progress to 60%
$activity->progress->Set(0.6);
$activity->progress->SetPattern(BAND_HVCROSS,"blue");
// Format the bar for the second activity
// ($row,$title,$startdate,$enddate)
$activity2 = new GanttBar(1,"Project","2001-12-21","2002-01-02","[30%]");
// Yellow diagonal line pattern on a red background
$activity2->SetPattern(BAND_RDIAG,"yellow");
$activity2->SetFillColor("red");
// Set absolute height
$activity2->SetHeight(10);
// Specify progress to 30%
$activity2->progress->Set(0.3);
$activity2->progress->SetPattern(BAND_HVCROSS,"blue");
// Finally add the bar to the graph
$graph->Add($activity);
$graph->Add($activity2);
// Add a vertical line
$vline = new GanttVLine("2001-12-24","Phase 1");
$vline->SetDayOffset(0.5);
//$graph->Add($vline);
// ... and display it
$graph->Stroke();
?>
| boabo/pxp | lib/jpgraph/src/Examples/ganttex16.php | PHP | gpl-3.0 | 2,180 |
/*! @license Firebase v4.3.1
Build: rev-b4fe95f
Terms: https://firebase.google.com/terms/ */
"use strict";
//# sourceMappingURL=requestmaker.js.map
| chidelmun/Zikki | node_modules/firebase/storage/implementation/requestmaker.js | JavaScript | gpl-3.0 | 149 |
package cn.nukkit.math;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class Vector3 implements Cloneable {
public double x;
public double y;
public double z;
public Vector3() {
this(0, 0, 0);
}
public Vector3(double x) {
this(x, 0, 0);
}
public Vector3(double x, double y) {
this(x, y, 0);
}
public Vector3(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public double getX() {
return this.x;
}
public double getY() {
return this.y;
}
public double getZ() {
return this.z;
}
public int getFloorX() {
return (int) Math.floor(this.x);
}
public int getFloorY() {
return (int) Math.floor(this.y);
}
public int getFloorZ() {
return (int) Math.floor(this.z);
}
public double getRight() {
return this.x;
}
public double getUp() {
return this.y;
}
public double getForward() {
return this.z;
}
public double getSouth() {
return this.x;
}
public double getWest() {
return this.z;
}
public Vector3 add(double x) {
return this.add(x, 0, 0);
}
public Vector3 add(double x, double y) {
return this.add(x, y, 0);
}
public Vector3 add(double x, double y, double z) {
return new Vector3(this.x + x, this.y + y, this.z + z);
}
public Vector3 add(Vector3 x) {
return new Vector3(this.x + x.getX(), this.y + x.getY(), this.z + x.getZ());
}
public Vector3 subtract() {
return this.subtract(0, 0, 0);
}
public Vector3 subtract(double x) {
return this.subtract(x, 0, 0);
}
public Vector3 subtract(double x, double y) {
return this.subtract(x, y, 0);
}
public Vector3 subtract(double x, double y, double z) {
return this.add(-x, -y, -z);
}
public Vector3 subtract(Vector3 x) {
return this.add(-x.getX(), -x.getY(), -x.getZ());
}
public Vector3 multiply(double number) {
return new Vector3(this.x * number, this.y * number, this.z * number);
}
public Vector3 divide(double number) {
return new Vector3(this.x / number, this.y / number, this.z / number);
}
public Vector3 ceil() {
return new Vector3((int) Math.ceil(this.x), (int) Math.ceil(this.y), (int) Math.ceil(this.z));
}
public Vector3 floor() {
return new Vector3(this.getFloorX(), this.getFloorY(), this.getFloorZ());
}
public Vector3 round() {
return new Vector3(Math.round(this.x), Math.round(this.y), Math.round(this.z));
}
public Vector3 abs() {
return new Vector3((int) Math.abs(this.x), (int) Math.abs(this.y), (int) Math.abs(this.z));
}
public Vector3 getSide(BlockFace face) {
return this.getSide(face, 1);
}
public Vector3 getSide(BlockFace face, int step) {
return new Vector3(this.getX() + face.getXOffset() * step, this.getY() + face.getYOffset() * step, this.getZ() + face.getZOffset() * step);
}
public Vector3 up() {
return up(1);
}
public Vector3 up(int step) {
return getSide(BlockFace.UP, step);
}
public Vector3 down() {
return down(1);
}
public Vector3 down(int step) {
return getSide(BlockFace.DOWN, step);
}
public Vector3 north() {
return north(1);
}
public Vector3 north(int step) {
return getSide(BlockFace.NORTH, step);
}
public Vector3 south() {
return south(1);
}
public Vector3 south(int step) {
return getSide(BlockFace.SOUTH, step);
}
public Vector3 east() {
return east(1);
}
public Vector3 east(int step) {
return getSide(BlockFace.EAST, step);
}
public Vector3 west() {
return west(1);
}
public Vector3 west(int step) {
return getSide(BlockFace.WEST, step);
}
public double distance(Vector3 pos) {
return Math.sqrt(this.distanceSquared(pos));
}
public double distanceSquared(Vector3 pos) {
return Math.pow(this.x - pos.x, 2) + Math.pow(this.y - pos.y, 2) + Math.pow(this.z - pos.z, 2);
}
public double maxPlainDistance() {
return this.maxPlainDistance(0, 0);
}
public double maxPlainDistance(double x) {
return this.maxPlainDistance(x, 0);
}
public double maxPlainDistance(double x, double z) {
return Math.max(Math.abs(this.x - x), Math.abs(this.z - z));
}
public double maxPlainDistance(Vector2 vector) {
return this.maxPlainDistance(vector.x, vector.y);
}
public double maxPlainDistance(Vector3 x) {
return this.maxPlainDistance(x.x, x.z);
}
public double length() {
return Math.sqrt(this.lengthSquared());
}
public double lengthSquared() {
return this.x * this.x + this.y * this.y + this.z * this.z;
}
public Vector3 normalize() {
double len = this.lengthSquared();
if (len > 0) {
return this.divide(Math.sqrt(len));
}
return new Vector3(0, 0, 0);
}
public double dot(Vector3 v) {
return this.x * v.x + this.y * v.y + this.z * v.z;
}
public Vector3 cross(Vector3 v) {
return new Vector3(
this.y * v.z - this.z * v.y,
this.z * v.x - this.x * v.z,
this.x * v.y - this.y * v.x
);
}
/**
* Returns a new vector with x value equal to the second parameter, along the line between this vector and the
* passed in vector, or null if not possible.
*/
public Vector3 getIntermediateWithXValue(Vector3 v, double x) {
double xDiff = v.x - this.x;
double yDiff = v.y - this.y;
double zDiff = v.z - this.z;
if (xDiff * xDiff < 0.0000001) {
return null;
}
double f = (x - this.x) / xDiff;
if (f < 0 || f > 1) {
return null;
} else {
return new Vector3(this.x + xDiff * f, this.y + yDiff * f, this.z + zDiff * f);
}
}
/**
* Returns a new vector with y value equal to the second parameter, along the line between this vector and the
* passed in vector, or null if not possible.
*/
public Vector3 getIntermediateWithYValue(Vector3 v, double y) {
double xDiff = v.x - this.x;
double yDiff = v.y - this.y;
double zDiff = v.z - this.z;
if (yDiff * yDiff < 0.0000001) {
return null;
}
double f = (y - this.y) / yDiff;
if (f < 0 || f > 1) {
return null;
} else {
return new Vector3(this.x + xDiff * f, this.y + yDiff * f, this.z + zDiff * f);
}
}
/**
* Returns a new vector with z value equal to the second parameter, along the line between this vector and the
* passed in vector, or null if not possible.
*/
public Vector3 getIntermediateWithZValue(Vector3 v, double z) {
double xDiff = v.x - this.x;
double yDiff = v.y - this.y;
double zDiff = v.z - this.z;
if (zDiff * zDiff < 0.0000001) {
return null;
}
double f = (z - this.z) / zDiff;
if (f < 0 || f > 1) {
return null;
} else {
return new Vector3(this.x + xDiff * f, this.y + yDiff * f, this.z + zDiff * f);
}
}
public Vector3 setComponents(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
return this;
}
@Override
public String toString() {
return "Vector3(x=" + this.x + ",y=" + this.y + ",z=" + this.z + ")";
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Vector3)) {
return false;
}
Vector3 other = (Vector3) obj;
return this.x == other.x && this.y == other.y && this.z == other.z;
}
@Override
public int hashCode() {
int hash = 7;
hash = 79 * hash + (int) (Double.doubleToLongBits(this.x) ^ Double.doubleToLongBits(this.x) >>> 32);
hash = 79 * hash + (int) (Double.doubleToLongBits(this.y) ^ Double.doubleToLongBits(this.y) >>> 32);
hash = 79 * hash + (int) (Double.doubleToLongBits(this.z) ^ Double.doubleToLongBits(this.z) >>> 32);
return hash;
}
public int rawHashCode() {
return super.hashCode();
}
@Override
public Vector3 clone() {
try {
return (Vector3) super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
public Vector3f asVector3f() {
return new Vector3f((float) this.x, (float) this.y, (float) this.z);
}
public BlockVector3 asBlockVector3() {
return new BlockVector3(this.getFloorX(), this.getFloorY(), this.getFloorZ());
}
} | JupiterDevelopmentTeam/JupiterDevelopmentTeam | src/main/java/cn/nukkit/math/Vector3.java | Java | gpl-3.0 | 9,009 |
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2020 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
End User License Agreement: www.juce.com/juce-6-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
class FileListTreeItem : public TreeViewItem,
private TimeSliceClient,
private AsyncUpdater,
private ChangeListener
{
public:
FileListTreeItem (FileTreeComponent& treeComp,
DirectoryContentsList* parentContents,
int indexInContents,
const File& f,
TimeSliceThread& t)
: file (f),
owner (treeComp),
parentContentsList (parentContents),
indexInContentsList (indexInContents),
subContentsList (nullptr, false),
thread (t)
{
DirectoryContentsList::FileInfo fileInfo;
if (parentContents != nullptr
&& parentContents->getFileInfo (indexInContents, fileInfo))
{
fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
isDirectory = fileInfo.isDirectory;
}
else
{
isDirectory = true;
}
}
~FileListTreeItem() override
{
thread.removeTimeSliceClient (this);
clearSubItems();
removeSubContentsList();
}
//==============================================================================
bool mightContainSubItems() override { return isDirectory; }
String getUniqueName() const override { return file.getFullPathName(); }
int getItemHeight() const override { return owner.getItemHeight(); }
var getDragSourceDescription() override { return owner.getDragAndDropDescription(); }
void itemOpennessChanged (bool isNowOpen) override
{
if (isNowOpen)
{
clearSubItems();
isDirectory = file.isDirectory();
if (isDirectory)
{
if (subContentsList == nullptr)
{
jassert (parentContentsList != nullptr);
auto l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
l->setDirectory (file,
parentContentsList->isFindingDirectories(),
parentContentsList->isFindingFiles());
setSubContentsList (l, true);
}
changeListenerCallback (nullptr);
}
}
}
void removeSubContentsList()
{
if (subContentsList != nullptr)
{
subContentsList->removeChangeListener (this);
subContentsList.reset();
}
}
void setSubContentsList (DirectoryContentsList* newList, const bool canDeleteList)
{
removeSubContentsList();
subContentsList = OptionalScopedPointer<DirectoryContentsList> (newList, canDeleteList);
newList->addChangeListener (this);
}
bool selectFile (const File& target)
{
if (file == target)
{
setSelected (true, true);
return true;
}
if (target.isAChildOf (file))
{
setOpen (true);
for (int maxRetries = 500; --maxRetries > 0;)
{
for (int i = 0; i < getNumSubItems(); ++i)
if (auto* f = dynamic_cast<FileListTreeItem*> (getSubItem (i)))
if (f->selectFile (target))
return true;
// if we've just opened and the contents are still loading, wait for it..
if (subContentsList != nullptr && subContentsList->isStillLoading())
{
Thread::sleep (10);
rebuildItemsFromContentList();
}
else
{
break;
}
}
}
return false;
}
void changeListenerCallback (ChangeBroadcaster*) override
{
rebuildItemsFromContentList();
}
void rebuildItemsFromContentList()
{
clearSubItems();
if (isOpen() && subContentsList != nullptr)
{
for (int i = 0; i < subContentsList->getNumFiles(); ++i)
addSubItem (new FileListTreeItem (owner, subContentsList, i,
subContentsList->getFile(i), thread));
}
}
void paintItem (Graphics& g, int width, int height) override
{
ScopedLock lock (iconUpdate);
if (file != File())
{
updateIcon (true);
if (icon.isNull())
thread.addTimeSliceClient (this);
}
owner.getLookAndFeel().drawFileBrowserRow (g, width, height,
file, file.getFileName(),
&icon, fileSize, modTime,
isDirectory, isSelected(),
indexInContentsList, owner);
}
void itemClicked (const MouseEvent& e) override
{
owner.sendMouseClickMessage (file, e);
}
void itemDoubleClicked (const MouseEvent& e) override
{
TreeViewItem::itemDoubleClicked (e);
owner.sendDoubleClickMessage (file);
}
void itemSelectionChanged (bool) override
{
owner.sendSelectionChangeMessage();
}
int useTimeSlice() override
{
updateIcon (false);
return -1;
}
void handleAsyncUpdate() override
{
owner.repaint();
}
const File file;
private:
FileTreeComponent& owner;
DirectoryContentsList* parentContentsList;
int indexInContentsList;
OptionalScopedPointer<DirectoryContentsList> subContentsList;
bool isDirectory;
TimeSliceThread& thread;
CriticalSection iconUpdate;
Image icon;
String fileSize, modTime;
void updateIcon (const bool onlyUpdateIfCached)
{
if (icon.isNull())
{
auto hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
auto im = ImageCache::getFromHashCode (hashCode);
if (im.isNull() && ! onlyUpdateIfCached)
{
im = juce_createIconForFile (file);
if (im.isValid())
ImageCache::addImageToCache (im, hashCode);
}
if (im.isValid())
{
{
ScopedLock lock (iconUpdate);
icon = im;
}
triggerAsyncUpdate();
}
}
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListTreeItem)
};
//==============================================================================
FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
: DirectoryContentsDisplayComponent (listToShow),
itemHeight (22)
{
setRootItemVisible (false);
refresh();
}
FileTreeComponent::~FileTreeComponent()
{
deleteRootItem();
}
void FileTreeComponent::refresh()
{
deleteRootItem();
auto root = new FileListTreeItem (*this, nullptr, 0, directoryContentsList.getDirectory(),
directoryContentsList.getTimeSliceThread());
root->setSubContentsList (&directoryContentsList, false);
setRootItem (root);
}
//==============================================================================
File FileTreeComponent::getSelectedFile (const int index) const
{
if (auto* item = dynamic_cast<const FileListTreeItem*> (getSelectedItem (index)))
return item->file;
return {};
}
void FileTreeComponent::deselectAllFiles()
{
clearSelectedItems();
}
void FileTreeComponent::scrollToTop()
{
getViewport()->getVerticalScrollBar().setCurrentRangeStart (0);
}
void FileTreeComponent::setDragAndDropDescription (const String& description)
{
dragAndDropDescription = description;
}
void FileTreeComponent::setSelectedFile (const File& target)
{
if (auto* t = dynamic_cast<FileListTreeItem*> (getRootItem()))
if (! t->selectFile (target))
clearSelectedItems();
}
void FileTreeComponent::setItemHeight (int newHeight)
{
if (itemHeight != newHeight)
{
itemHeight = newHeight;
if (auto* root = getRootItem())
root->treeHasChanged();
}
}
} // namespace juce
| danielrothmann/Roth-AIR | JuceLibraryCode/modules/juce_gui_basics/filebrowser/juce_FileTreeComponent.cpp | C++ | gpl-3.0 | 9,810 |
<?php
/**
*
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Newsletter\Controller\Adminhtml\Template;
class NewAction extends \Magento\Newsletter\Controller\Adminhtml\Template
{
/**
* Create new Newsletter Template
*
* @return void
*/
public function execute()
{
$this->_forward('edit');
}
}
| rajmahesh/magento2-master | vendor/magento/module-newsletter/Controller/Adminhtml/Template/NewAction.php | PHP | gpl-3.0 | 403 |
/*****************************************************************************
* Copyright (c) 2014-2019 OpenRCT2 developers
*
* For a complete list of all authors, please refer to contributors.md
* Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2
*
* OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/
#include "TileElement.h"
#include "../core/Guard.hpp"
#include "../interface/Window.h"
#include "../localisation/Localisation.h"
#include "../ride/Track.h"
#include "Banner.h"
#include "LargeScenery.h"
#include "Scenery.h"
uint8_t TileElementBase::GetType() const
{
return this->type & TILE_ELEMENT_TYPE_MASK;
}
void TileElementBase::SetType(uint8_t newType)
{
this->type &= ~TILE_ELEMENT_TYPE_MASK;
this->type |= (newType & TILE_ELEMENT_TYPE_MASK);
}
Direction TileElementBase::GetDirection() const
{
return this->type & TILE_ELEMENT_DIRECTION_MASK;
}
void TileElementBase::SetDirection(Direction direction)
{
this->type &= ~TILE_ELEMENT_DIRECTION_MASK;
this->type |= (direction & TILE_ELEMENT_DIRECTION_MASK);
}
Direction TileElementBase::GetDirectionWithOffset(uint8_t offset) const
{
return ((this->type & TILE_ELEMENT_DIRECTION_MASK) + offset) & TILE_ELEMENT_DIRECTION_MASK;
}
bool TileElementBase::IsLastForTile() const
{
return (this->flags & TILE_ELEMENT_FLAG_LAST_TILE) != 0;
}
void TileElementBase::SetLastForTile(bool on)
{
if (on)
flags |= TILE_ELEMENT_FLAG_LAST_TILE;
else
flags &= ~TILE_ELEMENT_FLAG_LAST_TILE;
}
bool TileElementBase::IsGhost() const
{
return (this->flags & TILE_ELEMENT_FLAG_GHOST) != 0;
}
void TileElementBase::SetGhost(bool isGhost)
{
if (isGhost)
{
this->flags |= TILE_ELEMENT_FLAG_GHOST;
}
else
{
this->flags &= ~TILE_ELEMENT_FLAG_GHOST;
}
}
bool tile_element_is_underground(TileElement* tileElement)
{
do
{
tileElement++;
if ((tileElement - 1)->IsLastForTile())
return false;
} while (tileElement->GetType() != TILE_ELEMENT_TYPE_SURFACE);
return true;
}
BannerIndex tile_element_get_banner_index(TileElement* tileElement)
{
rct_scenery_entry* sceneryEntry;
switch (tileElement->GetType())
{
case TILE_ELEMENT_TYPE_LARGE_SCENERY:
sceneryEntry = tileElement->AsLargeScenery()->GetEntry();
if (sceneryEntry->large_scenery.scrolling_mode == SCROLLING_MODE_NONE)
return BANNER_INDEX_NULL;
return tileElement->AsLargeScenery()->GetBannerIndex();
case TILE_ELEMENT_TYPE_WALL:
sceneryEntry = tileElement->AsWall()->GetEntry();
if (sceneryEntry == nullptr || sceneryEntry->wall.scrolling_mode == SCROLLING_MODE_NONE)
return BANNER_INDEX_NULL;
return tileElement->AsWall()->GetBannerIndex();
case TILE_ELEMENT_TYPE_BANNER:
return tileElement->AsBanner()->GetIndex();
default:
return BANNER_INDEX_NULL;
}
}
void tile_element_set_banner_index(TileElement* tileElement, BannerIndex bannerIndex)
{
switch (tileElement->GetType())
{
case TILE_ELEMENT_TYPE_WALL:
tileElement->AsWall()->SetBannerIndex(bannerIndex);
break;
case TILE_ELEMENT_TYPE_LARGE_SCENERY:
tileElement->AsLargeScenery()->SetBannerIndex(bannerIndex);
break;
case TILE_ELEMENT_TYPE_BANNER:
tileElement->AsBanner()->SetIndex(bannerIndex);
break;
default:
log_error("Tried to set banner index on unsuitable tile element!");
Guard::Assert(false);
}
}
void tile_element_remove_banner_entry(TileElement* tileElement)
{
auto bannerIndex = tile_element_get_banner_index(tileElement);
auto banner = GetBanner(bannerIndex);
if (banner != nullptr)
{
window_close_by_number(WC_BANNER, bannerIndex);
*banner = {};
}
}
uint8_t tile_element_get_ride_index(const TileElement* tileElement)
{
switch (tileElement->GetType())
{
case TILE_ELEMENT_TYPE_TRACK:
return tileElement->AsTrack()->GetRideIndex();
case TILE_ELEMENT_TYPE_ENTRANCE:
return tileElement->AsEntrance()->GetRideIndex();
case TILE_ELEMENT_TYPE_PATH:
return tileElement->AsPath()->GetRideIndex();
default:
return RIDE_ID_NULL;
}
}
void TileElement::ClearAs(uint8_t newType)
{
type = newType;
flags = 0;
base_height = 2;
clearance_height = 2;
std::fill_n(pad_04, sizeof(pad_04), 0x00);
std::fill_n(pad_08, sizeof(pad_08), 0x00);
}
void TileElementBase::Remove()
{
tile_element_remove((TileElement*)this);
}
// Rotate both of the values amount
const QuarterTile QuarterTile::Rotate(uint8_t amount) const
{
switch (amount)
{
case 0:
return QuarterTile{ *this };
break;
case 1:
{
auto rotVal1 = _val << 1;
auto rotVal2 = rotVal1 >> 4;
// Clear the bit from the tileQuarter
rotVal1 &= 0b11101110;
// Clear the bit from the zQuarter
rotVal2 &= 0b00010001;
return QuarterTile{ static_cast<uint8_t>(rotVal1 | rotVal2) };
}
case 2:
{
auto rotVal1 = _val << 2;
auto rotVal2 = rotVal1 >> 4;
// Clear the bit from the tileQuarter
rotVal1 &= 0b11001100;
// Clear the bit from the zQuarter
rotVal2 &= 0b00110011;
return QuarterTile{ static_cast<uint8_t>(rotVal1 | rotVal2) };
}
case 3:
{
auto rotVal1 = _val << 3;
auto rotVal2 = rotVal1 >> 4;
// Clear the bit from the tileQuarter
rotVal1 &= 0b10001000;
// Clear the bit from the zQuarter
rotVal2 &= 0b01110111;
return QuarterTile{ static_cast<uint8_t>(rotVal1 | rotVal2) };
}
default:
log_error("Tried to rotate QuarterTile invalid amount.");
return QuarterTile{ 0 };
}
}
uint8_t TileElementBase::GetOccupiedQuadrants() const
{
return flags & TILE_ELEMENT_OCCUPIED_QUADRANTS_MASK;
}
void TileElementBase::SetOccupiedQuadrants(uint8_t quadrants)
{
flags &= ~TILE_ELEMENT_OCCUPIED_QUADRANTS_MASK;
flags |= (quadrants & TILE_ELEMENT_OCCUPIED_QUADRANTS_MASK);
}
int32_t TileElementBase::GetBaseZ() const
{
return base_height * 8;
}
void TileElementBase::SetBaseZ(int32_t newZ)
{
base_height = (newZ / 8);
}
int32_t TileElementBase::GetClearanceZ() const
{
return clearance_height * 8;
}
void TileElementBase::SetClearanceZ(int32_t newZ)
{
clearance_height = (newZ / 8);
}
| IntelOrca/OpenRCT2 | src/openrct2/world/TileElement.cpp | C++ | gpl-3.0 | 6,843 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Library functions for WIRIS plugin for Atto.
*
* @package tinymce
* @subpackage tiny_mce_wiris
* @copyright Maths for More S.L. <info@wiris.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
class tinymce_tiny_mce_wiris extends editor_tinymce_plugin {
protected $buttons = array('tiny_mce_wiris_formulaEditor', 'tiny_mce_wiris_CAS');
protected function update_init_params(array &$params, context $context,
array $options = null) {
global $PAGE, $CFG;
$PAGE->requires->js('/lib/editor/tinymce/plugins/tiny_mce_wiris/baseURL.js', false);
// Add button after emoticon button in advancedbuttons3.
$added = $this->add_button_after($params, 3, 'tiny_mce_wiris_formulaEditor', '', false);
$added = $this->add_button_after($params, 3, 'tiny_mce_wiris_formulaEditorChemistry', '', false);
$added = $this->add_button_after($params, 3, 'tiny_mce_wiris_CAS', '', false);
// Add JS file, which uses default name.
$this->add_js_plugin($params);
$filterwiris = $CFG->dirroot . '/filter/wiris/filter.php';
if (!file_exists($filterwiris)) {
$PAGE->requires->js('/lib/editor/tinymce/plugins/tiny_mce_wiris/js/message.js', false);
}
}
}
| nitro2010/moodle | lib/editor/tinymce/plugins/tiny_mce_wiris/lib.php | PHP | gpl-3.0 | 2,050 |
var searchData=
[
['save_5fcomments',['save_comments',['../useful__functions_8php.html#af56aec073a82606e9a7dac498de28d96',1,'useful_functions.php']]],
['save_5fexperiment_5flist',['save_experiment_list',['../choose__experiments_8php.html#a5d24f39ae6c336d7828523216bce6fae',1,'choose_experiments.php']]],
['save_5fsessions',['save_sessions',['../useful__functions_8php.html#a38a4632f417ceaa2f1c09c3ed0494d5e',1,'useful_functions.php']]],
['save_5fsignup_5fto_5fdb',['save_signup_to_db',['../useful__functions_8php.html#a0dca9d754b1a0d7b5401c446878844c5',1,'useful_functions.php']]],
['save_5fuser_5fexpt_5fchoices',['save_user_expt_choices',['../useful__functions_8php.html#a461a04526110df604708381a9eac7da8',1,'useful_functions.php']]],
['signup_5fexists',['signup_exists',['../useful__functions_8php.html#a7cf6d3ac90a6fca8c3f595e68b6e62cc',1,'useful_functions.php']]]
];
| mnd22/chaos-signup | html/search/functions_7.js | JavaScript | gpl-3.0 | 884 |
<?php
/**
*
* ThinkUp/webapp/_lib/model/class.UserMySQLDAO.php
*
* Copyright (c) 2009-2013 Gina Trapani
*
* LICENSE:
*
* This file is part of ThinkUp (http://thinkup.com).
*
* ThinkUp 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.
*
* ThinkUp 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 ThinkUp. If not, see
* <http://www.gnu.org/licenses/>.
*
*
* User Data Access Object MySQL Implementation
*
* @license http://www.gnu.org/licenses/gpl.html
* @copyright 2009-2013 Gina Trapani
* @author Gina Trapani <ginatrapani[at]gmail[dot]com>
*
*/
class UserMySQLDAO extends PDODAO implements UserDAO {
/**
* Get the SQL to generate average_tweets_per_day number
* @TODO rename "tweets" "posts"
* @return str SQL calcuation
*/
private function getAverageTweetCount() {
return "round(post_count/(datediff(curdate(), joined)), 2) as avg_tweets_per_day";
}
public function isUserInDB($user_id, $network) {
$q = "SELECT user_id ";
$q .= "FROM #prefix#users ";
$q .= "WHERE user_id = :user_id AND network = :network;";
$vars = array(
':user_id'=>(string)$user_id,
':network'=>$network
);
if ($this->profiler_enabled) Profiler::setDAOMethod(__METHOD__);
$ps = $this->execute($q, $vars);
return $this->getDataIsReturned($ps);
}
public function isUserInDBByName($username, $network) {
$q = "SELECT user_id ";
$q .= "FROM #prefix#users ";
$q .= "WHERE user_name = :username AND network = :network";
$vars = array(
':username'=>$username,
':network'=>$network
);
if ($this->profiler_enabled) Profiler::setDAOMethod(__METHOD__);
$ps = $this->execute($q, $vars);
return $this->getDataIsReturned($ps);
}
public function updateUsers($users_to_update) {
$count = 0;
$status_message = "";
if (sizeof($users_to_update) > 0) {
$status_message .= count($users_to_update)." users queued for insert or update; ";
foreach ($users_to_update as $user) {
$count += $this->updateUser($user);
}
$status_message .= "$count users affected.";
}
$this->logger->logInfo($status_message, __METHOD__.','.__LINE__);
$status_message = "";
return $count;
}
public function updateUser($user) {
if (!isset($user->username)) {
return 0;
}
$status_message = "";
$has_friend_count = $user->friend_count != '' ? true : false;
$has_favorites_count = $user->favorites_count != '' ? true : false;
$has_last_post = $user->last_post != '' ? true : false;
$has_last_post_id = $user->last_post_id != '' ? true : false;
$network = $user->network != '' ? $user->network : 'twitter';
$user->follower_count = $user->follower_count != '' ? $user->follower_count : 0;
$user->post_count = $user->post_count != '' ? $user->post_count : 0;
$vars = array(
':user_id'=>(string)$user->user_id,
':username'=>$user->username,
':full_name'=>$user->full_name,
':avatar'=>$user->avatar,
':location'=>$user->location,
':description'=>$user->description,
':url'=>$user->url,
':is_protected'=>$this->convertBoolToDB($user->is_protected),
':follower_count'=>$user->follower_count,
':post_count'=>$user->post_count,
':found_in'=>$user->found_in,
':joined'=>$user->joined,
':network'=>$user->network
);
$is_user_in_storage = false;
$is_user_in_storage = $this->isUserInDB($user->user_id, $user->network);
if (!$is_user_in_storage) {
$q = "INSERT INTO #prefix#users (user_id, user_name, full_name, avatar, location, description, url, ";
$q .= "is_protected, follower_count, post_count, ".($has_friend_count ? "friend_count, " : "")." ".
($has_favorites_count ? "favorites_count, " : "")." ".
($has_last_post ? "last_post, " : "")." found_in, joined, network ".
($has_last_post_id ? ", last_post_id" : "").") ";
$q .= "VALUES ( :user_id, :username, :full_name, :avatar, :location, :description, :url, :is_protected, ";
$q .= ":follower_count, :post_count, ".($has_friend_count ? ":friend_count, " : "")." ".
($has_favorites_count ? ":favorites_count, " : "")." ".
($has_last_post ? ":last_post, " : "")." :found_in, :joined, :network ".
($has_last_post_id ? ", :last_post_id " : "")." )";
} else {
$q = "UPDATE #prefix#users SET full_name = :full_name, avatar = :avatar, location = :location, ";
$q .= "user_name = :username, description = :description, url = :url, is_protected = :is_protected, ";
$q .= "follower_count = :follower_count, post_count = :post_count, ".
($has_friend_count ? "friend_count= :friend_count, " : "")." ".
($has_favorites_count ? "favorites_count= :favorites_count, " : "")." ".
($has_last_post ? "last_post= :last_post, " : "")." last_updated = NOW(), found_in = :found_in, ";
$q .= "joined = :joined, network = :network ".
($has_last_post_id ? ", last_post_id = :last_post_id" : "")." ";
$q .= "WHERE user_id = :user_id AND network = :network;";
}
if ($has_friend_count) {
$vars[':friend_count'] = $user->friend_count;
}
if ($has_favorites_count) {
$vars[':favorites_count'] = $user->favorites_count;
}
if ($has_last_post) {
$vars[':last_post'] = $user->last_post;
}
if ($has_last_post_id) {
$vars[':last_post_id'] = $user->last_post_id;
}
if ($this->profiler_enabled) Profiler::setDAOMethod(__METHOD__);
$ps = $this->execute($q, $vars);
$results = $this->getUpdateCount($ps);
return $results;
}
public function getDetails($user_id, $network) {
$q = "SELECT * , ".$this->getAverageTweetCount()." ";
$q .= "FROM #prefix#users u ";
$q .= "WHERE u.user_id = :user_id AND u.network = :network;";
$vars = array(
':user_id'=>(string)$user_id,
':network'=>$network
);
if ($this->profiler_enabled) Profiler::setDAOMethod(__METHOD__);
$ps = $this->execute($q, $vars);
return $this->getDataRowAsObject($ps, "User");
}
public function getUserByName($user_name, $network) {
$q = "SELECT * , ".$this->getAverageTweetCount()." ";
$q .= "FROM #prefix#users u ";
$q .= "WHERE u.user_name = :user_name AND u.network = :network";
$vars = array(
':user_name'=>$user_name,
':network'=>$network
);
if ($this->profiler_enabled) Profiler::setDAOMethod(__METHOD__);
$ps = $this->execute($q, $vars);
return $this->getDataRowAsObject($ps, "User");
}
}
| agilee/ThinkUp | webapp/_lib/dao/class.UserMySQLDAO.php | PHP | gpl-3.0 | 7,596 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package VerilogCompiler.SyntacticTree;
import VerilogCompiler.SemanticCheck.ErrorHandler;
import VerilogCompiler.SemanticCheck.ExpressionType;
import VerilogCompiler.SyntacticTree.Expressions.Expression;
/**
*
* @author Néstor A. Bermúdez < nestor.bermudezs@gmail.com >
*/
public class Range extends VNode {
Expression minValue;
Expression maxValue;
public Range(Expression minValue, Expression maxValue, int line, int column) {
super(line, column);
this.minValue = minValue;
this.maxValue = maxValue;
}
public Expression getMinValue() {
return minValue;
}
public void setMinValue(Expression minValue) {
this.minValue = minValue;
}
public Expression getMaxValue() {
return maxValue;
}
public void setMaxValue(Expression maxValue) {
this.maxValue = maxValue;
}
@Override
public String toString() {
return String.format("[%s:%s]", this.minValue, this.maxValue);
}
@Override
public ExpressionType validateSemantics() {
ExpressionType minReturnType = minValue.validateSemantics();
ExpressionType maxReturnType = maxValue.validateSemantics();
if (minReturnType != ExpressionType.INTEGER || maxReturnType != ExpressionType.INTEGER)
{
ErrorHandler.getInstance().handleError(line, column, "range min and max value must be integer");
}
return null;
}
@Override
public VNode getCopy() {
return new Range((Expression)minValue.getCopy(), (Expression)maxValue.getCopy(), line, column);
}
}
| CastellarFrank/ArchSim | src/VerilogCompiler/SyntacticTree/Range.java | Java | gpl-3.0 | 1,723 |
import random
from google.appengine.api import memcache
from google.appengine.ext import ndb
SHARD_KEY_TEMPLATE = 'shard-{}-{:d}'
class GeneralCounterShardConfig(ndb.Model):
num_shards = ndb.IntegerProperty(default=20)
@classmethod
def all_keys(cls, name):
config = cls.get_or_insert(name)
shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)]
return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings]
class GeneralCounterShard(ndb.Model):
count = ndb.IntegerProperty(default=0)
def get_count(name):
total = memcache.get(name)
if total is None:
total = 0
parent_key = ndb.Key('ShardCounterParent', name)
shard_query = GeneralCounterShard.query(ancestor=parent_key)
shard_counters = shard_query.fetch(limit=None)
for counter in shard_counters:
if counter is not None:
total += counter.count
memcache.add(name, total, 7200) # 2 hours to expire
return total
def increment(name):
config = GeneralCounterShardConfig.get_or_insert(name)
return _increment(name, config.num_shards)
@ndb.transactional
def _increment(name, num_shards):
index = random.randint(0, num_shards - 1)
shard_key_string = SHARD_KEY_TEMPLATE.format(name, index)
parent_key = ndb.Key('ShardCounterParent', name)
counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key)
if counter is None:
counter = GeneralCounterShard(parent = parent_key, id=shard_key_string)
counter.count += 1
counter.put()
rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache
if rval is None:
return get_count(name)
return rval
@ndb.transactional
def increase_shards(name, num_shards):
config = GeneralCounterShardConfig.get_or_insert(name)
if config.num_shards < num_shards:
config.num_shards = num_shards
config.put()
| VirtuosoChris/appengine | experimental/shardcounter_sync.py | Python | gpl-3.0 | 2,052 |
'use strict';
var async = require('async');
var nconf = require('nconf');
var querystring = require('querystring');
var meta = require('../meta');
var pagination = require('../pagination');
var user = require('../user');
var topics = require('../topics');
var plugins = require('../plugins');
var helpers = require('./helpers');
var unreadController = module.exports;
unreadController.get = function (req, res, next) {
var page = parseInt(req.query.page, 10) || 1;
var results;
var cid = req.query.cid;
var filter = req.query.filter || '';
var settings;
async.waterfall([
function (next) {
plugins.fireHook('filter:unread.getValidFilters', { filters: Object.assign({}, helpers.validFilters) }, next);
},
function (data, _next) {
if (!data.filters[filter]) {
return next();
}
async.parallel({
watchedCategories: function (next) {
helpers.getWatchedCategories(req.uid, cid, next);
},
settings: function (next) {
user.getSettings(req.uid, next);
},
}, _next);
},
function (_results, next) {
results = _results;
settings = results.settings;
var start = Math.max(0, (page - 1) * settings.topicsPerPage);
var stop = start + settings.topicsPerPage - 1;
var cutoff = req.session.unreadCutoff ? req.session.unreadCutoff : topics.unreadCutoff();
topics.getUnreadTopics({
cid: cid,
uid: req.uid,
start: start,
stop: stop,
filter: filter,
cutoff: cutoff,
}, next);
},
function (data, next) {
user.blocks.filter(req.uid, data.topics, function (err, filtered) {
data.topics = filtered;
next(err, data);
});
},
function (data) {
data.title = meta.config.homePageTitle || '[[pages:home]]';
data.pageCount = Math.max(1, Math.ceil(data.topicCount / settings.topicsPerPage));
data.pagination = pagination.create(page, data.pageCount, req.query);
if (settings.usePagination && (page < 1 || page > data.pageCount)) {
req.query.page = Math.max(1, Math.min(data.pageCount, page));
return helpers.redirect(res, '/unread?' + querystring.stringify(req.query));
}
data.categories = results.watchedCategories.categories;
data.allCategoriesUrl = 'unread' + helpers.buildQueryString('', filter, '');
data.selectedCategory = results.watchedCategories.selectedCategory;
data.selectedCids = results.watchedCategories.selectedCids;
if (req.originalUrl.startsWith(nconf.get('relative_path') + '/api/unread') || req.originalUrl.startsWith(nconf.get('relative_path') + '/unread')) {
data.title = '[[pages:unread]]';
data.breadcrumbs = helpers.buildBreadcrumbs([{ text: '[[unread:title]]' }]);
}
data.filters = helpers.buildFilters('unread', filter, req.query);
data.selectedFilter = data.filters.find(function (filter) {
return filter && filter.selected;
});
res.render('unread', data);
},
], next);
};
unreadController.unreadTotal = function (req, res, next) {
var filter = req.query.filter || '';
async.waterfall([
function (next) {
plugins.fireHook('filter:unread.getValidFilters', { filters: Object.assign({}, helpers.validFilters) }, next);
},
function (data, _next) {
if (!data.filters[filter]) {
return next();
}
topics.getTotalUnread(req.uid, filter, _next);
},
function (data) {
res.json(data);
},
], next);
};
| An-dz/NodeBB | src/controllers/unread.js | JavaScript | gpl-3.0 | 3,327 |
# This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico 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.
#
# Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>.
class Serializer(object):
schemaless = True
encapsulate = True
registry = {}
def __init__(self, query_params, pretty=False, **kwargs):
self.pretty = pretty
self._query_params = query_params
self._fileName = None
self._lastModified = None
self._extra_args = kwargs
@classmethod
def register(cls, tag, serializer):
cls.registry[tag] = serializer
@classmethod
def getAllFormats(cls):
return list(cls.registry)
@classmethod
def create(cls, dformat, query_params=None, **kwargs):
"""
A serializer factory
"""
query_params = query_params or {}
serializer = cls.registry.get(dformat)
if serializer:
return serializer(query_params, **kwargs)
else:
raise Exception("Serializer for '%s' does not exist!" % dformat)
def getMIMEType(self):
return self._mime
def set_headers(self, response):
response.content_type = self.getMIMEType()
def __call__(self, obj, *args, **kwargs):
self._obj = obj
self._data = self._execute(obj, *args, **kwargs)
return self._data
from indico.web.http_api.metadata.json import JSONSerializer
from indico.web.http_api.metadata.xml import XMLSerializer
| belokop/indico_bare | indico/web/http_api/metadata/serializer.py | Python | gpl-3.0 | 2,039 |
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Model\Spi;
/**
* Interface ResourceInterface
*/
interface OrderPaymentResourceInterface
{
/**
* Save object data
*
* @param \Magento\Framework\Model\AbstractModel $object
* @return $this
*/
public function save(\Magento\Framework\Model\AbstractModel $object);
/**
* Load an object
*
* @param mixed $value
* @param \Magento\Framework\Model\AbstractModel $object
* @param string|null $field field to load by (defaults to model id)
* @return mixed
*/
public function load(\Magento\Framework\Model\AbstractModel $object, $value, $field = null);
/**
* Delete the object
*
* @param \Magento\Framework\Model\AbstractModel $object
* @return mixed
*/
public function delete(\Magento\Framework\Model\AbstractModel $object);
}
| rajmahesh/magento2-master | vendor/magento/module-sales/Model/Spi/OrderPaymentResourceInterface.php | PHP | gpl-3.0 | 959 |
(function () {
'use strict';
angular.module('driver.tools.export', [
'ui.bootstrap',
'ui.router',
'driver.customReports',
'driver.resources',
'angular-spinkit',
]);
})();
| WorldBank-Transport/DRIVER | web/app/scripts/tools/export/module.js | JavaScript | gpl-3.0 | 225 |
"use strict";
exports.__esModule = true;
var vueClient_1 = require("../../bibliotheque/vueClient");
console.log("* Chargement du script");
/* Test - déclaration d'une variable externe - Possible
cf. declare
*/
function centreNoeud() {
return JSON.parse(vueClient_1.contenuBalise(document, 'centre'));
}
function voisinsNoeud() {
var v = JSON.parse(vueClient_1.contenuBalise(document, 'voisins'));
var r = [];
var id;
for (id in v) {
r.push(v[id]);
}
return r;
}
function adresseServeur() {
return vueClient_1.contenuBalise(document, 'adresseServeur');
}
/*
type CanalChat = CanalClient<FormatMessageTchat>;
// A initialiser
var canal: CanalChat;
var noeud: Noeud<FormatSommetTchat>;
function envoyerMessage(texte: string, destinataire: Identifiant) {
let msg: MessageTchat = creerMessageCommunication(noeud.centre().enJSON().id, destinataire, texte);
console.log("- Envoi du message brut : " + msg.brut());
console.log("- Envoi du message net : " + msg.net());
canal.envoyerMessage(msg);
initialiserEntree('message_' + destinataire, "");
}
// A exécuter après chargement de la page
function initialisation(): void {
console.log("* Initialisation après chargement du DOM ...")
noeud = creerNoeud<FormatSommetTchat>(centreNoeud(), voisinsNoeud(), creerSommetTchat);
canal = new CanalClient<FormatMessageTchat>(adresseServeur());
canal.enregistrerTraitementAReception((m: FormatMessageTchat) => {
let msg = new MessageTchat(m);
console.log("- Réception du message brut : " + msg.brut());
console.log("- Réception du message net : " + msg.net());
posterNL('logChats', msg.net());
});
console.log("* ... du noeud et du canal côté client en liaison avec le serveur : " + adresseServeur());
// Gestion des événements pour les éléments du document.
//document.getElementById("boutonEnvoi").addEventListener("click", <EventListenerOrEventListenerObject>(e => {alert("click!");}), true);
let id: Identifiant;
let v = noeud.voisins();
for (id in v) {
console.log("id : " +id);
let idVal = id;
gererEvenementElement("boutonEnvoi_" + idVal, "click", e => {
console.log("id message_" + idVal);
console.log("entree : " + recupererEntree("message_" + idVal));
envoyerMessage(recupererEntree("message_" + idVal), idVal);
});
}
<form id="envoi">
<input type="text" id="message_id1">
<input class="button" type="button" id="boutonEnvoi_id1" value="Envoyer un message à {{nom id1}}."
onClick="envoyerMessage(this.form.message.value, "id1")">
</form>
console.log("* ... et des gestionnaires d'événements sur des éléments du document.");
}
// Gestion des événements pour le document
console.log("* Enregistrement de l'initialisation");
gererEvenementDocument('DOMContentLoaded', initialisation);
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', initialisation());
</script>
*/
//# sourceMappingURL=clientChat.js.map | hgrall/merite | src/communication/v0/typeScript/build/tchat/client/clientChat.js | JavaScript | gpl-3.0 | 3,134 |
(function ($) {
function FewbricksDevHelper() {
var $this = this;
/**
*
*/
this.init = function() {
$this.cssClassFull = 'fewbricks-info-pane--full';
if(!$this.initMainElm()) {
return;
}
$this.initToggler();
$this.$mainElm.show();
}
/**
*
*/
this.initMainElm = function() {
$this.$mainElm = $('#fewbricks-info-pane');
if($this.$mainElm.length === 0) {
return false;
}
if(typeof fewbricksInfoPane !== 'undefined' && typeof fewbricksInfoPane.startHeight !== 'undefined') {
$this.toggleMainElm(fewbricksInfoPane.startHeight);
}
return true;
}
/**
*
*/
this.initToggler = function() {
$('[data-fewbricks-info-pane-toggler]')
.unbind('click')
.on('click', function() {
let height = $(this).attr('data-fewbricks-info-pane-height');
$this.toggleMainElm(height);
document.cookie = 'fewbricks_info_pane_height=' + height;
});
}
/**
*
*/
this.toggleMainElm = function(height) {
if(height === 'minimized') {
$this.$mainElm.attr('style', function(i, style)
{
return style && style.replace(/height[^;]+;?/g, '');
});
} else {
$this.$mainElm.height(height + 'vh');
}
}
/**
*
* @returns {*|boolean}
*/
this.mainElmIsFull = function() {
return $this.$mainElm.hasClass($this.cssClassFull);
}
}
$(document).ready(function () {
(new FewbricksDevHelper()).init();
});
})(jQuery);
| folbert/fewbricks | assets/scripts/info-pane.js | JavaScript | gpl-3.0 | 1,977 |
/**
* ...
* @author paul
*/
function initCBX(object, id, options) {
var design = "assets";
if(object == null){
jQuery.noConflict();
var cboxClass;
cboxClass = jQuery(id).attr("class");
if(jQuery.browser.msie && parseInt(jQuery.browser.version)<8 ){
jQuery(id).colorbox();
}
else{
if(cboxClass.indexOf("cboxElement") == -1){
if(options.classes.image.id){
jQuery('.'+options.classes.image.id).colorbox({transition:options.classes.image.transition, slideshow:options.classes.image.slideshow, slideshowSpeed:options.classes.image.slideshowSpeed});
}
if(options.classes.video){
if(options.classes.video.id){
jQuery('.'+options.classes.video.id).colorbox({iframe:true, innerWidth:options.classes.video.innerWidth, innerHeight:options.classes.video.innerHeight, transition:options.classes.image.transition, slideshow:options.classes.image.slideshow, slideshowSpeed:options.classes.image.slideshowSpeed});
}
}
if(options.classes.swf){
if(options.classes.swf.id){
var cbxSWFSrc = jQuery('.'+options.classes.swf.id).attr("href");
var objEmbd = '<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" WIDTH="'+options.classes.video.innerWidth+'" HEIGHT="'+options.classes.video.innerHeight+'" id="cbxSWF" ALIGN="">'+
'<PARAM NAME=movie VALUE="'+cbxSWFSrc+'">' +
'<PARAM NAME=quality VALUE=high>' +
'<PARAM NAME=wmode VALUE=transparent>'+
'<PARAM NAME=bgcolor VALUE=#333399>'+
'<EMBED src="'+cbxSWFSrc+'" quality=high wmode=transparent WIDTH="'+options.classes.video.innerWidth+'" HEIGHT="'+options.classes.video.innerHeight+'" NAME="Yourfilename" ALIGN="" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></EMBED>'+
'</OBJECT>';
jQuery('.'+options.classes.swf.id).colorbox({html:objEmbd, transition:options.classes.image.transition, slideshow:options.classes.image.slideshow, slideshowSpeed:options.classes.image.slideshowSpeed});
}
}
}
}
jQuery(id).trigger('click');
return;
}
loadjQuery = function(filename) {
loadjQuery.getScript(object.path+"/"+filename);
loadjQuery.retry(0);
}
loadColorbox = function(filename) {
loadColorbox.getScript(object.path+"/"+filename);
loadColorbox.retry(0);
}
loadjQuery.getScript = function(filename) {
if(typeof jQuery == "undefined"){
var script = document.createElement('script');
script.setAttribute("type","text/javascript");
script.setAttribute("src", filename);
document.getElementsByTagName("head")[0].appendChild(script);
}
}
loadColorbox.getScript = function(filename) {
if(typeof jQuery.colorbox == "undefined"){
var link = document.createElement('link');
link.setAttribute('media', 'screen');
link.setAttribute('href', object.path+'/'+design+'/colorbox.css');
link.setAttribute('rel', 'stylesheet');
document.getElementsByTagName("head")[0].appendChild(link);
var script = document.createElement('script');
script.setAttribute("type","text/javascript");
script.setAttribute("src", filename);
document.getElementsByTagName("head")[0].appendChild(script);
}
}
loadjQuery.retry = function(time_elapsed) {
if (typeof jQuery == "undefined") {
if (time_elapsed <= 5000) {
setTimeout("loadjQuery.retry(" + (time_elapsed + 200) + ")", 200);
}
}
else {
if(typeof jQuery.colorbox == "undefined"){
loadColorbox("jquery.colorbox-min.js");
}
}
}
loadColorbox.retry = function(time_elapsed) {
if (typeof jQuery.colorbox == "undefined") {
if (time_elapsed <= 5000) {
setTimeout("loadColorbox.retry(" + (time_elapsed + 200) + ")", 200);
}
}
}
if(typeof jQuery == "undefined"){
loadjQuery("jquery-1.7.2.min.js");
}
else if(typeof jQuery.colorbox == "undefined"){
loadColorbox("jquery.colorbox-min.js");
}
}
| PhoenixInteractiveNL/emuControlCenter | ecc-core/tools/3dGallery_scripts/circulargallery/colorbox/swf.js.communication.js | JavaScript | gpl-3.0 | 3,990 |
#include "gx2r_buffer.h"
#include "gx2r_displaylist.h"
#include "gx2_displaylist.h"
#include <common/log.h>
namespace gx2
{
void
GX2RBeginDisplayListEx(GX2RBuffer *displayList,
uint32_t unused,
GX2RResourceFlags flags)
{
if (!displayList || !displayList->buffer) {
return;
}
auto size = displayList->elemCount * displayList->elemSize;
GX2BeginDisplayListEx(displayList->buffer, size, TRUE);
}
uint32_t
GX2REndDisplayList(GX2RBuffer *displayList)
{
auto size = GX2EndDisplayList(displayList->buffer);
decaf_check(size < (displayList->elemCount * displayList->elemSize));
return size;
}
void
GX2RCallDisplayList(GX2RBuffer *displayList,
uint32_t size)
{
if (!displayList || !displayList->buffer) {
return;
}
GX2CallDisplayList(displayList->buffer, size);
}
void
GX2RDirectCallDisplayList(GX2RBuffer *displayList,
uint32_t size)
{
if (!displayList || !displayList->buffer) {
return;
}
GX2DirectCallDisplayList(displayList->buffer, size);
}
} // namespace gx2
| petmac/decaf-emu | src/libdecaf/src/modules/gx2/gx2r_displaylist.cpp | C++ | gpl-3.0 | 1,114 |
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'newpage', 'eo', {
toolbar: 'Nova Paĝo'
} );
| vanpouckesven/cosnics | src/Chamilo/Libraries/Resources/Javascript/HtmlEditor/Ckeditor/src/plugins/newpage/lang/eo.js | JavaScript | gpl-3.0 | 226 |
// $Id: ActionAddClientDependencyAction.java 41 2010-04-03 20:04:12Z marcusvnac $
// Copyright (c) 2007 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
package org.argouml.uml.ui.foundation.core;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.argouml.i18n.Translator;
import org.argouml.kernel.ProjectManager;
import org.argouml.model.Model;
import org.argouml.uml.ui.AbstractActionAddModelElement2;
/**
* An Action to add client dependencies to some modelelement.
*
* @author Michiel
*/
public class ActionAddClientDependencyAction extends
AbstractActionAddModelElement2 {
/**
* The constructor.
*/
public ActionAddClientDependencyAction() {
super();
setMultiSelect(true);
}
/*
* Constraint: This code only deals with 1 supplier per dependency!
* TODO: How to support more?
*
* @see org.argouml.uml.ui.AbstractActionAddModelElement#doIt(java.util.List)
*/
protected void doIt(Collection selected) {
Set oldSet = new HashSet(getSelected());
for (Object client : selected) {
if (oldSet.contains(client)) {
oldSet.remove(client); //to be able to remove dependencies later
} else {
Model.getCoreFactory().buildDependency(getTarget(), client);
}
}
Collection toBeDeleted = new ArrayList();
Collection dependencies = Model.getFacade().getClientDependencies(
getTarget());
for (Object dependency : dependencies) {
if (oldSet.containsAll(Model.getFacade().getSuppliers(dependency))) {
toBeDeleted.add(dependency);
}
}
ProjectManager.getManager().getCurrentProject()
.moveToTrash(toBeDeleted);
}
/*
* @see org.argouml.uml.ui.AbstractActionAddModelElement#getChoices()
*/
protected List getChoices() {
List ret = new ArrayList();
Object model =
ProjectManager.getManager().getCurrentProject().getModel();
if (getTarget() != null) {
ret.addAll(Model.getModelManagementHelper()
.getAllModelElementsOfKind(model,
"org.omg.uml.foundation.core.ModelElement"));
ret.remove(getTarget());
}
return ret;
}
/*
* @see org.argouml.uml.ui.AbstractActionAddModelElement#getDialogTitle()
*/
protected String getDialogTitle() {
return Translator.localize("dialog.title.add-client-dependency");
}
/*
* @see org.argouml.uml.ui.AbstractActionAddModelElement#getSelected()
*/
protected List getSelected() {
List v = new ArrayList();
Collection c = Model.getFacade().getClientDependencies(getTarget());
for (Object cd : c) {
v.addAll(Model.getFacade().getSuppliers(cd));
}
return v;
}
}
| ckaestne/LEADT | workspace/argouml_critics/argouml-app/src/org/argouml/uml/ui/foundation/core/ActionAddClientDependencyAction.java | Java | gpl-3.0 | 4,569 |
require 'spec_helper'
require 'rubybot/plugins/tweet'
require 'support/twitter_mock'
RSpec.describe Rubybot::Plugins::Tweet do
include Cinch::Test
describe '#commands' do
subject { described_class.new(make_bot).commands }
it('returns a single command') { is_expected.to have_exactly(1).items }
end
let(:bot) { make_bot described_class, get_plugin_configuration(described_class) }
it 'doesn\'t match an unrelated url' do
expect(get_replies make_message(bot, 'asdf')).to have_exactly(0).items
end
it 'gives tweet data for a twitter url' do
replies = get_replies make_message(bot,
'https://twitter.com/AUser/status/43212344123',
channel: 'a')
expect(replies).to have_exactly(1).items
expect(replies.first.event).to eq :message
expect(replies.first.text).to eq '@AUser: asdf'
end
end
| robotbrain/rubybot | spec/rubybot/plugins/tweet_spec.rb | Ruby | gpl-3.0 | 908 |
var searchData=
[
['transfer_20commands',['Transfer Commands',['../group___d_a_p__transfer__gr.html',1,'']]]
];
| Stanford-BDML/super-scamp | vendor/CMSIS/CMSIS/Documentation/DAP/html/search/groups_74.js | JavaScript | gpl-3.0 | 114 |
"""Data models for referral system."""
from __future__ import unicode_literals
from builtins import map
from django.db import models
from django.core.urlresolvers import reverse
from pttrack.models import (ReferralType, ReferralLocation, Note,
ContactMethod, CompletableMixin,)
from followup.models import ContactResult, NoAptReason, NoShowReason
class Referral(Note):
"""A record of a particular patient's referral to a particular center."""
STATUS_SUCCESSFUL = 'S'
STATUS_PENDING = 'P'
STATUS_UNSUCCESSFUL = 'U'
# Status if there are no referrals of a specific type
# Used in aggregate_referral_status
NO_REFERRALS_CURRENTLY = "No referrals currently"
REFERRAL_STATUSES = (
(STATUS_SUCCESSFUL, 'Successful'),
(STATUS_PENDING, 'Pending'),
(STATUS_UNSUCCESSFUL, 'Unsuccessful'),
)
location = models.ManyToManyField(ReferralLocation)
comments = models.TextField(blank=True)
status = models.CharField(
max_length=50, choices=REFERRAL_STATUSES, default=STATUS_PENDING)
kind = models.ForeignKey(
ReferralType,
help_text="The kind of care the patient should recieve at the "
"referral location.")
def __str__(self):
"""Provides string to display on front end for referral.
For FQHC referrals, returns referral kind and date.
For non-FQHC referrals, returns referral location and date.
"""
formatted_date = self.written_datetime.strftime("%D")
if self.kind.is_fqhc:
return "%s referral on %s" % (self.kind, formatted_date)
else:
location_names = [loc.name for loc in self.location.all()]
locations = " ,".join(location_names)
return "Referral to %s on %s" % (locations, formatted_date)
@staticmethod
def aggregate_referral_status(referrals):
referral_status_output = ""
if referrals:
all_successful = all(referral.status == Referral.STATUS_SUCCESSFUL
for referral in referrals)
if all_successful:
referral_status_output = (dict(Referral.REFERRAL_STATUSES)
[Referral.STATUS_SUCCESSFUL])
else:
# Determine referral status based on the last FQHC referral
referral_status_output = (dict(Referral.REFERRAL_STATUSES)
[referrals.last().status])
else:
referral_status_output = Referral.NO_REFERRALS_CURRENTLY
return referral_status_output
class FollowupRequest(Note, CompletableMixin):
referral = models.ForeignKey(Referral)
contact_instructions = models.TextField()
MARK_DONE_URL_NAME = 'new-patient-contact'
ADMIN_URL_NAME = ''
def class_name(self):
return self.__class__.__name__
def short_name(self):
return "Referral"
def summary(self):
return self.contact_instructions
def mark_done_url(self):
return reverse(self.MARK_DONE_URL_NAME,
args=(self.referral.patient.id,
self.referral.id,
self.id))
def admin_url(self):
return reverse(
'admin:referral_followuprequest_change',
args=(self.id,)
)
def __str__(self):
formatted_date = self.due_date.strftime("%D")
return 'Followup with %s on %s about %s' % (self.patient,
formatted_date,
self.referral)
class PatientContact(Note):
followup_request = models.ForeignKey(FollowupRequest)
referral = models.ForeignKey(Referral)
contact_method = models.ForeignKey(
ContactMethod,
null=False,
blank=False,
help_text="What was the method of contact?")
contact_status = models.ForeignKey(
ContactResult,
blank=False,
null=False,
help_text="Did you make contact with the patient about this referral?")
PTSHOW_YES = "Y"
PTSHOW_NO = "N"
PTSHOW_OPTS = [(PTSHOW_YES, "Yes"),
(PTSHOW_NO, "No")]
has_appointment = models.CharField(
choices=PTSHOW_OPTS,
blank=True, max_length=1,
verbose_name="Appointment scheduled?",
help_text="Did the patient make an appointment?")
no_apt_reason = models.ForeignKey(
NoAptReason,
blank=True,
null=True,
verbose_name="No appointment reason",
help_text="If the patient didn't make an appointment, why not?")
appointment_location = models.ManyToManyField(
ReferralLocation,
blank=True,
help_text="Where did the patient make an appointment?")
pt_showed = models.CharField(
max_length=1,
choices=PTSHOW_OPTS,
blank=True,
null=True,
verbose_name="Appointment attended?",
help_text="Did the patient show up to the appointment?")
no_show_reason = models.ForeignKey(
NoShowReason,
blank=True,
null=True,
help_text="If the patient didn't go to the appointment, why not?")
def short_text(self):
"""Return a short text description of this followup and what happened.
Used on the patient chart view as the text in the list of followups.
"""
text = ""
locations = " ,".join(map(str, self.appointment_location.all()))
if self.pt_showed == self.PTSHOW_YES:
text = "Patient went to appointment at " + locations + "."
else:
if self.has_appointment == self.PTSHOW_YES:
text = ("Patient made appointment at " + locations +
"but has not yet gone.")
else:
if self.contact_status.patient_reached:
text = ("Successfully contacted patient but the "
"patient has not made an appointment yet.")
else:
text = "Did not successfully contact patient"
return text
| SaturdayNeighborhoodHealthClinic/osler | referral/models.py | Python | gpl-3.0 | 6,199 |
//# MatrixInverse.cc: The inverse of an expression returning a Jones matrix.
//#
//# Copyright (C) 2005
//# ASTRON (Netherlands Institute for Radio Astronomy)
//# P.O.Box 2, 7990 AA Dwingeloo, The Netherlands
//#
//# This file is part of the LOFAR software suite.
//# The LOFAR software suite 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.
//#
//# The LOFAR software suite 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 the LOFAR software suite. If not, see <http://www.gnu.org/licenses/>.
//#
//# $Id$
#include <lofar_config.h>
#include <BBSKernel/Expr/MatrixInverse.h>
// Inverse of a 2x2 matrix:
//
// (a b) ( d -b)
// If A = ( ) then inverse(A) = ( ) / (ad - bc)
// (c d) (-c a)
namespace LOFAR
{
namespace BBS
{
MatrixInverse::MatrixInverse(const Expr<JonesMatrix>::ConstPtr &expr)
: BasicUnaryExpr<JonesMatrix, JonesMatrix>(expr)
{
}
const JonesMatrix::View MatrixInverse::evaluateImpl(const Grid&,
const JonesMatrix::View &arg0) const
{
JonesMatrix::View result;
Matrix invDet(1.0 / (arg0(0, 0) * arg0(1, 1) - arg0(0, 1) * arg0(1, 0)));
result.assign(0, 0, arg0(1, 1) * invDet);
result.assign(0, 1, arg0(0, 1) * -invDet);
result.assign(1, 0, arg0(1, 0) * -invDet);
result.assign(1, 1, arg0(0, 0) * invDet);
return result;
}
} // namespace BBS
} // namespace LOFAR
| kernsuite-debian/lofar | CEP/Calibration/BBSKernel/src/Expr/MatrixInverse.cc | C++ | gpl-3.0 | 1,851 |
// @flow
import React, { Component } from 'react'
import { withStyles } from 'material-ui/styles'
import Profile from 'models/Profile'
import IconButton from 'material-ui/IconButton'
import Typography from 'material-ui/Typography'
import FontAwesome from 'react-fontawesome'
import Avatar from 'components/common/Avatar'
import Pubkey from 'components/common/Pubkey'
import InsetText from 'components/common/InsetText'
class ShowProfile extends Component {
props: {
profile: Profile,
onEditClick: () => any
}
render() {
const { classes, profile } = this.props
return (
<div>
<div className={classes.header}>
<div className={classes.lateral} />
<Typography className={classes.identity}>{profile.identity}</Typography>
<IconButton className={classes.lateral} onClick={this.props.onEditClick}><FontAwesome name="pencil" /></IconButton>
</div>
{ profile.avatarUrl
? <Avatar person={profile} className={classes.avatar} />
: <div className={classes.noAvatar}><Typography>No avatar</Typography></div>
}
<InsetText text={profile.bio} placeholder='No biography' />
<Typography align="center" variant="body2">
Share your Arbore ID
</Typography>
<Pubkey pubkey={profile.pubkey} />
</div>
)
}
}
const style = theme => ({
header: {
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
margin: '10px 0 20px',
},
avatar: {
width: '200px !important',
height: '200px !important',
margin: 'auto',
userSelect: 'none',
pointerEvents: 'none',
},
noAvatar: {
width: 200,
height: 200,
borderRadius: '50%',
backgroundColor: theme.palette.background.dark,
margin: 'auto',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
},
identity: {
margin: '0 10px 0 !important',
fontSize: '2em !important',
textAlign: 'center',
flexGrow: 1,
},
lateral: {
width: '20px !important',
},
})
export default withStyles(style)(ShowProfile)
| MichaelMure/TotallyNotArbore | app/components/profile/ShowProfile.js | JavaScript | gpl-3.0 | 2,101 |
package fr.ybo.transportscommun.activity.commun;
import android.widget.ImageButton;
public interface ChangeIconActionBar {
public void changeIconActionBar(ImageButton imageButton);
}
| ybonnel/TransportsRennes | TransportsCommun/src/fr/ybo/transportscommun/activity/commun/ChangeIconActionBar.java | Java | gpl-3.0 | 188 |
/* Copyright (C) 2003-2013 Runtime Revolution Ltd.
This file is part of LiveCode.
LiveCode is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License v3 as published by the Free
Software Foundation.
LiveCode 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 LiveCode. If not see <http://www.gnu.org/licenses/>. */
#include "prefix.h"
#include "globdefs.h"
#include "png.h"
#include "filedefs.h"
#include "objdefs.h"
#include "parsedef.h"
#include "mcio.h"
#include "uidc.h"
#include "util.h"
#include "image.h"
#include "globals.h"
#include "imageloader.h"
#define NATIVE_ALPHA_BEFORE ((kMCGPixelFormatNative & kMCGPixelAlphaPositionFirst) == kMCGPixelAlphaPositionFirst)
#define NATIVE_ORDER_BGR ((kMCGPixelFormatNative & kMCGPixelOrderRGB) == 0)
#if NATIVE_ALPHA_BEFORE
#define MCPNG_FILLER_POSITION PNG_FILLER_BEFORE
#else
#define MCPNG_FILLER_POSITION PNG_FILLER_AFTER
#endif
extern "C" void fakeread(png_structp png_ptr, png_bytep data, png_size_t length)
{
uint8_t **t_data_ptr = (uint8_t**)png_get_io_ptr(png_ptr);
memcpy(data, *t_data_ptr, length);
*t_data_ptr += length;
}
extern "C" void fakeflush(png_structp png_ptr)
{}
bool MCImageValidatePng(const void *p_data, uint32_t p_length, uint16_t& r_width, uint16_t& r_height)
{
png_structp png_ptr;
png_ptr = png_create_read_struct((char *)PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
png_infop info_ptr;
info_ptr = png_create_info_struct(png_ptr);
png_infop end_info_ptr;
end_info_ptr = png_create_info_struct(png_ptr);
// If we return to this point, its an error.
if (setjmp(png_jmpbuf(png_ptr)))
{
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info_ptr);
return false;
}
png_set_read_fn(png_ptr, &p_data, fakeread);
png_read_info(png_ptr, info_ptr);
png_uint_32 width, height;
int interlace_type, compression_type, filter_type, bit_depth, color_type;
png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_type);
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info_ptr);
r_width = (uint16_t)width;
r_height = (uint16_t)height;
return true;
}
////////////////////////////////////////////////////////////////////////////////
extern "C" void stream_read(png_structp png_ptr, png_bytep data, png_size_t length)
{
IO_handle t_stream = (IO_handle)png_get_io_ptr(png_ptr);
uint4 t_length;
t_length = length;
if (IO_read(data, length, t_stream) != IO_NORMAL)
png_error(png_ptr, (char *)"pnglib read error");
}
static void MCPNGSetNativePixelFormat(png_structp p_png)
{
#if NATIVE_ORDER_BGR
png_set_bgr(p_png);
#endif
#if NATIVE_ALPHA_BEFORE
png_set_swap_alpha(p_png);
#endif
}
class MCPNGImageLoader : public MCImageLoader
{
public:
MCPNGImageLoader(IO_handle p_stream);
virtual ~MCPNGImageLoader();
virtual MCImageLoaderFormat GetFormat() { return kMCImageFormatPNG; }
protected:
virtual bool LoadHeader(uint32_t &r_width, uint32_t &r_height, uint32_t &r_xhot, uint32_t &r_yhot, MCStringRef &r_name, uint32_t &r_frame_count, MCImageMetadata &r_metadata);
virtual bool LoadFrames(MCBitmapFrame *&r_frames, uint32_t &r_count);
private:
png_structp m_png;
png_infop m_info;
png_infop m_end_info;
int m_bit_depth;
int m_color_type;
};
MCPNGImageLoader::MCPNGImageLoader(IO_handle p_stream) : MCImageLoader(p_stream)
{
m_png = nil;
m_info = nil;
m_end_info = nil;
}
MCPNGImageLoader::~MCPNGImageLoader()
{
if (m_png != nil)
png_destroy_read_struct(&m_png, &m_info, &m_end_info);
}
bool MCPNGImageLoader::LoadHeader(uint32_t &r_width, uint32_t &r_height, uint32_t &r_xhot, uint32_t &r_yhot, MCStringRef &r_name, uint32_t &r_frame_count, MCImageMetadata &r_metadata)
{
bool t_success = true;
t_success = nil != (m_png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL));
if (t_success)
t_success = nil != (m_info = png_create_info_struct(m_png));
if (t_success)
t_success = nil != (m_end_info = png_create_info_struct(m_png));
if (t_success)
{
if (setjmp(png_jmpbuf(m_png)))
{
t_success = false;
}
}
if (t_success)
{
png_set_read_fn(m_png, GetStream(), stream_read);
png_read_info(m_png, m_info);
}
png_uint_32 t_width, t_height;
int t_interlace_method, t_compression_method, t_filter_method;
if (t_success)
{
png_get_IHDR(m_png, m_info, &t_width, &t_height,
&m_bit_depth, &m_color_type,
&t_interlace_method, &t_compression_method, &t_filter_method);
}
// MERG-2014-09-12: [[ ImageMetadata ]] load image metatadata
if (t_success)
{
uint32_t t_X;
uint32_t t_Y;
int t_units;
if (png_get_pHYs(m_png, m_info, &t_X, &t_Y, &t_units) && t_units != PNG_RESOLUTION_UNKNOWN)
{
MCImageMetadata t_metadata;
MCMemoryClear(&t_metadata, sizeof(t_metadata));
t_metadata.has_density = true;
t_metadata.density = floor(t_X * 0.0254 + 0.5);
r_metadata = t_metadata;
}
}
if (t_success)
{
r_width = t_width;
r_height = t_height;
r_xhot = r_yhot = 0;
r_name = MCValueRetain(kMCEmptyString);
r_frame_count = 1;
}
return t_success;
}
bool MCPNGImageLoader::LoadFrames(MCBitmapFrame *&r_frames, uint32_t &r_count)
{
bool t_success = true;
MCBitmapFrame *t_frame;
t_frame = nil;
MCColorTransformRef t_color_xform;
t_color_xform = nil;
if (setjmp(png_jmpbuf(m_png)))
{
t_success = false;
}
int t_interlace_passes;
uint32_t t_width, t_height;
if (t_success)
t_success = GetGeometry(t_width, t_height);
if (t_success)
t_success = MCMemoryNew(t_frame);
if (t_success)
t_success = MCImageBitmapCreate(t_width, t_height, t_frame->image);
if (t_success)
{
bool t_need_alpha = false;
t_interlace_passes = png_set_interlace_handling(m_png);
if (m_color_type == PNG_COLOR_TYPE_PALETTE)
png_set_palette_to_rgb(m_png);
if (m_color_type == PNG_COLOR_TYPE_GRAY || m_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb(m_png);
if (png_get_valid(m_png, m_info, PNG_INFO_tRNS))
{
png_set_tRNS_to_alpha(m_png);
t_need_alpha = true;
/* OVERHAUL - REVISIT - assume image has transparent pixels if tRNS is present */
t_frame->image->has_transparency = true;
}
if (m_color_type & PNG_COLOR_MASK_ALPHA)
{
t_need_alpha = true;
/* OVERHAUL - REVISIT - assume image has alpha if color type allows it */
t_frame->image->has_alpha = t_frame->image->has_transparency = true;
}
else if (!t_need_alpha)
png_set_add_alpha(m_png, 0xFF, MCPNG_FILLER_POSITION);
if (m_bit_depth == 16)
png_set_strip_16(m_png);
MCPNGSetNativePixelFormat(m_png);
}
// MW-2009-12-10: Support for color profiles
// Try to get an embedded ICC profile...
if (t_success && t_color_xform == nil && png_get_valid(m_png, m_info, PNG_INFO_iCCP))
{
png_charp t_ccp_name;
png_bytep t_ccp_profile;
int t_ccp_compression_type;
png_uint_32 t_ccp_profile_length;
png_get_iCCP(m_png, m_info, &t_ccp_name, &t_ccp_compression_type, &t_ccp_profile, &t_ccp_profile_length);
MCColorSpaceInfo t_csinfo;
t_csinfo . type = kMCColorSpaceEmbedded;
t_csinfo . embedded . data = t_ccp_profile;
t_csinfo . embedded . data_size = t_ccp_profile_length;
t_color_xform = MCscreen -> createcolortransform(t_csinfo);
}
// Next try an sRGB style profile...
if (t_success && t_color_xform == nil && png_get_valid(m_png, m_info, PNG_INFO_sRGB))
{
int t_intent;
png_get_sRGB(m_png, m_info, &t_intent);
MCColorSpaceInfo t_csinfo;
t_csinfo . type = kMCColorSpaceStandardRGB;
t_csinfo . standard . intent = (MCColorSpaceIntent)t_intent;
t_color_xform = MCscreen -> createcolortransform(t_csinfo);
}
// Finally try for cHRM + gAMA...
if (t_success && t_color_xform == nil && png_get_valid(m_png, m_info, PNG_INFO_cHRM) &&
png_get_valid(m_png, m_info, PNG_INFO_gAMA))
{
MCColorSpaceInfo t_csinfo;
t_csinfo . type = kMCColorSpaceCalibratedRGB;
png_get_cHRM(m_png, m_info,
&t_csinfo . calibrated . white_x, &t_csinfo . calibrated . white_y,
&t_csinfo . calibrated . red_x, &t_csinfo . calibrated . red_y,
&t_csinfo . calibrated . green_x, &t_csinfo . calibrated . green_y,
&t_csinfo . calibrated . blue_x, &t_csinfo . calibrated . blue_y);
png_get_gAMA(m_png, m_info, &t_csinfo . calibrated . gamma);
t_color_xform = MCscreen -> createcolortransform(t_csinfo);
}
// Could not create any kind, so fallback to gamma transform.
if (t_success && t_color_xform == nil)
{
double image_gamma;
if (png_get_gAMA(m_png, m_info, &image_gamma))
png_set_gamma(m_png, MCgamma, image_gamma);
else
png_set_gamma(m_png, MCgamma, 0.45);
}
if (t_success)
{
for (uindex_t t_pass = 0; t_pass < t_interlace_passes; t_pass++)
{
png_bytep t_data_ptr = (png_bytep)t_frame->image->data;
for (uindex_t i = 0; i < t_height; i++)
{
png_read_row(m_png, t_data_ptr, nil);
t_data_ptr += t_frame->image->stride;
}
}
}
if (t_success)
png_read_end(m_png, m_end_info);
// transform colours using extracted colour profile
if (t_success && t_color_xform != nil)
MCImageBitmapApplyColorTransform(t_frame->image, t_color_xform);
if (t_color_xform != nil)
MCscreen -> destroycolortransform(t_color_xform);
if (t_success)
{
r_frames = t_frame;
r_count = 1;
}
else
MCImageFreeFrames(t_frame, 1);
return t_success;
}
bool MCImageLoaderCreateForPNGStream(IO_handle p_stream, MCImageLoader *&r_loader)
{
MCPNGImageLoader *t_loader;
t_loader = new MCPNGImageLoader(p_stream);
if (t_loader == nil)
return false;
r_loader = t_loader;
return true;
}
////////////////////////////////////////////////////////////////////////////////
// embed stream within wrapper struct containing byte count
// so we can update byte_count as we go
struct MCPNGWriteContext
{
IO_handle stream;
uindex_t byte_count;
};
extern "C" void fakewrite(png_structp png_ptr, png_bytep data, png_size_t length)
{
MCPNGWriteContext *t_context = (MCPNGWriteContext*)png_get_io_ptr(png_ptr);
if (IO_write(data, sizeof(uint1), length, t_context->stream) != IO_NORMAL)
png_error(png_ptr, (char *)"pnglib write error");
t_context->byte_count += length;
}
// MERG-2014-07-16: [[ ImageMetadata ]] Parse the metadata array
static void parsemetadata(png_structp png_ptr, png_infop info_ptr, MCImageMetadata *p_metadata)
{
if (p_metadata == nil)
return;
if (p_metadata -> has_density)
{
real64_t t_ppi = p_metadata -> density;
if (t_ppi > 0)
{
// Convert to pixels per metre from pixels per inch
png_set_pHYs(png_ptr, info_ptr, t_ppi / 0.0254, t_ppi / 0.0254, PNG_RESOLUTION_METER);
}
}
}
bool MCImageEncodePNG(MCImageIndexedBitmap *p_indexed, MCImageMetadata *p_metadata, IO_handle p_stream, uindex_t &r_bytes_written)
{
bool t_success = true;
MCPNGWriteContext t_context;
t_context.stream = p_stream;
t_context.byte_count = 0;
png_structp t_png_ptr = nil;
png_infop t_info_ptr = nil;
png_color *t_png_palette = nil;
png_byte *t_png_transparency = nil;
png_bytep t_data_ptr = nil;
uindex_t t_stride = 0;
/*init png stuff*/
if (t_success)
{
t_success = nil != (t_png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
(png_voidp)NULL, (png_error_ptr)NULL,
(png_error_ptr)NULL));
}
if (t_success)
t_success = nil != (t_info_ptr = png_create_info_struct(t_png_ptr));
/*in case of png error*/
if (setjmp(png_jmpbuf(t_png_ptr)))
t_success = false;
if (t_success)
png_set_write_fn(t_png_ptr,(png_voidp)&t_context,fakewrite,fakeflush);
if (t_success)
{
png_set_IHDR(t_png_ptr, t_info_ptr, p_indexed->width, p_indexed->height, 8,
PNG_COLOR_TYPE_PALETTE, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
png_set_gAMA(t_png_ptr, t_info_ptr, 1/MCgamma);
}
// MERG-2014-07-16: [[ ImageMetadata ]] Parse the metadata array
if (t_success)
parsemetadata(t_png_ptr, t_info_ptr, p_metadata);
if (t_success)
t_success = MCMemoryNewArray(p_indexed->palette_size, t_png_palette);
/*create palette for 8 bit*/
if (t_success)
{
for (uindex_t i = 0; i < p_indexed->palette_size ; i++)
{
t_png_palette[i].red = p_indexed->palette[i].red >> 8;
t_png_palette[i].green = p_indexed->palette[i].green >> 8;
t_png_palette[i].blue = p_indexed->palette[i].blue >> 8;
}
png_set_PLTE(t_png_ptr, t_info_ptr, t_png_palette, p_indexed->palette_size);
}
if (MCImageIndexedBitmapHasTransparency(p_indexed))
{
if (t_success)
t_success = MCMemoryAllocate(p_indexed->palette_size, t_png_transparency);
if (t_success)
{
memset(t_png_transparency, 0xFF, p_indexed->palette_size);
t_png_transparency[p_indexed->transparent_index] = 0x00;
png_set_tRNS(t_png_ptr, t_info_ptr, t_png_transparency, p_indexed->palette_size, NULL);
}
}
if (t_success)
png_write_info(t_png_ptr, t_info_ptr);
if (t_success)
{
t_data_ptr = (png_bytep)p_indexed->data;
t_stride = p_indexed->stride;
}
if (t_success)
{
for (uindex_t i = 0; i < p_indexed->height; i++)
{
png_write_row(t_png_ptr, t_data_ptr);
t_data_ptr += t_stride;
}
}
if (t_success)
png_write_end(t_png_ptr, t_info_ptr);
if (t_png_ptr != nil)
png_destroy_write_struct(&t_png_ptr, &t_info_ptr);
if (t_png_palette != nil)
MCMemoryDeleteArray(t_png_palette);
if (t_png_transparency != nil)
MCMemoryDeallocate(t_png_transparency);
if (t_success)
r_bytes_written = t_context.byte_count;
return t_success;
}
bool MCImageEncodePNG(MCImageBitmap *p_bitmap, MCImageMetadata *p_metadata, IO_handle p_stream, uindex_t &r_bytes_written)
{
bool t_success = true;
MCPNGWriteContext t_context;
t_context.stream = p_stream;
t_context.byte_count = 0;
png_structp t_png_ptr = nil;
png_infop t_info_ptr = nil;
png_color *t_png_palette = nil;
png_byte *t_png_transparency = nil;
png_bytep t_data_ptr = nil;
uindex_t t_stride = 0;
MCImageIndexedBitmap *t_indexed = nil;
if (MCImageConvertBitmapToIndexed(p_bitmap, false, t_indexed))
{
t_success = MCImageEncodePNG(t_indexed, p_metadata, p_stream, r_bytes_written);
MCImageFreeIndexedBitmap(t_indexed);
return t_success;
}
/*init png stuff*/
if (t_success)
{
t_success = nil != (t_png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
(png_voidp)NULL, (png_error_ptr)NULL,
(png_error_ptr)NULL));
}
if (t_success)
t_success = nil != (t_info_ptr = png_create_info_struct(t_png_ptr));
/*in case of png error*/
if (setjmp(png_jmpbuf(t_png_ptr)))
t_success = false;
if (t_success)
png_set_write_fn(t_png_ptr,(png_voidp)&t_context,fakewrite,fakeflush);
bool t_fully_opaque = true;
if (t_success)
{
t_fully_opaque = !MCImageBitmapHasTransparency(p_bitmap);
png_set_IHDR(t_png_ptr, t_info_ptr, p_bitmap->width, p_bitmap->height, 8,
t_fully_opaque ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
png_set_gAMA(t_png_ptr, t_info_ptr, 1/MCgamma);
}
// MERG-2014-07-16: [[ ImageMetadata ]] Parse the metadata array
if (t_success)
parsemetadata(t_png_ptr, t_info_ptr, p_metadata);
if (t_success)
{
png_write_info(t_png_ptr, t_info_ptr);
if (t_fully_opaque)
png_set_filler(t_png_ptr, 0, MCPNG_FILLER_POSITION);
MCPNGSetNativePixelFormat(t_png_ptr);
}
if (t_success)
{
t_data_ptr = (png_bytep)p_bitmap->data;
t_stride = p_bitmap->stride;
}
if (t_success)
{
for (uindex_t i = 0; i < p_bitmap->height; i++)
{
png_write_row(t_png_ptr, t_data_ptr);
t_data_ptr += t_stride;
}
}
if (t_success)
png_write_end(t_png_ptr, t_info_ptr);
if (t_png_ptr != nil)
png_destroy_write_struct(&t_png_ptr, &t_info_ptr);
if (t_png_palette != nil)
MCMemoryDeleteArray(t_png_palette);
if (t_png_transparency != nil)
MCMemoryDeallocate(t_png_transparency);
if (t_success)
r_bytes_written = t_context.byte_count;
return t_success;
}
////////////////////////////////////////////////////////////////////////////////
| bright-sparks/livecode | engine/src/ipng.cpp | C++ | gpl-3.0 | 16,341 |
<?php
ob_start();
session_start();
if (session_status() == PHP_SESSION_NONE) {
require_once('index.php');
header($uri . '/index.php');
}
?>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="Creates a new University by a Super Admin">
<title>Create University</title>
<link rel = "stylesheet" href = "http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="container form-sigin">
<?php
//HTML tags for error messages
$err = "<h4 class=\"form-signin-error\">";
$suc = "<h4 class=\"form-signin-success\">";
$end = "</h4>";
$success = $rso = "";
$rsoErr = "";
$missing_data = [];
$name = [];
//Populates dropdown
require_once('connect.php');
$queryDB = "SELECT * FROM rso";
$result = mysqli_query($database, $queryDB);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
array_push($name,$row['name']);
}
}
if (empty($_POST["rsoSel"]))
{
$missing_data[] = "RSO";
$rsoErr = $err."RSO is required".$end;
}
else {
$rso = trim_input($_POST["rsoSel"]);
}
// Check for each required input data that has been POSTed through Request Method
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($missing_data)) {
require_once('connect.php');
$query = "INSERT INTO member (student_id, rso) VALUES (?, ?)";
$stmt = mysqli_prepare($database, $query);
mysqli_stmt_bind_param($stmt, "ss", $_SESSION['username'], $rso);
mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
if ($affected_rows == 1) {
mysqli_stmt_close($stmt);
mysqli_close($database);
$success = $suc."You've join an RSO".$end;
}
else {
$success = $err."Please reselect a RSO".$end;
mysqli_stmt_close($stmt);
mysqli_close($database);
}
}
}
//process input data
function trim_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
</div>
<div class="flex-container">
<header>
<h1> JOIN RSO </h1>
<span><b><?php echo "Welcome ". $_SESSION['username'] . "<br />";
if($_SESSION['user_type']=='s'){ echo "Student Account";}
elseif($_SESSION['user_type']=='a'){ echo "Admin Account";}
elseif($_SESSION['user_type']=='sa'){ echo "Super Admin Account";}?></b></span><br />
<a href="LOGOUT.php" target="_self"> Log Out</a><br />
</header>
<nav class="nav">
<ul>
<?php
if($_SESSION['user_type']== 's'){
echo " <li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"dashboard.php\" target=\"_self\"> Dashboard</a></b></li>
<li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"joinRSO.php\" target=\"_self\"> Join RSO</a></b></li>
<li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"createrso.php\" target=\"_self\"> Create RSO</a><br /></b></li>";
}
elseif($_SESSION['user_type']== 'a'){
echo " <li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"dashboard.php\" target=\"_self\"> Dashboard</a></b></li>
<li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"createEvent.html\" target=\"_self\"> Create Event</a><br /></b></li>
<li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"joinRSO.php\" target=\"_self\"> Join RSO</a></b></li>
<li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"createrso.php\" target=\"_self\"> Create RSO</a><br /></b></li>";
}
elseif($_SESSION['user_type']== 'sa'){
echo " <li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"dashboard.php\" target=\"_self\"> Dashboard</a></b></li>
<li><b> <a class = \"btn btn-mg btn-primary btn-block\" href=\"createuniversity.php\" target=\"_self\"> Create University</a></b></li>";
}
?>
</ul>
</nav>
<article class="article">
<div class="container">
<form class="form-signin" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<?php echo $success; ?>
<?php echo $rsoErr ?>
<select class="form-control" name="rsoSel">
<?php
for($x = 0; $x <= count($name); $x++){
echo "<option value=" . $name[$x] . ">" . $name[$x] . "</option>";
}
?>
<input class = "btn btn-lg btn-primary btn-block" type="submit" value="Join"></input><br />
</form>
</div>
</article>
<div>
</body>
</html>
| emcyroyale/COP4710-10 | CollegeEvents2/joinrso.php | PHP | gpl-3.0 | 4,944 |
<?php
/**
* Class for the definition of a widget that is
* called by the class of the main module
*
* @package SZGoogle
* @subpackage Widgets
* @author Massimo Della Rovere
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/
if (!defined('SZ_PLUGIN_GOOGLE') or !SZ_PLUGIN_GOOGLE) die();
// Before the definition of the class, check if there is a definition
// with the same name or the same as previously defined in other script
if (!class_exists('SZGoogleWidgetDriveSaveButton'))
{
class SZGoogleWidgetDriveSaveButton extends SZGoogleWidget
{
/**
* Definition the constructor function, which is called
* at the time of the creation of an instance of this class
*/
function __construct()
{
parent::__construct('SZ-Google-Drive-Save-Button',__('SZ-Google - Drive Save Button','szgoogleadmin'),array(
'classname' => 'sz-widget-google sz-widget-google-drive sz-widget-google-drive-save-button',
'description' => ucfirst(__('google drive save button.','szgoogleadmin'))
));
}
/**
* Generation of the HTML code of the widget
* for the full display in the sidebar associated
*/
function widget($args,$instance)
{
// Checking whether there are the variables that are used during the processing
// the script and check the default values in case they were not specified
$options = $this->common_empty(array(
'url' => '', // default value
'filename' => '', // default value
'sitename' => '', // default value
'text' => '', // default value
'img' => '', // default value
'position' => '', // default value
'align' => '', // default value
'margintop' => '', // default value
'marginright' => '', // default value
'marginbottom' => '', // default value
'marginleft' => '', // default value
'marginunit' => '', // default value
),$instance);
// Definition of the control variables of the widget, these values
// do not affect the items of basic but affect some aspects
$controls = $this->common_empty(array(
'badge' => '', // default value
),$instance);
// If the widget I excluded from the badge button I reset
// the variables of the badge possibly set and saved
if ($controls['badge'] != '1') {
$options['img'] = '';
$options['text'] = '';
$options['position'] = '';
}
// Create the HTML code for the current widget recalling the basic
// function which is also invoked by the corresponding shortcode
$OBJC = new SZGoogleActionDriveSave();
$HTML = $OBJC->getHTMLCode($options);
// Output HTML code linked to the widget to
// display call to the general standard for wrap
echo $this->common_widget($args,$instance,$HTML);
}
/**
* Changing parameters related to the widget FORM
* with storing the values directly in the database
*/
function update($new_instance,$old_instance)
{
// Performing additional operations on fields of the
// form widget before it is stored in the database
return $this->common_update(array(
'title' => '0', // strip_tags
'badge' => '1', // strip_tags
'url' => '0', // strip_tags
'text' => '0', // strip_tags
'img' => '1', // strip_tags
'align' => '1', // strip_tags
'position' => '1', // strip_tags
),$new_instance,$old_instance);
}
/**
* FORM display the widget in the management of
* sidebar in the administration panel of wordpress
*/
function form($instance)
{
// Creating arrays for list fields that must be
// present in the form before calling wp_parse_args()
$array = array(
'title' => '', // default value
'badge' => '', // default value
'url' => '', // default value
'text' => '', // default value
'img' => '', // default value
'align' => '', // default value
'position' => '', // default value
);
// Creating arrays for list of fields to be retrieved FORM
// and loading the file with the HTML template to display
extract(wp_parse_args($instance,$array),EXTR_OVERWRITE);
// Calling the template for displaying the part
// that concerns the administration panel (admin)
@include(dirname(SZ_PLUGIN_GOOGLE_MAIN).'/admin/widgets/SZGoogleWidget.php');
@include(dirname(SZ_PLUGIN_GOOGLE_MAIN).'/admin/widgets/' .__CLASS__.'.php');
}
}
} | rossonet/maker_imola_city | app-root/data/plugins/sz-google/classes/widget/SZGoogleWidgetDriveSaveButton.php | PHP | gpl-3.0 | 4,458 |
<?php
//require_once 'PEAR.php';
// commented by yogatama for use in gtfw
//require_once 'oleread.inc';
///////
//define('Spreadsheet_Excel_Reader_HAVE_ICONV', function_exists('iconv'));
//define('Spreadsheet_Excel_Reader_HAVE_MB', function_exists('mb_convert_encoding'));
define('Spreadsheet_Excel_Reader_BIFF8', 0x600);
define('Spreadsheet_Excel_Reader_BIFF7', 0x500);
define('Spreadsheet_Excel_Reader_WorkbookGlobals', 0x5);
define('Spreadsheet_Excel_Reader_Worksheet', 0x10);
define('Spreadsheet_Excel_Reader_Type_BOF', 0x809);
define('Spreadsheet_Excel_Reader_Type_EOF', 0x0a);
define('Spreadsheet_Excel_Reader_Type_BOUNDSHEET', 0x85);
define('Spreadsheet_Excel_Reader_Type_DIMENSION', 0x200);
define('Spreadsheet_Excel_Reader_Type_ROW', 0x208);
define('Spreadsheet_Excel_Reader_Type_DBCELL', 0xd7);
define('Spreadsheet_Excel_Reader_Type_FILEPASS', 0x2f);
define('Spreadsheet_Excel_Reader_Type_NOTE', 0x1c);
define('Spreadsheet_Excel_Reader_Type_TXO', 0x1b6);
define('Spreadsheet_Excel_Reader_Type_RK', 0x7e);
define('Spreadsheet_Excel_Reader_Type_RK2', 0x27e);
define('Spreadsheet_Excel_Reader_Type_MULRK', 0xbd);
define('Spreadsheet_Excel_Reader_Type_MULBLANK', 0xbe);
define('Spreadsheet_Excel_Reader_Type_INDEX', 0x20b);
define('Spreadsheet_Excel_Reader_Type_SST', 0xfc);
define('Spreadsheet_Excel_Reader_Type_EXTSST', 0xff);
define('Spreadsheet_Excel_Reader_Type_CONTINUE', 0x3c);
define('Spreadsheet_Excel_Reader_Type_LABEL', 0x204);
define('Spreadsheet_Excel_Reader_Type_LABELSST', 0xfd);
define('Spreadsheet_Excel_Reader_Type_NUMBER', 0x203);
define('Spreadsheet_Excel_Reader_Type_NAME', 0x18);
define('Spreadsheet_Excel_Reader_Type_ARRAY', 0x221);
define('Spreadsheet_Excel_Reader_Type_STRING', 0x207);
define('Spreadsheet_Excel_Reader_Type_FORMULA', 0x406);
define('Spreadsheet_Excel_Reader_Type_FORMULA2', 0x6);
define('Spreadsheet_Excel_Reader_Type_FORMAT', 0x41e);
define('Spreadsheet_Excel_Reader_Type_XF', 0xe0);
define('Spreadsheet_Excel_Reader_Type_BOOLERR', 0x205);
define('Spreadsheet_Excel_Reader_Type_UNKNOWN', 0xffff);
define('Spreadsheet_Excel_Reader_Type_NINETEENFOUR', 0x22);
define('Spreadsheet_Excel_Reader_Type_MERGEDCELLS', 0xE5);
define('Spreadsheet_Excel_Reader_utcOffsetDays' , 25569);
define('Spreadsheet_Excel_Reader_utcOffsetDays1904', 24107);
define('Spreadsheet_Excel_Reader_msInADay', 24 * 60 * 60);
//define('Spreadsheet_Excel_Reader_DEF_NUM_FORMAT', "%.2f");
define('Spreadsheet_Excel_Reader_DEF_NUM_FORMAT', "%s");
// function file_get_contents for PHP < 4.3.0
// Thanks Marian Steinbach for this function
if (!function_exists('file_get_contents')) {
function file_get_contents($filename, $use_include_path = 0) {
$data = '';
$file = @fopen($filename, "rb", $use_include_path);
if ($file) {
while (!feof($file)) $data .= fread($file, 1024);
fclose($file);
} else {
// There was a problem opening the file
$data = FALSE;
}
return $data;
}
}
//class Spreadsheet_Excel_Reader extends PEAR {
class Spreadsheet_Excel_Reader {
var $boundsheets = array();
var $formatRecords = array();
var $sst = array();
var $sheets = array();
var $data;
var $pos;
var $_ole;
var $_defaultEncoding;
var $_defaultFormat = Spreadsheet_Excel_Reader_DEF_NUM_FORMAT;
var $_columnsFormat = array();
var $_rowoffset = 1;
var $_coloffset = 1;
var $dateFormats = array (
0xe => "d/m/Y",
0xf => "d-M-Y",
0x10 => "d-M",
0x11 => "M-Y",
0x12 => "h:i a",
0x13 => "h:i:s a",
0x14 => "H:i",
0x15 => "H:i:s",
0x16 => "d/m/Y H:i",
0x2d => "i:s",
0x2e => "H:i:s",
0x2f => "i:s.S");
var $numberFormats = array(
0x1 => "%1.0f", // "0"
0x2 => "%1.2f", // "0.00",
0x3 => "%1.0f", //"#,##0",
0x4 => "%1.2f", //"#,##0.00",
0x5 => "%1.0f", /*"$#,##0;($#,##0)",*/
0x6 => '$%1.0f', /*"$#,##0;($#,##0)",*/
0x7 => '$%1.2f', //"$#,##0.00;($#,##0.00)",
0x8 => '$%1.2f', //"$#,##0.00;($#,##0.00)",
0x9 => '%1.0f%%', // "0%"
0xa => '%1.2f%%', // "0.00%"
0xb => '%1.2f', // 0.00E00",
0x25 => '%1.0f', // "#,##0;(#,##0)",
0x26 => '%1.0f', //"#,##0;(#,##0)",
0x27 => '%1.2f', //"#,##0.00;(#,##0.00)",
0x28 => '%1.2f', //"#,##0.00;(#,##0.00)",
0x29 => '%1.0f', //"#,##0;(#,##0)",
0x2a => '$%1.0f', //"$#,##0;($#,##0)",
0x2b => '%1.2f', //"#,##0.00;(#,##0.00)",
0x2c => '$%1.2f', //"$#,##0.00;($#,##0.00)",
0x30 => '%1.0f'); //"##0.0E0";
function Spreadsheet_Excel_Reader(){
$this->_ole =& new OLERead();
$this->setUTFEncoder('iconv');
}
function setOutputEncoding($Encoding){
$this->_defaultEncoding = $Encoding;
}
/**
* $encoder = 'iconv' or 'mb'
* set iconv if you would like use 'iconv' for encode UTF-16LE to your encoding
* set mb if you would like use 'mb_convert_encoding' for encode UTF-16LE to your encoding
*/
function setUTFEncoder($encoder = 'iconv'){
$this->_encoderFunction = '';
if ($encoder == 'iconv'){
$this->_encoderFunction = function_exists('iconv') ? 'iconv' : '';
}elseif ($encoder == 'mb') {
$this->_encoderFunction = function_exists('mb_convert_encoding') ? 'mb_convert_encoding' : '';
}
}
function setRowColOffset($iOffset){
$this->_rowoffset = $iOffset;
$this->_coloffset = $iOffset;
}
function setDefaultFormat($sFormat){
$this->_defaultFormat = $sFormat;
}
function setColumnFormat($column, $sFormat){
$this->_columnsFormat[$column] = $sFormat;
}
function read($sFileName) {
$errlevel = error_reporting();
//error_reporting($errlevel ^ E_NOTICE);
$res = $this->_ole->read($sFileName);
// oops, something goes wrong (Darko Miljanovic)
if($res === false) {
// check error code
if($this->_ole->error == 1) {
// bad file
die('The filename ' . $sFileName . ' is not readable');
}
// check other error codes here (eg bad fileformat, etc...)
}
$this->data = $this->_ole->getWorkBook();
/*
$res = $this->_ole->read($sFileName);
if ($this->isError($res)) {
// var_dump($res);
return $this->raiseError($res);
}
$total = $this->_ole->ppsTotal();
for ($i = 0; $i < $total; $i++) {
if ($this->_ole->isFile($i)) {
$type = unpack("v", $this->_ole->getData($i, 0, 2));
if ($type[''] == 0x0809) { // check if it's a BIFF stream
$this->_index = $i;
$this->data = $this->_ole->getData($i, 0, $this->_ole->getDataLength($i));
break;
}
}
}
if ($this->_index === null) {
return $this->raiseError("$file doesn't seem to be an Excel file");
}
*/
//var_dump($this->data);
//echo "data =".$this->data;
$this->pos = 0;
//$this->readRecords();
$this->_parse();
error_reporting($errlevel);
}
function _parse(){
$pos = 0;
$code = ord($this->data[$pos]) | ord($this->data[$pos+1])<<8;
$length = ord($this->data[$pos+2]) | ord($this->data[$pos+3])<<8;
$version = ord($this->data[$pos + 4]) | ord($this->data[$pos + 5])<<8;
$substreamType = ord($this->data[$pos + 6]) | ord($this->data[$pos + 7])<<8;
//echo "Start parse code=".base_convert($code,10,16)." version=".base_convert($version,10,16)." substreamType=".base_convert($substreamType,10,16).""."\n";
if (($version != Spreadsheet_Excel_Reader_BIFF8) && ($version != Spreadsheet_Excel_Reader_BIFF7)) {
return false;
}
if ($substreamType != Spreadsheet_Excel_Reader_WorkbookGlobals){
return false;
}
//print_r($rec);
$pos += $length + 4;
$code = ord($this->data[$pos]) | ord($this->data[$pos+1])<<8;
$length = ord($this->data[$pos+2]) | ord($this->data[$pos+3])<<8;
while ($code != Spreadsheet_Excel_Reader_Type_EOF){
switch ($code) {
case Spreadsheet_Excel_Reader_Type_SST:
//echo "Type_SST\n";
$spos = $pos + 4;
$limitpos = $spos + $length;
$uniqueStrings = $this->_GetInt4d($this->data, $spos+4);
$spos += 8;
for ($i = 0; $i < $uniqueStrings; $i++) {
// Read in the number of characters
if ($spos == $limitpos) {
$opcode = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$conlength = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
if ($opcode != 0x3c) {
return -1;
}
$spos += 4;
$limitpos = $spos + $conlength;
}
$numChars = ord($this->data[$spos]) | (ord($this->data[$spos+1]) << 8);
//echo "i = $i pos = $pos numChars = $numChars ";
$spos += 2;
$optionFlags = ord($this->data[$spos]);
$spos++;
$asciiEncoding = (($optionFlags & 0x01) == 0) ;
$extendedString = ( ($optionFlags & 0x04) != 0);
// See if string contains formatting information
$richString = ( ($optionFlags & 0x08) != 0);
if ($richString) {
// Read in the crun
$formattingRuns = ord($this->data[$spos]) | (ord($this->data[$spos+1]) << 8);
$spos += 2;
}
if ($extendedString) {
// Read in cchExtRst
$extendedRunLength = $this->_GetInt4d($this->data, $spos);
$spos += 4;
}
$len = ($asciiEncoding)? $numChars : $numChars*2;
if ($spos + $len < $limitpos) {
$retstr = substr($this->data, $spos, $len);
$spos += $len;
}else{
// found countinue
$retstr = substr($this->data, $spos, $limitpos - $spos);
$bytesRead = $limitpos - $spos;
$charsLeft = $numChars - (($asciiEncoding) ? $bytesRead : ($bytesRead / 2));
$spos = $limitpos;
while ($charsLeft > 0){
$opcode = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$conlength = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
if ($opcode != 0x3c) {
return -1;
}
$spos += 4;
$limitpos = $spos + $conlength;
$option = ord($this->data[$spos]);
$spos += 1;
if ($asciiEncoding && ($option == 0)) {
$len = min($charsLeft, $limitpos - $spos); // min($charsLeft, $conlength);
$retstr .= substr($this->data, $spos, $len);
$charsLeft -= $len;
$asciiEncoding = true;
}elseif (!$asciiEncoding && ($option != 0)){
$len = min($charsLeft * 2, $limitpos - $spos); // min($charsLeft, $conlength);
$retstr .= substr($this->data, $spos, $len);
$charsLeft -= $len/2;
$asciiEncoding = false;
}elseif (!$asciiEncoding && ($option == 0)) {
// Bummer - the string starts off as Unicode, but after the
// continuation it is in straightforward ASCII encoding
$len = min($charsLeft, $limitpos - $spos); // min($charsLeft, $conlength);
for ($j = 0; $j < $len; $j++) {
$retstr .= $this->data[$spos + $j].chr(0);
}
$charsLeft -= $len;
$asciiEncoding = false;
}else{
$newstr = '';
for ($j = 0; $j < strlen($retstr); $j++) {
$newstr = $retstr[$j].chr(0);
}
$retstr = $newstr;
$len = min($charsLeft * 2, $limitpos - $spos); // min($charsLeft, $conlength);
$retstr .= substr($this->data, $spos, $len);
$charsLeft -= $len/2;
$asciiEncoding = false;
//echo "Izavrat\n";
}
$spos += $len;
}
}
$retstr = ($asciiEncoding) ? $retstr : $this->_encodeUTF16($retstr);
// echo "Str $i = $retstr\n";
if ($richString){
$spos += 4 * $formattingRuns;
}
// For extended strings, skip over the extended string data
if ($extendedString) {
$spos += $extendedRunLength;
}
//if ($retstr == 'Derby'){
// echo "bb\n";
//}
$this->sst[]=$retstr;
}
/*$continueRecords = array();
while ($this->getNextCode() == Type_CONTINUE) {
$continueRecords[] = &$this->nextRecord();
}
//echo " 1 Type_SST\n";
$this->shareStrings = new SSTRecord($r, $continueRecords);
//print_r($this->shareStrings->strings);
*/
// echo 'SST read: '.($time_end-$time_start)."\n";
break;
case Spreadsheet_Excel_Reader_Type_FILEPASS:
return false;
break;
case Spreadsheet_Excel_Reader_Type_NAME:
//echo "Type_NAME\n";
break;
case Spreadsheet_Excel_Reader_Type_FORMAT:
$indexCode = ord($this->data[$pos+4]) | ord($this->data[$pos+5]) << 8;
if ($version == Spreadsheet_Excel_Reader_BIFF8) {
$numchars = ord($this->data[$pos+6]) | ord($this->data[$pos+7]) << 8;
if (ord($this->data[$pos+8]) == 0){
$formatString = substr($this->data, $pos+9, $numchars);
} else {
$formatString = substr($this->data, $pos+9, $numchars*2);
}
} else {
$numchars = ord($this->data[$pos+6]);
$formatString = substr($this->data, $pos+7, $numchars*2);
}
$this->formatRecords[$indexCode] = $formatString;
// echo "Type.FORMAT\n";
break;
case Spreadsheet_Excel_Reader_Type_XF:
//global $dateFormats, $numberFormats;
$indexCode = ord($this->data[$pos+6]) | ord($this->data[$pos+7]) << 8;
//echo "\nType.XF ".count($this->formatRecords['xfrecords'])." $indexCode ";
if (array_key_exists($indexCode, $this->dateFormats)) {
//echo "isdate ".$dateFormats[$indexCode];
$this->formatRecords['xfrecords'][] = array(
'type' => 'date',
'format' => $this->dateFormats[$indexCode]
);
}elseif (array_key_exists($indexCode, $this->numberFormats)) {
//echo "isnumber ".$this->numberFormats[$indexCode];
$this->formatRecords['xfrecords'][] = array(
'type' => 'number',
'format' => $this->numberFormats[$indexCode]
);
}else{
$isdate = FALSE;
if ($indexCode > 0){
if (isset($this->formatRecords[$indexCode]))
$formatstr = $this->formatRecords[$indexCode];
//echo '.other.';
//echo "\ndate-time=$formatstr=\n";
if ($formatstr)
if (preg_match("/[^hmsday\/\-:\s]/i", $formatstr) == 0) { // found day and time format
$isdate = TRUE;
$formatstr = str_replace('mm', 'i', $formatstr);
$formatstr = str_replace('h', 'H', $formatstr);
//echo "\ndate-time $formatstr \n";
}
}
if ($isdate){
$this->formatRecords['xfrecords'][] = array(
'type' => 'date',
'format' => $formatstr,
);
}else{
$this->formatRecords['xfrecords'][] = array(
'type' => 'other',
'format' => '',
'code' => $indexCode
);
}
}
//echo "\n";
break;
case Spreadsheet_Excel_Reader_Type_NINETEENFOUR:
//echo "Type.NINETEENFOUR\n";
$this->nineteenFour = (ord($this->data[$pos+4]) == 1);
break;
case Spreadsheet_Excel_Reader_Type_BOUNDSHEET:
//echo "Type.BOUNDSHEET\n";
$rec_offset = $this->_GetInt4d($this->data, $pos+4);
$rec_typeFlag = ord($this->data[$pos+8]);
$rec_visibilityFlag = ord($this->data[$pos+9]);
$rec_length = ord($this->data[$pos+10]);
if ($version == Spreadsheet_Excel_Reader_BIFF8){
$chartype = ord($this->data[$pos+11]);
if ($chartype == 0){
$rec_name = substr($this->data, $pos+12, $rec_length);
} else {
$rec_name = $this->_encodeUTF16(substr($this->data, $pos+12, $rec_length*2));
}
}elseif ($version == Spreadsheet_Excel_Reader_BIFF7){
$rec_name = substr($this->data, $pos+11, $rec_length);
}
$this->boundsheets[] = array('name'=>$rec_name,
'offset'=>$rec_offset);
break;
}
//echo "Code = ".base_convert($r['code'],10,16)."\n";
$pos += $length + 4;
$code = ord($this->data[$pos]) | ord($this->data[$pos+1])<<8;
$length = ord($this->data[$pos+2]) | ord($this->data[$pos+3])<<8;
//$r = &$this->nextRecord();
//echo "1 Code = ".base_convert($r['code'],10,16)."\n";
}
foreach ($this->boundsheets as $key=>$val){
$this->sn = $key;
$this->_parsesheet($val['offset']);
}
return true;
}
function _parsesheet($spos){
$cont = true;
// read BOF
$code = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$length = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
$version = ord($this->data[$spos + 4]) | ord($this->data[$spos + 5])<<8;
$substreamType = ord($this->data[$spos + 6]) | ord($this->data[$spos + 7])<<8;
if (($version != Spreadsheet_Excel_Reader_BIFF8) && ($version != Spreadsheet_Excel_Reader_BIFF7)) {
return -1;
}
if ($substreamType != Spreadsheet_Excel_Reader_Worksheet){
return -2;
}
//echo "Start parse code=".base_convert($code,10,16)." version=".base_convert($version,10,16)." substreamType=".base_convert($substreamType,10,16).""."\n";
$spos += $length + 4;
//var_dump($this->formatRecords);
//echo "code $code $length";
while($cont) {
//echo "mem= ".memory_get_usage()."\n";
// $r = &$this->file->nextRecord();
$lowcode = ord($this->data[$spos]);
if ($lowcode == Spreadsheet_Excel_Reader_Type_EOF) break;
$code = $lowcode | ord($this->data[$spos+1])<<8;
$length = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
$spos += 4;
$this->sheets[$this->sn]['maxrow'] = $this->_rowoffset - 1;
$this->sheets[$this->sn]['maxcol'] = $this->_coloffset - 1;
//echo "Code=".base_convert($code,10,16)." $code\n";
unset($this->rectype);
$this->multiplier = 1; // need for format with %
switch ($code) {
case Spreadsheet_Excel_Reader_Type_DIMENSION:
//echo 'Type_DIMENSION ';
if (!isset($this->numRows)) {
if (($length == 10) || ($version == Spreadsheet_Excel_Reader_BIFF7)){
$this->sheets[$this->sn]['numRows'] = ord($this->data[$spos+2]) | ord($this->data[$spos+3]) << 8;
$this->sheets[$this->sn]['numCols'] = ord($this->data[$spos+6]) | ord($this->data[$spos+7]) << 8;
} else {
$this->sheets[$this->sn]['numRows'] = ord($this->data[$spos+4]) | ord($this->data[$spos+5]) << 8;
$this->sheets[$this->sn]['numCols'] = ord($this->data[$spos+10]) | ord($this->data[$spos+11]) << 8;
}
}
//echo 'numRows '.$this->numRows.' '.$this->numCols."\n";
break;
case Spreadsheet_Excel_Reader_Type_MERGEDCELLS:
$cellRanges = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
for ($i = 0; $i < $cellRanges; $i++) {
$fr = ord($this->data[$spos + 8*$i + 2]) | ord($this->data[$spos + 8*$i + 3])<<8;
$lr = ord($this->data[$spos + 8*$i + 4]) | ord($this->data[$spos + 8*$i + 5])<<8;
$fc = ord($this->data[$spos + 8*$i + 6]) | ord($this->data[$spos + 8*$i + 7])<<8;
$lc = ord($this->data[$spos + 8*$i + 8]) | ord($this->data[$spos + 8*$i + 9])<<8;
//$this->sheets[$this->sn]['mergedCells'][] = array($fr + 1, $fc + 1, $lr + 1, $lc + 1);
if ($lr - $fr > 0) {
$this->sheets[$this->sn]['cellsInfo'][$fr+1][$fc+1]['rowspan'] = $lr - $fr + 1;
}
if ($lc - $fc > 0) {
$this->sheets[$this->sn]['cellsInfo'][$fr+1][$fc+1]['colspan'] = $lc - $fc + 1;
}
}
//echo "Merged Cells $cellRanges $lr $fr $lc $fc\n";
break;
case Spreadsheet_Excel_Reader_Type_RK:
case Spreadsheet_Excel_Reader_Type_RK2:
//echo 'Spreadsheet_Excel_Reader_Type_RK'."\n";
$row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
$rknum = $this->_GetInt4d($this->data, $spos + 6);
$numValue = $this->_GetIEEE754($rknum);
//echo $numValue." ";
if ($this->isDate($spos)) {
list($string, $raw) = $this->createDate($numValue);
}else{
$raw = $numValue;
if (isset($this->_columnsFormat[$column + 1])){
$this->curformat = $this->_columnsFormat[$column + 1];
}
$string = sprintf($this->curformat, $numValue * $this->multiplier);
//$this->addcell(RKRecord($r));
}
$this->addcell($row, $column, $string, $raw);
//echo "Type_RK $row $column $string $raw {$this->curformat}\n";
break;
case Spreadsheet_Excel_Reader_Type_LABELSST:
$row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
$xfindex = ord($this->data[$spos+4]) | ord($this->data[$spos+5])<<8;
$index = $this->_GetInt4d($this->data, $spos + 6);
//var_dump($this->sst);
$this->addcell($row, $column, $this->sst[$index]);
//echo "LabelSST $row $column $string\n";
break;
case Spreadsheet_Excel_Reader_Type_MULRK:
$row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$colFirst = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
$colLast = ord($this->data[$spos + $length - 2]) | ord($this->data[$spos + $length - 1])<<8;
$columns = $colLast - $colFirst + 1;
$tmppos = $spos+4;
for ($i = 0; $i < $columns; $i++) {
$numValue = $this->_GetIEEE754($this->_GetInt4d($this->data, $tmppos + 2));
if ($this->isDate($tmppos-4)) {
list($string, $raw) = $this->createDate($numValue);
}else{
$raw = $numValue;
if (isset($this->_columnsFormat[$colFirst + $i + 1])){
$this->curformat = $this->_columnsFormat[$colFirst + $i + 1];
}
$string = sprintf($this->curformat, $numValue * $this->multiplier);
}
//$rec['rknumbers'][$i]['xfindex'] = ord($rec['data'][$pos]) | ord($rec['data'][$pos+1]) << 8;
$tmppos += 6;
$this->addcell($row, $colFirst + $i, $string, $raw);
//echo "MULRK $row ".($colFirst + $i)." $string\n";
}
//MulRKRecord($r);
// Get the individual cell records from the multiple record
//$num = ;
break;
case Spreadsheet_Excel_Reader_Type_NUMBER:
$row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
$tmp = unpack("ddouble", substr($this->data, $spos + 6, 8)); // It machine machine dependent
if ($this->isDate($spos)) {
list($string, $raw) = $this->createDate($tmp['double']);
// $this->addcell(DateRecord($r, 1));
}else{
//$raw = $tmp[''];
if (isset($this->_columnsFormat[$column + 1])){
$this->curformat = $this->_columnsFormat[$column + 1];
}
$raw = $this->createNumber($spos);
$string = sprintf($this->curformat, $raw * $this->multiplier);
// $this->addcell(NumberRecord($r));
}
$this->addcell($row, $column, $string, $raw);
//echo "Number $row $column $string\n";
break;
case Spreadsheet_Excel_Reader_Type_FORMULA:
case Spreadsheet_Excel_Reader_Type_FORMULA2:
$row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
if ((ord($this->data[$spos+6])==0) && (ord($this->data[$spos+12])==255) && (ord($this->data[$spos+13])==255)) {
//String formula. Result follows in a STRING record
//echo "FORMULA $row $column Formula with a string<br>\n";
} elseif ((ord($this->data[$spos+6])==1) && (ord($this->data[$spos+12])==255) && (ord($this->data[$spos+13])==255)) {
//Boolean formula. Result is in +2; 0=false,1=true
} elseif ((ord($this->data[$spos+6])==2) && (ord($this->data[$spos+12])==255) && (ord($this->data[$spos+13])==255)) {
//Error formula. Error code is in +2;
} elseif ((ord($this->data[$spos+6])==3) && (ord($this->data[$spos+12])==255) && (ord($this->data[$spos+13])==255)) {
//Formula result is a null string.
} else {
// result is a number, so first 14 bytes are just like a _NUMBER record
$tmp = unpack("ddouble", substr($this->data, $spos + 6, 8)); // It machine machine dependent
if ($this->isDate($spos)) {
list($string, $raw) = $this->createDate($tmp['double']);
// $this->addcell(DateRecord($r, 1));
}else{
//$raw = $tmp[''];
if (isset($this->_columnsFormat[$column + 1])){
$this->curformat = $this->_columnsFormat[$column + 1];
}
$raw = $this->createNumber($spos);
$string = sprintf($this->curformat, $raw * $this->multiplier);
// $this->addcell(NumberRecord($r));
}
$this->addcell($row, $column, $string, $raw);
//echo "Number $row $column $string\n";
}
break;
case Spreadsheet_Excel_Reader_Type_BOOLERR:
$row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
$string = ord($this->data[$spos+6]);
$this->addcell($row, $column, $string);
//echo 'Type_BOOLERR '."\n";
break;
case Spreadsheet_Excel_Reader_Type_ROW:
case Spreadsheet_Excel_Reader_Type_DBCELL:
case Spreadsheet_Excel_Reader_Type_MULBLANK:
break;
case Spreadsheet_Excel_Reader_Type_LABEL:
$row = ord($this->data[$spos]) | ord($this->data[$spos+1])<<8;
$column = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8;
$this->addcell($row, $column, substr($this->data, $spos + 8, ord($this->data[$spos + 6]) | ord($this->data[$spos + 7])<<8));
// $this->addcell(LabelRecord($r));
break;
case Spreadsheet_Excel_Reader_Type_EOF:
$cont = false;
break;
default:
//echo ' unknown :'.base_convert($r['code'],10,16)."\n";
break;
}
$spos += $length;
}
if (!isset($this->sheets[$this->sn]['numRows']))
$this->sheets[$this->sn]['numRows'] = $this->sheets[$this->sn]['maxrow'];
if (!isset($this->sheets[$this->sn]['numCols']))
$this->sheets[$this->sn]['numCols'] = $this->sheets[$this->sn]['maxcol'];
}
function isDate($spos){
//$xfindex = GetInt2d(, 4);
$xfindex = ord($this->data[$spos+4]) | ord($this->data[$spos+5]) << 8;
//echo 'check is date '.$xfindex.' '.$this->formatRecords['xfrecords'][$xfindex]['type']."\n";
//var_dump($this->formatRecords['xfrecords'][$xfindex]);
if ($this->formatRecords['xfrecords'][$xfindex]['type'] == 'date') {
$this->curformat = $this->formatRecords['xfrecords'][$xfindex]['format'];
$this->rectype = 'date';
return true;
} else {
if ($this->formatRecords['xfrecords'][$xfindex]['type'] == 'number') {
$this->curformat = $this->formatRecords['xfrecords'][$xfindex]['format'];
$this->rectype = 'number';
if (($xfindex == 0x9) || ($xfindex == 0xa)){
$this->multiplier = 100;
}
}else{
$this->curformat = $this->_defaultFormat;
$this->rectype = 'unknown';
}
return false;
}
}
function createDate($numValue){
if ($numValue > 1){
$utcDays = $numValue - ($this->nineteenFour ? Spreadsheet_Excel_Reader_utcOffsetDays1904 : Spreadsheet_Excel_Reader_utcOffsetDays);
$utcValue = round($utcDays * Spreadsheet_Excel_Reader_msInADay);
$string = date ($this->curformat, $utcValue);
$raw = $utcValue;
}else{
$raw = $numValue;
$hours = floor($numValue * 24);
$mins = floor($numValue * 24 * 60) - $hours * 60;
$secs = floor($numValue * Spreadsheet_Excel_Reader_msInADay) - $hours * 60 * 60 - $mins * 60;
$string = date ($this->curformat, mktime($hours, $mins, $secs));
}
return array($string, $raw);
}
function createNumber($spos){
$rknumhigh = $this->_GetInt4d($this->data, $spos + 10);
$rknumlow = $this->_GetInt4d($this->data, $spos + 6);
//for ($i=0; $i<8; $i++) { echo ord($this->data[$i+$spos+6]) . " "; } echo "<br>";
$sign = ($rknumhigh & 0x80000000) >> 31;
$exp = ($rknumhigh & 0x7ff00000) >> 20;
$mantissa = (0x100000 | ($rknumhigh & 0x000fffff));
$mantissalow1 = ($rknumlow & 0x80000000) >> 31;
$mantissalow2 = ($rknumlow & 0x7fffffff);
$value = $mantissa / pow( 2 , (20- ($exp - 1023)));
if ($mantissalow1 != 0) $value += 1 / pow (2 , (21 - ($exp - 1023)));
$value += $mantissalow2 / pow (2 , (52 - ($exp - 1023)));
//echo "Sign = $sign, Exp = $exp, mantissahighx = $mantissa, mantissalow1 = $mantissalow1, mantissalow2 = $mantissalow2<br>\n";
if ($sign) {$value = -1 * $value;}
return $value;
}
function addcell($row, $col, $string, $raw = ''){
//echo "ADD cel $row-$col $string\n";
$this->sheets[$this->sn]['maxrow'] = max($this->sheets[$this->sn]['maxrow'], $row + $this->_rowoffset);
$this->sheets[$this->sn]['maxcol'] = max($this->sheets[$this->sn]['maxcol'], $col + $this->_coloffset);
$this->sheets[$this->sn]['cells'][$row + $this->_rowoffset][$col + $this->_coloffset] = $string;
if ($raw)
$this->sheets[$this->sn]['cellsInfo'][$row + $this->_rowoffset][$col + $this->_coloffset]['raw'] = $raw;
if (isset($this->rectype))
$this->sheets[$this->sn]['cellsInfo'][$row + $this->_rowoffset][$col + $this->_coloffset]['type'] = $this->rectype;
}
function _GetIEEE754($rknum){
if (($rknum & 0x02) != 0) {
$value = $rknum >> 2;
} else {
//mmp
// first comment out the previously existing 7 lines of code here
// $tmp = unpack("d", pack("VV", 0, ($rknum & 0xfffffffc)));
// //$value = $tmp[''];
// if (array_key_exists(1, $tmp)) {
// $value = $tmp[1];
// } else {
// $value = $tmp[''];
// }
// I got my info on IEEE754 encoding from
// http://research.microsoft.com/~hollasch/cgindex/coding/ieeefloat.html
// The RK format calls for using only the most significant 30 bits of the
// 64 bit floating point value. The other 34 bits are assumed to be 0
// So, we use the upper 30 bits of $rknum as follows...
$sign = ($rknum & 0x80000000) >> 31;
$exp = ($rknum & 0x7ff00000) >> 20;
$mantissa = (0x100000 | ($rknum & 0x000ffffc));
$value = $mantissa / pow( 2 , (20- ($exp - 1023)));
if ($sign) {$value = -1 * $value;}
//end of changes by mmp
}
if (($rknum & 0x01) != 0) {
$value /= 100;
}
return $value;
}
function _encodeUTF16($string){
$result = $string;
if ($this->_defaultEncoding){
switch ($this->_encoderFunction){
case 'iconv' : $result = iconv('UTF-16LE', $this->_defaultEncoding, $string);
break;
case 'mb_convert_encoding' : $result = mb_convert_encoding($string, $this->_defaultEncoding, 'UTF-16LE' );
break;
}
}
return $result;
}
function _GetInt4d($data, $pos) {
$value = ord($data[$pos]) | (ord($data[$pos+1]) << 8) | (ord($data[$pos+2]) << 16) | (ord($data[$pos+3]) << 24);
if ($value>=4294967294) {
$value=-2;
}
if ($value >= 4000000000 && $value < 4294967294) // Add these lines
{
$value = -2 - 4294967294 + $value;
} // End add lines
return $value;
}
}
?>
| 4n6g4/gtsdm | malra/gtfw_base3.2/main/lib/ExcelReader/reader.php | PHP | gpl-3.0 | 41,610 |
<?php
/** ---------------------------------------------------------------------
* app/helpers/htmlFormHelpers.php : miscellaneous functions
* ----------------------------------------------------------------------
* CollectiveAccess
* Open-source collections management software
* ----------------------------------------------------------------------
*
* Software by Whirl-i-Gig (http://www.whirl-i-gig.com)
* Copyright 2008-2019 Whirl-i-Gig
*
* For more information visit http://www.CollectiveAccess.org
*
* This program is free software; you may redistribute it and/or modify it under
* the terms of the provided license as published by Whirl-i-Gig
*
* CollectiveAccess is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* This source code is free and modifiable under the terms of
* GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See
* the "license.txt" file for details, or visit the CollectiveAccess web site at
* http://www.CollectiveAccess.org
*
* @package CollectiveAccess
* @subpackage utils
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License version 3
*
* ----------------------------------------------------------------------
*/
/**
*
*/
# ------------------------------------------------------------------------------------------------
/**
* Creates an HTML <select> form element
*
* @param string $ps_name Name of the element
* @param array $pa_content Associative array with keys as display options and values as option values. If the 'contentArrayUsesKeysForValues' is set then keys use interpreted as option values and values as display options.
* @param array $pa_attributes Optional associative array of <select> tag options; keys are attribute names and values are attribute values
* @param array $pa_options Optional associative array of options. Valid options are:
* value = the default value of the element
* values = an array of values for the element, when the <select> allows multiple selections
* disabledOptions = an associative array indicating whether options are disabled or not; keys are option *values*, values are boolean (true=disabled; false=enabled)
* contentArrayUsesKeysForValues = normally the keys of the $pa_content array are used as display options and the values as option values. Setting 'contentArrayUsesKeysForValues' to true will reverse the interpretation, using keys as option values.
* useOptionsForValues = set values to be the same as option text. [Default is false]
* width = width of select in characters or pixels. If specifying pixels use "px" as the units (eg. 100px)
* colors =
* @return string HTML code representing the drop-down list
*/
function caHTMLSelect($ps_name, $pa_content, $pa_attributes=null, $pa_options=null) {
if (!is_array($pa_content)) { $pa_content = array(); }
if (is_array($va_dim = caParseFormElementDimension(isset($pa_options['width']) ? $pa_options['width'] : null))) {
if ($va_dim['type'] == 'pixels') {
$pa_attributes['style'] = "width: ".$va_dim['dimension']."px; ".$pa_attributes['style'];
} else {
// Approximate character width using 1 character = 6 pixels of width
$pa_attributes['style'] = "width: ".($va_dim['dimension'] * 6)."px; ".$pa_attributes['style'];
}
}
if (is_array($va_dim = caParseFormElementDimension(isset($pa_options['height']) ? $pa_options['height'] : null))) {
if ($va_dim['type'] == 'pixels') {
$pa_attributes['style'] = "height: ".$va_dim['dimension']."px; ".$pa_attributes['style'];
} else {
// Approximate character width using 1 character = 6 pixels of width
$pa_attributes['size'] = $va_dim['dimension'];
}
}
$vs_attr_string = _caHTMLMakeAttributeString($pa_attributes, $pa_options);
$vs_element = "<select name='{$ps_name}' {$vs_attr_string}>\n";
$vs_selected_val = isset($pa_options['value']) ? $pa_options['value'] : null;
if (is_array($pa_options['values']) && $vs_selected_val) { $vs_selected_val = null; }
$va_selected_vals = isset($pa_options['values']) ? $pa_options['values'] : array();
$va_disabled_options = isset($pa_options['disabledOptions']) ? $pa_options['disabledOptions'] : array();
$vb_content_is_list = caIsIndexedArray($pa_content);
$va_colors = array();
if (isset($pa_options['colors']) && is_array($pa_options['colors'])) {
$va_colors = $pa_options['colors'];
}
$vb_use_options_for_values = caGetOption('useOptionsForValues', $pa_options, false);
$vb_uses_color = false;
if (isset($pa_options['contentArrayUsesKeysForValues']) && $pa_options['contentArrayUsesKeysForValues']) {
foreach($pa_content as $vs_val => $vs_opt) {
if ($vb_use_options_for_values) { $vs_val = preg_replace("!^[\s]+!", "", preg_replace("![\s]+$!", "", str_replace(" ", "", $vs_opt))); }
if ($COLOR = ($vs_color = $va_colors[$vs_val]) ? " data-color='#{$vs_color}'" : '') { $vb_uses_color = true; }
if (is_null($vs_selected_val) || !($SELECTED = (((string)$vs_selected_val === (string)$vs_val) && strlen($vs_selected_val)) ? ' selected="1"' : '')) {
$SELECTED = (is_array($va_selected_vals) && in_array($vs_val, $va_selected_vals)) ? ' selected="1"' : '';
}
$DISABLED = (isset($va_disabled_options[$vs_val]) && $va_disabled_options[$vs_val]) ? ' disabled="1"' : '';
$vs_element .= "<option value='".htmlspecialchars($vs_val, ENT_QUOTES, 'UTF-8')."'{$SELECTED}{$DISABLED}{$COLOR}>".$vs_opt."</option>\n";
}
} else {
if ($vb_content_is_list) {
foreach($pa_content as $vs_val) {
if ($COLOR = ($vs_color = $va_colors[$vs_val]) ? " data-color='#{$vs_color}'" : '') { $vb_uses_color = true; }
if (is_null($vs_selected_val) || !($SELECTED = ((string)$vs_selected_val === (string)$vs_val) ? ' selected="1"' : '')) {
$SELECTED = (is_array($va_selected_vals) && in_array($vs_val, $va_selected_vals)) ? ' selected="1"' : '';
}
$DISABLED = (isset($va_disabled_options[$vs_val]) && $va_disabled_options[$vs_val]) ? ' disabled="1"' : '';
$vs_element .= "<option value='".htmlspecialchars($vs_val, ENT_QUOTES, 'UTF-8')."'{$SELECTED}{$DISABLED}{$COLOR}>".$vs_val."</option>\n";
}
} else {
foreach($pa_content as $vs_opt => $vs_val) {
if ($vb_use_options_for_values) { $vs_val = preg_replace("!^[\s]+!", "", preg_replace("![\s]+$!", "", str_replace(" ", "", $vs_opt))); }
if ($COLOR = ($vs_color = $va_colors[$vs_val]) ? " data-color='#{$vs_color}'" : '') { $vb_uses_color = true; }
if (is_null($vs_selected_val) || !($SELECTED = ((string)$vs_selected_val === (string)$vs_val) ? ' selected="1"' : '')) {
$SELECTED = (is_array($va_selected_vals) && in_array($vs_val, $va_selected_vals)) ? ' selected="1"' : '';
}
$DISABLED = (isset($va_disabled_options[$vs_val]) && $va_disabled_options[$vs_val]) ? ' disabled="1"' : '';
$vs_element .= "<option value='".htmlspecialchars($vs_val, ENT_QUOTES, 'UTF-8')."'{$SELECTED}{$DISABLED}{$COLOR}>".$vs_opt."</option>\n";
}
}
}
$vs_element .= "</select>\n";
if ($vb_uses_color && isset($pa_attributes['id']) && $pa_attributes['id']) {
$vs_element .= "<script type='text/javascript'>jQuery(document).ready(function() { var f; jQuery('#".$pa_attributes['id']."').on('change', f=function() { var c = jQuery('#".$pa_attributes['id']."').find('option:selected').data('color'); jQuery('#".$pa_attributes['id']."').css('background-color', c ? c : '#fff'); return false;}); f(); });</script>";
}
return $vs_element;
}
# ------------------------------------------------------------------------------------------------
/**
* Render an HTML text form element (<input type="text"> or <textarea> depending upon height).
*
* @param string $ps_name The name of the rendered form element
* @param array $pa_attributes An array of attributes to include in the rendered HTML form element. If you need to set class, id, alt or other attributes, set them here.
* @param array Options include:
* width = Width of element in pixels (number with "px" suffix) or characters (number with no suffix) [Default is null]
* height = Height of element in pixels (number with "px" suffix) or characters (number with no suffix) [Default is null]
* usewysiwygeditor = Use rich text editor (CKEditor) for text element. Only available when the height of the text element is multi-line. [Default is false]
* cktoolbar = app.conf directive name to pull CKEditor toolbar spec from. [Default is wysiwyg_editor_toolbar]
* contentUrl = URL to use to load content when CKEditor is use with CA-specific plugins. [Default is null]
* textAreaTagName =
* @return string
*/
function caHTMLTextInput($ps_name, $pa_attributes=null, $pa_options=null) {
$vb_is_textarea = false;
$va_styles = array();
$vb_use_wysiwyg_editor = caGetOption('usewysiwygeditor', $pa_options, false);
$vn_width = $vn_height = null;
if (is_array($va_dim = caParseFormElementDimension(
(isset($pa_options['width']) ? $pa_options['width'] :
(isset($pa_attributes['size']) ? $pa_attributes['size'] :
(isset($pa_attributes['width']) ? $pa_attributes['width'] : null)
)
)
))) {
if ($va_dim['type'] == 'pixels') {
$va_styles[] = "width: ".($vn_width = $va_dim['dimension'])."px;";
unset($pa_attributes['width']);
unset($pa_attributes['size']);
unset($pa_attributes['cols']);
} else {
// width is in characters
$pa_attributes['size'] = $va_dim['dimension'];
$vn_width = $va_dim['dimension'] * 6;
}
}
if (!$vn_width) $vn_width = 300;
if (is_array($va_dim = caParseFormElementDimension(
(isset($pa_options['height']) ? $pa_options['height'] :
(isset($pa_attributes['height']) ? $pa_attributes['height'] : null)
)
))) {
if ($va_dim['type'] == 'pixels') {
$va_styles[] = "height: ".($vn_height = $va_dim['dimension'])."px;";
unset($pa_attributes['height']);
unset($pa_attributes['rows']);
$vb_is_textarea = true;
} else {
// height is in characters
if (($pa_attributes['rows'] = $va_dim['dimension']) > 1) {
$vb_is_textarea = true;
}
$vn_height = $va_dim['dimension'] * 12;
}
} else {
if (($pa_attributes['rows'] = (isset($pa_attributes['height']) && $pa_attributes['height']) ? $pa_attributes['height'] : 1) > 1) {
$vb_is_textarea = true;
}
}
if (!$vn_height) $vn_height = 300;
$pa_attributes['style'] = join(" ", $va_styles);
// WYSIWYG editor requires an DOM ID so generate one if none is explicitly set
if ($vb_use_wysiwyg_editor && !isset($pa_attributes['id'])) {
$pa_attributes['id'] = "{$ps_name}_element";
}
if ($vb_is_textarea) {
$tag_name = caGetOption('textAreaTagName', $pa_options, 'textarea');
$vs_value = $pa_attributes['value'];
if ($pa_attributes['size']) { $pa_attributes['cols'] = $pa_attributes['size']; }
unset($pa_attributes['size']);
unset($pa_attributes['value']);
$vs_attr_string = _caHTMLMakeAttributeString($pa_attributes, $pa_options);
$vs_element = "<{$tag_name} name='{$ps_name}' wrap='soft' {$vs_attr_string}>".$vs_value."</{$tag_name}>\n";
} else {
$pa_attributes['size'] = !$pa_attributes['size'] ? $pa_attributes['width'] : $pa_attributes['size'];
$vs_attr_string = _caHTMLMakeAttributeString($pa_attributes, $pa_options);
$vs_element = "<input name='{$ps_name}' {$vs_attr_string} type='text'/>\n";
}
if ($vb_use_wysiwyg_editor) {
AssetLoadManager::register("ckeditor");
$o_config = Configuration::load();
if(!is_array($va_toolbar_config = $o_config->getAssoc(caGetOption('cktoolbar', $pa_options, 'wysiwyg_editor_toolbar')))) { $va_toolbar_config = []; }
$vs_content_url = caGetOption('contentUrl', $pa_options, '');
$va_lookup_urls = caGetOption('lookupUrls', $pa_options, null);
$vs_element .= "<script type='text/javascript'>jQuery(document).ready(function() {
var ckEditor = CKEDITOR.replace( '".$pa_attributes['id']."',
{
toolbar : ".json_encode(array_values($va_toolbar_config)).",
width: '{$vn_width}px',
height: '{$vn_height}px',
toolbarLocation: 'top',
enterMode: CKEDITOR.ENTER_BR,
contentUrl: '{$vs_content_url}',
lookupUrls: ".json_encode($va_lookup_urls)."
});
ckEditor.on('instanceReady', function(){
ckEditor.document.on( 'keydown', function(e) {if (caUI && caUI.utils) { caUI.utils.showUnsavedChangesWarning(true); } });
});
});
</script>";
}
return $vs_element;
}
# ------------------------------------------------------------------------------------------------
function caHTMLHiddenInput($ps_name, $pa_attributes=null, $pa_options=null) {
$vs_attr_string = _caHTMLMakeAttributeString($pa_attributes, $pa_options);
$vs_element = "<input name='{$ps_name}' {$vs_attr_string} type='hidden'/>\n";
return $vs_element;
}
# ------------------------------------------------------------------------------------------------
/**
* Creates set of radio buttons
*
* $ps_name - name of the element
* $pa_content - associative array with keys as display options and values as option values
* $pa_attributes - optional associative array of <input> tag options applied to each radio button; keys are attribute names and values are attribute values
* $pa_options - optional associative array of options. Valid options are:
* value = the default value of the element
* disabledOptions = an associative array indicating whether options are disabled or not; keys are option *values*, values are boolean (true=disabled; false=enabled)
*/
function caHTMLRadioButtonsInput($ps_name, $pa_content, $pa_attributes=null, $pa_options=null) {
$vs_attr_string = _caHTMLMakeAttributeString($pa_attributes, $pa_options);
$vs_selected_val = isset($pa_options['value']) ? $pa_options['value'] : null;
$va_disabled_options = isset($pa_options['disabledOptions']) ? $pa_options['disabledOptions'] : array();
$vb_content_is_list = (array_key_exists(0, $pa_content)) ? true : false;
$vs_id = isset($pa_attributes['id']) ? $pa_attributes['id'] : null;
unset($pa_attributes['id']);
$vn_i = 0;
if ($vb_content_is_list) {
foreach($pa_content as $vs_val) {
$vs_id_attr = ($vs_id) ? 'id="'.$vs_id.'_'.$vn_i.'"' : '';
$SELECTED = ($vs_selected_val == $vs_val) ? ' selected="1"' : '';
$DISABLED = (isset($va_disabled_options[$vs_val]) && $va_disabled_options[$vs_val]) ? ' disabled="1"' : '';
$vs_element .= "<input type='radio' name='{$ps_name}' {$vs_id_attr} value='".htmlspecialchars($vs_val, ENT_QUOTES, 'UTF-8')."'{$SELECTED}{$DISABLED}> ".$vs_val."\n";
$vn_i++;
}
} else {
foreach($pa_content as $vs_opt => $vs_val) {
$vs_id_attr = ($vs_id) ? 'id="'.$vs_id.'_'.$vn_i.'"' : '';
$SELECTED = ($vs_selected_val == $vs_val) ? ' selected="1"' : '';
$DISABLED = (isset($va_disabled_options[$vs_val]) && $va_disabled_options[$vs_val]) ? ' disabled="1"' : '';
$vs_element .= "<input type='radio' name='{$ps_name}' {$vs_id_attr} value='".htmlspecialchars($vs_val, ENT_QUOTES, 'UTF-8')."'{$SELECTED}{$DISABLED}> ".$vs_opt."\n";
$vn_i++;
}
}
return $vs_element;
}
# ------------------------------------------------------------------------------------------------
/**
* Create a single radio button
*
* $ps_name - name of the element
* $pa_attributes - optional associative array of <input> tag options applied to the radio button; keys are attribute names and values are attribute values
* $pa_options - optional associative array of options. Valid options are:
* checked = if true, value will be selected by default
* disabled = boolean indicating if radio button is enabled or not (true=disabled; false=enabled)
*/
function caHTMLRadioButtonInput($ps_name, $pa_attributes=null, $pa_options=null) {
if(caGetOption('checked', $pa_options, false)) { $pa_attributes['checked'] = 1; }
if(caGetOption('disabled', $pa_options, false)) { $pa_attributes['disabled'] = 1; }
$vs_attr_string = _caHTMLMakeAttributeString($pa_attributes);
// standard check box
$vs_element = "<input name='{$ps_name}' {$vs_attr_string} type='radio'/>\n";
return $vs_element;
}
# ------------------------------------------------------------------------------------------------
/**
* Creates a checkbox
*
* $ps_name - name of the element
* $pa_attributes - optional associative array of <input> tag options applied to the checkbox; keys are attribute names and values are attribute values
* $pa_options - optional associative array of options. Valid options are:
* value = the default value of the element
* disabled = boolean indicating if checkbox is enabled or not (true=disabled; false=enabled)
* returnValueIfUnchecked = boolean indicating if checkbox should return value in request if unchecked; default is false
*/
function caHTMLCheckboxInput($ps_name, $pa_attributes=null, $pa_options=null) {
if (array_key_exists('checked', $pa_attributes) && !$pa_attributes['checked']) { unset($pa_attributes['checked']); }
if (array_key_exists('CHECKED', $pa_attributes) && !$pa_attributes['CHECKED']) { unset($pa_attributes['CHECKED']); }
if(caGetOption('disabled', $pa_options, false)) { $pa_attributes['disabled'] = 1; }
$vs_attr_string = _caHTMLMakeAttributeString($pa_attributes, $pa_options);
if (isset($pa_options['returnValueIfUnchecked']) && $pa_options['returnValueIfUnchecked']) {
// javascript-y check box that returns form value even if unchecked
$vs_element = "<input name='{$ps_name}' {$vs_attr_string} type='checkbox'/>\n";
unset($pa_attributes['id']);
$pa_attributes['value'] = $pa_options['returnValueIfUnchecked'];
$vs_attr_string = _caHTMLMakeAttributeString($pa_attributes, $pa_options);
$vs_element = "<input name='{$ps_name}' {$vs_attr_string} type='hidden'/>\n". $vs_element;
} else {
// standard check box
$vs_element = "<input name='{$ps_name}' {$vs_attr_string} type='checkbox'/>\n";
}
return $vs_element;
}
# ------------------------------------------------------------------------------------------------
function caHTMLLink($ps_content, $pa_attributes=null, $pa_options=null) {
$vs_attr_string = _caHTMLMakeAttributeString($pa_attributes, $pa_options);
$vs_element = "<a {$vs_attr_string}>{$ps_content}</a>";
return $vs_element;
}
# ------------------------------------------------------------------------------------------------
/**
* Generates an HTML <img> or Tilepic embed tag with supplied URL and attributes
*
* @param $ps_url string The image URL
* @param $pa_options array Options include:
* scaleCSSWidthTo = width in pixels to *style* via CSS the returned image to. Does not actually alter the image. Aspect ratio of the image is preserved, with the combination of scaleCSSWidthTo and scaleCSSHeightTo being taken as a bounding box for the image. Only applicable to standard <img> tags. Tilepic display size cannot be styled using CSS; use the "width" and "height" options instead.
* scaleCSSHeightTo = height in pixels to *style* via CSS the returned image to.
*
* @return string
*/
function caHTMLImage($ps_url, $pa_options=null) {
if (!is_array($pa_options)) { $pa_options = array(); }
$va_attributes = array('src' => $ps_url);
foreach(array('name', 'id',
'width', 'height',
'vspace', 'hspace', 'alt', 'title', 'usemap', 'align', 'border', 'class', 'style') as $vs_attr) {
if (isset($pa_options[$vs_attr])) { $va_attributes[$vs_attr] = $pa_options[$vs_attr]; }
}
// Allow data-* attributes
foreach($pa_options as $vs_k => $vs_v) {
if (substr($vs_k, 0, 5) == 'data-') { $va_attributes[$vs_k] = $vs_v; }
}
$vn_scale_css_width_to = caGetOption('scaleCSSWidthTo', $pa_options, null);
$vn_scale_css_height_to = caGetOption('scaleCSSHeightTo', $pa_options, null);
if ($vn_scale_css_width_to || $vn_scale_css_height_to) {
if (!$vn_scale_css_width_to) { $vn_scale_css_width_to = $vn_scale_css_height_to; }
if (!$vn_scale_css_height_to) { $vn_scale_css_height_to = $vn_scale_css_width_to; }
$va_scaled_dimensions = caFitImageDimensions($va_attributes['width'], $va_attributes['height'], $vn_scale_css_width_to, $vn_scale_css_height_to);
$va_attributes['width'] = $va_scaled_dimensions['width'].'px';
$va_attributes['height'] = $va_scaled_dimensions['height'].'px';
}
$vs_attr_string = _caHTMLMakeAttributeString($va_attributes, $pa_options);
if(preg_match("/\.tpc\$/", $ps_url)) {
#
# Tilepic
#
$vn_width = (int)$pa_options["width"];
$vn_height = (int)$pa_options["height"];
$vn_tile_width = caGetOption('tile_width', $pa_options, 256, array('castTo'=>'int'));
$vn_tile_height = caGetOption('tile_height', $pa_options, 256, array('castTo'=>'int'));
// Tiles must be square.
if ($vn_tile_width != $vn_tile_height){
$vn_tile_height = $vn_tile_width;
}
$vn_layers = (int)$pa_options["layers"];
if (!($vs_id_name = (string)$pa_options["idname"])) {
$vs_id_name = (string)$pa_options["id"];
}
$vn_viewer_width = $pa_options["viewer_width"];
$vn_viewer_height = $pa_options["viewer_height"];
$vs_annotation_load_url = caGetOption("annotation_load_url", $pa_options, null);
$vs_annotation_save_url = caGetOption("annotation_save_url", $pa_options, null);
$vs_help_load_url = caGetOption("help_load_url", $pa_options, null);
$vb_read_only = caGetOption("read_only", $pa_options, null);
$vs_annotation_editor_panel = caGetOption("annotationEditorPanel", $pa_options, null);
$vs_annotation_editor_url = caGetOption("annotationEditorUrl", $pa_options, null);
$vs_viewer_base_url = caGetOption("viewer_base_url", $pa_options, __CA_URL_ROOT__);
$o_config = Configuration::load();
if (!$vn_viewer_width || !$vn_viewer_height) {
$vn_viewer_width = (int)$o_config->get("tilepic_viewer_width");
if (!$vn_viewer_width) { $vn_viewer_width = 500; }
$vn_viewer_height = (int)$o_config->get("tilepic_viewer_height");
if (!$vn_viewer_height) { $vn_viewer_height = 500; }
}
$vs_error_tag = caGetOption("alt_image_tag", $pa_options, '');
$vn_viewer_width_with_units = $vn_viewer_width;
$vn_viewer_height_with_units = $vn_viewer_height;
if (preg_match('!^[\d]+$!', $vn_viewer_width)) { $vn_viewer_width_with_units .= 'px'; }
if (preg_match('!^[\d]+$!', $vn_viewer_height)) { $vn_viewer_height_with_units .= 'px'; }
if(!is_array($va_viewer_opts_from_app_config = $o_config->getAssoc('image_viewer_options'))) { $va_viewer_opts_from_app_config = array(); }
$va_opts = array_merge(array(
'id' => "{$vs_id_name}_viewer",
'src' => "{$vs_viewer_base_url}/viewers/apps/tilepic.php?p={$ps_url}&t=",
'annotationLoadUrl' => $vs_annotation_load_url,
'annotationSaveUrl' => $vs_annotation_save_url,
'annotationEditorPanel' => $vs_annotation_editor_panel,
'annotationEditorUrl' => $vs_annotation_editor_url,
'annotationEditorLink' => _t('More...'),
'helpLoadUrl' => $vs_help_load_url,
'lockAnnotations' => ($vb_read_only ? true : false),
'showAnnotationTools' => ($vb_read_only ? false : true)
), $va_viewer_opts_from_app_config);
$va_opts['info'] = array(
'width' => $vn_width,
'height' => $vn_height,
// Set tile size using function options.
'tilesize'=> $vn_tile_width,
'levels' => $vn_layers
);
$vs_tag = "
<div id='{$vs_id_name}' style='width:{$vn_viewer_width_with_units}; height: {$vn_viewer_height_with_units}; position: relative; z-index: 0;'>
{$vs_error_tag}
</div>
<script type='text/javascript'>
var elem = document.createElement('canvas');
if (elem.getContext && elem.getContext('2d')) {
jQuery(document).ready(function() {
jQuery('#{$vs_id_name}').tileviewer(".json_encode($va_opts).");
});
}
</script>\n";
return $vs_tag;
} else {
#
# Standard image
#
if (!isset($pa_options["width"])) $pa_options["width"] = 100;
if (!isset($pa_options["height"])) $pa_options["height"] = 100;
if (($ps_url) && ($pa_options["width"] > 0) && ($pa_options["height"] > 0)) {
$vs_element = "<img {$vs_attr_string} />";
} else {
$vs_element = "";
}
}
return $vs_element;
}
# ------------------------------------------------------------------------------------------------
/**
* Create string for use in HTML tags out of attribute array.
*
* @param array $pa_attributes
* @param array $pa_options Optional array of options. Supported options are:
* dontConvertAttributeQuotesToEntities = if true, attribute values are not passed through htmlspecialchars(); if you set this be sure to only use single quotes in your attribute values or escape all double quotes since double quotes are used to enclose tem
*/
function _caHTMLMakeAttributeString($pa_attributes, $pa_options=null) {
$va_attr_settings = array();
if (is_array($pa_attributes)) {
foreach($pa_attributes as $vs_attr => $vs_attr_val) {
if (is_array($vs_attr_val)) { $vs_attr_val = join(" ", $vs_attr_val); }
if (is_object($vs_attr_val)) { continue; }
if (isset($pa_options['dontConvertAttributeQuotesToEntities']) && $pa_options['dontConvertAttributeQuotesToEntities']) {
$va_attr_settings[] = $vs_attr.'="'.$vs_attr_val.'"';
} else {
$va_attr_settings[] = $vs_attr.'=\''.htmlspecialchars($vs_attr_val, ENT_QUOTES, 'UTF-8').'\'';
}
}
}
return join(' ', $va_attr_settings);
}
# ------------------------------------------------------------------------------------------------
/**
* Takes an HTML form field ($ps_field), a text label ($ps_table), and DOM ID to wrap the label in ($ps_id)
* and a block of help/descriptive text ($ps_description) and returns a formatted block of HTML with
* a jQuery-based tool tip attached. Formatting is performed using the format defined in app.conf
* by the 'form_element_display_format' config directive unless overridden by a format passed in
* the optional $ps_format parameter.
*
* Note that $ps_description is also optional. If it is omitted or passed blank then no tooltip is attached
*/
function caHTMLMakeLabeledFormElement($ps_field, $ps_label, $ps_id, $ps_description='', $ps_format='', $pb_emit_tooltip=true) {
$o_config = Configuration::load();
if (!$ps_format) {
$ps_format = $o_config->get('form_element_display_format');
}
$vs_formatted_element = str_replace("^LABEL",'<span id="'.$ps_id.'">'.$ps_label.'</span>', $ps_format);
$vs_formatted_element = str_replace("^ELEMENT", $ps_field, $vs_formatted_element);
$vs_formatted_element = str_replace("^EXTRA", '', $vs_formatted_element);
if ($ps_description && $pb_emit_tooltip) {
TooltipManager::add('#'.$ps_id, "<h3>{$ps_label}</h3>{$ps_description}");
}
return $vs_formatted_element;
}
# ------------------------------------------------------------------------------------------------
| collectiveaccess/providence | app/helpers/htmlFormHelpers.php | PHP | gpl-3.0 | 27,259 |
/*
* This file is part of EasyRPG Player.
*
* EasyRPG Player 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.
*
* EasyRPG Player 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 EasyRPG Player. If not, see <http://www.gnu.org/licenses/>.
*/
// Headers
#include "audio.h"
#include "system.h"
#include "baseui.h"
AudioInterface& Audio() {
static EmptyAudio default_;
return DisplayUi? DisplayUi->GetAudio() : default_;
}
| Lobomon/Player-for-QT | src/audio.cpp | C++ | gpl-3.0 | 882 |
"""Add timetable related tables
Revision ID: 33a1d6f25951
Revises: 225d0750c216
Create Date: 2015-11-25 14:05:51.856236
"""
import sqlalchemy as sa
from alembic import op
from indico.core.db.sqlalchemy import PyIntEnum, UTCDateTime
from indico.modules.events.timetable.models.entries import TimetableEntryType
# revision identifiers, used by Alembic.
revision = '33a1d6f25951'
down_revision = '225d0750c216'
def upgrade():
# Break
op.create_table(
'breaks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(), nullable=False),
sa.Column('description', sa.Text(), nullable=False),
sa.Column('duration', sa.Interval(), nullable=False),
sa.Column('text_color', sa.String(), nullable=False),
sa.Column('background_color', sa.String(), nullable=False),
sa.Column('room_name', sa.String(), nullable=False),
sa.Column('inherit_location', sa.Boolean(), nullable=False),
sa.Column('address', sa.Text(), nullable=False),
sa.Column('venue_id', sa.Integer(), nullable=True, index=True),
sa.Column('venue_name', sa.String(), nullable=False),
sa.Column('room_id', sa.Integer(), nullable=True, index=True),
sa.CheckConstraint("(room_id IS NULL) OR (venue_name = '' AND room_name = '')",
name='no_custom_location_if_room'),
sa.CheckConstraint("(venue_id IS NULL) OR (venue_name = '')", name='no_venue_name_if_venue_id'),
sa.CheckConstraint("(room_id IS NULL) OR (venue_id IS NOT NULL)", name='venue_id_if_room_id'),
sa.CheckConstraint("NOT inherit_location OR (venue_id IS NULL AND room_id IS NULL AND venue_name = '' AND "
"room_name = '' AND address = '')", name='inherited_location'),
sa.CheckConstraint("(text_color = '') = (background_color = '')", name='both_or_no_colors'),
sa.CheckConstraint("text_color != '' AND background_color != ''", name='colors_not_empty'),
sa.ForeignKeyConstraint(['room_id'], ['roombooking.rooms.id']),
sa.ForeignKeyConstraint(['venue_id'], ['roombooking.locations.id']),
sa.ForeignKeyConstraint(['venue_id', 'room_id'], ['roombooking.rooms.location_id', 'roombooking.rooms.id']),
sa.PrimaryKeyConstraint('id'),
schema='events'
)
# TimetableEntry
op.create_table(
'timetable_entries',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('event_id', sa.Integer(), nullable=False, index=True),
sa.Column('parent_id', sa.Integer(), nullable=True, index=True),
sa.Column('session_block_id', sa.Integer(), nullable=True, index=True, unique=True),
sa.Column('contribution_id', sa.Integer(), nullable=True, index=True, unique=True),
sa.Column('break_id', sa.Integer(), nullable=True, index=True, unique=True),
sa.Column('type', PyIntEnum(TimetableEntryType), nullable=False),
sa.Column('start_dt', UTCDateTime, nullable=False),
sa.Index('ix_timetable_entries_start_dt_desc', sa.text('start_dt DESC')),
sa.CheckConstraint('type != 1 OR parent_id IS NULL', name='valid_parent'),
sa.CheckConstraint('type != 1 OR (contribution_id IS NULL AND break_id IS NULL AND '
'session_block_id IS NOT NULL)', name='valid_session_block'),
sa.CheckConstraint('type != 2 OR (session_block_id IS NULL AND break_id IS NULL AND '
'contribution_id IS NOT NULL)', name='valid_contribution'),
sa.CheckConstraint('type != 3 OR (contribution_id IS NULL AND session_block_id IS NULL AND '
'break_id IS NOT NULL)', name='valid_break'),
sa.ForeignKeyConstraint(['break_id'], ['events.breaks.id']),
sa.ForeignKeyConstraint(['contribution_id'], ['events.contributions.id']),
sa.ForeignKeyConstraint(['event_id'], ['events.events.id']),
sa.ForeignKeyConstraint(['parent_id'], ['events.timetable_entries.id']),
sa.ForeignKeyConstraint(['session_block_id'], ['events.session_blocks.id']),
sa.PrimaryKeyConstraint('id'),
schema='events'
)
def downgrade():
op.drop_table('timetable_entries', schema='events')
op.drop_table('breaks', schema='events')
| belokop/indico_bare | migrations/versions/201511251405_33a1d6f25951_add_timetable_related_tables.py | Python | gpl-3.0 | 4,295 |
module ComboFieldTagHelper
def combo_field_tag(name, value, option_tags = nil, options = {})
select_placeholder = options[:select_placeholder] || "Select existing value"
input_placeholder = options[:input_placeholder] || "Enter new value"
id = options[:id]
klass = options[:class] || 'combo-field'
required = options[:required]
help = options[:help]
unless options[:label] == false
label_html = label_tag(options[:label] || name, nil, class: "#{'required' if required}")
end
select_options = {
prompt: '',
class: "#{klass} form-control #{'required' if required}",
data: { placeholder: select_placeholder }
}
select_options[:id] = "#{id}_select" if id.present?
select_html = select_tag name, option_tags, select_options
text_field_options = {
class: "form-control",
placeholder: input_placeholder
}
text_field_options[:id] = "#{id}_text" if id.present?
text_field_html = text_field_tag name, value, text_field_options
if help
select_html << content_tag(:small, help.html_safe, class: 'help-block')
end
<<-HTML.html_safe
<div class='combo-field-wrapper #{klass}-wrapper'>
#{label_html}
<div class='combo-field-select #{klass}-select'>#{select_html}</div>
<div class='combo-field-alternative'>or</div>
<div class='combo-field-input #{klass}-input'>
#{text_field_html}
<a href='#' class='clear-input hidden'>×</a>
</div>
</div>
HTML
end
end
| TGAC/brassica | app/helpers/combo_field_tag_helper.rb | Ruby | gpl-3.0 | 1,529 |
{
"": {
"domain": "ckan",
"lang": "cs_CZ",
"plural-forms": "nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;"
},
"An Error Occurred": [
null,
"Nastala chyba"
],
"Are you sure you want to perform this action?": [
null,
"Jste si jistí, že chcete provést tuto akci?"
],
"Cancel": [
null,
"Zrušit"
],
"Confirm": [
null,
"Potvrdit"
],
"Edit": [
null,
"Upravit"
],
"Failed to load data API information": [
null,
"Pokus o získání informací pomocí API selhal"
],
"Follow": [
null,
"Sledovat"
],
"Hide": [
null,
"Skrýt"
],
"Image": [
null,
"Obrázek"
],
"Input is too short, must be at least one character": [
null,
"Zadaný vstup je příliš krátký, musíte zadat alespoň jeden znak"
],
"Link": [
null,
"Odkaz"
],
"Link to a URL on the internet (you can also link to an API)": [
null,
"Odkaz na internetovou URL adresu (můžete také zadat odkaz na API)"
],
"Loading...": [
null,
"Nahrávám ..."
],
"No matches found": [
null,
"Nenalezena žádná shoda"
],
"Please Confirm Action": [
null,
"Prosím potvrďte akci"
],
"Remove": [
null,
"Odstranit"
],
"Reorder resources": [
null,
"Změnit pořadí zdrojů"
],
"Reset this": [
null,
"Resetovat"
],
"Resource uploaded": [
null,
"Zdroj nahrán"
],
"Save order": [
null,
"Uložit pořadí"
],
"Saving...": [
null,
"Ukládám..."
],
"Show more": [
null,
"Ukázat více"
],
"Start typing…": [
null,
"Začněte psát..."
],
"There are unsaved modifications to this form": [
null,
"Tento formulář obsahuje neuložené změny"
],
"There is no API data to load for this resource": [
null,
"Tento zdroj neobsahuje žádná data, která lze poskytnou přes API"
],
"URL": [
null,
"URL"
],
"Unable to authenticate upload": [
null,
"Nastala chyba autentizace při nahrávání dat"
],
"Unable to get data for uploaded file": [
null,
"Nelze získat data z nahraného souboru"
],
"Unable to upload file": [
null,
"Nelze nahrát soubor"
],
"Unfollow": [
null,
"Přestat sledovat"
],
"Upload": [
null,
"Nahrát"
],
"Upload a file": [
null,
"Nahrát soubor"
],
"Upload a file on your computer": [
null,
"Nahrát soubor na Váš počítač"
],
"You are uploading a file. Are you sure you want to navigate away and stop this upload?": [
null,
"Právě nahráváte soubor. Jste si opravdu jistí, že chcete tuto stránku opustit a ukončit tak nahrávání?"
],
"show less": [
null,
"ukázat méně"
],
"show more": [
null,
"ukázat více"
]
} | nucleo-digital/ckan-theme-cmbd | public/base/i18n/cs_CZ.js | JavaScript | gpl-3.0 | 2,840 |
package net.einsteinsci.betterbeginnings.items;
import net.einsteinsci.betterbeginnings.register.IBBName;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemTool;
import java.util.HashSet;
import java.util.Set;
public abstract class ItemKnife extends ItemTool implements IBBName
{
public static final float DAMAGE = 3.0f;
public ItemKnife(ToolMaterial material)
{
super(DAMAGE, material, getBreakable());
}
public static Set getBreakable()
{
Set<Block> s = new HashSet<>();
// s.add(Blocks.log);
// s.add(Blocks.log2);
// s.add(Blocks.planks);
s.add(Blocks.pumpkin);
s.add(Blocks.lit_pumpkin);
s.add(Blocks.melon_block);
s.add(Blocks.clay);
s.add(Blocks.grass);
s.add(Blocks.mycelium);
s.add(Blocks.leaves);
s.add(Blocks.leaves2);
s.add(Blocks.brown_mushroom_block);
s.add(Blocks.red_mushroom_block);
s.add(Blocks.glass);
s.add(Blocks.glass_pane);
s.add(Blocks.soul_sand);
s.add(Blocks.stained_glass);
s.add(Blocks.stained_glass_pane);
s.add(Blocks.cactus);
return s;
}
@Override
public boolean shouldRotateAroundWhenRendering()
{
return true;
}
@Override
public int getHarvestLevel(ItemStack stack, String toolClass)
{
return toolMaterial.getHarvestLevel();
}
@Override
public Set<String> getToolClasses(ItemStack stack)
{
Set<String> res = new HashSet<>();
res.add("knife");
return res;
}
// ...which also requires this...
@Override
public ItemStack getContainerItem(ItemStack itemStack)
{
ItemStack result = itemStack.copy();
result.setItemDamage(itemStack.getItemDamage() + 1);
return result;
}
// Allows durability-based crafting.
@Override
public boolean hasContainerItem(ItemStack stack)
{
return true;
}
@Override
public abstract String getName();
}
| Leviathan143/betterbeginnings | src/main/java/net/einsteinsci/betterbeginnings/items/ItemKnife.java | Java | gpl-3.0 | 1,851 |
/****************************************************************************/
/// @file MSEdge.cpp
/// @author Christian Roessel
/// @author Jakob Erdmann
/// @author Christoph Sommer
/// @author Daniel Krajzewicz
/// @author Laura Bieker
/// @author Michael Behrisch
/// @author Sascha Krieg
/// @date Tue, 06 Mar 2001
/// @version $Id: MSEdge.cpp 13107 2012-12-02 13:57:34Z behrisch $
///
// A road/street connecting two junctions
/****************************************************************************/
// SUMO, Simulation of Urban MObility; see http://sumo.sourceforge.net/
// Copyright (C) 2001-2012 DLR (http://www.dlr.de/) and contributors
/****************************************************************************/
//
// This file is part of SUMO.
// SUMO 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.
//
/****************************************************************************/
// ===========================================================================
// included modules
// ===========================================================================
#ifdef _MSC_VER
#include <windows_config.h>
#else
#include <config.h>
#endif
#include <algorithm>
#include <iostream>
#include <cassert>
#include <utils/common/StringTokenizer.h>
#include <utils/options/OptionsCont.h>
#include "MSEdge.h"
#include "MSLane.h"
#include "MSLaneChanger.h"
#include "MSGlobals.h"
#include "MSVehicle.h"
#include "MSEdgeWeightsStorage.h"
#ifdef HAVE_INTERNAL
#include <mesosim/MELoop.h>
#include <mesosim/MESegment.h>
#include <mesosim/MEVehicle.h>
#endif
#ifdef CHECK_MEMORY_LEAKS
#include <foreign/nvwa/debug_new.h>
#endif // CHECK_MEMORY_LEAKS
// ===========================================================================
// static member definitions
// ===========================================================================
MSEdge::DictType MSEdge::myDict;
std::vector<MSEdge*> MSEdge::myEdges;
// ===========================================================================
// member method definitions
// ===========================================================================
MSEdge::MSEdge(const std::string& id, int numericalID,
const EdgeBasicFunction function,
const std::string& streetName) :
Named(id), myNumericalID(numericalID), myLanes(0),
myLaneChanger(0), myFunction(function), myVaporizationRequests(0),
myLastFailedInsertionTime(-1), myStreetName(streetName) {}
MSEdge::~MSEdge() {
delete myLaneChanger;
for (AllowedLanesCont::iterator i1 = myAllowed.begin(); i1 != myAllowed.end(); i1++) {
delete(*i1).second;
}
for (ClassedAllowedLanesCont::iterator i2 = myClassedAllowed.begin(); i2 != myClassedAllowed.end(); i2++) {
for (AllowedLanesCont::iterator i1 = (*i2).second.begin(); i1 != (*i2).second.end(); i1++) {
delete(*i1).second;
}
}
delete myLanes;
// Note: Lanes are delete using MSLane::clear();
}
void
MSEdge::initialize(std::vector<MSLane*>* lanes) {
assert(myFunction == EDGEFUNCTION_DISTRICT || lanes != 0);
myLanes = lanes;
if (myLanes && myLanes->size() > 1 && myFunction != EDGEFUNCTION_INTERNAL) {
myLaneChanger = new MSLaneChanger(myLanes, OptionsCont::getOptions().getBool("lanechange.allow-swap"));
}
}
void
MSEdge::closeBuilding() {
myAllowed[0] = new std::vector<MSLane*>();
for (std::vector<MSLane*>::iterator i = myLanes->begin(); i != myLanes->end(); ++i) {
myAllowed[0]->push_back(*i);
const MSLinkCont& lc = (*i)->getLinkCont();
for (MSLinkCont::const_iterator j = lc.begin(); j != lc.end(); ++j) {
MSLane* toL = (*j)->getLane();
if (toL != 0) {
MSEdge& to = toL->getEdge();
//
if (std::find(mySuccessors.begin(), mySuccessors.end(), &to) == mySuccessors.end()) {
mySuccessors.push_back(&to);
}
if (std::find(to.myPredeccesors.begin(), to.myPredeccesors.end(), this) == to.myPredeccesors.end()) {
to.myPredeccesors.push_back(this);
}
//
if (myAllowed.find(&to) == myAllowed.end()) {
myAllowed[&to] = new std::vector<MSLane*>();
}
myAllowed[&to]->push_back(*i);
}
#ifdef HAVE_INTERNAL_LANES
toL = (*j)->getViaLane();
if (toL != 0) {
MSEdge& to = toL->getEdge();
to.myPredeccesors.push_back(this);
}
#endif
}
}
std::sort(mySuccessors.begin(), mySuccessors.end(), by_id_sorter());
rebuildAllowedLanes();
}
void
MSEdge::rebuildAllowedLanes() {
// clear myClassedAllowed.
// it will be rebuilt on demand
for (ClassedAllowedLanesCont::iterator i2 = myClassedAllowed.begin(); i2 != myClassedAllowed.end(); i2++) {
for (AllowedLanesCont::iterator i1 = (*i2).second.begin(); i1 != (*i2).second.end(); i1++) {
delete(*i1).second;
}
}
myClassedAllowed.clear();
// rebuild myMinimumPermissions and myCombinedPermissions
myMinimumPermissions = SVCFreeForAll;
myCombinedPermissions = 0;
for (std::vector<MSLane*>::iterator i = myLanes->begin(); i != myLanes->end(); ++i) {
myMinimumPermissions &= (*i)->getPermissions();
myCombinedPermissions |= (*i)->getPermissions();
}
}
// ------------ Access to the edge's lanes
MSLane*
MSEdge::leftLane(const MSLane* const lane) const {
std::vector<MSLane*>::iterator laneIt = find(myLanes->begin(), myLanes->end(), lane);
if (laneIt == myLanes->end() || laneIt == myLanes->end() - 1) {
return 0;
}
return *(laneIt + 1);
}
MSLane*
MSEdge::rightLane(const MSLane* const lane) const {
std::vector<MSLane*>::iterator laneIt = find(myLanes->begin(), myLanes->end(), lane);
if (laneIt == myLanes->end() || laneIt == myLanes->begin()) {
return 0;
}
return *(laneIt - 1);
}
const std::vector<MSLane*>*
MSEdge::allowedLanes(const MSEdge& destination, SUMOVehicleClass vclass) const {
return allowedLanes(&destination, vclass);
}
const std::vector<MSLane*>*
MSEdge::allowedLanes(SUMOVehicleClass vclass) const {
return allowedLanes(0, vclass);
}
const std::vector<MSLane*>*
MSEdge::getAllowedLanesWithDefault(const AllowedLanesCont& c, const MSEdge* dest) const {
AllowedLanesCont::const_iterator it = c.find(dest);
if (it == c.end()) {
return 0;
}
return it->second;
}
const std::vector<MSLane*>*
MSEdge::allowedLanes(const MSEdge* destination, SUMOVehicleClass vclass) const {
if ((myMinimumPermissions & vclass) == vclass) {
// all lanes allow vclass
return getAllowedLanesWithDefault(myAllowed, destination);
}
// look up cached result in myClassedAllowed
ClassedAllowedLanesCont::const_iterator i = myClassedAllowed.find(vclass);
if (i != myClassedAllowed.end()) {
// can use cached value
const AllowedLanesCont& c = (*i).second;
return getAllowedLanesWithDefault(c, destination);
} else {
// this vclass is requested for the first time. rebuild all destinations
// go through connected edges
for (AllowedLanesCont::const_iterator i1 = myAllowed.begin(); i1 != myAllowed.end(); ++i1) {
const MSEdge* edge = i1->first;
const std::vector<MSLane*>* lanes = i1->second;
myClassedAllowed[vclass][edge] = new std::vector<MSLane*>();
// go through lanes approaching current edge
for (std::vector<MSLane*>::const_iterator i2 = lanes->begin(); i2 != lanes->end(); ++i2) {
// allows the current vehicle class?
if ((*i2)->allowsVehicleClass(vclass)) {
// -> may be used
myClassedAllowed[vclass][edge]->push_back(*i2);
}
}
// assert that 0 is returned if no connection is allowed for a class
if (myClassedAllowed[vclass][edge]->size() == 0) {
delete myClassedAllowed[vclass][edge];
myClassedAllowed[vclass][edge] = 0;
}
}
return myClassedAllowed[vclass][destination];
}
}
// ------------
SUMOTime
MSEdge::incVaporization(SUMOTime) {
++myVaporizationRequests;
return 0;
}
SUMOTime
MSEdge::decVaporization(SUMOTime) {
--myVaporizationRequests;
return 0;
}
MSLane*
MSEdge::getFreeLane(const std::vector<MSLane*>* allowed, const SUMOVehicleClass vclass) const {
if (allowed == 0) {
allowed = allowedLanes(vclass);
}
MSLane* res = 0;
if (allowed != 0) {
unsigned int noCars = INT_MAX;
for (std::vector<MSLane*>::const_iterator i = allowed->begin(); i != allowed->end(); ++i) {
if ((*i)->getVehicleNumber() < noCars) {
res = (*i);
noCars = (*i)->getVehicleNumber();
}
}
}
return res;
}
MSLane*
MSEdge::getDepartLane(const MSVehicle& veh) const {
switch (veh.getParameter().departLaneProcedure) {
case DEPART_LANE_GIVEN:
if ((int) myLanes->size() <= veh.getParameter().departLane || !(*myLanes)[veh.getParameter().departLane]->allowsVehicleClass(veh.getVehicleType().getVehicleClass())) {
return 0;
}
return (*myLanes)[veh.getParameter().departLane];
case DEPART_LANE_RANDOM:
return RandHelper::getRandomFrom(*allowedLanes(veh.getVehicleType().getVehicleClass()));
case DEPART_LANE_FREE:
return getFreeLane(0, veh.getVehicleType().getVehicleClass());
case DEPART_LANE_ALLOWED_FREE:
if (veh.getRoute().size() == 1) {
return getFreeLane(0, veh.getVehicleType().getVehicleClass());
} else {
return getFreeLane(allowedLanes(**(veh.getRoute().begin() + 1)), veh.getVehicleType().getVehicleClass());
}
case DEPART_LANE_BEST_FREE: {
const std::vector<MSVehicle::LaneQ>& bl = veh.getBestLanes(false, (*myLanes)[0]);
SUMOReal bestLength = -1;
for (std::vector<MSVehicle::LaneQ>::const_iterator i = bl.begin(); i != bl.end(); ++i) {
if ((*i).length > bestLength) {
bestLength = (*i).length;
}
}
std::vector<MSLane*>* bestLanes = new std::vector<MSLane*>();
for (std::vector<MSVehicle::LaneQ>::const_iterator i = bl.begin(); i != bl.end(); ++i) {
if ((*i).length == bestLength) {
bestLanes->push_back((*i).lane);
}
}
MSLane* ret = getFreeLane(bestLanes, veh.getVehicleType().getVehicleClass());
delete bestLanes;
return ret;
}
case DEPART_LANE_DEFAULT:
default:
break;
}
if (!(*myLanes)[0]->allowsVehicleClass(veh.getVehicleType().getVehicleClass())) {
return 0;
}
return (*myLanes)[0];
}
bool
MSEdge::insertVehicle(SUMOVehicle& v, SUMOTime time) const {
// when vaporizing, no vehicles are inserted...
if (isVaporizing()) {
return false;
}
#ifdef HAVE_INTERNAL
if (MSGlobals::gUseMesoSim) {
const SUMOVehicleParameter& pars = v.getParameter();
SUMOReal pos = 0.0;
switch (pars.departPosProcedure) {
case DEPART_POS_GIVEN:
if (pars.departPos >= 0.) {
pos = pars.departPos;
} else {
pos = pars.departPos + getLength();
}
if (pos < 0 || pos > getLength()) {
WRITE_WARNING("Invalid departPos " + toString(pos) + " given for vehicle '" +
v.getID() + "'. Inserting at lane end instead.");
pos = getLength();
}
break;
case DEPART_POS_RANDOM:
case DEPART_POS_RANDOM_FREE:
pos = RandHelper::rand(getLength());
break;
default:
break;
}
bool result = false;
MESegment* segment = MSGlobals::gMesoNet->getSegmentForEdge(*this, pos);
MEVehicle* veh = static_cast<MEVehicle*>(&v);
if (pars.departPosProcedure == DEPART_POS_FREE) {
while (segment != 0 && !result) {
result = segment->initialise(veh, time);
segment = segment->getNextSegment();
}
} else {
result = segment->initialise(veh, time);
}
return result;
}
#else
UNUSED_PARAMETER(time);
#endif
MSLane* insertionLane = getDepartLane(static_cast<MSVehicle&>(v));
return insertionLane != 0 && insertionLane->insertVehicle(static_cast<MSVehicle&>(v));
}
void
MSEdge::changeLanes(SUMOTime t) {
if (myFunction == EDGEFUNCTION_INTERNAL) {
return;
}
assert(myLaneChanger != 0);
myLaneChanger->laneChange(t);
}
#ifdef HAVE_INTERNAL_LANES
const MSEdge*
MSEdge::getInternalFollowingEdge(MSEdge* followerAfterInternal) const {
//@todo to be optimized
for (std::vector<MSLane*>::const_iterator i = myLanes->begin(); i != myLanes->end(); ++i) {
MSLane* l = *i;
const MSLinkCont& lc = l->getLinkCont();
for (MSLinkCont::const_iterator j = lc.begin(); j != lc.end(); ++j) {
MSLink* link = *j;
if (&link->getLane()->getEdge() == followerAfterInternal) {
if (link->getViaLane() != 0) {
return &link->getViaLane()->getEdge();
} else {
return 0; // network without internal links
}
}
}
}
return 0;
}
#endif
SUMOReal
MSEdge::getCurrentTravelTime(SUMOReal minSpeed) const {
assert(minSpeed > 0);
SUMOReal v = 0;
#ifdef HAVE_INTERNAL
if (MSGlobals::gUseMesoSim) {
MESegment* first = MSGlobals::gMesoNet->getSegmentForEdge(*this);
unsigned segments = 0;
do {
v += first->getMeanSpeed();
first = first->getNextSegment();
segments++;
} while (first != 0);
v /= (SUMOReal) segments;
} else {
#endif
for (std::vector<MSLane*>::iterator i = myLanes->begin(); i != myLanes->end(); ++i) {
v += (*i)->getMeanSpeed();
}
v /= (SUMOReal) myLanes->size();
#ifdef HAVE_INTERNAL
}
#endif
v = MAX2(minSpeed, v);
return getLength() / v;
}
bool
MSEdge::dictionary(const std::string& id, MSEdge* ptr) {
DictType::iterator it = myDict.find(id);
if (it == myDict.end()) {
// id not in myDict.
myDict[id] = ptr;
if (ptr->getNumericalID() != -1) {
while ((int)myEdges.size() < ptr->getNumericalID() + 1) {
myEdges.push_back(0);
}
myEdges[ptr->getNumericalID()] = ptr;
}
return true;
}
return false;
}
MSEdge*
MSEdge::dictionary(const std::string& id) {
DictType::iterator it = myDict.find(id);
if (it == myDict.end()) {
// id not in myDict.
return 0;
}
return it->second;
}
MSEdge*
MSEdge::dictionary(size_t id) {
assert(myEdges.size() > id);
return myEdges[id];
}
size_t
MSEdge::dictSize() {
return myDict.size();
}
size_t
MSEdge::numericalDictSize() {
return myEdges.size();
}
void
MSEdge::clear() {
for (DictType::iterator i = myDict.begin(); i != myDict.end(); ++i) {
delete(*i).second;
}
myDict.clear();
}
void
MSEdge::insertIDs(std::vector<std::string>& into) {
for (DictType::iterator i = myDict.begin(); i != myDict.end(); ++i) {
into.push_back((*i).first);
}
}
void
MSEdge::parseEdgesList(const std::string& desc, std::vector<const MSEdge*>& into,
const std::string& rid) {
if (desc[0] == BinaryFormatter::BF_ROUTE) {
std::istringstream in(desc, std::ios::binary);
char c;
in >> c;
FileHelpers::readEdgeVector(in, into, rid);
} else {
StringTokenizer st(desc);
parseEdgesList(st.getVector(), into, rid);
}
}
void
MSEdge::parseEdgesList(const std::vector<std::string>& desc, std::vector<const MSEdge*>& into,
const std::string& rid) {
for (std::vector<std::string>::const_iterator i = desc.begin(); i != desc.end(); ++i) {
const MSEdge* edge = MSEdge::dictionary(*i);
// check whether the edge exists
if (edge == 0) {
throw ProcessError("The edge '" + *i + "' within the route " + rid + " is not known."
+ "\n The route can not be build.");
}
into.push_back(edge);
}
}
SUMOReal
MSEdge::getDistanceTo(const MSEdge* other) const {
if (getLanes().size() > 0 && other->getLanes().size() > 0) {
return getLanes()[0]->getShape()[-1].distanceTo2D(other->getLanes()[0]->getShape()[0]);
} else {
return 0; // optimism is just right for astar
}
}
SUMOReal
MSEdge::getLength() const {
return getLanes()[0]->getLength();
}
SUMOReal
MSEdge::getSpeedLimit() const {
// @note lanes might have different maximum speeds in theory
return getLanes()[0]->getSpeedLimit();
}
SUMOReal
MSEdge::getVehicleMaxSpeed(const SUMOVehicle* const veh) const {
// @note lanes might have different maximum speeds in theory
return getLanes()[0]->getVehicleMaxSpeed(veh);
}
/****************************************************************************/
| rudhir-upretee/SUMO_Src | src/microsim/MSEdge.cpp | C++ | gpl-3.0 | 17,842 |
package es.ucm.fdi.emf.model.ed2.diagram.sheet;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.jface.viewers.BaseLabelProvider;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.graphics.Image;
import es.ucm.fdi.emf.model.ed2.diagram.navigator.Ed2NavigatorGroup;
import es.ucm.fdi.emf.model.ed2.diagram.part.Ed2VisualIDRegistry;
import es.ucm.fdi.emf.model.ed2.diagram.providers.Ed2ElementTypes;
/**
* @generated
*/
public class Ed2SheetLabelProvider extends BaseLabelProvider implements
ILabelProvider {
/**
* @generated
*/
public String getText(Object element) {
element = unwrap(element);
if (element instanceof Ed2NavigatorGroup) {
return ((Ed2NavigatorGroup) element).getGroupName();
}
IElementType etype = getElementType(getView(element));
return etype == null ? "" : etype.getDisplayName();
}
/**
* @generated
*/
public Image getImage(Object element) {
IElementType etype = getElementType(getView(unwrap(element)));
return etype == null ? null : Ed2ElementTypes.getImage(etype);
}
/**
* @generated
*/
private Object unwrap(Object element) {
if (element instanceof IStructuredSelection) {
return ((IStructuredSelection) element).getFirstElement();
}
return element;
}
/**
* @generated
*/
private View getView(Object element) {
if (element instanceof View) {
return (View) element;
}
if (element instanceof IAdaptable) {
return (View) ((IAdaptable) element).getAdapter(View.class);
}
return null;
}
/**
* @generated
*/
private IElementType getElementType(View view) {
// For intermediate views climb up the containment hierarchy to find the one associated with an element type.
while (view != null) {
int vid = Ed2VisualIDRegistry.getVisualID(view);
IElementType etype = Ed2ElementTypes.getElementType(vid);
if (etype != null) {
return etype;
}
view = view.eContainer() instanceof View ? (View) view.eContainer()
: null;
}
return null;
}
}
| RubenM13/E-EDD-2.0 | es.ucm.fdi.ed2.emf.diagram/src/es/ucm/fdi/emf/model/ed2/diagram/sheet/Ed2SheetLabelProvider.java | Java | gpl-3.0 | 2,246 |
######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Universal charset detector code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2001
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
# Shy Shalom - original C code
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
import constants, sys
from charsetgroupprober import CharSetGroupProber
from sbcharsetprober import SingleByteCharSetProber
from langcyrillicmodel import Win1251CyrillicModel, Koi8rModel, Latin5CyrillicModel, MacCyrillicModel, Ibm866Model, Ibm855Model
from langgreekmodel import Latin7GreekModel, Win1253GreekModel
from langbulgarianmodel import Latin5BulgarianModel, Win1251BulgarianModel
from langhungarianmodel import Latin2HungarianModel, Win1250HungarianModel
from langthaimodel import TIS620ThaiModel
from langhebrewmodel import Win1255HebrewModel
from hebrewprober import HebrewProber
class SBCSGroupProber(CharSetGroupProber):
def __init__(self):
CharSetGroupProber.__init__(self)
self._mProbers = [ \
SingleByteCharSetProber(Win1251CyrillicModel),
SingleByteCharSetProber(Koi8rModel),
SingleByteCharSetProber(Latin5CyrillicModel),
SingleByteCharSetProber(MacCyrillicModel),
SingleByteCharSetProber(Ibm866Model),
SingleByteCharSetProber(Ibm855Model),
SingleByteCharSetProber(Latin7GreekModel),
SingleByteCharSetProber(Win1253GreekModel),
SingleByteCharSetProber(Latin5BulgarianModel),
SingleByteCharSetProber(Win1251BulgarianModel),
SingleByteCharSetProber(Latin2HungarianModel),
SingleByteCharSetProber(Win1250HungarianModel),
SingleByteCharSetProber(TIS620ThaiModel),
]
hebrewProber = HebrewProber()
logicalHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, constants.False, hebrewProber)
visualHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, constants.True, hebrewProber)
hebrewProber.set_model_probers(logicalHebrewProber, visualHebrewProber)
self._mProbers.extend([hebrewProber, logicalHebrewProber, visualHebrewProber])
self.reset()
| disabler/isida3 | lib/chardet/sbcsgroupprober.py | Python | gpl-3.0 | 2,948 |
# frozen_string_literal: true
# How minitest plugins. See https://github.com/simplecov-ruby/simplecov/pull/756 for why we need this.
# https://github.com/seattlerb/minitest#writing-extensions
module Minitest
def self.plugin_simplecov_init(_options)
if defined?(SimpleCov)
SimpleCov.external_at_exit = true
Minitest.after_run do
SimpleCov.at_exit_behavior
end
end
end
end
| BeGe78/esood | vendor/bundle/ruby/3.0.0/gems/simplecov-0.21.2/lib/minitest/simplecov_plugin.rb | Ruby | gpl-3.0 | 411 |
//***************************************************************************
//
// Copyright (c) 1999 - 2006 Intel Corporation
//
// 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.
//
//***************************************************************************
/**
@file FileScanner.cpp
This module defines ...
*/
//***************************************************************************
// Defines
//***************************************************************************
//***************************************************************************
// Includes
//***************************************************************************
#include "FileScanner.h"
#include "IFXException.h"
#include "IFXMatrix4x4.h"
#include "Color.h"
#include "Quat.h"
#include "Point.h"
#include "Int3.h"
#include "Int2.h"
#include "MetaDataList.h"
#include "Tokens.h"
#include <ctype.h>
#include <wchar.h>
using namespace U3D_IDTF;
//***************************************************************************
// Constants
//***************************************************************************
//***************************************************************************
// Enumerations
//***************************************************************************
//***************************************************************************
// Classes, structures and types
//***************************************************************************
//***************************************************************************
// Global data
//***************************************************************************
//***************************************************************************
// Local data
//***************************************************************************
//***************************************************************************
// Local function prototypes
//***************************************************************************
//***************************************************************************
// Public methods
//***************************************************************************
FileScanner::FileScanner()
{
m_currentCharacter[0] = 0;
m_currentCharacter[1] = 0;
m_used = TRUE;
}
FileScanner::~FileScanner()
{
}
IFXRESULT FileScanner::Initialize( const IFXCHAR* pFileName )
{
IFXRESULT result = IFX_OK;
result = m_file.Initialize( pFileName );
if( IFXSUCCESS( result ) )
m_currentCharacter[0] = m_file.ReadCharacter();
return result;
}
IFXRESULT FileScanner::Scan( IFXString* pToken, U32 scanLine )
{
// try to use fscanf
IFXRESULT result = IFX_OK;
if( NULL != pToken )
{
if( scanLine )
SkipBlanks();
else
SkipSpaces();
if( TRUE == IsEndOfFile() )
result = IFX_E_EOF;
else
{
U8 i = 0;
U8 buffer[MAX_STRING_LENGTH] = {0};
while( 0 == IsSpace( GetCurrentCharacter() ) && !IsEndOfFile() )
{
buffer[i++] = GetCurrentCharacter();
NextCharacter();
}
result = pToken->Assign(buffer);
}
}
else
result = IFX_E_INVALID_POINTER;
return result;
}
IFXRESULT FileScanner::ScanString( IFXString* pString )
{
IFXRESULT result = IFX_OK;
if( NULL == pString )
result = IFX_E_INVALID_POINTER;
if( IFXSUCCESS( result ) )
{
SkipSpaces();
if( '"' == GetCurrentCharacter() )
{
// found string, skip first quote
NextCharacter();
U32 i = 0;
U8 scanBuffer[MAX_STRING_LENGTH+2];
while( '"' != GetCurrentCharacter() && i < MAX_STRING_LENGTH )
{
if( '\\' == GetCurrentCharacter())
{
NextCharacter();
U8 currentCharacter = GetCurrentCharacter();
switch (currentCharacter)
{
case '\\':
scanBuffer[i++] = '\\';
break;
case 'n':
scanBuffer[i++] = '\n';
break;
case 't':
scanBuffer[i++] = '\t';
break;
case 'r':
scanBuffer[i++] = '\r';
break;
case '"':
scanBuffer[i++] = '"';
break;
default:
scanBuffer[i++] = currentCharacter;
}
}
else
scanBuffer[i++] = GetCurrentCharacter();
NextCharacter();
}
NextCharacter(); // skip last double quote
scanBuffer[i] = 0;
/// @todo: Converter Unicode support
// convert one byte string to unicode
pString->Assign( scanBuffer );
}
else
{
result = IFX_E_STRING_NOT_FOUND;
}
}
return result;
}
IFXRESULT FileScanner::ScanFloat( F32* pNumber )
{
IFXRESULT result = IFX_OK;
if( NULL == pNumber )
result = IFX_E_INVALID_POINTER;
if( IFXSUCCESS( result ) )
{
//this F32 format is preferred
#ifdef F32_EXPONENTIAL
IFXString buffer;
U32 fpos;
result = m_file.GetPosition( &fpos );
if( IFXSUCCESS( result ) )
result = Scan( &buffer, 1 );
if( IFXSUCCESS( result ) )
{
I32 scanResult = swscanf( buffer.Raw(), L"%g", pNumber );
if( 0 == scanResult || EOF == scanResult )
{
result = IFX_E_FLOAT_NOT_FOUND;
// new token found, not float
// do not allow client to continue scan for new tokens
m_used = TRUE;
m_currentToken = buffer;
fpos--;
m_file.SetPosition( fpos );
NextCharacter();
}
}
#else
I32 sign = 1;
U32 value = 0;
SkipBlanks();
if( '-' == GetCurrentCharacter() )
{
sign = -1;
NextCharacter();
}
if( '-' == GetCurrentCharacter() || '+' == GetCurrentCharacter() )
NextCharacter();
while( isdigit( GetCurrentCharacter() ) )
{
value = ( value*10 ) + ( GetCurrentCharacter() - '0' );
NextCharacter();
}
// there should be fraction part of float
if( '.' == GetCurrentCharacter() )
{
F32 fraction = 0.0f;
F32 divisor = 10.0f;
if( '.' == GetCurrentCharacter() )
NextCharacter();
while( isdigit( GetCurrentCharacter() ) )
{
fraction += ( GetCurrentCharacter() - '0' ) / divisor;
divisor *=10.0f;
NextCharacter();
}
*pNumber = static_cast<float>(value);
*pNumber += fraction;
*pNumber *= sign;
}
else
{
result = IFX_E_FLOAT_NOT_FOUND;
}
#endif
}
return result;
}
IFXRESULT FileScanner::ScanInteger( I32* pNumber )
{
IFXRESULT result = IFX_OK;
IFXString buffer;
if( NULL == pNumber )
result = IFX_E_INVALID_POINTER;
if( IFXSUCCESS( result ) )
{
I32 sign = 1;
I32 value = 0;
SkipSpaces();
if( '-' == GetCurrentCharacter() )
{
sign = -1;
}
if( '-' == GetCurrentCharacter() || '+' == GetCurrentCharacter() )
{
NextCharacter();
}
while( isdigit( GetCurrentCharacter() ) )
{
value = (value*10) + (GetCurrentCharacter() - '0');
NextCharacter();
}
*pNumber = value * sign;
}
return result;
}
IFXRESULT FileScanner::ScanHex( I32* pNumber )
{
IFXRESULT result = IFX_OK;
IFXString buffer;
if( NULL == pNumber )
result = IFX_E_INVALID_POINTER;
if( IFXSUCCESS( result ) )
result = Scan( &buffer );
if( IFXSUCCESS( result ) )
{
buffer.ForceUppercase();
int scanResult = swscanf( buffer.Raw(), L"%X", pNumber );
if( 0 == scanResult || EOF == scanResult )
{
result = IFX_E_INT_NOT_FOUND;
}
}
return result;
}
IFXRESULT FileScanner::ScanTM( IFXMatrix4x4* pMatrix )
{
IFXRESULT result = IFX_OK;
F32 matrix[16];
U32 i;
for( i = 0; i < 16 && IFXSUCCESS( result ); ++i )
{
result = ScanFloat( &matrix[i] );
if( 0 == (i + 1)%4 )
{
// skip end of line
SkipSpaces();
}
}
if( IFXSUCCESS( result ) )
{
*pMatrix = matrix;
SkipSpaces();
}
return result;
}
IFXRESULT FileScanner::ScanColor( Color* pColor )
{
IFXRESULT result = IFX_OK;
F32 red = 0.0f, green = 0.0f, blue = 0.0f, alpha = 0.0f;
result = ScanFloat( &red );
if( IFXSUCCESS( result ) )
result = ScanFloat( &green );
if( IFXSUCCESS( result ) )
result = ScanFloat( &blue );
if( IFXSUCCESS( result ) )
{
result = ScanFloat( &alpha );
if( IFXSUCCESS( result ) )
{
// 4 component color
IFXVector4 color( red, green, blue, alpha );
pColor->SetColor( color );
}
else if( IFX_E_FLOAT_NOT_FOUND == result )
{
// 3 component color
IFXVector4 color( red, green, blue );
pColor->SetColor( color );
result = IFX_OK;
}
SkipSpaces();
}
return result;
}
IFXRESULT FileScanner::ScanQuat( Quat* pQuat )
{
IFXRESULT result = IFX_OK;
F32 w = 0.0f, x = 0.0f, y = 0.0f, z = 0.0f;
result = ScanFloat( &w );
if( IFXSUCCESS( result ) )
result = ScanFloat( &x );
if( IFXSUCCESS( result ) )
result = ScanFloat( &y );
if( IFXSUCCESS( result ) )
{
result = ScanFloat( &z );
if( IFXSUCCESS( result ) )
{
IFXVector4 quat( w, x, y, z );
pQuat->SetQuat( quat );
SkipSpaces();
}
}
return result;
}
IFXRESULT FileScanner::ScanPoint( Point* pPoint )
{
IFXRESULT result = IFX_OK;
F32 x = 0.0f, y = 0.0f, z = 0.0f;
result = ScanFloat( &x );
if( IFXSUCCESS( result ) )
result = ScanFloat( &y );
if( IFXSUCCESS( result ) )
result = ScanFloat( &z );
if( IFXSUCCESS( result ) )
{
IFXVector3 point( x, y, z );
pPoint->SetPoint( point );
SkipSpaces();
}
return result;
}
IFXRESULT FileScanner::ScanVector4( IFXVector4* pVector4 )
{
IFXRESULT result = IFX_OK;
F32 x = 0.0f, y = 0.0f, z = 0.0f, w = 0.0f;
result = ScanFloat( &x );
if( IFXSUCCESS( result ) )
result = ScanFloat( &y );
if( IFXSUCCESS( result ) )
result = ScanFloat( &z );
if( IFXSUCCESS( result ) )
result = ScanFloat( &w );
if( IFXSUCCESS( result ) )
{
pVector4->Set( x, y, z, w );
SkipSpaces();
}
return result;
}
IFXRESULT FileScanner::ScanInt3( Int3* pData )
{
IFXRESULT result = IFX_OK;
I32 x = 0, y = 0, z = 0;
result = ScanInteger( &x );
if( IFXSUCCESS( result ) )
result = ScanInteger( &y );
if( IFXSUCCESS( result ) )
result = ScanInteger( &z );
if( IFXSUCCESS( result ) )
{
pData->SetData( x, y, z );
SkipSpaces();
}
return result;
}
IFXRESULT FileScanner::ScanInt2( Int2* pData )
{
IFXRESULT result = IFX_OK;
I32 x = 0, y = 0;
result = ScanInteger( &x );
if( IFXSUCCESS( result ) )
result = ScanInteger( &y );
if( IFXSUCCESS( result ) )
{
pData->SetData( x, y );
SkipSpaces();
}
return result;
}
IFXRESULT FileScanner::ScanToken( const IFXCHAR* pToken )
{
// try to use fscanf
IFXRESULT result = IFX_OK;
if( NULL != pToken )
{
if( TRUE == m_used )
{
// previous token was successfuly used and we can scan next
SkipSpaces();
if( TRUE == IsEndOfFile() )
result = IFX_E_EOF;
else
{
U8 buffer[MAX_STRING_LENGTH];
U32 i = 0;
if( IDTF_END_BLOCK != GetCurrentCharacter() )
{
while( ( 0 == IsSpace( GetCurrentCharacter() ) ) &&
!IsEndOfFile() &&
i < MAX_STRING_LENGTH
)
{
buffer[i++] = GetCurrentCharacter();
NextCharacter();
}
buffer[i] = 0;
/// @todo: Converter unicode support
m_currentToken.Assign( buffer );
}
else
{
// block terminator found
// do not allow client to continue scan for new tokens
m_used = FALSE;
}
}
}
/// @todo: Converter Unicode support
// convert one byte token to unicode
IFXString token( pToken );
if( m_currentToken != token )
{
m_used = FALSE;
result = IFX_E_TOKEN_NOT_FOUND;
}
else
m_used = TRUE;
}
else
result = IFX_E_INVALID_POINTER;
return result;
}
IFXRESULT FileScanner::ScanStringToken( const IFXCHAR* pToken, IFXString* pValue )
{
IFXRESULT result = IFX_OK;
if( NULL != pToken && NULL != pValue )
{
result = ScanToken( pToken );
if( IFXSUCCESS( result ) )
result = ScanString( pValue );
}
else
result = IFX_E_INVALID_POINTER;
return result;
}
IFXRESULT FileScanner::ScanIntegerToken( const IFXCHAR* pToken, I32* pValue )
{
IFXRESULT result = IFX_OK;
if( NULL != pToken && NULL != pValue )
{
result = ScanToken( pToken );
if( IFXSUCCESS( result ) )
result = ScanInteger( pValue );
}
else
result = IFX_E_INVALID_POINTER;
return result;
}
IFXRESULT FileScanner::ScanHexToken( const IFXCHAR* pToken, I32* pValue )
{
IFXRESULT result = IFX_OK;
if( NULL != pToken && NULL != pValue )
{
result = ScanToken( pToken );
if( IFXSUCCESS( result ) )
result = ScanHex( pValue );
}
else
result = IFX_E_INVALID_POINTER;
return result;
}
IFXRESULT FileScanner::ScanFloatToken( const IFXCHAR* pToken, F32* pValue )
{
IFXRESULT result = IFX_OK;
if( NULL != pToken && NULL != pValue )
{
result = ScanToken( pToken );
if( IFXSUCCESS( result ) )
result = ScanFloat( pValue );
}
else
result = IFX_E_INVALID_POINTER;
return result;
}
IFXRESULT FileScanner::ScanTMToken( const IFXCHAR* pToken, IFXMatrix4x4* pValue )
{
IFXRESULT result = IFX_OK;
if( NULL != pToken && NULL != pValue )
{
result = ScanToken( pToken );
if( IFXSUCCESS( result ) )
result = FindBlockStarter();
if( IFXSUCCESS( result ) )
result = ScanTM( pValue );
if( IFXSUCCESS( result ) )
result = FindBlockTerminator();
}
else
result = IFX_E_INVALID_POINTER;
return result;
}
IFXRESULT FileScanner::ScanColorToken( const IFXCHAR* pToken, Color* pValue )
{
IFXRESULT result = IFX_OK;
if( NULL != pToken && NULL != pValue )
{
result = ScanToken( pToken );
if( IFXSUCCESS( result ) )
result = ScanColor( pValue );
}
else
result = IFX_E_INVALID_POINTER;
return result;
}
IFXRESULT FileScanner::ScanQuatToken( const IFXCHAR* pToken, Quat* pValue )
{
IFXRESULT result = IFX_OK;
if( NULL != pToken && NULL != pValue )
{
result = ScanToken( pToken );
if( IFXSUCCESS( result ) )
result = ScanQuat( pValue );
}
else
result = IFX_E_INVALID_POINTER;
return result;
}
IFXRESULT FileScanner::ScanPointToken( const IFXCHAR* pToken, Point* pValue )
{
IFXRESULT result = IFX_OK;
if( NULL != pToken && NULL != pValue )
{
result = ScanToken( pToken );
if( IFXSUCCESS( result ) )
result = ScanPoint( pValue );
}
else
result = IFX_E_INVALID_POINTER;
return result;
}
IFXRESULT FileScanner::FindBlockStarter()
{
IFXRESULT result = IFX_OK;
SkipSpaces();
if( TRUE == IsEndOfFile() )
result = IFX_E_EOF;
else
{
if( GetCurrentCharacter() == IDTF_BEGIN_BLOCK )
{
NextCharacter();
SkipSpaces();
}
else
result = IFX_E_STARTER_NOT_FOUND;
}
return result;
}
IFXRESULT FileScanner::FindBlockTerminator()
{
IFXRESULT result = IFX_OK;
SkipSpaces();
if( TRUE == IsEndOfFile() )
result = IFX_E_EOF;
else
{
if( GetCurrentCharacter() == IDTF_END_BLOCK )
{
// block terminator found
// allow client to scan for next token
m_used = TRUE;
NextCharacter();
}
else
result = IFX_E_TERMINATOR_NOT_FOUND;
}
return result;
}
//***************************************************************************
// Protected methods
//***************************************************************************
BOOL FileScanner::IsSpace( I8 character )
{
return isspace( character );
}
BOOL FileScanner::IsEndOfFile()
{
return m_file.IsEndOfFile();
}
void FileScanner::SkipSpaces()
{
while( 0 != isspace( GetCurrentCharacter() ) && !m_file.IsEndOfFile() )
NextCharacter();
}
void FileScanner::SkipBlanks()
{
while( ( ' ' == GetCurrentCharacter() || '\t' == GetCurrentCharacter() )
&& !m_file.IsEndOfFile() )
NextCharacter();
}
U8 FileScanner::NextCharacter()
{
return m_currentCharacter[0] = m_file.ReadCharacter();
}
//***************************************************************************
// Private methods
//***************************************************************************
//***************************************************************************
// Global functions
//***************************************************************************
//***************************************************************************
// Local functions
//***************************************************************************
| cnr-isti-vclab/meshlab | src/external/u3d/src/IDTF/FileScanner.cpp | C++ | gpl-3.0 | 16,279 |
cordova.define('cordova/plugin_list', function(require, exports, module) {
module.exports = [
{
"file": "plugins/cordova-plugin-device/www/device.js",
"id": "cordova-plugin-device.device",
"pluginId": "cordova-plugin-device",
"clobbers": [
"device"
]
},
{
"file": "plugins/cordova-plugin-device/src/browser/DeviceProxy.js",
"id": "cordova-plugin-device.DeviceProxy",
"pluginId": "cordova-plugin-device",
"runs": true
},
{
"file": "plugins/cordova-plugin-device-orientation/www/CompassError.js",
"id": "cordova-plugin-device-orientation.CompassError",
"pluginId": "cordova-plugin-device-orientation",
"clobbers": [
"CompassError"
]
},
{
"file": "plugins/cordova-plugin-device-orientation/www/CompassHeading.js",
"id": "cordova-plugin-device-orientation.CompassHeading",
"pluginId": "cordova-plugin-device-orientation",
"clobbers": [
"CompassHeading"
]
},
{
"file": "plugins/cordova-plugin-device-orientation/www/compass.js",
"id": "cordova-plugin-device-orientation.compass",
"pluginId": "cordova-plugin-device-orientation",
"clobbers": [
"navigator.compass"
]
},
{
"file": "plugins/cordova-plugin-device-orientation/src/browser/CompassProxy.js",
"id": "cordova-plugin-device-orientation.CompassProxy",
"pluginId": "cordova-plugin-device-orientation",
"runs": true
},
{
"file": "plugins/cordova-plugin-dialogs/www/notification.js",
"id": "cordova-plugin-dialogs.notification",
"pluginId": "cordova-plugin-dialogs",
"merges": [
"navigator.notification"
]
},
{
"file": "plugins/cordova-plugin-dialogs/www/browser/notification.js",
"id": "cordova-plugin-dialogs.notification_browser",
"pluginId": "cordova-plugin-dialogs",
"merges": [
"navigator.notification"
]
},
{
"file": "plugins/cordova-plugin-network-information/www/network.js",
"id": "cordova-plugin-network-information.network",
"pluginId": "cordova-plugin-network-information",
"clobbers": [
"navigator.connection",
"navigator.network.connection"
]
},
{
"file": "plugins/cordova-plugin-network-information/www/Connection.js",
"id": "cordova-plugin-network-information.Connection",
"pluginId": "cordova-plugin-network-information",
"clobbers": [
"Connection"
]
},
{
"file": "plugins/cordova-plugin-network-information/src/browser/network.js",
"id": "cordova-plugin-network-information.NetworkInfoProxy",
"pluginId": "cordova-plugin-network-information",
"runs": true
},
{
"file": "plugins/cordova-plugin-splashscreen/www/splashscreen.js",
"id": "cordova-plugin-splashscreen.SplashScreen",
"pluginId": "cordova-plugin-splashscreen",
"clobbers": [
"navigator.splashscreen"
]
},
{
"file": "plugins/cordova-plugin-splashscreen/src/browser/SplashScreenProxy.js",
"id": "cordova-plugin-splashscreen.SplashScreenProxy",
"pluginId": "cordova-plugin-splashscreen",
"runs": true
},
{
"file": "plugins/cordova-plugin-statusbar/www/statusbar.js",
"id": "cordova-plugin-statusbar.statusbar",
"pluginId": "cordova-plugin-statusbar",
"clobbers": [
"window.StatusBar"
]
},
{
"file": "plugins/cordova-plugin-statusbar/src/browser/statusbar.js",
"id": "cordova-plugin-statusbar.statusbar.Browser",
"pluginId": "cordova-plugin-statusbar",
"merges": [
"window.StatusBar"
]
},
{
"file": "plugins/phonegap-plugin-mobile-accessibility/www/mobile-accessibility.js",
"id": "phonegap-plugin-mobile-accessibility.mobile-accessibility",
"pluginId": "phonegap-plugin-mobile-accessibility",
"clobbers": [
"window.MobileAccessibility"
]
},
{
"file": "plugins/phonegap-plugin-mobile-accessibility/www/MobileAccessibilityNotifications.js",
"id": "phonegap-plugin-mobile-accessibility.MobileAccessibilityNotifications",
"pluginId": "phonegap-plugin-mobile-accessibility",
"clobbers": [
"MobileAccessibilityNotifications"
]
},
{
"file": "plugins/cordova-plugin-device-motion/www/Acceleration.js",
"id": "cordova-plugin-device-motion.Acceleration",
"pluginId": "cordova-plugin-device-motion",
"clobbers": [
"Acceleration"
]
},
{
"file": "plugins/cordova-plugin-device-motion/www/accelerometer.js",
"id": "cordova-plugin-device-motion.accelerometer",
"pluginId": "cordova-plugin-device-motion",
"clobbers": [
"navigator.accelerometer"
]
},
{
"file": "plugins/cordova-plugin-device-motion/src/browser/AccelerometerProxy.js",
"id": "cordova-plugin-device-motion.AccelerometerProxy",
"pluginId": "cordova-plugin-device-motion",
"runs": true
},
{
"file": "plugins/cordova-plugin-globalization/www/GlobalizationError.js",
"id": "cordova-plugin-globalization.GlobalizationError",
"pluginId": "cordova-plugin-globalization",
"clobbers": [
"window.GlobalizationError"
]
},
{
"file": "plugins/cordova-plugin-globalization/www/globalization.js",
"id": "cordova-plugin-globalization.globalization",
"pluginId": "cordova-plugin-globalization",
"clobbers": [
"navigator.globalization"
]
},
{
"file": "plugins/cordova-plugin-globalization/www/browser/moment.js",
"id": "cordova-plugin-globalization.moment",
"pluginId": "cordova-plugin-globalization",
"runs": true
},
{
"file": "plugins/cordova-plugin-globalization/src/browser/GlobalizationProxy.js",
"id": "cordova-plugin-globalization.GlobalizationProxy",
"pluginId": "cordova-plugin-globalization",
"runs": true
},
{
"file": "plugins/cordova-plugin-inappbrowser/www/inappbrowser.js",
"id": "cordova-plugin-inappbrowser.inappbrowser",
"pluginId": "cordova-plugin-inappbrowser",
"clobbers": [
"cordova.InAppBrowser.open",
"window.open"
]
},
{
"file": "plugins/cordova-plugin-inappbrowser/src/browser/InAppBrowserProxy.js",
"id": "cordova-plugin-inappbrowser.InAppBrowserProxy",
"pluginId": "cordova-plugin-inappbrowser",
"merges": [
""
]
},
{
"file": "plugins/cordova-plugin-file/www/DirectoryEntry.js",
"id": "cordova-plugin-file.DirectoryEntry",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.DirectoryEntry"
]
},
{
"file": "plugins/cordova-plugin-file/www/DirectoryReader.js",
"id": "cordova-plugin-file.DirectoryReader",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.DirectoryReader"
]
},
{
"file": "plugins/cordova-plugin-file/www/Entry.js",
"id": "cordova-plugin-file.Entry",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.Entry"
]
},
{
"file": "plugins/cordova-plugin-file/www/File.js",
"id": "cordova-plugin-file.File",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.File"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileEntry.js",
"id": "cordova-plugin-file.FileEntry",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileEntry"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileError.js",
"id": "cordova-plugin-file.FileError",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileError"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileReader.js",
"id": "cordova-plugin-file.FileReader",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileReader"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileSystem.js",
"id": "cordova-plugin-file.FileSystem",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileSystem"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileUploadOptions.js",
"id": "cordova-plugin-file.FileUploadOptions",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileUploadOptions"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileUploadResult.js",
"id": "cordova-plugin-file.FileUploadResult",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileUploadResult"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileWriter.js",
"id": "cordova-plugin-file.FileWriter",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileWriter"
]
},
{
"file": "plugins/cordova-plugin-file/www/Flags.js",
"id": "cordova-plugin-file.Flags",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.Flags"
]
},
{
"file": "plugins/cordova-plugin-file/www/LocalFileSystem.js",
"id": "cordova-plugin-file.LocalFileSystem",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.LocalFileSystem"
],
"merges": [
"window"
]
},
{
"file": "plugins/cordova-plugin-file/www/Metadata.js",
"id": "cordova-plugin-file.Metadata",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.Metadata"
]
},
{
"file": "plugins/cordova-plugin-file/www/ProgressEvent.js",
"id": "cordova-plugin-file.ProgressEvent",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.ProgressEvent"
]
},
{
"file": "plugins/cordova-plugin-file/www/fileSystems.js",
"id": "cordova-plugin-file.fileSystems",
"pluginId": "cordova-plugin-file"
},
{
"file": "plugins/cordova-plugin-file/www/requestFileSystem.js",
"id": "cordova-plugin-file.requestFileSystem",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.requestFileSystem"
]
},
{
"file": "plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js",
"id": "cordova-plugin-file.resolveLocalFileSystemURI",
"pluginId": "cordova-plugin-file",
"merges": [
"window"
]
},
{
"file": "plugins/cordova-plugin-file/www/browser/isChrome.js",
"id": "cordova-plugin-file.isChrome",
"pluginId": "cordova-plugin-file",
"runs": true
},
{
"file": "plugins/cordova-plugin-file/www/browser/Preparing.js",
"id": "cordova-plugin-file.Preparing",
"pluginId": "cordova-plugin-file",
"runs": true
},
{
"file": "plugins/cordova-plugin-file/src/browser/FileProxy.js",
"id": "cordova-plugin-file.browserFileProxy",
"pluginId": "cordova-plugin-file",
"runs": true
},
{
"file": "plugins/cordova-plugin-file/www/fileSystemPaths.js",
"id": "cordova-plugin-file.fileSystemPaths",
"pluginId": "cordova-plugin-file",
"merges": [
"cordova"
],
"runs": true
},
{
"file": "plugins/cordova-plugin-file/www/browser/FileSystem.js",
"id": "cordova-plugin-file.firefoxFileSystem",
"pluginId": "cordova-plugin-file",
"merges": [
"window.FileSystem"
]
},
{
"file": "plugins/cordova-plugin-media/www/MediaError.js",
"id": "cordova-plugin-media.MediaError",
"pluginId": "cordova-plugin-media",
"clobbers": [
"window.MediaError"
]
},
{
"file": "plugins/cordova-plugin-media/www/Media.js",
"id": "cordova-plugin-media.Media",
"pluginId": "cordova-plugin-media",
"clobbers": [
"window.Media"
]
},
{
"file": "plugins/cordova-plugin-media/www/browser/Media.js",
"id": "cordova-plugin-media.BrowserMedia",
"pluginId": "cordova-plugin-media",
"clobbers": [
"window.Media"
]
}
];
module.exports.metadata =
// TOP OF METADATA
{
"cordova-plugin-console": "1.0.5",
"cordova-plugin-device": "1.1.4",
"cordova-plugin-device-orientation": "1.0.5",
"cordova-plugin-dialogs": "1.2.1",
"cordova-plugin-network-information": "1.2.1",
"cordova-plugin-splashscreen": "3.2.2",
"cordova-plugin-statusbar": "2.1.3",
"cordova-plugin-whitelist": "1.2.2",
"phonegap-plugin-mobile-accessibility": "1.0.5-dev",
"cordova-plugin-device-motion": "1.2.4",
"cordova-plugin-globalization": "1.0.6",
"cordova-plugin-inappbrowser": "1.3.0",
"cordova-plugin-compat": "1.1.0",
"cordova-plugin-file": "4.3.2",
"cordova-plugin-media": "2.2.0"
}
// BOTTOM OF METADATA
}); | Nullpo/Kallat-Tablero | platforms/browser/www/cordova_plugins.js | JavaScript | gpl-3.0 | 13,698 |
<?php
// Controller for latestdeaths.
class Deaths extends Controller {
public function index() {
require("config.php");
$this->load->database();
if(@$_REQUEST['world'] == 0)
$world = 0;
else
$world = (int)@$_REQUEST['world'];
$world_name = ($config['worlds'] == $world);
$players_deaths = $this->db->query('SELECT `player_deaths`.`id`, `player_deaths`.`date`, `player_deaths`.`level`, `players`.`name`, `players`.`world_id` FROM `player_deaths` LEFT JOIN `players` ON `player_deaths`.`player_id` = `players`.`id` ORDER BY `date` DESC LIMIT 0,'.$config['latestdeathlimit'])->result();
if (!empty($players_deaths))
{
foreach ($players_deaths as $death)
{
$sql = $this->db->query('SELECT environment_killers.name AS monster_name, players.name AS player_name, players.deleted AS player_exists FROM killers LEFT JOIN environment_killers ON killers.id = environment_killers.kill_id LEFT JOIN player_killers ON killers.id = player_killers.kill_id LEFT JOIN players ON players.id = player_killers.player_id WHERE killers.death_id = '.$death->id.' ORDER BY killers.final_hit DESC, killers.id ASC')->result();
$players_rows = '<td><a href="?subtopic=characters&name='.urlencode($death->name).'"><b>'.$death->name.'</b></a> ';
$i = 0;
$count = count($death);
foreach($sql as $deaths)
{
$i++;
if($deaths->player_name != "")
{
if($i == 1)
$players_rows .= "killed at level <b>".$death->level."</b>";
else if($i == $count)
$players_rows .= " and";
else
$players_rows .= ",";
$players_rows .= " by ";
if($deaths->monster_name != "")
$players_rows .= $deaths->monster_name." summoned by ";
if($deaths->player_exists == 0)
$players_rows .= "<a href=\"index.php?subtopic=characters&name=".urlencode($deaths->player_name)."\">";
$players_rows .= $deaths->player_name;
if($deaths->player_exists == 0)
$players_rows .= "</a>";
}
else
{
if($i == 1)
$players_rows .= "died at level <b>".$death->level."</b>";
else if($i == $count)
$players_rows .= " and";
else
$players_rows .= ",";
$players_rows .= " by ".$deaths->monster_name;
}
$players_rows .= "</td>";
$data['deaths'][] = array('players_rows'=>$players_rows,'date'=>$death->date,'name'=>$death->name,'player_name'=>$deaths->player_name,'monster_name'=>$deaths->monster_name,'player_exists'=>$deaths->player_exists);
$players_rows = "";
}
}
$this->load->helper("form");
$this->load->view("deaths", $data);
}
else
{
echo "<h1>There are no players killed yet.</h1>";
}
}
}
?> | avuenja/modernaac | system/application/controllers/deaths.php | PHP | gpl-3.0 | 2,690 |
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2017 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from typing import Any, Dict, Set
from snapcraft import project
from snapcraft.internal.project_loader import grammar
from snapcraft.internal import pluginhandler, repo
from ._package_transformer import package_transformer
class PartGrammarProcessor:
"""Process part properties that support grammar.
Stage packages example:
>>> from unittest import mock
>>> import snapcraft
>>> # Pretend that all packages are valid
>>> repo = mock.Mock()
>>> repo.is_valid.return_value = True
>>> plugin = mock.Mock()
>>> plugin.stage_packages = [{'try': ['foo']}]
>>> processor = PartGrammarProcessor(
... plugin=plugin,
... properties={},
... project=snapcraft.project.Project(),
... repo=repo)
>>> processor.get_stage_packages()
{'foo'}
Build packages example:
>>> from unittest import mock
>>> import snapcraft
>>> # Pretend that all packages are valid
>>> repo = mock.Mock()
>>> repo.is_valid.return_value = True
>>> plugin = mock.Mock()
>>> plugin.build_packages = [{'try': ['foo']}]
>>> processor = PartGrammarProcessor(
... plugin=plugin,
... properties={},
... project=snapcraft.project.Project(),
... repo=repo)
>>> processor.get_build_packages()
{'foo'}
Source example:
>>> from unittest import mock
>>> import snapcraft
>>> plugin = mock.Mock()
>>> plugin.properties = {'source': [{'on amd64': 'foo'}, 'else fail']}
>>> processor = PartGrammarProcessor(
... plugin=plugin,
... properties=plugin.properties,
... project=snapcraft.project.Project(),
... repo=None)
>>> processor.get_source()
'foo'
"""
def __init__(
self,
*,
plugin: pluginhandler.PluginHandler,
properties: Dict[str, Any],
project: project.Project,
repo: "repo.Ubuntu"
) -> None:
self._project = project
self._repo = repo
self._build_snap_grammar = getattr(plugin, "build_snaps", [])
self.__build_snaps = set() # type: Set[str]
self._build_package_grammar = getattr(plugin, "build_packages", [])
self.__build_packages = set() # type: Set[str]
self._stage_package_grammar = getattr(plugin, "stage_packages", [])
self.__stage_packages = set() # type: Set[str]
source_grammar = properties.get("source", [""])
if not isinstance(source_grammar, list):
self._source_grammar = [source_grammar]
else:
self._source_grammar = source_grammar
self.__source = ""
def get_source(self) -> str:
if not self.__source:
# The grammar is array-based, even though we only support a single
# source.
processor = grammar.GrammarProcessor(
self._source_grammar, self._project, lambda s: True
)
source_array = processor.process()
if len(source_array) > 0:
self.__source = source_array.pop()
return self.__source
def get_build_snaps(self) -> Set[str]:
if not self.__build_snaps:
processor = grammar.GrammarProcessor(
self._build_snap_grammar,
self._project,
repo.snaps.SnapPackage.is_valid_snap,
)
self.__build_snaps = processor.process()
return self.__build_snaps
def get_build_packages(self) -> Set[str]:
if not self.__build_packages:
processor = grammar.GrammarProcessor(
self._build_package_grammar,
self._project,
self._repo.build_package_is_valid,
transformer=package_transformer,
)
self.__build_packages = processor.process()
return self.__build_packages
def get_stage_packages(self) -> Set[str]:
if not self.__stage_packages:
processor = grammar.GrammarProcessor(
self._stage_package_grammar,
self._project,
self._repo.is_valid,
transformer=package_transformer,
)
self.__stage_packages = processor.process()
return self.__stage_packages
| sergiusens/snapcraft | snapcraft/internal/project_loader/grammar_processing/_part_grammar_processor.py | Python | gpl-3.0 | 4,927 |
#include <cmath>
#include <cfloat> // DBL_MAX
#include "Action_GIST.h"
#include "CpptrajStdio.h"
#include "Constants.h"
#include "DataSet_MatrixFlt.h"
#include "DataSet_GridFlt.h"
#include "DataSet_GridDbl.h"
#include "ProgressBar.h"
#include "StringRoutines.h"
#include "DistRoutines.h"
#ifdef _OPENMP
# include <omp.h>
#endif
const double Action_GIST::maxD_ = DBL_MAX;
Action_GIST::Action_GIST() :
debug_(0),
numthreads_(1),
#ifdef CUDA
numberAtoms_(0),
numberAtomTypes_(0),
headAtomType_(0),
solvent_(NULL),
NBindex_c_(NULL),
molecule_c_(NULL),
paramsLJ_c_(NULL),
max_c_(NULL),
min_c_(NULL),
result_w_c_(NULL),
result_s_c_(NULL),
result_O_c_(NULL),
result_N_c_(NULL),
#endif
gridspacing_(0),
gridcntr_(0.0),
griddim_(0.0),
gO_(0),
gH_(0),
Esw_(0),
Eww_(0),
dTStrans_(0),
dTSorient_(0),
dTSsix_(0),
neighbor_norm_(0),
dipole_(0),
order_norm_(0),
dipolex_(0),
dipoley_(0),
dipolez_(0),
PME_(0),
U_PME_(0),
ww_Eij_(0),
G_max_(0.0),
CurrentParm_(0),
datafile_(0),
eijfile_(0),
infofile_(0),
fltFmt_(TextFormat::GDOUBLE),
intFmt_(TextFormat::INTEGER),
BULK_DENS_(0.0),
temperature_(0.0),
NeighborCut2_(12.25), // 3.5^2
// system_potential_energy_(0),
// solute_potential_energy_(0),
MAX_GRID_PT_(0),
NSOLVENT_(0),
N_ON_GRID_(0),
nMolAtoms_(0),
NFRAME_(0),
max_nwat_(0),
doOrder_(false),
doEij_(false),
skipE_(false),
includeIons_(true)
{}
/** GIST help */
void Action_GIST::Help() const {
mprintf("\t[doorder] [doeij] [skipE] [skipS] [refdens <rdval>] [temp <tval>]\n"
"\t[noimage] [gridcntr <xval> <yval> <zval>] [excludeions]\n"
"\t[griddim <nx> <ny> <nz>] [gridspacn <spaceval>] [neighborcut <ncut>]\n"
"\t[prefix <filename prefix>] [ext <grid extension>] [out <output suffix>]\n"
"\t[floatfmt {double|scientific|general}] [floatwidth <fw>] [floatprec <fp>]\n"
"\t[intwidth <iw>]\n"
"\t[info <info suffix>]\n");
# ifdef LIBPME
mprintf("\t[nopme|pme %s\n\t %s\n\t %s]\n", EwaldOptions::KeywordsCommon1(), EwaldOptions::KeywordsCommon2(), EwaldOptions::KeywordsPME());
# endif
mprintf("Perform Grid Inhomogenous Solvation Theory calculation.\n"
#ifdef CUDA
"The option doeij is not available, when using the CUDA accelerated version,\n"
"as this would need way too much memory."
#endif
);
}
/** Init GIST action. */
Action::RetType Action_GIST::Init(ArgList& actionArgs, ActionInit& init, int debugIn)
{
debug_ = debugIn;
# ifdef MPI
if (init.TrajComm().Size() > 1) {
mprinterr("Error: 'gist' action does not work with > 1 process (%i processes currently).\n",
init.TrajComm().Size());
return Action::ERR;
}
# endif
gist_init_.Start();
prefix_ = actionArgs.GetStringKey("prefix");
if (prefix_.empty()) prefix_.assign("gist");
std::string ext = actionArgs.GetStringKey("ext");
if (ext.empty()) ext.assign(".dx");
std::string gistout = actionArgs.GetStringKey("out");
if (gistout.empty()) gistout.assign(prefix_ + "-output.dat");
datafile_ = init.DFL().AddCpptrajFile( gistout, "GIST output" );
if (datafile_ == 0) return Action::ERR;
// Info file: if not specified use STDOUT
gistout = actionArgs.GetStringKey("info");
if (!gistout.empty()) gistout = prefix_ + "-" + gistout;
infofile_ = init.DFL().AddCpptrajFile( gistout, "GIST info", DataFileList::TEXT, true );
if (infofile_ == 0) return Action::ERR;
// Grid files
DataFile* file_gO = init.DFL().AddDataFile( prefix_ + "-gO" + ext );
DataFile* file_gH = init.DFL().AddDataFile( prefix_ + "-gH" + ext );
DataFile* file_Esw = init.DFL().AddDataFile(prefix_ + "-Esw-dens" + ext);
DataFile* file_Eww = init.DFL().AddDataFile(prefix_ + "-Eww-dens" + ext);
DataFile* file_dTStrans = init.DFL().AddDataFile(prefix_ + "-dTStrans-dens" + ext);
DataFile* file_dTSorient = init.DFL().AddDataFile(prefix_ + "-dTSorient-dens" + ext);
DataFile* file_dTSsix = init.DFL().AddDataFile(prefix_ + "-dTSsix-dens" + ext);
DataFile* file_neighbor_norm = init.DFL().AddDataFile(prefix_ + "-neighbor-norm" + ext);
DataFile* file_dipole = init.DFL().AddDataFile(prefix_ + "-dipole-dens" + ext);
DataFile* file_order_norm = init.DFL().AddDataFile(prefix_ + "-order-norm" + ext);
DataFile* file_dipolex = init.DFL().AddDataFile(prefix_ + "-dipolex-dens" + ext);
DataFile* file_dipoley = init.DFL().AddDataFile(prefix_ + "-dipoley-dens" + ext);
DataFile* file_dipolez = init.DFL().AddDataFile(prefix_ + "-dipolez-dens" + ext);
// Output format keywords
std::string floatfmt = actionArgs.GetStringKey("floatfmt");
if (!floatfmt.empty()) {
if (floatfmt == "double")
fltFmt_.SetFormatType(TextFormat::DOUBLE);
else if (floatfmt == "scientific")
fltFmt_.SetFormatType(TextFormat::SCIENTIFIC);
else if (floatfmt == "general")
fltFmt_.SetFormatType(TextFormat::GDOUBLE);
else {
mprinterr("Error: Unrecognized format type for 'floatfmt': %s\n", floatfmt.c_str());
return Action::ERR;
}
}
fltFmt_.SetFormatWidthPrecision( actionArgs.getKeyInt("floatwidth", 0),
actionArgs.getKeyInt("floatprec", -1) );
intFmt_.SetFormatWidth( actionArgs.getKeyInt("intwidth", 0) );
// Other keywords
double neighborCut = actionArgs.getKeyDouble("neighborcut", 3.5);
NeighborCut2_ = neighborCut * neighborCut;
includeIons_ = !actionArgs.hasKey("excludeions");
imageOpt_.InitImaging( !(actionArgs.hasKey("noimage")), actionArgs.hasKey("nonortho") );
doOrder_ = actionArgs.hasKey("doorder");
doEij_ = actionArgs.hasKey("doeij");
#ifdef CUDA
if (this->doEij_) {
mprinterr("Error: 'doeij' cannot be specified when using CUDA.\n");
return Action::ERR;
}
#endif
skipE_ = actionArgs.hasKey("skipE");
if (skipE_) {
if (doEij_) {
mprinterr("Error: 'doeij' cannot be specified if 'skipE' is specified.\n");
return Action::ERR;
}
}
// Parse PME options
// TODO once PME output is stable, make pme true the default when LIBPME present.
//# ifdef LIBPME
// usePme_ = true;
//# else
usePme_ = false;
//# endif
# ifdef CUDA
// Disable PME for CUDA
usePme_ = false;
# endif
if (actionArgs.hasKey("pme"))
usePme_ = true;
else if (actionArgs.hasKey("nopme"))
usePme_ = false;
// PME and doeij are not compatible
if (usePme_ && doEij_) {
mprinterr("Error: 'doeij' cannot be used with PME. Specify 'nopme' to use 'doeij'\n");
return Action::ERR;
}
if (usePme_) {
# ifdef LIBPME
pmeOpts_.AllowLjPme(false);
if (pmeOpts_.GetOptions(EwaldOptions::PME, actionArgs, "GIST")) {
mprinterr("Error: Getting PME options for GIST failed.\n");
return Action::ERR;
}
# else
mprinterr("Error: 'pme' with GIST requires compilation with LIBPME.\n");
return Action::ERR;
# endif
}
DataFile* file_energy_pme = 0;
DataFile* file_U_energy_pme = 0;
if (usePme_) {
file_energy_pme = init.DFL().AddDataFile(prefix_ + "-Water-Etot-pme-dens" + ext);
file_U_energy_pme = init.DFL().AddDataFile(prefix_ + "-Solute-Etot-pme-dens"+ ext);
}
this->skipS_ = actionArgs.hasKey("skipS");
if (doEij_) {
eijfile_ = init.DFL().AddCpptrajFile(prefix_ + "-Eww_ij.dat", "GIST Eij matrix file");
if (eijfile_ == 0) return Action::ERR;
}
// Set Bulk Density 55.5M
BULK_DENS_ = actionArgs.getKeyDouble("refdens", 0.0334);
if ( BULK_DENS_ > (0.0334*1.2) )
mprintf("Warning: water reference density is high, consider using 0.0334 for 1g/cc water density\n");
else if ( BULK_DENS_ < (0.0334*0.8) )
mprintf("Warning: water reference density is low, consider using 0.0334 for 1g/cc water density\n");
temperature_ = actionArgs.getKeyDouble("temp", 300.0);
if (temperature_ < 0.0) {
mprinterr("Error: Negative temperature specified.\n");
return Action::ERR;
}
// Grid spacing
gridspacing_ = actionArgs.getKeyDouble("gridspacn", 0.50);
// Grid center
gridcntr_ = Vec3(0.0);
if ( actionArgs.hasKey("gridcntr") ) {
gridcntr_[0] = actionArgs.getNextDouble(-1);
gridcntr_[1] = actionArgs.getNextDouble(-1);
gridcntr_[2] = actionArgs.getNextDouble(-1);
} else
mprintf("Warning: No grid center values specified, using default (origin)\n");
// Grid dimensions
int nx = 40;
int ny = 40;
int nz = 40;
if ( actionArgs.hasKey("griddim") ) {
nx = actionArgs.getNextInteger(-1);
ny = actionArgs.getNextInteger(-1);
nz = actionArgs.getNextInteger(-1);
} else
mprintf("Warning: No grid dimension values specified, using default (40,40,40)\n");
griddim_ = Vec3((double)nx, (double)ny, (double)nz);
// Data set name
std::string dsname = actionArgs.GetStringKey("name");
if (dsname.empty())
dsname = init.DSL().GenerateDefaultName("GIST");
// Set up DataSets.
gO_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "gO"));
gH_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "gH"));
Esw_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "Esw"));
Eww_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "Eww"));
dTStrans_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "dTStrans"));
dTSorient_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "dTSorient"));
dTSsix_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "dTSsix"));
neighbor_norm_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "neighbor"));
dipole_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname, "dipole"));
order_norm_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_DBL, MetaData(dsname, "order"));
dipolex_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_DBL, MetaData(dsname, "dipolex"));
dipoley_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_DBL, MetaData(dsname, "dipoley"));
dipolez_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_DBL, MetaData(dsname, "dipolez"));
if (gO_==0 || gH_==0 || Esw_==0 || Eww_==0 || dTStrans_==0 || dTSorient_==0 ||
dTSsix_==0 || neighbor_norm_==0 || dipole_==0 || order_norm_==0 ||
dipolex_==0 || dipoley_==0 || dipolez_==0)
return Action::ERR;
if (usePme_) {
PME_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT, MetaData(dsname,"PME"));
U_PME_ = (DataSet_3D*)init.DSL().AddSet(DataSet::GRID_FLT,MetaData(dsname,"U_PME"));
if (PME_ == 0 || U_PME_ == 0) return Action::ERR;
}
if (doEij_) {
ww_Eij_ = (DataSet_MatrixFlt*)init.DSL().AddSet(DataSet::MATRIX_FLT, MetaData(dsname, "Eij"));
if (ww_Eij_ == 0) return Action::ERR;
}
// Allocate DataSets. TODO non-orthogonal grids as well
Vec3 v_spacing( gridspacing_ );
gO_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
MAX_GRID_PT_ = gO_->Size();
gH_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
Esw_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
Eww_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
dTStrans_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
dTSorient_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
dTSsix_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
neighbor_norm_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
dipole_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
order_norm_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
dipolex_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
dipoley_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
dipolez_->Allocate_N_C_D(nx, ny, nz, gridcntr_, v_spacing);
if (usePme_) {
PME_->Allocate_N_C_D(nx,ny,nz,gridcntr_,v_spacing);
U_PME_->Allocate_N_C_D(nx,ny,nz,gridcntr_,v_spacing);
}
if (ww_Eij_ != 0) {
if (ww_Eij_->AllocateTriangle( MAX_GRID_PT_ )) {
mprinterr("Error: Could not allocate memory for water-water Eij matrix.\n");
return Action::ERR;
}
}
// Add sets to files
file_gO->AddDataSet( gO_ );
file_gH->AddDataSet( gH_ );
file_Esw->AddDataSet( Esw_ );
file_Eww->AddDataSet( Eww_ );
file_dTStrans->AddDataSet( dTStrans_ );
file_dTSorient->AddDataSet( dTSorient_ );
file_dTSsix->AddDataSet( dTSsix_ );
file_neighbor_norm->AddDataSet( neighbor_norm_ );
file_dipole->AddDataSet( dipole_ );
file_order_norm->AddDataSet( order_norm_ );
file_dipolex->AddDataSet( dipolex_ );
file_dipoley->AddDataSet( dipoley_ );
file_dipolez->AddDataSet( dipolez_ );
if (usePme_) {
file_energy_pme->AddDataSet(PME_);
file_U_energy_pme->AddDataSet(U_PME_);
}
// Set up grid params TODO non-orthogonal as well
G_max_ = Vec3( (double)nx * gridspacing_ + 1.5,
(double)ny * gridspacing_ + 1.5,
(double)nz * gridspacing_ + 1.5 );
N_waters_.assign( MAX_GRID_PT_, 0 );
N_solute_atoms_.assign( MAX_GRID_PT_, 0);
N_hydrogens_.assign( MAX_GRID_PT_, 0 );
voxel_xyz_.resize( MAX_GRID_PT_ ); // [] = X Y Z
voxel_Q_.resize( MAX_GRID_PT_ ); // [] = W4 X4 Y4 Z4
numthreads_ = 1;
# ifdef _OPENMP
# pragma omp parallel
{
if (omp_get_thread_num() == 0)
numthreads_ = omp_get_num_threads();
}
# endif
if (!skipE_) {
E_UV_VDW_.resize( numthreads_ );
E_UV_Elec_.resize( numthreads_ );
E_VV_VDW_.resize( numthreads_ );
E_VV_Elec_.resize( numthreads_ );
neighbor_.resize( numthreads_ );
for (int thread = 0; thread != numthreads_; thread++) {
E_UV_VDW_[thread].assign( MAX_GRID_PT_, 0 );
E_UV_Elec_[thread].assign( MAX_GRID_PT_, 0 );
E_VV_VDW_[thread].assign( MAX_GRID_PT_, 0 );
E_VV_Elec_[thread].assign( MAX_GRID_PT_, 0 );
neighbor_[thread].assign( MAX_GRID_PT_, 0 );
}
if (usePme_) {
E_pme_.assign( MAX_GRID_PT_, 0 );
U_E_pme_.assign( MAX_GRID_PT_, 0 );
//E_pme_.resize( numthreads_);
//U_E_pme_.resize(numthreads_);
//for (int thread = 0; thread != numthreads_; thread++) {
// E_pme_[thread].assign( MAX_GRID_PT_,0);
// U_E_pme_[thread].assign( MAX_GRID_PT_,0);
//}
}
# ifdef _OPENMP
if (doEij_) {
// Since allocating a separate matrix for every thread will consume a lot
// of memory and since the Eij matrices tend to be sparse since solute is
// often present, each thread will record any interaction energies they
// calculate separately and add to the Eij matrix afterwards to avoid
// memory clashes. Probably not ideal if the bulk of the grid is water however.
EIJ_V1_.resize( numthreads_ );
EIJ_V2_.resize( numthreads_ );
EIJ_EN_.resize( numthreads_ );
}
# endif
#ifdef CUDA
if (this->skipE_ && this->doOrder_) {
mprintf("When the keyword \"skipE\" is supplied, \"doorder\" cannot be"
" chosen, as both calculations are done on the GPU at the same"
" time.\nIgnoring \"doorder!\"\n");
}
#endif
}
//Box gbox;
//gbox.SetBetaLengths( 90.0, (double)nx * gridspacing_,
// (double)ny * gridspacing_,
// (double)nz * gridspacing_ );
//grid_.Setup_O_Box( nx, ny, nz, gO_->GridOrigin(), gbox );
//grid_.Setup_O_D( nx, ny, nz, gO_->GridOrigin(), v_spacing );
mprintf(" GIST:\n");
mprintf("\tOutput prefix= '%s', grid output extension= '%s'\n", prefix_.c_str(), ext.c_str());
mprintf("\tOutput float format string= '%s', output integer format string= '%s'\n", fltFmt_.fmt(), intFmt_.fmt());
mprintf("\tGIST info written to '%s'\n", infofile_->Filename().full());
mprintf("\tName for data sets: %s\n", dsname.c_str());
if (doOrder_)
mprintf("\tDoing order calculation.\n");
else
mprintf("\tSkipping order calculation.\n");
if (skipE_)
mprintf("\tSkipping energy calculation.\n");
else {
mprintf("\tPerforming energy calculation.\n");
if (numthreads_ > 1)
mprintf("\tParallelizing energy calculation with %i threads.\n", numthreads_);
if (usePme_) {
mprintf("\tUsing PME.\n");
pmeOpts_.PrintOptions();
}
}
mprintf("\tCut off for determining solvent O-O neighbors is %f Ang\n", sqrt(NeighborCut2_));
if (includeIons_)
mprintf("\tIons will be included in the solute region.\n");
else
mprintf("\tIons will be excluded from the calculation.\n");
if (doEij_) {
mprintf("\tComputing and printing water-water Eij matrix, output to '%s'\n",
eijfile_->Filename().full());
mprintf("\tWater-water Eij matrix size is %s\n",
ByteString(ww_Eij_->MemUsageInBytes(), BYTE_DECIMAL).c_str());
} else
mprintf("\tSkipping water-water Eij matrix.\n");
mprintf("\tWater reference density: %6.4f molecules/Ang^3\n", BULK_DENS_);
mprintf("\tSimulation temperature: %6.4f K\n", temperature_);
if (imageOpt_.UseImage())
mprintf("\tDistances will be imaged.\n");
else
mprintf("\tDistances will not be imaged.\n");
if (imageOpt_.ForceNonOrtho())
mprintf("\tWill use non-orthogonal imaging routines for all cell types.\n");
gO_->GridInfo();
mprintf("\tNumber of voxels: %u, voxel volume: %f Ang^3\n",
MAX_GRID_PT_, gO_->Bin().VoxelVolume());
mprintf("#Please cite these papers if you use GIST results in a publication:\n"
"# Steven Ramsey, Crystal Nguyen, Romelia Salomon-Ferrer, Ross C. Walker, Michael K. Gilson, and Tom Kurtzman. J. Comp. Chem. 37 (21) 2016\n"
"# Crystal Nguyen, Michael K. Gilson, and Tom Young, arXiv:1108.4876v1 (2011)\n"
"# Crystal N. Nguyen, Tom Kurtzman Young, and Michael K. Gilson,\n"
"# J. Chem. Phys. 137, 044101 (2012)\n"
"# Lazaridis, J. Phys. Chem. B 102, 3531–3541 (1998)\n"
#ifdef LIBPME
"#When using the PME-enhanced version of GIST, please cite:\n"
"# Lieyang Chen, Anthony Cruz, Daniel R. Roe, Andy C. Simmonett, Lauren Wickstrom, Nanjie Deng, Tom Kurtzman. JCTC (2021) DOI: 10.1021/acs.jctc.0c01185\n"
#endif
#ifdef CUDA
"#When using the GPU parallelized version of GIST, please cite:\n"
"# Johannes Kraml, Anna S. Kamenik, Franz Waibl, Michael Schauperl, Klaus R. Liedl, JCTC (2019)\n"
#endif
);
# ifdef GIST_USE_NONORTHO_DIST2
mprintf("DEBUG: Using regular non-orthogonal distance routine.\n");
# endif
gist_init_.Stop();
return Action::OK;
}
/// \return True if given floating point values are not equal within a tolerance
static inline bool NotEqual(double v1, double v2) { return ( fabs(v1 - v2) > Constants::SMALL ); }
/** Set up GIST action. */
Action::RetType Action_GIST::Setup(ActionSetup& setup) {
gist_setup_.Start();
CurrentParm_ = setup.TopAddress();
// We need box info
if (!setup.CoordInfo().TrajBox().HasBox()) {
mprinterr("Error: Must have explicit solvent with periodic boundaries!");
return Action::ERR;
}
imageOpt_.SetupImaging( setup.CoordInfo().TrajBox().HasBox() );
#ifdef CUDA
this->numberAtoms_ = setup.Top().Natom();
this->solvent_ = new bool[this->numberAtoms_];
#endif
// Initialize PME
if (usePme_) {
# ifdef LIBPME
if (gistPme_.Init( setup.CoordInfo().TrajBox(), pmeOpts_, debug_ )) {
mprinterr("Error: GIST PME init failed.\n");
return Action::ERR;
}
// By default all atoms are selected for GIST PME to match up with atom_voxel_ array.
if (gistPme_.Setup_PME_GIST( setup.Top(), numthreads_, NeighborCut2_ )) {
mprinterr("Error: GIST PME setup/array allocation failed.\n");
return Action::ERR;
}
# else
mprinterr("Error: GIST PME requires compilation with LIBPME.\n");
return Action::ERR;
# endif
}
// Get molecule number for each solvent molecule
//mol_nums_.clear();
O_idxs_.clear();
A_idxs_.clear();
atom_voxel_.clear();
atomIsSolute_.clear();
atomIsSolventO_.clear();
U_idxs_.clear();
// NOTE: these are just guesses
O_idxs_.reserve( setup.Top().Nsolvent() );
A_idxs_.reserve( setup.Top().Natom() );
// atom_voxel_ and atomIsSolute will be indexed by atom #
atom_voxel_.assign( setup.Top().Natom(), OFF_GRID_ );
atomIsSolute_.assign(setup.Top().Natom(), false);
atomIsSolventO_.assign(setup.Top().Natom(), false);
U_idxs_.reserve(setup.Top().Natom()-setup.Top().Nsolvent()*nMolAtoms_);
unsigned int midx = 0;
unsigned int NsolventAtoms = 0;
unsigned int NsoluteAtoms = 0;
bool isFirstSolvent = true;
for (Topology::mol_iterator mol = setup.Top().MolStart();
mol != setup.Top().MolEnd(); ++mol, ++midx)
{
if (mol->IsSolvent()) {
// NOTE: We assume the oxygen is the first atom!
int o_idx = mol->MolUnit().Front();
#ifdef CUDA
this->headAtomType_ = setup.Top()[o_idx].TypeIndex();
#endif
// Check that molecule has correct # of atoms
unsigned int molNumAtoms = (unsigned int)mol->NumAtoms();
if (nMolAtoms_ == 0) {
nMolAtoms_ = molNumAtoms;
mprintf("\tEach solvent molecule has %u atoms\n", nMolAtoms_);
} else if (molNumAtoms != nMolAtoms_) {
mprinterr("Error: All solvent molecules must have same # atoms.\n"
"Error: Molecule '%s' has %u atoms, expected %u.\n",
setup.Top().TruncResNameNum( setup.Top()[o_idx].ResNum() ).c_str(),
molNumAtoms, nMolAtoms_);
return Action::ERR;
}
//mol_nums_.push_back( midx ); // TODO needed?
// Check that first atom is actually Oxygen
if (setup.Top()[o_idx].Element() != Atom::OXYGEN) {
mprinterr("Error: Molecule '%s' is not water or does not have oxygen atom.\n",
setup.Top().TruncResNameNum( setup.Top()[o_idx].ResNum() ).c_str());
return Action::ERR;
}
O_idxs_.push_back( o_idx );
atomIsSolventO_[o_idx] = true;
// Check that the next two atoms are Hydrogens
if (setup.Top()[o_idx+1].Element() != Atom::HYDROGEN ||
setup.Top()[o_idx+2].Element() != Atom::HYDROGEN)
{
mprinterr("Error: Molecule '%s' does not have hydrogen atoms.\n",
setup.Top().TruncResNameNum( setup.Top()[o_idx].ResNum() ).c_str());
return Action::ERR;
}
// Save all atom indices for energy calc, including extra points
for (unsigned int IDX = 0; IDX != nMolAtoms_; IDX++) {
A_idxs_.push_back( o_idx + IDX );
atomIsSolute_[A_idxs_.back()] = false; // The identity of the atom is water
atom_voxel_[A_idxs_.back()] = OFF_GRID_;
#ifdef CUDA
this->molecule_.push_back( setup.Top()[o_idx + IDX ].MolNum() );
this->charges_.push_back( setup.Top()[o_idx + IDX ].Charge() );
this->atomTypes_.push_back( setup.Top()[o_idx + IDX ].TypeIndex() );
this->solvent_[ o_idx + IDX ] = true;
#endif
}
NsolventAtoms += nMolAtoms_;
// If first solvent molecule, save charges. If not, check that charges match.
if (isFirstSolvent) {
double q_sum = 0.0;
Q_.reserve( nMolAtoms_ );
for (unsigned int IDX = 0; IDX != nMolAtoms_; IDX++) {
Q_.push_back( setup.Top()[o_idx+IDX].Charge() );
q_sum += Q_.back();
//mprintf("DEBUG: Q= %20.10E q_sum= %20.10E\n", setup.Top()[o_idx+IDX].Charge(), q_sum);
}
// Sanity checks.
// NOTE: We know indices 1 and 2 are hydrogens (with 0 being oxygen); this is checked above.
if (NotEqual(Q_[1], Q_[2]))
mprintf("Warning: Charges on water hydrogens do not match (%g, %g).\n", Q_[1], Q_[2]);
if (fabs( q_sum ) > 0.0)
mprintf("Warning: Charges on water do not sum to 0 (%g)\n", q_sum);
//mprintf("DEBUG: Water charges: O=%g H1=%g H2=%g\n", q_O_, q_H1_, q_H2_);
} else {
for (unsigned int IDX = 0; IDX < nMolAtoms_; IDX++) {
double q_atom = setup.Top()[o_idx+IDX].Charge();
if (NotEqual(Q_[IDX], q_atom)) {
mprintf("Warning: Charge on water '%s' (%g) does not match first water (%g).\n",
setup.Top().TruncResAtomName( o_idx+IDX ).c_str(), q_atom, Q_[IDX]);
}
}
}
isFirstSolvent = false;
} else {
// This is a non-solvent molecule. Save atom indices. May want to exclude
// if only 1 atom (probably ion).
if (mol->NumAtoms() > 1 || includeIons_) {
for (Unit::const_iterator seg = mol->MolUnit().segBegin();
seg != mol->MolUnit().segEnd(); ++seg)
{
for (int u_idx = seg->Begin(); u_idx != seg->End(); ++u_idx) {
A_idxs_.push_back( u_idx );
atomIsSolute_[A_idxs_.back()] = true; // the identity of the atom is solute
NsoluteAtoms++;
U_idxs_.push_back( u_idx ); // store the solute atom index for locating voxel index
#ifdef CUDA
this->molecule_.push_back( setup.Top()[ u_idx ].MolNum() );
this->charges_.push_back( setup.Top()[ u_idx ].Charge() );
this->atomTypes_.push_back( setup.Top()[ u_idx ].TypeIndex() );
this->solvent_[ u_idx ] = false;
#endif
}
}
}
}
}
NSOLVENT_ = O_idxs_.size();
mprintf("\t%zu solvent molecules, %u solvent atoms, %u solute atoms (%zu total).\n",
O_idxs_.size(), NsolventAtoms, NsoluteAtoms, A_idxs_.size());
if (doOrder_ && NSOLVENT_ < 5) {
mprintf("Warning: Less than 5 solvent molecules. Cannot perform order calculation.\n");
doOrder_ = false;
}
// Allocate space for saving indices of water atoms that are on the grid
// Estimate how many solvent molecules can possibly fit onto the grid.
// Add some extra voxels as a buffer.
double max_voxels = (double)MAX_GRID_PT_ + (1.10 * (double)MAX_GRID_PT_);
double totalVolume = max_voxels * gO_->Bin().VoxelVolume();
double max_mols = totalVolume * BULK_DENS_;
//mprintf("\tEstimating grid can fit a max of %.0f solvent molecules (w/ 10%% buffer).\n",
// max_mols);
OnGrid_idxs_.reserve( (size_t)max_mols * (size_t)nMolAtoms_ );
N_ON_GRID_ = 0;
if (!skipE_) {
if (imageOpt_.ImagingEnabled())
mprintf("\tImaging enabled for energy distance calculations.\n");
else
mprintf("\tNo imaging will be performed for energy distance calculations.\n");
}
#ifdef CUDA
NonbondParmType nb = setup.Top().Nonbond();
this->NBIndex_ = nb.NBindex();
this->numberAtomTypes_ = nb.Ntypes();
for (unsigned int i = 0; i < nb.NBarray().size(); ++i) {
this->lJParamsA_.push_back( (float) nb.NBarray().at(i).A() );
this->lJParamsB_.push_back( (float) nb.NBarray().at(i).B() );
}
try {
allocateCuda(((void**)&this->NBindex_c_), this->NBIndex_.size() * sizeof(int));
allocateCuda((void**)&this->max_c_, 3 * sizeof(float));
allocateCuda((void**)&this->min_c_, 3 * sizeof(float));
allocateCuda((void**)&this->result_w_c_, this->numberAtoms_ * sizeof(float));
allocateCuda((void**)&this->result_s_c_, this->numberAtoms_ * sizeof(float));
allocateCuda((void**)&this->result_O_c_, this->numberAtoms_ * 4 * sizeof(int));
allocateCuda((void**)&this->result_N_c_, this->numberAtoms_ * sizeof(int));
} catch (CudaException &e) {
mprinterr("Error: Could not allocate memory on GPU!\n");
this->freeGPUMemory();
return Action::ERR;
}
try {
this->copyToGPU();
} catch (CudaException &e) {
return Action::ERR;
}
#endif
gist_setup_.Stop();
return Action::OK;
}
const Vec3 Action_GIST::x_lab_ = Vec3(1.0, 0.0, 0.0);
const Vec3 Action_GIST::y_lab_ = Vec3(0.0, 1.0, 0.0);
const Vec3 Action_GIST::z_lab_ = Vec3(0.0, 0.0, 1.0);
const double Action_GIST::QFAC_ = Constants::ELECTOAMBER * Constants::ELECTOAMBER;
const int Action_GIST::OFF_GRID_ = -1;
/* Calculate the charge-charge, vdw interaction using pme, frame by frame
*
*/
void Action_GIST::NonbondEnergy_pme(Frame const& frameIn)
{
# ifdef LIBPME
// Two energy terms for the whole system
//double ene_pme_all = 0.0;
//double ene_vdw_all = 0.0;
// pointer to the E_pme_, where has the voxel-wise pme energy for water
double* E_pme_grid = &E_pme_[0];
// pointer to U_E_pme_, where has the voxel-wise pme energy for solute
double* U_E_pme_grid = &U_E_pme_[0];
gistPme_.CalcNonbondEnergy_GIST(frameIn, atom_voxel_, atomIsSolute_, atomIsSolventO_,
E_UV_VDW_, E_UV_Elec_, E_VV_VDW_, E_VV_Elec_,
neighbor_);
// system_potential_energy_ += ene_pme_all + ene_vdw_all;
// Water energy on the GIST grid
double pme_sum = 0.0;
for (unsigned int gidx=0; gidx < N_ON_GRID_; gidx++ )
{
int a = OnGrid_idxs_[gidx]; // index of the atom of on-grid solvent;
int a_voxel = atom_voxel_[a]; // index of the voxel
double nonbond_energy = gistPme_.E_of_atom(a);
pme_sum += nonbond_energy;
E_pme_grid[a_voxel] += nonbond_energy;
}
// Solute energy on the GIST grid
double solute_on_grid_sum = 0.0; // To sum up the potential energy on solute atoms that on the grid
for (unsigned int uidx=0; uidx < U_onGrid_idxs_.size(); uidx++ )
{
int u = U_onGrid_idxs_[uidx]; // index of the solute atom on the grid
int u_voxel = atom_voxel_[u];
double u_nonbond_energy = gistPme_.E_of_atom(u);
solute_on_grid_sum += u_nonbond_energy;
U_E_pme_grid[u_voxel] += u_nonbond_energy;
}
/*
// Total solute energy
double solute_sum = 0.0;
for (unsigned int uidx=0; uidx < U_idxs_.size(); uidx++)
{
int u = U_idxs_[uidx];
double u_nonbond_energy = gistPme_.E_of_atom(u);
solute_sum += u_nonbond_energy;
solute_potential_energy_ += u_nonbond_energy; // used to calculated the ensemble energy for all solute, will print out in terminal
}
*/
//mprintf("The total potential energy on water atoms: %f \n", pme_sum);
# else /*LIBPME */
mprinterr("Error: Compiled without LIBPME\n");
return;
# endif /*LIBPME */
}
/** Non-bonded energy calc. */
void Action_GIST::Ecalc(double rij2, double q1, double q2, NonbondType const& LJ,
double& Evdw, double& Eelec)
{
double rij = sqrt(rij2);
// VDW
double r2 = 1.0 / rij2;
double r6 = r2 * r2 * r2;
double r12 = r6 * r6;
double f12 = LJ.A() * r12; // A/r^12
double f6 = LJ.B() * r6; // B/r^6
Evdw = f12 - f6; // (A/r^12)-(B/r^6)
// Coulomb
double qiqj = QFAC_ * q1 * q2;
Eelec = qiqj / rij;
}
/** Calculate the energy between all solute/solvent atoms and solvent atoms
* on the grid. This is done after the intial GIST calculations
* so that all waters have voxels assigned in atom_voxel_.
* NOTE: This routine modifies the coordinates in OnGrid_XYZ_ when the cell
* has nonorthogonal shape in order to properly satsify the minimum
* image convention, so any calculations that rely on the on grid
* coordinates (like Order()) must be done *BEFORE* this routine.
*/
void Action_GIST::NonbondEnergy(Frame const& frameIn, Topology const& topIn)
{
// Set up imaging info.
if (imageOpt_.ImagingType() == ImageOption::NONORTHO) {
// Wrap on-grid water coords back to primary cell TODO openmp
double* ongrid_xyz = &OnGrid_XYZ_[0];
int maxXYZ = (int)OnGrid_XYZ_.size();
int idx;
# ifdef _OPENMP
# pragma omp parallel private(idx)
{
# pragma omp for
# endif
for (idx = 0; idx < maxXYZ; idx += 3)
{
double* XYZ = ongrid_xyz + idx;
// Convert to frac coords
frameIn.BoxCrd().FracCell().TimesVec( XYZ, XYZ );
// Wrap to primary cell
XYZ[0] = XYZ[0] - floor(XYZ[0]);
XYZ[1] = XYZ[1] - floor(XYZ[1]);
XYZ[2] = XYZ[2] - floor(XYZ[2]);
// Convert back to Cartesian
frameIn.BoxCrd().UnitCell().TransposeMult( XYZ, XYZ );
}
# ifdef _OPENMP
}
# endif
}
// mprintf("DEBUG: NSolventAtoms= %zu NwatAtomsOnGrid= %u\n", O_idxs_.size()*nMolAtoms_, N_ON_GRID_);
double* E_UV_VDW = &(E_UV_VDW_[0][0]);
double* E_UV_Elec = &(E_UV_Elec_[0][0]);
double* E_VV_VDW = &(E_VV_VDW_[0][0]);
double* E_VV_Elec = &(E_VV_Elec_[0][0]);
float* Neighbor = &(neighbor_[0][0]);
double Evdw, Eelec;
int aidx;
int maxAidx = (int)A_idxs_.size();
// Loop over all solute + solvent atoms
# ifdef _OPENMP
int mythread;
Iarray* eij_v1 = 0;
Iarray* eij_v2 = 0;
Farray* eij_en = 0;
# pragma omp parallel private(aidx, mythread, E_UV_VDW, E_UV_Elec, E_VV_VDW, E_VV_Elec, Neighbor, Evdw, Eelec, eij_v1, eij_v2, eij_en)
{
mythread = omp_get_thread_num();
E_UV_VDW = &(E_UV_VDW_[mythread][0]);
E_UV_Elec = &(E_UV_Elec_[mythread][0]);
E_VV_VDW = &(E_VV_VDW_[mythread][0]);
E_VV_Elec = &(E_VV_Elec_[mythread][0]);
Neighbor = (&neighbor_[mythread][0]);
if (doEij_) {
eij_v1 = &(EIJ_V1_[mythread]);
eij_v2 = &(EIJ_V2_[mythread]);
eij_en = &(EIJ_EN_[mythread]);
eij_v1->clear();
eij_v2->clear();
eij_en->clear();
}
# pragma omp for
# endif
for (aidx = 0; aidx < maxAidx; aidx++)
{
int a1 = A_idxs_[aidx]; // Index of atom1
int a1_voxel = atom_voxel_[a1]; // Voxel of atom1
int a1_mol = topIn[ a1 ].MolNum(); // Molecule # of atom 1
Vec3 A1_XYZ( frameIn.XYZ( a1 ) ); // Coord of atom1
double qA1 = topIn[ a1 ].Charge(); // Charge of atom1
bool a1IsO = atomIsSolventO_[a1];
std::vector<Vec3> vImages;
if (imageOpt_.ImagingType() == ImageOption::NONORTHO) {
// Convert to frac coords
Vec3 vFrac = frameIn.BoxCrd().FracCell() * A1_XYZ;
// Wrap to primary unit cell
vFrac[0] = vFrac[0] - floor(vFrac[0]);
vFrac[1] = vFrac[1] - floor(vFrac[1]);
vFrac[2] = vFrac[2] - floor(vFrac[2]);
// Calculate all images of this atom
vImages.reserve(27);
for (int ix = -1; ix != 2; ix++)
for (int iy = -1; iy != 2; iy++)
for (int iz = -1; iz != 2; iz++)
// Convert image back to Cartesian
vImages.push_back( frameIn.BoxCrd().UnitCell().TransposeMult( vFrac + Vec3(ix,iy,iz) ) );
}
// Loop over all solvent atoms on the grid
for (unsigned int gidx = 0; gidx < N_ON_GRID_; gidx++)
{
int a2 = OnGrid_idxs_[gidx]; // Index of on-grid solvent
int a2_mol = topIn[ a2 ].MolNum(); // Molecule # of on-grid solvent
if (a1_mol != a2_mol)
{
int a2_voxel = atom_voxel_[a2]; // Voxel of on-grid solvent
const double* A2_XYZ = (&OnGrid_XYZ_[0])+gidx*3; // Coord of on-grid solvent
if (atomIsSolute_[a1]) {
// Solute to on-grid solvent energy
// Calculate distance
//gist_nonbond_dist_.Start();
double rij2;
if (imageOpt_.ImagingType() == ImageOption::NONORTHO) {
# ifdef GIST_USE_NONORTHO_DIST2
rij2 = DIST2_ImageNonOrtho(A1_XYZ, A2_XYZ, frameIn.BoxCrd().UnitCell(), frameIn.BoxCrd().FracCell());
# else
rij2 = maxD_;
for (std::vector<Vec3>::const_iterator vCart = vImages.begin();
vCart != vImages.end(); ++vCart)
{
double x = (*vCart)[0] - A2_XYZ[0];
double y = (*vCart)[1] - A2_XYZ[1];
double z = (*vCart)[2] - A2_XYZ[2];
rij2 = std::min(rij2, x*x + y*y + z*z);
}
# endif
} else if (imageOpt_.ImagingType() == ImageOption::ORTHO)
rij2 = DIST2_ImageOrtho( A1_XYZ, A2_XYZ, frameIn.BoxCrd() );
else
rij2 = DIST2_NoImage( A1_XYZ, A2_XYZ );
//gist_nonbond_dist_.Stop();
//gist_nonbond_UV_.Start();
// Calculate energy
Ecalc( rij2, qA1, topIn[ a2 ].Charge(), topIn.GetLJparam(a1, a2), Evdw, Eelec );
E_UV_VDW[a2_voxel] += Evdw;
E_UV_Elec[a2_voxel] += Eelec;
//gist_nonbond_UV_.Stop();
} else {
// Off-grid/on-grid solvent to on-grid solvent energy
// Only do the energy calculation if not previously done or atom1 not on grid
if (a2 != a1 && (a2 > a1 || a1_voxel == OFF_GRID_))
{
// Calculate distance
//gist_nonbond_dist_.Start();
double rij2;
if (imageOpt_.ImagingType() == ImageOption::NONORTHO) {
# ifdef GIST_USE_NONORTHO_DIST2
rij2 = DIST2_ImageNonOrtho(A1_XYZ, A2_XYZ, frameIn.BoxCrd().UnitCell(), frameIn.BoxCrd().FracCell());
# else
rij2 = maxD_;
for (std::vector<Vec3>::const_iterator vCart = vImages.begin();
vCart != vImages.end(); ++vCart)
{
double x = (*vCart)[0] - A2_XYZ[0];
double y = (*vCart)[1] - A2_XYZ[1];
double z = (*vCart)[2] - A2_XYZ[2];
rij2 = std::min(rij2, x*x + y*y + z*z);
}
# endif
} else if (imageOpt_.ImagingType() == ImageOption::ORTHO)
rij2 = DIST2_ImageOrtho( A1_XYZ, A2_XYZ, frameIn.BoxCrd() );
else
rij2 = DIST2_NoImage( A1_XYZ, A2_XYZ );
//gist_nonbond_dist_.Stop();
//gist_nonbond_VV_.Start();
// Calculate energy
Ecalc( rij2, qA1, topIn[ a2 ].Charge(), topIn.GetLJparam(a1, a2), Evdw, Eelec );
//mprintf("DEBUG1: v1= %i v2= %i EVV %i %i Vdw= %f Elec= %f\n", a2_voxel, a1_voxel, a2, a1, Evdw, Eelec);
E_VV_VDW[a2_voxel] += Evdw;
E_VV_Elec[a2_voxel] += Eelec;
// Store water neighbor using only O-O distance
bool is_O_O = (a1IsO && atomIsSolventO_[a2]);
if (is_O_O && rij2 < NeighborCut2_)
Neighbor[a2_voxel] += 1.0;
// If water atom1 was also on the grid update its energy as well.
if ( a1_voxel != OFF_GRID_ ) {
E_VV_VDW[a1_voxel] += Evdw;
E_VV_Elec[a1_voxel] += Eelec;
if (is_O_O && rij2 < NeighborCut2_)
Neighbor[a1_voxel] += 1.0;
if (doEij_) {
if (a1_voxel != a2_voxel) {
# ifdef _OPENMP
eij_v1->push_back( a1_voxel );
eij_v2->push_back( a2_voxel );
eij_en->push_back( Evdw + Eelec );
# else
ww_Eij_->UpdateElement(a1_voxel, a2_voxel, Evdw + Eelec);
# endif
}
}
}
//gist_nonbond_VV_.Stop();
}
}
} // END a1 and a2 not in same molecule
} // End loop over all solvent atoms on grid
} // End loop over all solvent + solute atoms
# ifdef _OPENMP
} // END pragma omp parallel
if (doEij_) {
// Add any Eijs to matrix
for (unsigned int thread = 0; thread != EIJ_V1_.size(); thread++)
for (unsigned int idx = 0; idx != EIJ_V1_[thread].size(); idx++)
ww_Eij_->UpdateElement(EIJ_V1_[thread][idx], EIJ_V2_[thread][idx], EIJ_EN_[thread][idx]);
}
# endif
}
/** GIST order calculation. */
void Action_GIST::Order(Frame const& frameIn) {
// Loop over all solvent molecules that are on the grid
for (unsigned int gidx = 0; gidx < N_ON_GRID_; gidx += nMolAtoms_)
{
int oidx1 = OnGrid_idxs_[gidx];
int voxel1 = atom_voxel_[oidx1];
Vec3 XYZ1( (&OnGrid_XYZ_[0])+gidx*3 );
// Find coordinates for 4 closest neighbors to this water (on or off grid).
// TODO set up overall grid in DoAction.
// TODO initialize WAT?
Vec3 WAT[4];
double d1 = maxD_;
double d2 = maxD_;
double d3 = maxD_;
double d4 = maxD_;
for (unsigned int sidx2 = 0; sidx2 < NSOLVENT_; sidx2++)
{
int oidx2 = O_idxs_[sidx2];
if (oidx2 != oidx1)
{
const double* XYZ2 = frameIn.XYZ( oidx2 );
double dist2 = DIST2_NoImage( XYZ1.Dptr(), XYZ2 );
if (dist2 < d1) {
d4 = d3; d3 = d2; d2 = d1; d1 = dist2;
WAT[3] = WAT[2]; WAT[2] = WAT[1]; WAT[1] = WAT[0]; WAT[0] = XYZ2;
} else if (dist2 < d2) {
d4 = d3; d3 = d2; d2 = dist2;
WAT[3] = WAT[2]; WAT[2] = WAT[1]; WAT[1] = XYZ2;
} else if (dist2 < d3) {
d4 = d3; d3 = dist2;
WAT[3] = WAT[2]; WAT[2] = XYZ2;
} else if (dist2 < d4) {
d4 = dist2;
WAT[3] = XYZ2;
}
}
}
// Compute the tetrahedral order parameter
double sum = 0.0;
for (int mol1 = 0; mol1 < 3; mol1++) {
for (int mol2 = mol1 + 1; mol2 < 4; mol2++) {
Vec3 v1 = WAT[mol1] - XYZ1;
Vec3 v2 = WAT[mol2] - XYZ1;
double r1 = v1.Magnitude2();
double r2 = v2.Magnitude2();
double cos = (v1* v2) / sqrt(r1 * r2);
sum += (cos + 1.0/3)*(cos + 1.0/3);
}
}
order_norm_->UpdateVoxel(voxel1, (1.0 - (3.0/8)*sum));
//mprintf("DBG: gidx= %u oidx1=%i voxel1= %i XYZ1={%g, %g, %g} sum= %g\n", gidx, oidx1, voxel1, XYZ1[0], XYZ1[1], XYZ1[2], sum);
} // END loop over all solvent molecules
}
/** GIST action */
Action::RetType Action_GIST::DoAction(int frameNum, ActionFrame& frm) {
gist_action_.Start();
NFRAME_++;
// TODO only !skipE?
N_ON_GRID_ = 0;
OnGrid_idxs_.clear();
OnGrid_XYZ_.clear();
// Determine imaging type
# ifdef DEBUG_GIST
//mprintf("DEBUG: Is_X_Aligned_Ortho() = %i Is_X_Aligned() = %i\n", (int)frm.Frm().BoxCrd().Is_X_Aligned_Ortho(), (int)frm.Frm().BoxCrd().Is_X_Aligned());
frm.Frm().BoxCrd().UnitCell().Print("Ucell");
frm.Frm().BoxCrd().FracCell().Print("Frac");
# endif
if (imageOpt_.ImagingEnabled())
imageOpt_.SetImageType( frm.Frm().BoxCrd().Is_X_Aligned_Ortho() );
# ifdef DEBUG_GIST
switch (imageOpt_.ImagingType()) {
case ImageOption::NO_IMAGE : mprintf("DEBUG: No Image.\n"); break;
case ImageOption::ORTHO : mprintf("DEBUG: Orthogonal image.\n"); break;
case ImageOption::NONORTHO : mprintf("DEBUG: Nonorthogonal image.\n"); break;
}
# endif
// CUDA necessary information
size_t bin_i, bin_j, bin_k;
Vec3 const& Origin = gO_->Bin().GridOrigin();
// Loop over each solvent molecule
for (unsigned int sidx = 0; sidx < NSOLVENT_; sidx++)
{
gist_grid_.Start();
int oidx = O_idxs_[sidx];
for (unsigned int IDX = 0; IDX != nMolAtoms_; IDX++)
atom_voxel_[oidx+IDX] = OFF_GRID_;
const double* O_XYZ = frm.Frm().XYZ( oidx );
// Get vector of water oxygen to grid origin.
Vec3 W_G( O_XYZ[0] - Origin[0],
O_XYZ[1] - Origin[1],
O_XYZ[2] - Origin[2] );
gist_grid_.Stop();
// Check if water oxygen is no more then 1.5 Ang from grid
// NOTE: using <= to be consistent with original code
if ( W_G[0] <= G_max_[0] && W_G[0] >= -1.5 &&
W_G[1] <= G_max_[1] && W_G[1] >= -1.5 &&
W_G[2] <= G_max_[2] && W_G[2] >= -1.5 )
{
const double* H1_XYZ = frm.Frm().XYZ( oidx + 1 );
const double* H2_XYZ = frm.Frm().XYZ( oidx + 2 );
// Try to bin the oxygen
if ( gO_->Bin().Calc( O_XYZ[0], O_XYZ[1], O_XYZ[2], bin_i, bin_j, bin_k ) )
{
// Oxygen is inside the grid. Record the voxel.
// NOTE hydrogens/EP always assigned to same voxel for energy purposes.
int voxel = (int)gO_->CalcIndex(bin_i, bin_j, bin_k);
const double* wXYZ = O_XYZ;
for (unsigned int IDX = 0; IDX != nMolAtoms_; IDX++) {
atom_voxel_[oidx+IDX] = voxel;
//OnGrid_idxs_[N_ON_GRID_+IDX] = oidx + IDX;
OnGrid_idxs_.push_back( oidx+IDX );
OnGrid_XYZ_.push_back( wXYZ[0] );
OnGrid_XYZ_.push_back( wXYZ[1] );
OnGrid_XYZ_.push_back( wXYZ[2] );
wXYZ+=3;
}
N_ON_GRID_ += nMolAtoms_;
//mprintf("DEBUG1: Water atom %i voxel %i\n", oidx, voxel);
N_waters_[voxel]++;
max_nwat_ = std::max( N_waters_[voxel], max_nwat_ );
// ----- EULER ---------------------------
gist_euler_.Start();
// Record XYZ coords of water atoms (nonEP) in voxel TODO need EP?
voxel_xyz_[voxel].push_back( O_XYZ[0] );
voxel_xyz_[voxel].push_back( O_XYZ[1] );
voxel_xyz_[voxel].push_back( O_XYZ[2] );
// Get O-HX vectors
Vec3 H1_wat( H1_XYZ[0]-O_XYZ[0], H1_XYZ[1]-O_XYZ[1], H1_XYZ[2]-O_XYZ[2] );
Vec3 H2_wat( H2_XYZ[0]-O_XYZ[0], H2_XYZ[1]-O_XYZ[1], H2_XYZ[2]-O_XYZ[2] );
H1_wat.Normalize();
H2_wat.Normalize();
Vec3 ar1 = H1_wat.Cross( x_lab_ ); // ar1 = V cross U
Vec3 sar = ar1; // sar = V cross U
ar1.Normalize();
//mprintf("------------------------------------------\n");
//H1_wat.Print("DEBUG: H1_wat");
//x_lab_.Print("DEBUG: x_lab_");
//ar1.Print("DEBUG: ar1");
//sar.Print("DEBUG: sar");
double dp1 = x_lab_ * H1_wat; // V dot U
double theta = acos(dp1);
double sign = sar * H1_wat;
//mprintf("DEBUG0: dp1= %f theta= %f sign= %f\n", dp1, theta, sign);
// NOTE: Use SMALL instead of 0 to avoid issues with denormalization
if (sign > Constants::SMALL)
theta /= 2.0;
else
theta /= -2.0;
double w1 = cos(theta);
double sin_theta = sin(theta);
//mprintf("DEBUG0: theta= %f w1= %f sin_theta= %f\n", theta, w1, sin_theta);
double x1 = ar1[0] * sin_theta;
double y1 = ar1[1] * sin_theta;
double z1 = ar1[2] * sin_theta;
double w2 = w1;
double x2 = x1;
double y2 = y1;
double z2 = z1;
Vec3 H_temp;
H_temp[0] = ((w2*w2+x2*x2)-(y2*y2+z2*z2))*H1_wat[0];
H_temp[0] = (2*(x2*y2 + w2*z2)*H1_wat[1]) + H_temp[0];
H_temp[0] = (2*(x2*z2-w2*y2)*H1_wat[2]) + H_temp[0];
H_temp[1] = 2*(x2*y2 - w2*z2)* H1_wat[0];
H_temp[1] = ((w2*w2-x2*x2+y2*y2-z2*z2)*H1_wat[1]) + H_temp[1];
H_temp[1] = (2*(y2*z2+w2*x2)*H1_wat[2]) +H_temp[1];
H_temp[2] = 2*(x2*z2+w2*y2) *H1_wat[0];
H_temp[2] = (2*(y2*z2-w2*x2)*H1_wat[1]) + H_temp[2];
H_temp[2] = ((w2*w2-x2*x2-y2*y2+z2*z2)*H1_wat[2]) + H_temp[2];
H1_wat = H_temp;
Vec3 H_temp2;
H_temp2[0] = ((w2*w2+x2*x2)-(y2*y2+z2*z2))*H2_wat[0];
H_temp2[0] = (2*(x2*y2 + w2*z2)*H2_wat[1]) + H_temp2[0];
H_temp2[0] = (2*(x2*z2-w2*y2)*H2_wat[2]) +H_temp2[0];
H_temp2[1] = 2*(x2*y2 - w2*z2) *H2_wat[0];
H_temp2[1] = ((w2*w2-x2*x2+y2*y2-z2*z2)*H2_wat[1]) +H_temp2[1];
H_temp2[1] = (2*(y2*z2+w2*x2)*H2_wat[2]) +H_temp2[1];
H_temp2[2] = 2*(x2*z2+w2*y2)*H2_wat[0];
H_temp2[2] = (2*(y2*z2-w2*x2)*H2_wat[1]) +H_temp2[2];
H_temp2[2] = ((w2*w2-x2*x2-y2*y2+z2*z2)*H2_wat[2]) + H_temp2[2];
H2_wat = H_temp2;
Vec3 ar2 = H_temp.Cross(H_temp2);
ar2.Normalize();
double dp2 = ar2 * z_lab_;
theta = acos(dp2);
sar = ar2.Cross( z_lab_ );
sign = sar * H_temp;
if (sign < 0)
theta /= 2.0;
else
theta /= -2.0;
double w3 = cos(theta);
sin_theta = sin(theta);
double x3 = x_lab_[0] * sin_theta;
double y3 = x_lab_[1] * sin_theta;
double z3 = x_lab_[2] * sin_theta;
double w4 = w1*w3 - x1*x3 - y1*y3 - z1*z3;
double x4 = w1*x3 + x1*w3 + y1*z3 - z1*y3;
double y4 = w1*y3 - x1*z3 + y1*w3 + z1*x3;
double z4 = w1*z3 + x1*y3 - y1*x3 + z1*w3;
voxel_Q_[voxel].push_back( w4 );
voxel_Q_[voxel].push_back( x4 );
voxel_Q_[voxel].push_back( y4 );
voxel_Q_[voxel].push_back( z4 );
//mprintf("DEBUG1: sidx= %u voxel= %i wxyz4= %g %g %g %g\n", sidx, voxel, w4, x4, y4, z4);
//mprintf("DEBUG2: wxyz3= %g %g %g %g wxyz2= %g %g %g %g wxyz1= %g %g %g\n",
// w3, x3, y3, z3,
// w2, x2, y2, z2,
// w1, x1, y1, z1);
// NOTE: No need for nw_angle_ here, it is same as N_waters_
gist_euler_.Stop();
// ----- DIPOLE --------------------------
gist_dipole_.Start();
//mprintf("DEBUG1: voxel %i dipole %f %f %f\n", voxel,
// O_XYZ[0]*q_O_ + H1_XYZ[0]*q_H1_ + H2_XYZ[0]*q_H2_,
// O_XYZ[1]*q_O_ + H1_XYZ[1]*q_H1_ + H2_XYZ[1]*q_H2_,
// O_XYZ[2]*q_O_ + H1_XYZ[2]*q_H1_ + H2_XYZ[2]*q_H2_);
double DPX = 0.0;
double DPY = 0.0;
double DPZ = 0.0;
for (unsigned int IDX = 0; IDX != nMolAtoms_; IDX++) {
const double* XYZ = frm.Frm().XYZ( oidx+IDX );
DPX += XYZ[0] * Q_[IDX];
DPY += XYZ[1] * Q_[IDX];
DPZ += XYZ[2] * Q_[IDX];
}
dipolex_->UpdateVoxel(voxel, DPX);
dipoley_->UpdateVoxel(voxel, DPY);
dipolez_->UpdateVoxel(voxel, DPZ);
gist_dipole_.Stop();
// ---------------------------------------
}
// Water is at most 1.5A away from grid, so we need to check for H
// even if O is outside grid.
if (gO_->Bin().Calc( H1_XYZ[0], H1_XYZ[1], H1_XYZ[2], bin_i, bin_j, bin_k ) )
N_hydrogens_[ (int)gO_->CalcIndex(bin_i, bin_j, bin_k) ]++;
if (gO_->Bin().Calc( H2_XYZ[0], H2_XYZ[1], H2_XYZ[2], bin_i, bin_j, bin_k ) )
N_hydrogens_[ (int)gO_->CalcIndex(bin_i, bin_j, bin_k) ]++;
} // END water is within 1.5 Ang of grid
} // END loop over each solvent molecule
// Do solute grid assignment for PME
if (usePme_) {
U_onGrid_idxs_.clear();
gist_grid_.Start();
for (unsigned int s = 0; s != U_idxs_.size(); s++)
{
int uidx = U_idxs_[s]; // the solute atom index
atom_voxel_[uidx] = OFF_GRID_;
const double* u_XYZ = frm.Frm().XYZ( uidx );
// get the vector of this solute atom to the grid origin
Vec3 U_G( u_XYZ[0] - Origin[0],
u_XYZ[1] - Origin[1],
u_XYZ[2] - Origin[2]);
//size_t bin_i, bin_j, bin_k;
if ( U_G[0] <= G_max_[0] && U_G[0] >= -1.5 &&
U_G[1] <= G_max_[1] && U_G[1] >= -1.5 &&
U_G[2] <= G_max_[2] && U_G[2] >- -1.5)
{
if ( gO_->Bin().Calc(u_XYZ[0],u_XYZ[1],u_XYZ[2],bin_i,bin_j,bin_k)) // used the gO class function to calcaute voxel index
{
int voxel = (int)gO_->CalcIndex(bin_i,bin_j,bin_k);
atom_voxel_[uidx] = voxel; // asign the voxel index to the solute atom
//U_ON_GRID_ +=1; // add +1 to the number of atom on the GIST Grid
N_solute_atoms_[voxel] +=1; // add +1 to the solute atom num in this voxel
U_onGrid_idxs_.push_back(uidx); // The index of the solute atom on GIST Grid
}
}
}
gist_grid_.Stop();
}
# ifndef CUDA
// Do order calculation if requested.
// Do not do this for CUDA since CUDA nonbond routine handles the order calc.
// NOTE: This has to be done before the nonbond energy calc since
// the nonbond calc can modify the on-grid coordinates (for minimum
// image convention when cell is non-orthogonal).
gist_order_.Start();
if (doOrder_) Order(frm.Frm());
gist_order_.Stop();
# endif
// Do nonbond energy calc if not skipping energy
gist_nonbond_.Start();
if (!skipE_) {
if (usePme_) {
// PME
NonbondEnergy_pme( frm.Frm() );
} else {
// Non-PME
# ifdef CUDA
NonbondCuda(frm);
# else
NonbondEnergy(frm.Frm(), *CurrentParm_);
# endif
}
}
gist_nonbond_.Stop();
gist_action_.Stop();
return Action::OK;
}
/** Translational entropy calc between given water and all waters in voxel 2.
* \param VX voxel 1 water X
* \param VY voxel 1 water Y
* \param VZ voxel 1 water Z
* \param W4 voxel 1 water W4
* \param X4 voxel 1 water X4
* \param Y4 voxel 1 water Y4
* \param Z4 voxel 1 water Z4
* \param voxel2 Index of second voxel
*/
void Action_GIST::TransEntropy(float VX, float VY, float VZ,
float W4, float X4, float Y4, float Z4,
int voxel2, double& NNd, double& NNs) const
{
int nw_tot = N_waters_[voxel2];
Farray const& V_XYZ = voxel_xyz_[voxel2];
Farray const& V_Q = voxel_Q_[voxel2];
for (int n1 = 0; n1 != nw_tot; n1++)
{
int i1 = n1 * 3; // index into V_XYZ for n1
double dx = (double)(VX - V_XYZ[i1 ]);
double dy = (double)(VY - V_XYZ[i1+1]);
double dz = (double)(VZ - V_XYZ[i1+2]);
double dd = dx*dx+dy*dy+dz*dz;
if (dd < NNd && dd > 0) { NNd = dd; }
int q1 = n1 * 4; // index into V_Q for n1
double rR = 2.0 * acos( fabs(W4 * V_Q[q1 ] +
X4 * V_Q[q1+1] +
Y4 * V_Q[q1+2] +
Z4 * V_Q[q1+3] )); //add fabs for quaternions distance calculation
double ds = rR*rR + dd;
if (ds < NNs && ds > 0) { NNs = ds; }
}
}
// Action_GIST::SumEVV()
void Action_GIST::SumEVV() {
if (E_VV_VDW_.size() > 1) {
for (unsigned int gr_pt = 0; gr_pt != MAX_GRID_PT_; gr_pt++) {
for (unsigned int thread = 1; thread < E_VV_VDW_.size(); thread++) {
E_UV_VDW_[0][gr_pt] += E_UV_VDW_[thread][gr_pt];
E_UV_Elec_[0][gr_pt] += E_UV_Elec_[thread][gr_pt];
E_VV_VDW_[0][gr_pt] += E_VV_VDW_[thread][gr_pt];
E_VV_Elec_[0][gr_pt] += E_VV_Elec_[thread][gr_pt];
neighbor_[0][gr_pt] += neighbor_[thread][gr_pt];
}
}
}
}
/** Calculate average voxel energy for PME grids. */
void Action_GIST::CalcAvgVoxelEnergy_PME(double Vvox, DataSet_GridFlt& PME_dens, DataSet_GridFlt& U_PME_dens, Farray& PME_norm)
const
{
double PME_tot =0.0;
double U_PME_tot = 0.0;
mprintf("\t Calculating average voxel energies: \n");
ProgressBar E_progress(MAX_GRID_PT_);
for ( unsigned int gr_pt =0; gr_pt < MAX_GRID_PT_; gr_pt++)
{
E_progress.Update(gr_pt);
int nw_total = N_waters_[gr_pt];
if (nw_total >=1)
{
PME_dens[gr_pt] = E_pme_[gr_pt] / (NFRAME_ * Vvox);
PME_norm[gr_pt] = E_pme_[gr_pt] / nw_total;
PME_tot += PME_dens[gr_pt];
}else{
PME_dens[gr_pt]=0;
PME_norm[gr_pt]=0;
}
int ns_total = N_solute_atoms_[gr_pt];
if (ns_total >=1)
{
U_PME_dens[gr_pt] = U_E_pme_[gr_pt] / (NFRAME_ * Vvox);
U_PME_tot += U_PME_dens[gr_pt];
}else{
U_PME_dens[gr_pt]=0;
}
}
PME_tot *=Vvox;
U_PME_tot *=Vvox;
infofile_->Printf("Ensemble total water energy on the grid: %9.5f Kcal/mol \n", PME_tot);
infofile_->Printf("Ensemble total solute energy on the grid: %9.5f Kcal/mol \n",U_PME_tot);
// infofile_->Printf("Ensemble solute's total potential energy : %9.5f Kcal/mol \n", solute_potential_energy_ / NFRAME_);
// infofile_->Printf("Ensemble system's total potential energy: %9.5f Kcal/mol \n", system_potential_energy_/NFRAME_);
}
/** Calculate average voxel energy for GIST grids. */
void Action_GIST::CalcAvgVoxelEnergy(double Vvox, DataSet_GridFlt& Eww_dens, DataSet_GridFlt& Esw_dens,
Farray& Eww_norm, Farray& Esw_norm,
DataSet_GridDbl& qtet,
DataSet_GridFlt& neighbor_norm, Farray& neighbor_dens)
{
#ifndef CUDA
Darray const& E_UV_VDW = E_UV_VDW_[0];
Darray const& E_UV_Elec = E_UV_Elec_[0];
Darray const& E_VV_VDW = E_VV_VDW_[0];
Darray const& E_VV_Elec = E_VV_Elec_[0];
#endif
Farray const& Neighbor = neighbor_[0];
#ifndef CUDA
// Sum values from other threads if necessary
SumEVV();
#endif
double Eswtot = 0.0;
double Ewwtot = 0.0;
mprintf("\tCalculating average voxel energies:\n");
ProgressBar E_progress( MAX_GRID_PT_ );
for (unsigned int gr_pt = 0; gr_pt < MAX_GRID_PT_; gr_pt++)
{
E_progress.Update( gr_pt );
//mprintf("DEBUG1: VV vdw=%f elec=%f\n", E_VV_VDW_[gr_pt], E_VV_Elec_[gr_pt]);
int nw_total = N_waters_[gr_pt]; // Total number of waters that have been in this voxel.
if (nw_total > 0) {
#ifndef CUDA
Esw_dens[gr_pt] = (E_UV_VDW[gr_pt] + E_UV_Elec[gr_pt]) / (NFRAME_ * Vvox);
Esw_norm[gr_pt] = (E_UV_VDW[gr_pt] + E_UV_Elec[gr_pt]) / nw_total;
Eww_dens[gr_pt] = (E_VV_VDW[gr_pt] + E_VV_Elec[gr_pt]) / (2 * NFRAME_ * Vvox);
Eww_norm[gr_pt] = (E_VV_VDW[gr_pt] + E_VV_Elec[gr_pt]) / (2 * nw_total);
#else
double esw = this->Esw_->operator[](gr_pt);
double eww = this->Eww_->operator[](gr_pt);
Esw_dens[gr_pt] = esw / (this->NFRAME_ * Vvox);
Esw_norm[gr_pt] = esw / nw_total;
Eww_dens[gr_pt] = eww / (this->NFRAME_ * Vvox);
Eww_norm[gr_pt] = eww / nw_total;
#endif
Eswtot += Esw_dens[gr_pt];
Ewwtot += Eww_dens[gr_pt];
} else {
Esw_dens[gr_pt]=0;
Esw_norm[gr_pt]=0;
Eww_norm[gr_pt]=0;
Eww_dens[gr_pt]=0;
}
// Compute the average number of water neighbor and average order parameter.
if (nw_total > 0) {
qtet[gr_pt] /= nw_total;
//mprintf("DEBUG1: neighbor= %8.1f nw_total= %8i\n", neighbor[gr_pt], nw_total);
neighbor_norm[gr_pt] = (double)Neighbor[gr_pt] / nw_total;
}
neighbor_dens[gr_pt] = (double)Neighbor[gr_pt] / (NFRAME_ * Vvox);
} // END loop over all grid points (voxels)
Eswtot *= Vvox;
Ewwtot *= Vvox;
infofile_->Printf("Total water-solute energy of the grid: Esw = %9.5f kcal/mol\n", Eswtot);
infofile_->Printf("Total unreferenced water-water energy of the grid: Eww = %9.5f kcal/mol\n",
Ewwtot);
}
/** Handle averaging for grids and output from GIST. */
void Action_GIST::Print() {
gist_print_.Start();
double Vvox = gO_->Bin().VoxelVolume();
mprintf(" GIST OUTPUT:\n");
// The variables are kept outside, so that they are declared for later use.
// Calculate orientational entropy
DataSet_GridFlt& dTSorient_dens = static_cast<DataSet_GridFlt&>( *dTSorient_ );
Farray dTSorient_norm( MAX_GRID_PT_, 0.0 );
double dTSorienttot = 0;
int nwtt = 0;
double dTSo = 0;
if (! this->skipS_) {
// LOOP over all voxels
mprintf("\tCalculating orientational entropy:\n");
ProgressBar oe_progress( MAX_GRID_PT_ );
for (unsigned int gr_pt = 0; gr_pt < MAX_GRID_PT_; gr_pt++) {
oe_progress.Update( gr_pt );
dTSorient_dens[gr_pt] = 0;
dTSorient_norm[gr_pt] = 0;
int nw_total = N_waters_[gr_pt]; // Total number of waters that have been in this voxel.
nwtt += nw_total;
//mprintf("DEBUG1: %u nw_total %i\n", gr_pt, nw_total);
if (nw_total > 1) {
for (int n0 = 0; n0 < nw_total; n0++)
{
double NNr = 10000;
int q0 = n0 * 4; // Index into voxel_Q_ for n0
for (int n1 = 0; n1 < nw_total; n1++)
{
if (n0 != n1) {
int q1 = n1 * 4; // Index into voxel_Q_ for n1
//mprintf("DEBUG1:\t\t q1= %8i {%12.4f %12.4f %12.4f %12.4f} q0= %8i {%12.4f %12.4f %12.4f %12.4f}\n",
// q1, voxel_Q_[gr_pt][q1 ], voxel_Q_[gr_pt][q1+1], voxel_Q_[gr_pt][q1+2], voxel_Q_[gr_pt][q1+3],
// q0, voxel_Q_[gr_pt][q0 ], voxel_Q_[gr_pt][q0+1], voxel_Q_[gr_pt][q0+2], voxel_Q_[gr_pt][q0+3]);
double rR = 2.0 * acos( fabs(voxel_Q_[gr_pt][q1 ] * voxel_Q_[gr_pt][q0 ]
+ voxel_Q_[gr_pt][q1+1] * voxel_Q_[gr_pt][q0+1]
+ voxel_Q_[gr_pt][q1+2] * voxel_Q_[gr_pt][q0+2]
+ voxel_Q_[gr_pt][q1+3] * voxel_Q_[gr_pt][q0+3] )); // add fabs for quaternion distance calculation
//mprintf("DEBUG1:\t\t %8i %8i %g\n", n0, n1, rR);
if (rR > 0 && rR < NNr) NNr = rR;
}
} // END inner loop over all waters for this voxel
if (NNr < 9999 && NNr > 0) {
double dbl = log(NNr*NNr*NNr*nw_total / (3.0*Constants::TWOPI));
//mprintf("DEBUG1: %u nw_total= %i NNr= %f dbl= %f\n", gr_pt, nw_total, NNr, dbl);
dTSorient_norm[gr_pt] += dbl;
dTSo += dbl;
}
} // END outer loop over all waters for this voxel
//mprintf("DEBUG1: dTSorient_norm %f\n", dTSorient_norm[gr_pt]);
dTSorient_norm[gr_pt] = Constants::GASK_KCAL * temperature_ *
((dTSorient_norm[gr_pt]/nw_total) + Constants::EULER_MASC);
double dtso_norm_nw = (double)dTSorient_norm[gr_pt] * (double)nw_total;
dTSorient_dens[gr_pt] = (dtso_norm_nw / (NFRAME_ * Vvox));
dTSorienttot += dTSorient_dens[gr_pt];
//mprintf("DEBUG1: %f\n", dTSorienttot);
}
} // END loop over all grid points (voxels)
dTSorienttot *= Vvox;
infofile_->Printf("Maximum number of waters found in one voxel for %d frames = %d\n",
NFRAME_, max_nwat_);
infofile_->Printf("Total referenced orientational entropy of the grid:"
" dTSorient = %9.5f kcal/mol, Nf=%d\n", dTSorienttot, NFRAME_);
}
// Compute translational entropy for each voxel
double dTStranstot = 0.0;
double dTSt = 0.0;
double dTSs = 0.0;
int nwts = 0;
unsigned int nx = gO_->NX();
unsigned int ny = gO_->NY();
unsigned int nz = gO_->NZ();
unsigned int addx = ny * nz;
unsigned int addy = nz;
unsigned int addz = 1;
DataSet_GridFlt& gO = static_cast<DataSet_GridFlt&>( *gO_ );
DataSet_GridFlt& gH = static_cast<DataSet_GridFlt&>( *gH_ );
DataSet_GridFlt& dTStrans = static_cast<DataSet_GridFlt&>( *dTStrans_ );
DataSet_GridFlt& dTSsix = static_cast<DataSet_GridFlt&>( *dTSsix_ );
Farray dTStrans_norm( MAX_GRID_PT_, 0.0 );
Farray dTSsix_norm( MAX_GRID_PT_, 0.0 );
// Loop over all grid points
if (! this->skipS_)
mprintf("\tCalculating translational entropy:\n");
else
mprintf("Calculating Densities:\n");
ProgressBar te_progress( MAX_GRID_PT_ );
for (unsigned int gr_pt = 0; gr_pt < MAX_GRID_PT_; gr_pt++) {
te_progress.Update( gr_pt );
int numplane = gr_pt / addx;
double W_dens = 1.0 * N_waters_[gr_pt] / (NFRAME_*Vvox);
gO[gr_pt] = W_dens / BULK_DENS_;
gH[gr_pt] = 1.0 * N_hydrogens_[gr_pt] / (NFRAME_*Vvox*2*BULK_DENS_);
if (! this->skipS_) {
int nw_total = N_waters_[gr_pt]; // Total number of waters that have been in this voxel.
for (int n0 = 0; n0 < nw_total; n0++)
{
double NNd = 10000;
double NNs = 10000;
int i0 = n0 * 3; // index into voxel_xyz_ for n0
float VX = voxel_xyz_[gr_pt][i0 ];
float VY = voxel_xyz_[gr_pt][i0+1];
float VZ = voxel_xyz_[gr_pt][i0+2];
int q0 = n0 * 4; // index into voxel_Q_ for n0
float W4 = voxel_Q_[gr_pt][q0 ];
float X4 = voxel_Q_[gr_pt][q0+1];
float Y4 = voxel_Q_[gr_pt][q0+2];
float Z4 = voxel_Q_[gr_pt][q0+3];
// First do own voxel
for (int n1 = 0; n1 < nw_total; n1++) {
if ( n1 != n0) {
int i1 = n1 * 3; // index into voxel_xyz_ for n1
double dx = (double)(VX - voxel_xyz_[gr_pt][i1 ]);
double dy = (double)(VY - voxel_xyz_[gr_pt][i1+1]);
double dz = (double)(VZ - voxel_xyz_[gr_pt][i1+2]);
double dd = dx*dx+dy*dy+dz*dz;
if (dd < NNd && dd > 0) { NNd = dd; }
int q1 = n1 * 4; // index into voxel_Q_ for n1
double rR = 2 * acos( fabs(W4*voxel_Q_[gr_pt][q1 ] +
X4*voxel_Q_[gr_pt][q1+1] +
Y4*voxel_Q_[gr_pt][q1+2] +
Z4*voxel_Q_[gr_pt][q1+3] )); //add fabs for quaternion distance calculation
double ds = rR*rR + dd;
if (ds < NNs && ds > 0) { NNs = ds; }
}
} // END self loop over all waters for this voxel
//mprintf("DEBUG1: self NNd=%f NNs=%f\n", NNd, NNs);
// Determine which directions are possible.
bool cannotAddZ = (nz == 0 || ( gr_pt%nz == nz-1 ));
bool cannotAddY = ((nz == 0 || ny-1 == 0) || ( gr_pt%(nz*(ny-1)+(numplane*addx)) < nz));
bool cannotAddX = (gr_pt >= addx * (nx-1) && gr_pt < addx * nx );
bool cannotSubZ = (nz == 0 || gr_pt%nz == 0);
bool cannotSubY = ((nz == 0 || ny == 0) || (gr_pt%addx < nz));
bool cannotSubX = ((nz == 0 || ny == 0) || (gr_pt < addx));
bool boundary = ( cannotAddZ || cannotAddY || cannotAddX ||
cannotSubZ || cannotSubY || cannotSubX );
if (!boundary) {
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addy, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addy, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addz + addy, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addz - addy, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addz + addy, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addz - addy, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addz + addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addz - addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addz + addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addz - addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addy + addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addy - addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addy + addx, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addy - addx, NNd, NNs);
// add the 8 more voxels for NNr searching
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addx + addy + addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addx + addy - addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addx - addy + addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt + addx - addy - addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addx + addy + addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addx + addy - addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addx - addy + addz, NNd, NNs);
TransEntropy(VX, VY, VZ, W4, X4, Y4, Z4, gr_pt - addx - addy - addz, NNd, NNs);
NNd = sqrt(NNd);
NNs = sqrt(NNs);
if (NNd < 3 && NNd > 0/*NNd < 9999 && NNd > 0*/) {
double dbl = log((NNd*NNd*NNd*NFRAME_*4*Constants::PI*BULK_DENS_)/3);
dTStrans_norm[gr_pt] += dbl;
dTSt += dbl;
dbl = log((NNs*NNs*NNs*NNs*NNs*NNs*NFRAME_*Constants::PI*BULK_DENS_)/48);
dTSsix_norm[gr_pt] += dbl;
dTSs += dbl;
//mprintf("DEBUG1: dbl=%f NNs=%f\n", dbl, NNs);
}
}
} // END loop over all waters for this voxel
if (dTStrans_norm[gr_pt] != 0) {
nwts += nw_total;
dTStrans_norm[gr_pt] = Constants::GASK_KCAL*temperature_*( (dTStrans_norm[gr_pt]/nw_total) +
Constants::EULER_MASC );
dTSsix_norm[gr_pt] = Constants::GASK_KCAL*temperature_*( (dTSsix_norm[gr_pt]/nw_total) +
Constants::EULER_MASC );
}
double dtst_norm_nw = (double)dTStrans_norm[gr_pt] * (double)nw_total;
dTStrans[gr_pt] = (dtst_norm_nw / (NFRAME_*Vvox));
double dtss_norm_nw = (double)dTSsix_norm[gr_pt] * (double)nw_total;
dTSsix[gr_pt] = (dtss_norm_nw / (NFRAME_*Vvox));
dTStranstot += dTStrans[gr_pt];
} // END loop over all grid points (voxels)
}
if (!this->skipS_) {
dTStranstot *= Vvox;
double dTSst = 0.0;
double dTStt = 0.0;
if (nwts > 0) {
dTSst = Constants::GASK_KCAL*temperature_*((dTSs/nwts) + Constants::EULER_MASC);
dTStt = Constants::GASK_KCAL*temperature_*((dTSt/nwts) + Constants::EULER_MASC);
}
double dTSot = Constants::GASK_KCAL*temperature_*((dTSo/nwtt) + Constants::EULER_MASC);
infofile_->Printf("watcount in vol = %d\n", nwtt);
infofile_->Printf("watcount in subvol = %d\n", nwts);
infofile_->Printf("Total referenced translational entropy of the grid:"
" dTStrans = %9.5f kcal/mol, Nf=%d\n", dTStranstot, NFRAME_);
infofile_->Printf("Total 6d if all one vox: %9.5f kcal/mol\n", dTSst);
infofile_->Printf("Total t if all one vox: %9.5f kcal/mol\n", dTStt);
infofile_->Printf("Total o if all one vox: %9.5f kcal/mol\n", dTSot);
}
// Compute average voxel energy. Allocate these sets even if skipping energy
// to be consistent with previous output.
DataSet_GridFlt& PME_dens = static_cast<DataSet_GridFlt&>( *PME_);
DataSet_GridFlt& U_PME_dens = static_cast<DataSet_GridFlt&>( *U_PME_);
DataSet_GridFlt& Esw_dens = static_cast<DataSet_GridFlt&>( *Esw_ );
DataSet_GridFlt& Eww_dens = static_cast<DataSet_GridFlt&>( *Eww_ );
DataSet_GridFlt& neighbor_norm = static_cast<DataSet_GridFlt&>( *neighbor_norm_ );
DataSet_GridDbl& qtet = static_cast<DataSet_GridDbl&>( *order_norm_ );
Farray Esw_norm( MAX_GRID_PT_, 0.0 );
Farray Eww_norm( MAX_GRID_PT_, 0.0 );
Farray PME_norm( MAX_GRID_PT_,0.0);
Farray neighbor_dens( MAX_GRID_PT_, 0.0 );
if (!skipE_) {
if (usePme_) {
CalcAvgVoxelEnergy_PME(Vvox, PME_dens, U_PME_dens, PME_norm);
}// else {
CalcAvgVoxelEnergy(Vvox, Eww_dens, Esw_dens, Eww_norm, Esw_norm, qtet,
neighbor_norm, neighbor_dens);
//}
}
// Compute average dipole density.
DataSet_GridFlt& pol = static_cast<DataSet_GridFlt&>( *dipole_ );
DataSet_GridDbl& dipolex = static_cast<DataSet_GridDbl&>( *dipolex_ );
DataSet_GridDbl& dipoley = static_cast<DataSet_GridDbl&>( *dipoley_ );
DataSet_GridDbl& dipolez = static_cast<DataSet_GridDbl&>( *dipolez_ );
for (unsigned int gr_pt = 0; gr_pt < MAX_GRID_PT_; gr_pt++)
{
dipolex[gr_pt] /= (Constants::DEBYE_EA * NFRAME_ * Vvox);
dipoley[gr_pt] /= (Constants::DEBYE_EA * NFRAME_ * Vvox);
dipolez[gr_pt] /= (Constants::DEBYE_EA * NFRAME_ * Vvox);
pol[gr_pt] = sqrt( dipolex[gr_pt]*dipolex[gr_pt] +
dipoley[gr_pt]*dipoley[gr_pt] +
dipolez[gr_pt]*dipolez[gr_pt] );
}
// Write the GIST output file.
// TODO: Make a data file format?
if (datafile_ != 0) {
mprintf("\tWriting GIST results for each voxel:\n");
// Create the format strings.
std::string fmtstr =
intFmt_.Fmt() + // grid point
" " + fltFmt_.Fmt() + // grid X
" " + fltFmt_.Fmt() + // grid Y
" " + fltFmt_.Fmt() + // grid Z
" " + intFmt_.Fmt() + // # waters
" " + fltFmt_.Fmt() + // gO
" " + fltFmt_.Fmt() + // gH
" " + fltFmt_.Fmt() + // dTStrans
" " + fltFmt_.Fmt() + // dTStrans_norm
" " + fltFmt_.Fmt() + // dTSorient_dens
" " + fltFmt_.Fmt() + // dTSorient_norm
" " + fltFmt_.Fmt() + // dTSsix
" " + fltFmt_.Fmt() + // dTSsix_norm
" " + fltFmt_.Fmt() + // Esw_dens
" " + fltFmt_.Fmt() + // Esw_norm
" " + fltFmt_.Fmt() + // Eww_dens
" " + fltFmt_.Fmt(); // EWW_norm
if (usePme_) {
fmtstr +=
" " + fltFmt_.Fmt() + // PME_dens
+ " " + fltFmt_.Fmt(); // PME_norm
}
fmtstr +=
" " + fltFmt_.Fmt() + // dipolex
" " + fltFmt_.Fmt() + // dipoley
" " + fltFmt_.Fmt() + // dipolez
" " + fltFmt_.Fmt() + // pol
" " + fltFmt_.Fmt() + // neighbor_dens
" " + fltFmt_.Fmt() + // neighbor_norm
" " + fltFmt_.Fmt() + // qtet
" \n"; // NEWLINE
if (debug_ > 0) mprintf("DEBUG: Fmt='%s'\n", fmtstr.c_str());
const char* gistOutputVersion;
if (usePme_)
gistOutputVersion = "v3";
else
gistOutputVersion = "v2";
// Do the header
datafile_->Printf("GIST Output %s "
"spacing=%.4f center=%.6f,%.6f,%.6f dims=%i,%i,%i \n"
"voxel xcoord ycoord zcoord population g_O g_H"
" dTStrans-dens(kcal/mol/A^3) dTStrans-norm(kcal/mol)"
" dTSorient-dens(kcal/mol/A^3) dTSorient-norm(kcal/mol)"
" dTSsix-dens(kcal/mol/A^3) dTSsix-norm(kcal/mol)"
" Esw-dens(kcal/mol/A^3) Esw-norm(kcal/mol)"
" Eww-dens(kcal/mol/A^3) Eww-norm-unref(kcal/mol)",
gistOutputVersion, gridspacing_,
gridcntr_[0], gridcntr_[1], gridcntr_[2],
(int)griddim_[0], (int)griddim_[1], (int)griddim_[2]);
if (usePme_)
datafile_->Printf(" PME-dens(kcal/mol/A^3) PME-norm(kcal/mol)");
datafile_->Printf(" Dipole_x-dens(D/A^3) Dipole_y-dens(D/A^3) Dipole_z-dens(D/A^3)"
" Dipole-dens(D/A^3) neighbor-dens(1/A^3) neighbor-norm order-norm\n");
// Loop over voxels
ProgressBar O_progress( MAX_GRID_PT_ );
for (unsigned int gr_pt = 0; gr_pt < MAX_GRID_PT_; gr_pt++) {
O_progress.Update( gr_pt );
size_t i, j, k;
gO_->ReverseIndex( gr_pt, i, j, k );
Vec3 XYZ = gO_->Bin().Center( i, j, k );
if (usePme_) {
datafile_->Printf(fmtstr.c_str(),
gr_pt, XYZ[0], XYZ[1], XYZ[2], N_waters_[gr_pt], gO[gr_pt], gH[gr_pt],
dTStrans[gr_pt], dTStrans_norm[gr_pt],
dTSorient_dens[gr_pt], dTSorient_norm[gr_pt],
dTSsix[gr_pt], dTSsix_norm[gr_pt],
Esw_dens[gr_pt], Esw_norm[gr_pt],
Eww_dens[gr_pt], Eww_norm[gr_pt],
PME_dens[gr_pt], PME_norm[gr_pt],
dipolex[gr_pt], dipoley[gr_pt], dipolez[gr_pt],
pol[gr_pt], neighbor_dens[gr_pt], neighbor_norm[gr_pt], qtet[gr_pt]);
} else {
datafile_->Printf(fmtstr.c_str(),
gr_pt, XYZ[0], XYZ[1], XYZ[2], N_waters_[gr_pt], gO[gr_pt], gH[gr_pt],
dTStrans[gr_pt], dTStrans_norm[gr_pt],
dTSorient_dens[gr_pt], dTSorient_norm[gr_pt],
dTSsix[gr_pt], dTSsix_norm[gr_pt],
Esw_dens[gr_pt], Esw_norm[gr_pt],
Eww_dens[gr_pt], Eww_norm[gr_pt],
dipolex[gr_pt], dipoley[gr_pt], dipolez[gr_pt],
pol[gr_pt], neighbor_dens[gr_pt], neighbor_norm[gr_pt], qtet[gr_pt]);
}
} // END loop over voxels
} // END datafile_ not null
// Write water-water interaction energy matrix
if (ww_Eij_ != 0) {
DataSet_MatrixFlt& ww_Eij = static_cast<DataSet_MatrixFlt&>( *ww_Eij_ );
double fac = 1.0 / (double)(NFRAME_ * 2);
for (unsigned int idx = 0; idx != ww_Eij.Size(); idx++) {
if (fabs(ww_Eij[idx]) < Constants::SMALL)
ww_Eij[idx] = 0.0;
else {
double val = (double)ww_Eij[idx];
ww_Eij[idx] = (float)(val * fac);
}
}
// Eij matrix output, skip any zeros.
for (unsigned int a = 1; a < MAX_GRID_PT_; a++) {
for (unsigned int l = 0; l < a; l++) {
double dbl = ww_Eij_->GetElement(a, l);
if (dbl != 0)
eijfile_->Printf("%10d %10d %12.5E\n", a, l, dbl);
}
}
}
gist_print_.Stop();
double total = gist_init_.Total() + gist_setup_.Total() +
gist_action_.Total() + gist_print_.Total();
mprintf("\tGIST timings:\n");
gist_init_.WriteTiming(1, "Init: ", total);
gist_setup_.WriteTiming(1, "Setup: ", total);
gist_action_.WriteTiming(1, "Action:", total);
gist_grid_.WriteTiming(2, "Grid: ", gist_action_.Total());
gist_nonbond_.WriteTiming(2, "Nonbond:", gist_action_.Total());
# ifdef LIBPME
if (usePme_)
gistPme_.Timing( gist_nonbond_.Total() );
# endif
//gist_nonbond_dist_.WriteTiming(3, "Dist2:", gist_nonbond_.Total());
//gist_nonbond_UV_.WriteTiming(3, "UV:", gist_nonbond_.Total());
//gist_nonbond_VV_.WriteTiming(3, "VV:", gist_nonbond_.Total());
//gist_nonbond_OV_.WriteTiming(3, "OV:", gist_nonbond_.Total());
gist_euler_.WriteTiming(2, "Euler: ", gist_action_.Total());
gist_dipole_.WriteTiming(2, "Dipole: ", gist_action_.Total());
gist_order_.WriteTiming(2, "Order: ", gist_action_.Total());
gist_print_.WriteTiming(1, "Print:", total);
mprintf("TIME:\tTotal: %.4f s\n", total);
#ifdef CUDA
this->freeGPUMemory();
#endif
}
#ifdef CUDA
void Action_GIST::NonbondCuda(ActionFrame frm) {
// Simply to get the information for the energetic calculations
std::vector<float> eww_result(this->numberAtoms_);
std::vector<float> esw_result(this->numberAtoms_);
std::vector<std::vector<int> > order_indices;
this->gist_nonbond_.Start();
float *recip = NULL;
float *ucell = NULL;
int boxinfo;
// Check Boxinfo and write the necessary data into recip, ucell and boxinfo.
switch(imageOpt_.ImagingType()) {
case ImageOption::NONORTHO:
recip = new float[9];
ucell = new float[9];
for (int i = 0; i < 9; ++i) {
ucell[i] = (float) frm.Frm().BoxCrd().UnitCell()[i];
recip[i] = (float) frm.Frm().BoxCrd().FracCell()[i];
}
boxinfo = 2;
break;
case ImageOption::ORTHO:
recip = new float[9];
recip[0] = frm.Frm().BoxCrd().Param(Box::X);
recip[1] = frm.Frm().BoxCrd().Param(Box::Y);
recip[2] = frm.Frm().BoxCrd().Param(Box::Z);
ucell = NULL;
boxinfo = 1;
break;
case ImageOption::NO_IMAGE:
recip = NULL;
ucell = NULL;
boxinfo = 0;
break;
default:
mprinterr("Error: Unexpected box information found.");
return;
}
std::vector<int> result_o = std::vector<int>(4 * this->numberAtoms_);
std::vector<int> result_n = std::vector<int>(this->numberAtoms_);
// Call the GPU Wrapper, which subsequently calls the kernel, after setup operations.
// Must create arrays from the vectors, does that by getting the address of the first element of the vector.
std::vector<std::vector<float> > e_result = doActionCudaEnergy(frm.Frm().xAddress(), this->NBindex_c_, this->numberAtomTypes_, this->paramsLJ_c_, this->molecule_c_, boxinfo, recip, ucell, this->numberAtoms_, this->min_c_,
this->max_c_, this->headAtomType_,this->NeighborCut2_, &(result_o[0]), &(result_n[0]), this->result_w_c_,
this->result_s_c_, this->result_O_c_, this->result_N_c_, this->doOrder_);
eww_result = e_result.at(0);
esw_result = e_result.at(1);
if (this->doOrder_) {
int counter = 0;
for (unsigned int i = 0; i < (4 * this->numberAtoms_); i += 4) {
++counter;
std::vector<int> temp;
for (unsigned int j = 0; j < 4; ++j) {
temp.push_back(result_o.at(i + j));
}
order_indices.push_back(temp);
}
}
delete[] recip; // Free memory
delete[] ucell; // Free memory
for (unsigned int sidx = 0; sidx < NSOLVENT_; sidx++) {
int headAtomIndex = O_idxs_[sidx];
size_t bin_i, bin_j, bin_k;
const double *vec = frm.Frm().XYZ(headAtomIndex);
int voxel = -1;
if (this->gO_->Bin().Calc(vec[0], vec[1], vec[2], bin_i, bin_j, bin_k)) {
voxel = this->gO_->CalcIndex(bin_i, bin_j, bin_k);
this->neighbor_.at(0).at(voxel) += result_n.at(headAtomIndex);
// This is not nice, as it assumes that O is set before the two Hydrogens
// might be the case, but is still not nice (in my opinion)
for (unsigned int IDX = 0; IDX != nMolAtoms_; IDX++) {
this->Esw_->UpdateVoxel(voxel, esw_result.at(headAtomIndex + IDX));
this->Eww_->UpdateVoxel(voxel, eww_result.at(headAtomIndex + IDX));
}
// Order calculation
if (this->doOrder_) {
double sum = 0;
Vec3 cent( frm.Frm().xAddress() + (headAtomIndex) * 3 );
std::vector<Vec3> vectors;
switch(imageOpt_.ImagingType()) {
case ImageOption::NONORTHO:
case ImageOption::ORTHO:
{
Vec3 vec(frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(0) * 3));
vectors.push_back( MinImagedVec(vec, cent, frm.Frm().BoxCrd().UnitCell(), frm.Frm().BoxCrd().FracCell()));
vec = Vec3(frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(1) * 3));
vectors.push_back( MinImagedVec(vec, cent, frm.Frm().BoxCrd().UnitCell(), frm.Frm().BoxCrd().FracCell()));
vec = Vec3(frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(2) * 3));
vectors.push_back( MinImagedVec(vec, cent, frm.Frm().BoxCrd().UnitCell(), frm.Frm().BoxCrd().FracCell()));
vec = Vec3(frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(3) * 3));
vectors.push_back( MinImagedVec(vec, cent, frm.Frm().BoxCrd().UnitCell(), frm.Frm().BoxCrd().FracCell()));
}
break;
default:
vectors.push_back( Vec3( frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(0) * 3) ) - cent );
vectors.push_back( Vec3( frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(1) * 3) ) - cent );
vectors.push_back( Vec3( frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(2) * 3) ) - cent );
vectors.push_back( Vec3( frm.Frm().xAddress() + (order_indices.at(headAtomIndex).at(3) * 3) ) - cent );
}
for (int i = 0; i < 3; ++i) {
for (int j = i + 1; j < 4; ++j) {
double cosThet = (vectors.at(i) * vectors.at(j)) / sqrt(vectors.at(i).Magnitude2() * vectors.at(j).Magnitude2());
sum += (cosThet + 1.0/3) * (cosThet + 1.0/3);
}
}
this->order_norm_->UpdateVoxel(voxel, 1.0 - (3.0/8.0) * sum);
}
}
}
this->gist_nonbond_.Stop();
}
/**
* Frees all the Memory on the GPU.
*/
void Action_GIST::freeGPUMemory(void) {
freeCuda(this->NBindex_c_);
freeCuda(this->molecule_c_);
freeCuda(this->paramsLJ_c_);
freeCuda(this->max_c_);
freeCuda(this->min_c_);
freeCuda(this->result_w_c_);
freeCuda(this->result_s_c_);
freeCuda(this->result_O_c_);
freeCuda(this->result_N_c_);
this->NBindex_c_ = NULL;
this->molecule_c_ = NULL;
this->paramsLJ_c_ = NULL;
this->max_c_ = NULL;
this->min_c_ = NULL;
this->result_w_c_= NULL;
this->result_s_c_= NULL;
this->result_O_c_ = NULL;
this->result_N_c_ = NULL;
}
/**
* Copies data from the CPU to the GPU.
* @throws: CudaException
*/
void Action_GIST::copyToGPU(void) {
try {
copyMemoryToDevice(&(this->NBIndex_[0]), this->NBindex_c_, this->NBIndex_.size() * sizeof(int));
copyMemoryToDeviceStruct(&(this->charges_[0]), &(this->atomTypes_[0]), this->solvent_, &(this->molecule_[0]), this->numberAtoms_, &(this->molecule_c_),
&(this->lJParamsA_[0]), &(this->lJParamsB_[0]), this->lJParamsA_.size(), &(this->paramsLJ_c_));
} catch (CudaException &ce) {
this->freeGPUMemory();
mprinterr("Error: Could not copy data to the device.\n");
throw ce;
} catch (std::exception &e) {
this->freeGPUMemory();
throw e;
}
}
#endif
| hainm/cpptraj | src/Action_GIST.cpp | C++ | gpl-3.0 | 83,454 |
<?php
/**
* Kiwitrees: Web based Family History software
* Copyright (C) 2012 to 2022 kiwitrees.net
*
* Derived from webtrees (www.webtrees.net)
* Copyright (C) 2010 to 2012 webtrees development team
*
* Derived from PhpGedView (phpgedview.sourceforge.net)
* Copyright (C) 2002 to 2010 PGV Development Team
*
* Kiwitrees 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 Kiwitrees. If not, see <http://www.gnu.org/licenses/>.
*/
if (!defined('KT_KIWITREES')) {
header('HTTP/1.0 403 Forbidden');
exit;
}
// add new custom_lang table
self::exec(
"CREATE TABLE IF NOT EXISTS `##custom_lang`(".
" custom_lang_id INTEGER NOT NULL AUTO_INCREMENT,".
" language VARCHAR(10) NOT NULL,".
" standard_text LONGTEXT NOT NULL,".
" custom_text LONGTEXT NOT NULL,".
" updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,".
" PRIMARY KEY (custom_lang_id)".
") COLLATE utf8_unicode_ci ENGINE=InnoDB"
);
// Update the version to indicate success
KT_Site::preference($schema_name, $next_version);
| kiwi3685/kiwitrees | includes/db_schema/db_schema_28_29.php | PHP | gpl-3.0 | 1,600 |
module.exports = { domain:"messages",
locale_data:{ messages:{ "":{ domain:"messages",
plural_forms:"nplurals=2; plural=(n != 1);",
lang:"el" },
"%(addonName)s %(startSpan)sby %(authorList)s%(endSpan)s":[ "%(addonName)s %(startSpan)s από %(authorList)s%(endSpan)s" ],
"Extension Metadata":[ "Μεταδεδομένα επέκτασης" ],
Screenshots:[ "Στιγμιότυπα" ],
"About this extension":[ "Σχετικά με την επέκταση" ],
"Rate your experience":[ "Αξιολογήστε την εμπειρία σας" ],
Category:[ "Κατηγορία" ],
"Used by":[ "Χρήση από" ],
Sentiment:[ "Αίσθηση" ],
Back:[ "Πίσω" ],
Submit:[ "Υποβολή" ],
"Please enter some text":[ "Παρακαλώ εισάγετε κείμενο" ],
"Write a review":[ "Γράψτε μια κριτική" ],
"Tell the world why you think this extension is fantastic!":[ "Πείτε στον κόσμο γιατί θεωρείτε ότι αυτή η επέκταση είναι φανταστική!" ],
"Privacy policy":[ "Πολιτική απορρήτου" ],
"Legal notices":[ "Νομικές σημειώσεις" ],
"View desktop site":[ "Προβολή ιστοσελίδας για υπολογιστές" ],
"Browse in your language":[ "Περιήγηση στη γλώσσα σας" ],
"Firefox Add-ons":[ "Πρόσθετα Firefox" ],
"How are you enjoying your experience with %(addonName)s?":[ "Απολαμβάνετε την εμπειρία σας με το %(addonName)s;" ],
"screenshot %(imageNumber)s of %(totalImages)s":[ "Στιγμιότυπο %(imageNumber)s από %(totalImages)s" ],
"Average rating: %(rating)s out of 5":[ "Μέση βαθμολογία: %(rating)s από 5" ],
"No ratings":[ "Καμία κριτική" ],
"%(users)s user":[ "%(users)s χρήστης",
"%(users)s χρήστες" ],
"Log out":[ "Αποσύνδεση" ],
"Log in/Sign up":[ "Σύνδεση/Εγγραφή" ],
"Add-ons for Firefox":[ "Πρόσθετα για το Firefox" ],
"What do you want Firefox to do?":[ "Τι θέλετε να κάνει το Firefox;" ],
"Block ads":[ "Αποκλεισμός διαφημίσεων" ],
Screenshot:[ "Στιγμιότυπο οθόνης" ],
"Save stuff":[ "Αποθήκευση στοιχείων" ],
"Shop online":[ "Διαδικτυακές αγορές" ],
"Be social":[ "Κοινωνικοποίηση" ],
"Share stuff":[ "Κοινή χρήση στοιχείων" ],
"Browse all extensions":[ "Περιήγηση σε όλες τις επεκτάσεις" ],
"How do you want Firefox to look?":[ "Τι εμφάνιση θέλετε να έχει το Firefox;" ],
Wild:[ "Άγρια" ],
Abstract:[ "Αφηρημένη" ],
Fashionable:[ "Μοδάτη" ],
Scenic:[ "Σκηνική" ],
Sporty:[ "Αθλητική" ],
Mystical:[ "Μυστική" ],
"Browse all themes":[ "Περιήγηση σε όλα τα θέματα" ],
"Downloading %(name)s.":[ "Γίνεται λήψη του %(name)s." ],
"Installing %(name)s.":[ "Γίνεται εγκατάσταση του %(name)s." ],
"%(name)s is installed and enabled. Click to uninstall.":[ "Το %(name)s έχει εγκατασταθεί και ενεργοποιηθεί. Κάντε κλικ για απεγκατάσταση." ],
"%(name)s is disabled. Click to enable.":[ "Το %(name)s έχει απενεργοποιηθεί. Κάντε κλικ για ενεργοποίηση." ],
"Uninstalling %(name)s.":[ "Γίνεται απεγκατάσταση του %(name)s." ],
"%(name)s is uninstalled. Click to install.":[ "Το %(name)s έχει απεγκατασταθεί. Κάντε κλικ για εγκατάσταση." ],
"Install state for %(name)s is unknown.":[ "Η κατάσταση εγκατάστασης για το %(name)s είναι άγνωστη." ],
Previous:[ "Προηγούμενη" ],
Next:[ "Επόμενη" ],
"Page %(currentPage)s of %(totalPages)s":[ "Σελίδα %(currentPage)s από %(totalPages)s" ],
"Your search for \"%(query)s\" returned %(count)s result.":[ "Η αναζήτησή σας για το \"%(query)s\" είχε %(count)s αποτέλεσμα.",
"Η αναζήτησή σας για το \"%(query)s\" είχε %(count)s αποτελέσματα." ],
"Searching...":[ "Αναζήτηση..." ],
"No results were found for \"%(query)s\".":[ "Δεν βρέθηκε κανένα αποτέλεσμα για το \"%(query)s\"." ],
"Please supply a valid search":[ "Παρακαλώ κάντε μια έγκυρη αναζήτηση" ] } },
_momentDefineLocale:function anonymous() {
//! moment.js locale configuration
//! locale : Greek [el]
//! author : Aggelos Karalias : https://github.com/mehiel
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['../moment'], factory) :
factory(global.moment)
}(this, (function (moment) { 'use strict';
function isFunction(input) {
return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
}
var el = moment.defineLocale('el', {
monthsNominativeEl : 'Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος'.split('_'),
monthsGenitiveEl : 'Ιανουαρίου_Φεβρουαρίου_Μαρτίου_Απριλίου_Μαΐου_Ιουνίου_Ιουλίου_Αυγούστου_Σεπτεμβρίου_Οκτωβρίου_Νοεμβρίου_Δεκεμβρίου'.split('_'),
months : function (momentToFormat, format) {
if (/D/.test(format.substring(0, format.indexOf('MMMM')))) { // if there is a day number before 'MMMM'
return this._monthsGenitiveEl[momentToFormat.month()];
} else {
return this._monthsNominativeEl[momentToFormat.month()];
}
},
monthsShort : 'Ιαν_Φεβ_Μαρ_Απρ_Μαϊ_Ιουν_Ιουλ_Αυγ_Σεπ_Οκτ_Νοε_Δεκ'.split('_'),
weekdays : 'Κυριακή_Δευτέρα_Τρίτη_Τετάρτη_Πέμπτη_Παρασκευή_Σάββατο'.split('_'),
weekdaysShort : 'Κυρ_Δευ_Τρι_Τετ_Πεμ_Παρ_Σαβ'.split('_'),
weekdaysMin : 'Κυ_Δε_Τρ_Τε_Πε_Πα_Σα'.split('_'),
meridiem : function (hours, minutes, isLower) {
if (hours > 11) {
return isLower ? 'μμ' : 'ΜΜ';
} else {
return isLower ? 'πμ' : 'ΠΜ';
}
},
isPM : function (input) {
return ((input + '').toLowerCase()[0] === 'μ');
},
meridiemParse : /[ΠΜ]\.?Μ?\.?/i,
longDateFormat : {
LT : 'h:mm A',
LTS : 'h:mm:ss A',
L : 'DD/MM/YYYY',
LL : 'D MMMM YYYY',
LLL : 'D MMMM YYYY h:mm A',
LLLL : 'dddd, D MMMM YYYY h:mm A'
},
calendarEl : {
sameDay : '[Σήμερα {}] LT',
nextDay : '[Αύριο {}] LT',
nextWeek : 'dddd [{}] LT',
lastDay : '[Χθες {}] LT',
lastWeek : function () {
switch (this.day()) {
case 6:
return '[το προηγούμενο] dddd [{}] LT';
default:
return '[την προηγούμενη] dddd [{}] LT';
}
},
sameElse : 'L'
},
calendar : function (key, mom) {
var output = this._calendarEl[key],
hours = mom && mom.hours();
if (isFunction(output)) {
output = output.apply(mom);
}
return output.replace('{}', (hours % 12 === 1 ? 'στη' : 'στις'));
},
relativeTime : {
future : 'σε %s',
past : '%s πριν',
s : 'λίγα δευτερόλεπτα',
m : 'ένα λεπτό',
mm : '%d λεπτά',
h : 'μία ώρα',
hh : '%d ώρες',
d : 'μία μέρα',
dd : '%d μέρες',
M : 'ένας μήνας',
MM : '%d μήνες',
y : 'ένας χρόνος',
yy : '%d χρόνια'
},
ordinalParse: /\d{1,2}η/,
ordinal: '%dη',
week : {
dow : 1, // Monday is the first day of the week.
doy : 4 // The week that contains Jan 4st is the first week of the year.
}
});
return el;
})));
} } | jasonthomas/addons-frontend | src/locale/el/amo.js | JavaScript | mpl-2.0 | 8,820 |