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
// META: timeout=long // META: script=../util/helpers.js // META: script=failures.js run_test(["AES-CTR"]);
mbrubeck/servo
tests/wpt/web-platform-tests/WebCryptoAPI/generateKey/failures_AES-CTR.https.any.js
JavaScript
mpl-2.0
108
from tqdm import tqdm from django.core.management.base import BaseCommand from django.db.models import Exists, OuterRef from ...models import Locality, Operator, Service class Command(BaseCommand): def handle(self, *args, **options): for locality in tqdm(Locality.objects.with_documents()): locality.search_vector = locality.document locality.save(update_fields=['search_vector']) has_services = Exists(Service.objects.filter(current=True, operator=OuterRef('pk'))) for operator in tqdm(Operator.objects.with_documents().filter(has_services)): operator.search_vector = operator.document operator.save(update_fields=['search_vector']) print(Operator.objects.filter(~has_services).update(search_vector=None)) for service in tqdm(Service.objects.with_documents().filter(current=True)): service.search_vector = service.document service.save(update_fields=['search_vector']) print(Service.objects.filter(current=False).update(search_vector=None))
jclgoodwin/bustimes.org.uk
busstops/management/commands/update_search_indexes.py
Python
mpl-2.0
1,072
# -*- coding: utf-8 -*- # Generated by Django 1.11.9 on 2018-05-01 08:10 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('os2webscanner', '0013_auto_20180501_1006'), ] operations = [ migrations.AlterModelTable( name='scan', table='os2webscanner_scan', ), ]
os2webscanner/os2webscanner
django-os2webscanner/os2webscanner/migrations/0014_auto_20180501_1010.py
Python
mpl-2.0
408
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ pvc.BaseChart .add({ /** * A map of {@link pvc.visual.Role} by name. * Do NOT modify the returned object. * @type Object<string,pvc.visual.Role> */ visualRoles: null, /** * The array of all {@link pvc.visual.Role} instances used by the chart. * Do NOT modify the returned array. * @type pvc.visual.Role[] */ visualRoleList: null, /** * The array of all {@link pvc.visual.Role} instances used by the chart * that are considered measures. * @type pvc.visual.Role[] * @private */ _measureVisualRoles: null, /** * Obtains an existing visual role given its name. * An error is thrown if a role with the specified name is not defined. * * The specified name may be: * <ul> * <li>the name of a chart visual role, </li> * <li>the local name of a visual role of the chart's main plot, or</li> * <li>the fully qualified name of a plot's visual role: "<plot name or id>.<local role name>".</li> * </ul> * * @param {string} roleName The visual role name. * @type pvc.visual.Role */ visualRole: function(roleName) { var role = def.getOwn(this.visualRoles, roleName); if(!role) throw def.error.operationInvalid('roleName', "There is no visual role with name '{0}'.", [roleName]); return role; }, /** * Obtains the array of all {@link pvc.visual.Role} instances used by the chart * that are considered measures. * * This is made lazily because the effective "measure" status * depends on the binding of the visual role, and * of it becoming discrete or continuous. * * Do NOT modify the returned array. * * @return {pvc.visual.Role[]} The array of measure visual roles. */ measureVisualRoles: function() { if(this.parent) return this.parent.measureVisualRoles(); return this._measureVisualRoles || (this._measureVisualRoles = this.visualRoleList.filter(function(r) { return r.isBound() && !r.isDiscrete() && r.isMeasure; })); }, measureDimensionsNames: function() { return def.query(this.measureVisualRoles()) .selectMany(function(r) { return r.grouping.dimensionNames(); }) .distinct() .array(); }, /** * Obtains the chart-level visual roles played by a given dimension name, in definition order. * Do NOT modify the returned array. * @param {string} dimName The name of the dimension. * @return {pvc.visual.Role[]} The array of visual roles or <tt>null</tt>, if none. */ visualRolesOf: function(dimName) { var visualRolesByDim = this._visRolesByDim; if(!visualRolesByDim) { visualRolesByDim = this._visRolesByDim = {}; this.visualRoleList.forEach(function(r) { if(!r.plot) { var g = r.grouping; if (g) g.dimensionNames().forEach(function (n) { def.array.lazy(visualRolesByDim, n).push(r); }); } }); } return def.getOwn(visualRolesByDim, dimName, null); }, _constructVisualRoles: function(/*options*/) { var parent = this.parent; if(parent) { this.visualRoles = parent.visualRoles; this.visualRoleList = parent.visualRoleList; } else { this.visualRoles = {}; this.visualRoleList = []; } }, _addVisualRole: function(name, keyArgs) { keyArgs = def.set(keyArgs, 'index', this.visualRoleList.length); var role = new pvc.visual.Role(name, keyArgs), names = [name]; // There's a way to refer to chart visual roles without danger // of matching the main plot's visual roles. if(!role.plot) names.push("$." + name); return this._addVisualRoleCore(role, names); }, _addVisualRoleCore: function(role, names) { if(!names) names = role.name; this.visualRoleList.push(role); if(def.array.is(names)) names.forEach(function(name) { this.visualRoles[name] = role; }, this); else this.visualRoles[names] = role; return role; }, /** * Initializes the chart-level visual roles. * @virtual */ _initChartVisualRoles: function() { this._addVisualRole('multiChart', { defaultDimension: 'multiChart*', requireIsDiscrete: true }); this._addVisualRole('dataPart', { defaultDimension: 'dataPart', requireIsDiscrete: true, requireSingleDimension: true, dimensionDefaults: {isHidden: true, comparer: def.compare} }); }, _getDataPartDimName: function(useDefault) { var role = this.visualRoles.dataPart, preGrouping; return role.isBound() ? role.lastDimensionName() : (preGrouping = role.preBoundGrouping()) ? preGrouping.lastDimensionName() : useDefault ? role.defaultDimensionGroup : null; }, /** * Processes a view specification. * * An error is thrown if the specified view specification does * not have at least one of the properties <i>role</i> or <i>dims</i>. * * @param {Object} viewSpec The view specification. * @param {string} [viewSpec.role] The name of a visual role. * @param {string|string[]} [viewSpec.dims] The name or names of the view's dimensions. */ _processViewSpec: function(viewSpec) { // If not yet processed if(!viewSpec.dimsKeys) { if(viewSpec.role) { var role = this.visualRoles[viewSpec.role], grouping = role && role.grouping; if(grouping) { viewSpec.dimNames = grouping.dimensionNames().slice().sort(); viewSpec.dimsKey = viewSpec.dimNames.join(","); } } else if(viewSpec.dims) { viewSpec.dimNames = viewSpec_normalizeDims(viewSpec.dims); viewSpec.dimsKey = String(viewSpec.dimNames); } else { throw def.error.argumentInvalid( "viewSpec", "Invalid view spec. No 'role' or 'dims' property."); } } } }); // TODO: expand dim* function viewSpec_normalizeDims(dims) { // Assume already normalized if(def.string.is(dims)) dims = dims.split(","); else if(!def.array.is(dims)) throw def.error.argumentInvalid('dims', "Must be a string or an array of strings."); return def.query(dims).distinct().sort().array(); }
Abpaula/ccc
package-res/ccc/core/base/chart/chart.visualRoles.js
JavaScript
mpl-2.0
7,092
/** * Add a context menu item to borderify the current tab. */ browser.menus.create({ id: "borderify-current-tab", title: "Borderify current tab", contexts: ["all"] }); /** * The borderify CSS. */ const borderCSS = 'body { border: 5px solid red };'; /* * Borderifies the current tab, and, using setTabValue, stores the fact * that this tab was borderified. */ async function borderify() { let tabArray = await browser.tabs.query({currentWindow: true, active: true}); let tabId = tabArray[0].id; await browser.tabs.insertCSS(tabId, {code: borderCSS}); await browser.sessions.setTabValue(tabId, "border-css", borderCSS); } browser.menus.onClicked.addListener(borderify); /* * When new tabs are created, we want to check, using getTabValue, whether * the tab has the borderified state. That would mean it was borderified, then * closed, then reopened, so we want to reapply the borderify CSS. * * But we can't insertCSS in onCreated, it's too early. So instead we make * an onUpdated listener, just for this tab. In onUpdated we check the tab ID, * and if this is our tab, insert the CSS and remove the listener. */ browser.tabs.onCreated.addListener((tab) => { async function borderifyRestored(targetTabId, thisTabId) { if (targetTabId === thisTabId) { let stored = await browser.sessions.getTabValue(targetTabId, "border-css"); if (stored) { let result = await browser.tabs.insertCSS(targetTabId, {code: stored}); } browser.tabs.onUpdated.removeListener(thisBorderifyRestored); } } let thisBorderifyRestored = borderifyRestored.bind(null, tab.id); browser.tabs.onUpdated.addListener(thisBorderifyRestored); });
mdn/webextensions-examples
session-state/background.js
JavaScript
mpl-2.0
1,698
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Office.Interop.Outlook; using Google.Apis.Calendar.v3.Data; namespace OutlookGoogleCalendarSync.OutlookOgcs { public interface Interface { void Connect(); void Disconnect(Boolean onlyWhenNoGUI = false); Boolean NoGUIexists(); Folders Folders(); Dictionary<string, MAPIFolder> CalendarFolders(); MAPIFolder UseOutlookCalendar(); void UseOutlookCalendar(MAPIFolder set); NameSpace GetCurrentUser(NameSpace oNS); String CurrentUserSMTP(); String CurrentUserName(); Boolean Offline(); void RefreshCategories(); String GetRecipientEmail(Recipient recipient); OlExchangeConnectionMode ExchangeConnectionMode(); String GetGlobalApptID(AppointmentItem ai); Event IANAtimezone_set(Event ev, AppointmentItem ai); void WindowsTimeZone_get(AppointmentItem ai, out String startTz, out String endTz); AppointmentItem WindowsTimeZone_set(AppointmentItem ai, Event ev, String attr = "Both", Boolean onlyTZattribute = false); /// <summary> /// Filter Outlook Item according to specified filter. /// </summary> /// <param name="outlookItems">Items to be filtered</param> /// <param name="filter">The logic by which to perform filter</param> /// <returns>Filtered items</returns> List<Object> FilterItems(Items outlookItems, String filter); MAPIFolder GetFolderByID(String entryID); void GetAppointmentByID(String entryID, out AppointmentItem ai); } }
phw198/OutlookGoogleCalendarSync
src/OutlookGoogleCalendarSync/OutlookOgcs/OutlookInterface.cs
C#
mpl-2.0
1,665
/*---------------------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v.2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. ----------------------------------------------------------*/ using System; using System.Diagnostics; namespace oscript { internal class MeasureBehavior : ExecuteScriptBehavior { public MeasureBehavior(string path, string[] args) : base(path, args) { } public override int Execute() { var sw = new Stopwatch(); Output.WriteLine("Script started: " + DateTime.Now + "\n"); sw.Start(); var exitCode = base.Execute(); sw.Stop(); Output.WriteLine("\nScript completed: " + DateTime.Now); Output.WriteLine("\nDuration: " + sw.Elapsed); return exitCode; } public static AppBehavior Create(CmdLineHelper helper) { var path = helper.Next(); return path != null ? new MeasureBehavior(path, helper.Tail()) : null; } } }
EvilBeaver/OneScript
src/oscript/MeasureBehavior.cs
C#
mpl-2.0
1,029
/** * An implementation for the IView, using SDL. * * License: Mozilla Public License Version 2.0 (https://www.mozilla.org/en-US/MPL/2.0/ OR See accompanying file LICENSE) * Authors: * - Dan Printzell */ #pragma once #include <hydra/ext/api.hpp> #include <hydra/view/view.hpp> #include <memory> namespace Hydra::View { namespace SDLView { HYDRA_GRAPHICS_API std::unique_ptr<IView> create(const std::string& title); }; }
HydraInteractive/Hydra
hydra_graphics/include/hydra/view/sdlview.hpp
C++
mpl-2.0
433
define(['Container', 'NumberStyle'], function(Container, NumberStyle) { /** * Percentage, between cow and ship, that the beam should end at * @const * @type number */ var MAX_BEAM_DISTANCE = 100; /** * Percentage, between ship and cow, that the beam should start at * @const * @type number */ var MIN_BEAM_DISTANCE = 0; /** * how long the cow should stay tinted before earning a point * @const * @type number */ var COW_GET_DELAY = 250; /** * The color of the cow when it has been hit by the tractor beam * @type number * @const */ var COW_TINT = 0x77FF77; /** * The saucer profile that measures how close a player is to abducting a cow. * When the player has retrieved a cow, this emits an 'abduct' event. * * @param {Object=} options Configuration options * @param {number=} [options.color] The color for the ship. @see Color * @param {number=} [options.speed=3] how quickly the beam should descend or * ascend, between 1 and 5, 5 being the fastest. * * @example * var b = new Beam(); * b.on('abduct', functon doSomething(){console.log('something'}); * b.active = true; * * @constructor * @name Beam */ function Beam(options) { var _this = this, _ship = new PIXI.Sprite.fromFrame('purpleSaucer.png'), _beam = new PIXI.Sprite.fromFrame('tractorBeam.png'), _cow = new PIXI.Sprite.fromFrame('cowProfile.png'), /** * The color of the ship. @see Color * @name color * @memberof Beam * @type number */ _color, /** * Whether or not the ascent and descent functions should respond. * If this is true, tractor beam will neither ascend nor descend. * The beam will pause momentarily when the cow has been hit. * @type boolean * @private */ _paused = false, /** * How many cows the user has retrieved * @type number * @name points * @memberof Beam */ _points = 0, /** * The holder for the points */ _pointsText = new PIXI.Text(_points, NumberStyle), /** * A number between MIN_BEAM_DISTANCE and MAX_BEAM_DISTANCE, representing how close the beam is to the cow * @private * @memberof Beam * @type number */ _distance = MIN_BEAM_DISTANCE, /** * Whether or not the beam should be descending * @name active * @memberof Beam * @type boolean */ _enabled = false, /** * Maps chosen speeds to times * @type Object */ _speeds = { 1: 1000, 2: 850, 3: 700, 4: 650, 5: 500 }, _ascentInterval = null, _descentInterval = null, /** * The maximum height the beam can be before it touches the cow. * @type number */ _maxBeamHeight = null, options = options || {}, /** * The speed that the tractor beam moves * @memberof Beam * @type number * @name speed */ _speed = _speeds[3]; PIXI.DisplayObjectContainer.call(_this); function _init() { var pad_x = 10; // tall enough to fit the cow, the ship, with room for the beam var box_width = _ship.width + pad_x; var box_height = (_cow.height + _ship.height)*2.5 + 5; var box = new Container('Cow Meter', box_width, box_height); var height = box_height - box.textHeight; _this.addChild(box); _cow.anchor.x = 0.5; _cow.y = height - _cow.height; _cow.x = box_width/2; _ship.anchor.x = 0.5; _ship.x = box_width/2; _ship.y = box.textHeight; _beam.anchor.x = 0.5; _beam.y = _ship.y + _ship.height - 10; _beam.x = box_width/2; _beam.height = 0; _beam.opacity = 0.7; _maxBeamHeight = height - _cow.height - _beam.y; _pointsText.y = _cow.y + _cow.height + 5; _pointsText.x = box.width/2 - _pointsText.width/2 + box.getBounds().x; _this.addChild(_ship); _this.addChild(_beam); _this.addChild(_cow); _this.addChild(_pointsText); window.t = _pointsText; Beam._index++; // so we can dispatch events (@see _retrieveCow) PIXI.EventTarget.call(_this); }; /** * Sets the distance of the tractor beam * @param number value Must be between MIN_BEAM_DISTANCE and MAX_BEAM_DISTANCE * @see score */ function _setDistance(value) { if(Number.parseInt(value) < MIN_BEAM_DISTANCE || Number.parseInt(value) > MAX_BEAM_DISTANCE) { throw "Tractor beam distance must be between " + MIN_BEAM_DISTANCE + '-' + MAX_BEAM_DISTANCE + ". Given: " + value; } _distance = value; _beam.height = (_distance/100)*_maxBeamHeight; }; /** * Sets the speed of the tractor beam * @param number value A number, from 1 to 5, representing how fast the * tractor beam should move * @see speed * @private */ function _setSpeed(value) { var speed = _speeds[value]; if(speed === undefined) { throw "Tractor beam speed must be between 1-5. Given: " + value; } _speed = speed; _resetMotion(); }; /** * Sets the total score * @see points * @private */ function _setPoints(points) { if(isNaN(parseInt(points, 10))) { return; } _points = points;; _pointsText.setText(""+points); } /** * Resets tractor beam's motion, which depends on whether or not the beam * is enabled and the current speed of the beam */ function _resetMotion() { clearInterval(_descentInterval); clearInterval(_ascentInterval); if(_enabled) { _descentInterval = setInterval(_descend, _this.speed); } else { _ascentInterval = setInterval(_ascend, _this.speed); } } /** * Gets the speed of the tractor beam * @return number A number, from 1 to 5, representing how fast the tractor * beam is moving * @see speed */ function _getSpeed() { for(key in _speeds) { if(_speeds[key] === _speed) { return key; } } }; function _ascend() { if(_paused) { return; } if(_distance <= MIN_BEAM_DISTANCE) { return; } _setDistance(_distance-1); }; function _descend() { if(_paused) { return; } if(_distance >= MAX_BEAM_DISTANCE) { _retrieveCow(); return; } _setDistance(_distance+1); }; /** * @param boolean value Whether or not the beam should be enabled */ function _setEnabled(value) { if(value == _enabled) { return; } _enabled = !!value; _resetMotion(); }; /** * Used when a beam hits the cow */ function _retrieveCow() { _paused = true; _cow.tint = COW_TINT; setTimeout(function() { _cow.tint = 0xFFFFFF; _paused = false; _setDistance(MIN_BEAM_DISTANCE); _this.points++; _this.emit({type: 'abduct'}); }, COW_GET_DELAY); }; Object.defineProperties(_this, { color: { enumerable: true, get: function() { return _color; } }, speed: { enumerable: true, get: _getSpeed, set: _setSpeed }, active: { enumerable: true, get: function() { return _enabled; }, set: _setEnabled }, points: { enumerable: true, get: function() { return _points; }, set: _setPoints } }); _init(); }; /** * Keeps track of how many saucers have been created (for colorization's sake) * @type number */ Beam._index = 0; Beam.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); Beam.prototype.constructor = Beam; return Beam; });
BYU-ODH/vocal-abduction
app/js/Beam.js
JavaScript
mpl-2.0
8,135
//go:build !consulent // +build !consulent package structs import ( "hash" "github.com/hashicorp/consul/acl" "github.com/hashicorp/consul/types" ) var emptyEnterpriseMeta = EnterpriseMeta{} // EnterpriseMeta stub type EnterpriseMeta struct{} func (m *EnterpriseMeta) ToEnterprisePolicyMeta() *acl.EnterprisePolicyMeta { return nil } func (m *EnterpriseMeta) estimateSize() int { return 0 } func (m *EnterpriseMeta) addToHash(_ hash.Hash, _ bool) { // do nothing } func (m *EnterpriseMeta) Merge(_ *EnterpriseMeta) { // do nothing } func (m *EnterpriseMeta) MergeNoWildcard(_ *EnterpriseMeta) { // do nothing } func (m *EnterpriseMeta) Matches(_ *EnterpriseMeta) bool { return true } func (m *EnterpriseMeta) IsSame(_ *EnterpriseMeta) bool { return true } func (m *EnterpriseMeta) LessThan(_ *EnterpriseMeta) bool { return false } func (m *EnterpriseMeta) WithWildcardNamespace() *EnterpriseMeta { return &emptyEnterpriseMeta } func (m *EnterpriseMeta) UnsetPartition() { // do nothing } // TODO(partition): stop using this func NewEnterpriseMetaInDefaultPartition(_ string) EnterpriseMeta { return emptyEnterpriseMeta } func NewEnterpriseMetaWithPartition(_, _ string) EnterpriseMeta { return emptyEnterpriseMeta } func (m *EnterpriseMeta) NamespaceOrDefault() string { return IntentionDefaultNamespace } func NamespaceOrDefault(_ string) string { return IntentionDefaultNamespace } func (m *EnterpriseMeta) NamespaceOrEmpty() string { return "" } func (m *EnterpriseMeta) InDefaultNamespace() bool { return true } func (m *EnterpriseMeta) PartitionOrDefault() string { return "default" } func EqualPartitions(_, _ string) bool { return true } func IsDefaultPartition(partition string) bool { return true } func PartitionOrDefault(_ string) string { return "default" } func (m *EnterpriseMeta) PartitionOrEmpty() string { return "" } func (m *EnterpriseMeta) InDefaultPartition() bool { return true } // ReplicationEnterpriseMeta stub func ReplicationEnterpriseMeta() *EnterpriseMeta { return &emptyEnterpriseMeta } // TODO(partition): stop using this func DefaultEnterpriseMetaInDefaultPartition() *EnterpriseMeta { return &emptyEnterpriseMeta } // DefaultEnterpriseMetaInPartition stub func DefaultEnterpriseMetaInPartition(_ string) *EnterpriseMeta { return &emptyEnterpriseMeta } func NodeEnterpriseMetaInPartition(_ string) *EnterpriseMeta { return &emptyEnterpriseMeta } // TODO(partition): stop using this func NodeEnterpriseMetaInDefaultPartition() *EnterpriseMeta { return &emptyEnterpriseMeta } // TODO(partition): stop using this func WildcardEnterpriseMetaInDefaultPartition() *EnterpriseMeta { return &emptyEnterpriseMeta } // WildcardEnterpriseMetaInPartition stub func WildcardEnterpriseMetaInPartition(_ string) *EnterpriseMeta { return &emptyEnterpriseMeta } // FillAuthzContext stub func (_ *EnterpriseMeta) FillAuthzContext(_ *acl.AuthorizerContext) {} func (_ *Node) FillAuthzContext(_ *acl.AuthorizerContext) {} func (_ *Coordinate) FillAuthzContext(_ *acl.AuthorizerContext) {} func (_ *NodeInfo) FillAuthzContext(_ *acl.AuthorizerContext) {} func (_ *EnterpriseMeta) Normalize() {} // FillAuthzContext stub func (_ *DirEntry) FillAuthzContext(_ *acl.AuthorizerContext) {} // FillAuthzContext stub func (_ *RegisterRequest) FillAuthzContext(_ *acl.AuthorizerContext) {} func (_ *RegisterRequest) GetEnterpriseMeta() *EnterpriseMeta { return nil } // OSS Stub func (op *TxnNodeOp) FillAuthzContext(ctx *acl.AuthorizerContext) {} // OSS Stub func (_ *TxnServiceOp) FillAuthzContext(_ *acl.AuthorizerContext) {} // OSS Stub func (_ *TxnCheckOp) FillAuthzContext(_ *acl.AuthorizerContext) {} func NodeNameString(node string, _ *EnterpriseMeta) string { return node } func ServiceIDString(id string, _ *EnterpriseMeta) string { return id } func ParseServiceIDString(input string) (string, *EnterpriseMeta) { return input, DefaultEnterpriseMetaInDefaultPartition() } func (sid ServiceID) String() string { return sid.ID } func ServiceIDFromString(input string) ServiceID { id, _ := ParseServiceIDString(input) return ServiceID{ID: id} } func ParseServiceNameString(input string) (string, *EnterpriseMeta) { return input, DefaultEnterpriseMetaInDefaultPartition() } func (n ServiceName) String() string { return n.Name } func ServiceNameFromString(input string) ServiceName { id, _ := ParseServiceNameString(input) return ServiceName{Name: id} } func (cid CheckID) String() string { return string(cid.ID) } func (_ *HealthCheck) Validate() error { return nil } func enterpriseRequestType(m MessageType) (string, bool) { return "", false } // CheckIDs returns the IDs for all checks associated with a session, regardless of type func (s *Session) CheckIDs() []types.CheckID { // Merge all check IDs into a single slice, since they will be handled the same way checks := make([]types.CheckID, 0, len(s.Checks)+len(s.NodeChecks)+len(s.ServiceChecks)) checks = append(checks, s.Checks...) for _, c := range s.NodeChecks { checks = append(checks, types.CheckID(c)) } for _, c := range s.ServiceChecks { checks = append(checks, types.CheckID(c.ID)) } return checks } func (t *Intention) HasWildcardSource() bool { return t.SourceName == WildcardSpecifier } func (t *Intention) HasWildcardDestination() bool { return t.DestinationName == WildcardSpecifier } func (s *ServiceNode) NodeIdentity() Identity { return Identity{ID: s.Node} }
hashicorp/consul
agent/structs/structs_oss.go
GO
mpl-2.0
5,467
var wirelib = (function() { var canvas, context, width, height, lines = [], cx, cy, cz, fl = 250, interval, loopCallback, running; function initWithCanvas(aCanvas) { canvas = aCanvas; if(canvas !== undefined) { width = canvas.width; height = canvas.height; cx = width / 2; cy = height / 2; cz = fl * 2; context = canvas.getContext("2d"); } } // fl stands for Focal length function project(p3d) { var p2d = {}, scale = fl / (fl + p3d.z + cz); p2d.x = cx + p3d.x * scale; p2d.y = cy + p3d.y * scale; return p2d; } function addLine() { var i, numPoints, points, line; points = (typeof arguments[0] === "object") ? arguments[0] : arguments; numPoints = points.length; if(numPoints >= 6) { line = {style:this.strokeStyle, width:this.lineWidth, points:[]}; lines.push(line); for(i = 0; i < numPoints; i += 3) { line.points.push({x:points[i], y:points[i + 1], z:points[i + 2]}); } } else { console.error("wirelib.addLine: You need to add at least two 3d points (6 numbers) to make a line."); } return line; } function addBox(x, y, z, w, h, d) { this.addLine(x - w / 2, y - h / 2, z - d / 2, x + w / 2, y - h / 2, z - d / 2, x + w / 2, y + h / 2, z - d / 2, x - w / 2, y + h / 2, z - d / 2, x - w / 2, y - h / 2, z - d / 2); this.addLine(x - w / 2, y - h / 2, z + d / 2, x + w / 2, y - h / 2, z + d / 2, x + w / 2, y + h / 2, z + d / 2, x - w / 2, y + h / 2, z + d / 2, x - w / 2, y - h / 2, z + d / 2); this.addLine(x - w / 2, y - h / 2, z - d / 2, x - w / 2, y - h / 2, z + d / 2); this.addLine(x + w / 2, y - h / 2, z - d / 2, x + w / 2, y - h / 2, z + d / 2); this.addLine(x + w / 2, y + h / 2, z - d / 2, x + w / 2, y + h / 2, z + d / 2); this.addLine(x - w / 2, y + h / 2, z - d / 2, x - w / 2, y + h / 2, z + d / 2); } function addRect(x, y, z, w, h) { this.addLine(x - w / 2, y - h / 2, z, x + w / 2, y - h / 2, z, x + w / 2, y + h / 2, z, x - w / 2, y + h / 2, z, x - w / 2, y - h / 2, z); } function addCircle(x, y, z, radius, segments) { var i, points = [], a; for(i = 0; i < segments; i += 1) { a = Math.PI * 2 * i / segments; points.push(x + Math.cos(a) * radius, y + Math.sin(a) * radius, z); } points.push(points[0], points[1], points[2]); this.addLine(points); } function draw() { var i, j, line, p2d; if(this.clearCanvas) { context.clearRect(0, 0, width, height); } for(i = 0; i < lines.length; i += 1) { context.beginPath(); line = lines[i]; p2d = project(line.points[0]); context.moveTo(p2d.x, p2d.y); for(j = 1; j < line.points.length; j += 1) { p2d = project(line.points[j]); context.lineTo(p2d.x, p2d.y); } context.lineWidth = line.width; context.strokeStyle = line.style; context.stroke(); } if(this.showCenter) { p2d = project({x:0, y:0, z:0}); context.strokeStyle = "#ff0000"; context.lineWidth = 0.5; context.beginPath(); context.arc(p2d.x, p2d.y, 5, 0, Math.PI * 2, false); context.stroke(); } } function loop(fps, callback) { if(!running) { var wl = this; running = true; loopCallback = callback; interval = setInterval(function() { loopCallback(); wl.draw(); }, 1000 / fps); } } function stop() { running = false; clearInterval(interval); } function rotateX(radians) { var i, j, p, y1, z1, line, cos = Math.cos(radians), sin = Math.sin(radians); for(i = 0; i < lines.length; i += 1) { line = lines[i]; for(j = 0; j < line.points.length; j += 1) { p = line.points[j]; y1 = p.y * cos - p.z * sin; z1 = p.z * cos + p.y * sin; p.y = y1; p.z = z1; } } } function rotateY(radians) { var i, j, p, x1, z1, line, cos = Math.cos(radians), sin = Math.sin(radians); for(i = 0; i < lines.length; i += 1) { line = lines[i]; for(j = 0; j < line.points.length; j += 1) { p = line.points[j]; z1 = p.z * cos - p.x * sin; x1 = p.x * cos + p.z * sin; p.x = x1; p.z = z1; } } } function rotateZ(radians) { var i, j, p, x1, y1, line, cos = Math.cos(radians), sin = Math.sin(radians); for(i = 0; i < lines.length; i += 1) { line = lines[i]; for(j = 0; j < line.points.length; j += 1) { p = line.points[j]; y1 = p.y * cos - p.x * sin; x1 = p.x * cos + p.y * sin; p.x = x1; p.y = y1; } } } function translate(x, y, z) { var i, j, p, line; for(i = 0; i < lines.length; i += 1) { line = lines[i]; for(j = 0; j < line.points.length; j += 1) { p = line.points[j]; p.x += x; p.y += y; p.z += z; } } } function jitter(amount) { var i, j, line; for(i = 0; i < lines.length; i += 1) { line = lines[i]; for(j = 0; j < line.points.length; j += 1) { p = line.points[j]; p.x += Math.random() * amount * 2 - amount; p.y += Math.random() * amount * 2 - amount; p.z += Math.random() * amount * 2 - amount; } } } function setCenter(x, y, z) { cx = x === null ? cx : x; cy = y === null ? cy : y; cz = z === null ? cz : z; } return {initWithCanvas:initWithCanvas, addLine:addLine, addBox:addBox, addRect:addRect, addCircle:addCircle, draw:draw, rotateX:rotateX, rotateY:rotateY, rotateZ:rotateZ, translate:translate, jitter:jitter, clearCanvas:true, strokeStyle:"#000000", lineWidth:1, loop:loop, stop:stop, showCenter:false, setCenter:setCenter }; }());
heliogabalo/The-side-of-the-source
Codigo/Games/Efects/3D-wirelib/wirelib.js
JavaScript
mpl-2.0
7,221
function listener(details) { let filter = browser.webRequest.filterResponseData(details.requestId); let decoder = new TextDecoder("utf-8"); let encoder = new TextEncoder(); filter.ondata = event => { let str = decoder.decode(event.data, {stream: true}); // Just change any instance of Example in the HTTP response // to WebExtension Example. str = str.replace(/Example/g, 'WebExtension Example'); filter.write(encoder.encode(str)); filter.disconnect(); } return {}; } browser.webRequest.onBeforeRequest.addListener( listener, {urls: ["https://example.com/*"], types: ["main_frame"]}, ["blocking"] );
mdn/webextensions-examples
http-response/background.js
JavaScript
mpl-2.0
667
/** * Created by slanska on 2016-12-30. */ ///<reference path="../typings/tsd.d.ts"/> import {TestService} from './helper'; describe('rolesManagement', () => { it('create a new role', (done) => { done(); }); it('delete non referenced role', (done) => { done(); }); it('cannot delete system role', (done) => { done(); }); it(`fetch all roles for the user, using user's own credentials`, (done) => { done(); }); it(`fetch all roles, using admin's roles`, (done) => { done(); }); it(`cannot fetch roles by non authorized user`, (done) => { done(); }); it(`cannot fetch roles by non authenticated client`, (done) => { done(); }); it('create domain specific role', (done) => { done(); }); it('delete domain specific role', (done) => { done(); }); });
slanska/nauth2
test/09_RoleManagement.ts
TypeScript
mpl-2.0
938
/** * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, you can obtain one at http://mozilla.org/MPL/2.0/. */ var caesar = require("./caesar"); exports["test encrypt/decrypt"] = function(assert) { /* verify decrypting the result of encryption yields the original response */ assert.strictEqual(caesar.decrypt(caesar.encrypt("flee at once", "errorscanocc"), "errorscanocc"), "flee at once", "fail if cannot decrypt encrypted text"); }; exports["test encrypt 0"] = function(assert) { /* !!!!! is equivalent to an offset of zero */ assert.strictEqual(caesar.encrypt("01234", "!!!!!"), "01234", "encrypt identity"); }; exports["test decrypt 0"] = function(assert) { /* !!!!! is equivalent to an offset of zero */ assert.strictEqual(caesar.decrypt("QRSTU", "!!!!!"), "QRSTU", "decrypt identity"); }; exports["test encrypt 3"] = function(assert) { /* $$$$$ is equivalent to an offset of three */ assert.strictEqual(caesar.encrypt("01234", "$$$$$"), "34567", "encrypt by 3"); }; exports["test decrypt 3"] = function(assert) { /* $$$$$ is equivalent to an offset of three */ assert.strictEqual(caesar.decrypt("34567", "$$$$$"), "01234", "decrypt by 3"); }; exports["test encrypt wrap"] = function(assert) { assert.strictEqual(caesar.encrypt("z", "$"), "#", "encrypt wrap"); }; exports["test decrypt wrap"] = function(assert) { assert.strictEqual(caesar.decrypt("#", "$"), "z", "decrypt wrap"); }; exports["test encrypt not a no-op"] = function(assert) { /* verify we cannot pass with a no op */ assert.notStrictEqual(caesar.encrypt("flee at once", "errors can o"), "flee at once", "fail if no-op"); }; require("sdk/test").run(exports);
jeffreystarr/plainsight-addon
test/test-caesar.js
JavaScript
mpl-2.0
1,791
package main import ( "context" "fmt" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/i18n/gi18n" ) func main() { var ( orderId = 865271654 orderAmount = 99.8 ) fmt.Println(g.I18n().Tf( gi18n.WithLanguage(context.TODO(), `en`), `{#OrderPaid}`, orderId, orderAmount, )) fmt.Println(g.I18n().Tf( gi18n.WithLanguage(context.TODO(), `zh-CN`), `{#OrderPaid}`, orderId, orderAmount, )) }
EngineQ/gf
.example/i18n/gi18n/gi18n.go
GO
mpl-2.0
417
#include <iostream> #include <cpplogger/cllogger.h> #include <ccsseqqueue.h> #include <cctest.h> #include <functional> #include <ffoption.h> using namespace std; int main(int argc, char** argv) { ff::CommandOption *ffop = ff::CommandOption::getInstance(); ffop->parseArgv(argc, argv); ffop->debugOption(); cc::SSeqQueue<int> squeue; squeue.init(); squeue.push(1); //cout <<FF_TO_SRTING(squeue)<<" size -> "<<squeue.count()<<endl; int x = 0; squeue.pop(x); cout <<"get x -> "<<x<<endl; //cout <<FF_TO_SRTING(squeue)<<" size -> "<<squeue.count()<<endl; #if __cplusplus >= 201103L cc::println(cc::splitString(string("1 2 4 dksja ida qwd www"), string("\\s+"))); #else cc::println(cc::splitString(string("1 2 4 dksja ida qwd www"))); #endif cout <<cc::trim(string(" ; "))<<endl; return 0; }
araraloren/FunctionFind
src/main.cpp
C++
mpl-2.0
874
package main import ( "fmt" "testing" ) var config ConfigFile = ConfigFile{} var strmCfg = StreamConfig{ "streamName", "name", "type", "url", "StreamApiKey", "RecordFormatString", nil, nil, } /* * Valid configuration - take timestamp as is */ func TestValidateEmtpySrcDest(t *testing.T) { var attrs = []Attribute{{"key", "timestamp", 16, "", ""}} strmCfg.RecordFormat = attrs config.Streams = []StreamConfig{strmCfg} err := config.validate() if err != nil { fmt.Println(err) t.Fail() } } /* * Valid configuration - valid timestamp formats */ func TestValidateCorrectSrcDest(t *testing.T) { var attrs = []Attribute{{"key", "timestamp", 16, "2006-01-02T15:04:05.999Z", "2006-01-02T15:04:05.999Z"}} strmCfg.RecordFormat = attrs config.Streams = []StreamConfig{strmCfg} err := config.validate() if err != nil { fmt.Println(err) t.Fail() } } /* * Valid configuration - slash formats to dash formats */ func TestValidateVariousDelimiterDate(t *testing.T) { var attrs = []Attribute{{"key", "timestamp", 16, "2006/01/02 15:04:05", "2006-01-02T15:04:05.999Z"}} strmCfg.RecordFormat = attrs config.Streams = []StreamConfig{strmCfg} err := config.validate() if err != nil { t.Fail() fmt.Println(err) } } /* * Invalid Config - valid source but no destination format */ func TestValidateNoDestinationFormat(t *testing.T) { var attrs = []Attribute{{"key", "timestamp", 16, "2006-01-02T15:04:05.999Z", ""}} strmCfg.RecordFormat = attrs config.Streams = []StreamConfig{strmCfg} err := config.validate() expected := "must specify Source & Destination Timestamp Format when datatype is Timestamp" if err.Error() != expected { t.Fail() } } /* * Invalid configuration - valid destination but no source format */ func TestValidateNoSourceFormat(t *testing.T) { var attrs = []Attribute{{"key", "timestamp", 16, "", "2006-01-02T15:04:05.999Z"}} strmCfg.RecordFormat = attrs config.Streams = []StreamConfig{strmCfg} err := config.validate() expected := "must specify Source Timestamp Format when datatype is Timestamp" if err.Error() != expected { t.Fail() fmt.Println(err) } } /* * Invalid configuration - invalid source format */ func TestValidateInvalidSource(t *testing.T) { var attrs = []Attribute{{"key", "timestamp", 16, "2006-01-02T15::05.999Z", "2006-01-02T15:04:05.999Z"}} strmCfg.RecordFormat = attrs config.Streams = []StreamConfig{strmCfg} err := config.validate() if err == nil { t.Fail() fmt.Println(err) } } /* * Invalid configuration - invalid destination format */ func TestValidateInvalidDestination(t *testing.T) { var attrs = []Attribute{{"key", "timestamp", 16, "2006-01-02T15:04:05.999Z", "2006-01-02T15::05.999Z"}} strmCfg.RecordFormat = attrs config.Streams = []StreamConfig{strmCfg} err := config.validate() if err == nil { t.Fail() fmt.Println(err) } } /* * Long source to short destination * Result - warns of a possible invalid format */ func TestValidateShortDestination(t *testing.T) { var attrs = []Attribute{{"key", "timestamp", 16, "2006-01-02T15:04:05.999Z", "2006-01-02"}} strmCfg.RecordFormat = attrs config.Streams = []StreamConfig{strmCfg} err := config.validate() if err != nil { t.Fail() fmt.Println(err) } } /* * Short Date to long date * Result - warns of a possible invalid format */ func TestValidateShortSource(t *testing.T) { var attrs = []Attribute{{"key", "timestamp", 16, "2006-01-02", "2006-01-02T15:04:05.999Z"}} strmCfg.RecordFormat = attrs config.Streams = []StreamConfig{strmCfg} err := config.validate() if err != nil { t.Fail() fmt.Println(err) } }
rem7/pushr
config_validate_timestamp_test.go
GO
mpl-2.0
3,623
<?php namespace Honeybee\Infrastructure\Migration; use Honeybee\Common\Error\RuntimeError; use Honeybee\Common\Util\PhpClassParser; use Honeybee\Common\Util\StringToolkit; use Honeybee\Infrastructure\Config\ConfigInterface; use Honeybee\ServiceLocatorInterface; use Symfony\Component\Finder\Finder; class FileSystemLoader implements MigrationLoaderInterface { protected $config; protected $service_locator; protected $file_finder; public function __construct( ConfigInterface $config, ServiceLocatorInterface $service_locator, Finder $file_finder = null ) { $this->config = $config; $this->service_locator = $service_locator; $this->file_finder= $file_finder?: new Finder; } /** * @return MigrationList */ public function loadMigrations() { $migration_dir = $this->config->get('directory'); if (!is_dir($migration_dir) || !is_readable($migration_dir)) { throw new RuntimeError(sprintf('Given migration path is not a readable directory: %s', $migration_dir)); } $migrations = []; $pattern = $this->config->get('pattern', '*.php'); $migration_files = $this->file_finder->create()->files()->name($pattern)->in($migration_dir)->sortByName(); foreach ($migration_files as $migration_file) { $class_parser = new PhpClassParser; $migration_class_info = $class_parser->parse((string)$migration_file); $migration_class = $migration_class_info->getFullyQualifiedClassName(); $migration_class_name = $migration_class_info->getClassName(); $class_format = $this->config->get('format', '#(?<version>\d{14}).(?<name>.+)$#'); if (!preg_match($class_format, $migration_class_name, $matches) || !isset($matches['name']) || !isset($matches['version']) ) { throw new RuntimeError('Invalid class name format for ' . $migration_class_name); } if (!class_exists($migration_class)) { require_once $migration_class_info->getFilePath(); } $migrations[] = $this->service_locator->make( $migration_class, [ ':state' => [ 'name' => StringToolkit::asSnakeCase($matches['name']), 'version' => $matches['version'] ] ] ); } return new MigrationList($migrations); } }
honeybee/honeybee
src/Infrastructure/Migration/FileSystemLoader.php
PHP
mpl-2.0
2,574
################################################################################ # THIS FILE IS 100% GENERATED BY ZPROJECT; DO NOT EDIT EXCEPT EXPERIMENTALLY # # Please refer to the README for information about making permanent changes. # ################################################################################ require 'ffi' require_relative 'ffi/version' module Zchannel module FFI extend ::FFI::Library def self.available? @available end begin lib_name = 'libzchannel' lib_paths = ['/usr/local/lib', '/opt/local/lib', '/usr/lib64'] .map { |path| "#{path}/#{lib_name}.#{::FFI::Platform::LIBSUFFIX}" } ffi_lib lib_paths + [lib_name] @available = true rescue LoadError warn "" warn "WARNING: ::Zchannel::FFI is not available without libzchannel." warn "" @available = false end if available? opts = { blocking: true # only necessary on MRI to deal with the GIL. } attach_function :zchanneler_new, [:string], :pointer, **opts attach_function :zchanneler_destroy, [:pointer], :void, **opts attach_function :zchanneler_send, [:pointer, :pointer, :int], :int, **opts attach_function :zchanneler_recv, [:pointer], :pointer, **opts attach_function :zchanneler_print, [:pointer], :void, **opts attach_function :zchanneler_test, [:bool], :void, **opts require_relative 'ffi/zchanneler' end end end ################################################################################ # THIS FILE IS 100% GENERATED BY ZPROJECT; DO NOT EDIT EXCEPT EXPERIMENTALLY # # Please refer to the README for information about making permanent changes. # ################################################################################
taotetek/zchannel
bindings/ruby/lib/zchannel/ffi.rb
Ruby
mpl-2.0
1,821
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package etomica.data.meter; import etomica.data.DataSourceScalar; import etomica.integrator.IntegratorMD; import etomica.units.Energy; /** * Acts as a DataSource to retrieve the energy from the integrator */ public class MeterKineticEnergyFromIntegrator extends DataSourceScalar { public MeterKineticEnergyFromIntegrator() { super("Kinetic Energy",Energy.DIMENSION); } public MeterKineticEnergyFromIntegrator(IntegratorMD aIntegrator) { this(); setIntegrator(aIntegrator); } public void setIntegrator(IntegratorMD newIntegrator) { integrator = newIntegrator; } public IntegratorMD getIntegrator() { return integrator; } public double getDataAsScalar() { return integrator.getKineticEnergy(); } private static final long serialVersionUID = 1L; private IntegratorMD integrator; }
ajschult/etomica
etomica-core/src/main/java/etomica/data/meter/MeterKineticEnergyFromIntegrator.java
Java
mpl-2.0
1,108
/** * The title screen. */ // SDK imports import ui.View; import ui.ImageView; import ui.TextView as TextView; import ui.widget.ButtonView as ButtonView; exports = Class(ui.ImageView, function (supr) { this.init = function (opts) { this._config = JSON.parse(CACHE['resources/conf/config.json']); opts = merge(opts, { x: 0, y: 0, width: this._config.screenWidth, height: this._config.screenHeight, image: "resources/images/bg1.jpg" }); supr(this, 'init', [opts]); this.build(); }; this.build = function() { var buttonWidth = 294; var buttonHeight = 61; var deviceWidth = this._config.screenWidth; var deviceHeight = this._config.screenHeight; var textview = new TextView({ superview: this, x: 0, y: 15, width: this._config.screenWidth, height: 50, text: "WeeBubble", autoSize: false, size: 38, verticalAlign: 'middle', horizontalAlign: 'center', wrap: false, color: '#000099' }); var buttonview = new ButtonView({ superview: this, width: buttonWidth, height: buttonHeight, x: (deviceWidth - buttonWidth) / 2, y: 3 * deviceHeight / 4, images: { down: "resources/images/start_button_selected.jpg", up: "resources/images/start_button_unselected.jpg" }, on: { down: bind(this, function () { }), up: bind(this, function () { this.emit('titlescreen:start'); }) } }); }; });
spil-peter-forgacs/weebubble
src/TitleScreen.js
JavaScript
mpl-2.0
1,827
package org.mozilla.mozstumbler; import android.net.Uri; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.widget.TextView; public class AboutActivity extends Activity { private static final String ABOUT_PAGE_URL = "https://location.services.mozilla.com/"; private static final String ABOUT_MAPBOX_URL = "https://www.mapbox.com/about/maps/"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); } @Override protected void onStart() { super.onStart(); TextView textView = (TextView) findViewById(R.id.about_version); String str = getResources().getString(R.string.about_version); str = String.format(str, PackageUtils.getAppVersion(this)); textView.setText(str); } public void onClick_ViewMore(View v) { Intent openAboutPage = new Intent(Intent.ACTION_VIEW, Uri.parse(ABOUT_PAGE_URL)); startActivity(openAboutPage); } public void onClick_ViewMapboxAttribution(View v) { Intent openMapboxPage = new Intent(Intent.ACTION_VIEW, Uri.parse(ABOUT_MAPBOX_URL)); startActivity(openMapboxPage); } @Override public boolean onCreateOptionsMenu(Menu menu) { return false; } }
5y/MozStumbler
src/org/mozilla/mozstumbler/AboutActivity.java
Java
mpl-2.0
1,423
#include "plastiqmethod.h" #include "plastiqqvboxlayout.h" #include "widgets/PlastiQQBoxLayout/plastiqqboxlayout.h" #include <QVBoxLayout> QHash<QByteArray, PlastiQMethod> PlastiQQVBoxLayout::plastiqConstructors = { { "QVBoxLayout()", { "QVBoxLayout", "", "QVBoxLayout*", 0, PlastiQMethod::Public, PlastiQMethod::Constructor } }, { "QVBoxLayout(QWidget*)", { "QVBoxLayout", "QWidget*", "QVBoxLayout*", 1, PlastiQMethod::Public, PlastiQMethod::Constructor } }, }; QHash<QByteArray, PlastiQMethod> PlastiQQVBoxLayout::plastiqMethods = { }; QHash<QByteArray, PlastiQMethod> PlastiQQVBoxLayout::plastiqSignals = { }; QHash<QByteArray, PlastiQProperty> PlastiQQVBoxLayout::plastiqProperties = { }; QHash<QByteArray, long> PlastiQQVBoxLayout::plastiqConstants = { }; QVector<PlastiQMetaObject*> PlastiQQVBoxLayout::plastiqInherits = { &PlastiQQBoxLayout::plastiq_static_metaObject }; const PlastiQ::ObjectType PlastiQQVBoxLayout::plastiq_static_objectType = PlastiQ::IsQObject; PlastiQMetaObject PlastiQQVBoxLayout::plastiq_static_metaObject = { { &PlastiQQBoxLayout::plastiq_static_metaObject, &plastiqInherits, "QVBoxLayout", &plastiq_static_objectType, &plastiqConstructors, &plastiqMethods, &plastiqSignals, &plastiqProperties, &plastiqConstants, plastiq_static_metacall } }; const PlastiQMetaObject *PlastiQQVBoxLayout::plastiq_metaObject() const { return &plastiq_static_metaObject; } void PlastiQQVBoxLayout::plastiq_static_metacall(PlastiQObject *object, PlastiQMetaObject::Call call, int id, const PMOGStack &stack) { if(call == PlastiQMetaObject::CreateInstance) { QVBoxLayout *o = Q_NULLPTR; switch(id) { case 0: o = new QVBoxLayout(); break; case 1: o = new QVBoxLayout(reinterpret_cast<QWidget*>(stack[1].s_voidp)); break; default: ; } /*%UPDATEWRAPPER%*/ PlastiQQVBoxLayout *p = new PlastiQQVBoxLayout(); p->plastiq_setData(reinterpret_cast<void*>(o), p); PlastiQObject *po = static_cast<PlastiQObject*>(p); *reinterpret_cast<PlastiQObject**>(stack[0].s_voidpp) = po; } else if(call == PlastiQMetaObject::CreateDataInstance) { PlastiQQVBoxLayout *p = new PlastiQQVBoxLayout(); p->plastiq_setData(stack[1].s_voidp, p); *reinterpret_cast<PlastiQObject**>(stack[0].s_voidpp) = p; } else if(call == PlastiQMetaObject::InvokeMethod || call == PlastiQMetaObject::InvokeStaticMember) { if(id >= 0) { id -= 0; PlastiQQBoxLayout::plastiq_static_metaObject.d.static_metacall(object, call, id, stack); return; } bool sc = call == PlastiQMetaObject::InvokeStaticMember; bool isWrapper = sc ? false : object->isWrapper(); QVBoxLayout *o = sc ? Q_NULLPTR : reinterpret_cast<QVBoxLayout*>(object->plastiq_data()); switch(id) { default: ; } } else if(call == PlastiQMetaObject::CreateConnection) { if(id >= 0) { id -= 0; PlastiQQBoxLayout::plastiq_static_metaObject.d.static_metacall(object, call, id, stack); return; } QVBoxLayout *o = reinterpret_cast<QVBoxLayout*>(object->plastiq_data()); PQObjectWrapper *sender = reinterpret_cast<PQObjectWrapper *>(stack[1].s_voidp); PQObjectWrapper *receiver = reinterpret_cast<PQObjectWrapper *>(stack[2].s_voidp); QByteArray slot = stack[3].s_bytearray; switch(id) { default: ; } } else if(call == PlastiQMetaObject::ToQObject) { QVBoxLayout *o = reinterpret_cast<QVBoxLayout*>(object->plastiq_data()); QObject *qo = qobject_cast<QObject*>(o); *reinterpret_cast<QObject**>(stack[0].s_voidpp) = qo; } else if(call == PlastiQMetaObject::HaveParent) { QVBoxLayout *o = reinterpret_cast<QVBoxLayout*>(object->plastiq_data()); stack[0].s_bool = o->parent() != Q_NULLPTR; } else if(call == PlastiQMetaObject::DownCast) { QByteArray className = stack[1].s_bytearray; QVBoxLayout *o = reinterpret_cast<QVBoxLayout*>(object->plastiq_data()); if(className == "QBoxLayout") { stack[0].s_voidp = static_cast<QBoxLayout*>(o); } else { stack[0].s_voidp = Q_NULLPTR; stack[0].name = "Q_NULLPTR"; } } } PlastiQQVBoxLayout::~PlastiQQVBoxLayout() { QVBoxLayout* o = reinterpret_cast<QVBoxLayout*>(plastiq_data()); if(o != Q_NULLPTR) { delete o; } o = Q_NULLPTR; plastiq_setData(Q_NULLPTR, Q_NULLPTR); }
ArtMares/PQStudio
Builder/plastiq/include/widgets/PlastiQQVBoxLayout/plastiqqvboxlayout.cpp
C++
mpl-2.0
4,622
package arm import ( "context" "github.com/hashicorp/packer-plugin-sdk/multistep" packersdk "github.com/hashicorp/packer-plugin-sdk/packer" "github.com/hashicorp/packer/builder/azure/common/constants" ) type StepSetCertificate struct { config *Config say func(message string) error func(e error) } func NewStepSetCertificate(config *Config, ui packersdk.Ui) *StepSetCertificate { var step = &StepSetCertificate{ config: config, say: func(message string) { ui.Say(message) }, error: func(e error) { ui.Error(e.Error()) }, } return step } func (s *StepSetCertificate) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { s.say("Setting the certificate's URL ...") var winRMCertificateUrl = state.Get(constants.ArmCertificateUrl).(string) s.config.tmpWinRMCertificateUrl = winRMCertificateUrl return multistep.ActionContinue } func (*StepSetCertificate) Cleanup(multistep.StateBag) { }
ricardclau/packer
builder/azure/arm/step_set_certificate.go
GO
mpl-2.0
941
#include "stdafx.h" #include "Map.h" #include "ShapeEditor.h" #include "EditorHelper.h" #include "MeasuringHelper.h" // ******************************************************* // OnSetCursor() // ******************************************************* BOOL CMapView::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) { HCURSOR NewCursor = NULL; if( nHitTest != HTCLIENT ) { COleControl::OnSetCursor( pWnd, nHitTest, message ); return TRUE; } bool hasGuiCursor = true; if (_copyrightLinkActive) { NewCursor = LoadCursor(NULL, IDC_HAND); } else { switch (_lastZooombarPart) { case ZoombarHandle: NewCursor = LoadCursor(NULL, IDC_SIZENS); break; case ZoombarMinus: case ZoombarPlus: case ZoombarBar: NewCursor = LoadCursor(NULL, IDC_HAND); break; default: hasGuiCursor = false; } } if (!hasGuiCursor) { NewCursor = GetCursorIcon(); if (!NewCursor) { m_mapCursor = crsrMapDefault; NewCursor = GetCursorIcon(); } } if (NewCursor != NULL) ::SetCursor( NewCursor ); else COleControl::OnSetCursor( pWnd, nHitTest, message ); return TRUE; } // ******************************************************* // GetCursorIcon() // ******************************************************* HCURSOR CMapView::GetCursorIcon() { HCURSOR newCursor = NULL; switch (m_mapCursor) { case crsrMapDefault: switch (m_cursorMode) { case cmZoomIn: newCursor = _reverseZooming ? _cursorZoomout : _cursorZoomin; break; case cmZoomOut: newCursor = _reverseZooming ? _cursorZoomin : _cursorZoomout; break; case cmPan: newCursor = (_useAlternatePanCursor == TRUE) ? _cursorAlternatePan : _cursorPan; break; case cmSelection: case cmSelectByPolygon: newCursor = _cursorSelect; break; case cmMeasure: newCursor = _cursorMeasure; break; case cmAddShape: newCursor = _cursorDigitize; break; case cmEditShape: newCursor = _cursorVertex; break; case cmIdentify: newCursor = _cursorIdentify; break; // don't look good enough /*case cmSelectByPolygon: NewCursor = _cursorSelect2; break; case cmRotateShapes: NewCursor = _cursorRotate; break; case cmMoveShapes: NewCursor = _cursorMove; break;*/ case cmNone: newCursor = (HCURSOR)m_uDCursorHandle; break; } break; case crsrAppStarting: newCursor = LoadCursor(NULL, IDC_APPSTARTING); break; case crsrArrow: newCursor = LoadCursor(NULL, IDC_ARROW); break; case crsrCross: newCursor = LoadCursor(NULL, IDC_CROSS); break; case crsrHelp: newCursor = LoadCursor(NULL, IDC_HELP); break; case crsrIBeam: newCursor = LoadCursor(NULL, IDC_IBEAM); break; case crsrNo: newCursor = LoadCursor(NULL, IDC_NO); break; case crsrSizeAll: newCursor = LoadCursor(NULL, IDC_SIZEALL); break; case crsrSizeNESW: newCursor = LoadCursor(NULL, IDC_SIZENESW); break; case crsrSizeNS: newCursor = LoadCursor(NULL, IDC_SIZENS); break; case crsrSizeNWSE: newCursor = LoadCursor(NULL, IDC_SIZENWSE); break; case crsrSizeWE: newCursor = LoadCursor(NULL, IDC_SIZEWE); break; case crsrUpArrow: newCursor = LoadCursor(NULL, IDC_UPARROW); break; case crsrHand: newCursor = LoadCursor(NULL, IDC_HAND); break; case crsrWait: if (!_disableWaitCursor) newCursor = LoadCursor(NULL, IDC_WAIT); break; case crsrUserDefined: newCursor = (HCURSOR)m_uDCursorHandle; break; } return newCursor; } // ******************************************************* // OnMapCursorChanged() // ******************************************************* void CMapView::OnMapCursorChanged() { OnSetCursor(this,0,0); } // ******************************************************* // GetCursorMode() // ******************************************************* tkCursorMode CMapView::GetCursorMode() { return (tkCursorMode)m_cursorMode; } // ******************************************************* // SetCursorMode() // ******************************************************* void CMapView::SetCursorMode(tkCursorMode mode) { UpdateCursor(mode, true); } // ******************************************************* // UpdateCursor() // ******************************************************* void CMapView::UpdateCursor(tkCursorMode newCursor, bool clearEditor) { if (newCursor == m_cursorMode) return; if (newCursor == cmRotateShapes) { if (!InitRotationTool()) return; } bool refreshNeeded = newCursor == cmRotateShapes || m_cursorMode == cmRotateShapes; if (MeasuringHelper::OnCursorChanged(_measuring, newCursor)) refreshNeeded = true; if (!EditorHelper::OnCursorChanged(_shapeEditor, clearEditor, newCursor, refreshNeeded)) return; m_cursorMode = newCursor; OnSetCursor(this, HTCLIENT, 0); if (refreshNeeded) RedrawCore(RedrawSkipDataLayers, true); } // ********************************************************* // SetWaitCursor() // ********************************************************* HCURSOR CMapView::SetWaitCursor() { if (_disableWaitCursor) return NULL; HCURSOR oldCursor = ::GetCursor(); CPoint cpos; GetCursorPos(&cpos); CRect wrect; GetWindowRect(&wrect); HWND wndActive = ::GetActiveWindow(); if ((wndActive == this->GetSafeHwnd()) || (wndActive == this->GetParentOwner()->GetSafeHwnd())) { if( wrect.PtInRect(cpos) && (m_mapCursor != crsrUserDefined) && !_disableWaitCursor) { ::SetCursor(LoadCursor(NULL, IDC_WAIT) ); } } return oldCursor; }
MapWindow/MapWinGIS
src/Control/Map_Cursors.cpp
C++
mpl-2.0
5,919
package openstack import ( "context" "fmt" imageservice "github.com/gophercloud/gophercloud/openstack/imageservice/v2/images" "github.com/hashicorp/packer-plugin-sdk/multistep" packersdk "github.com/hashicorp/packer-plugin-sdk/packer" ) type stepUpdateImageVisibility struct{} func (s *stepUpdateImageVisibility) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { ui := state.Get("ui").(packersdk.Ui) config := state.Get("config").(*Config) if config.SkipCreateImage { ui.Say("Skipping image update visibility...") return multistep.ActionContinue } imageId := state.Get("image").(string) if config.ImageVisibility == "" { return multistep.ActionContinue } imageClient, err := config.imageV2Client() if err != nil { err = fmt.Errorf("Error initializing image service client: %s", err) state.Put("error", err) return multistep.ActionHalt } ui.Say(fmt.Sprintf("Updating image visibility to %s", config.ImageVisibility)) r := imageservice.Update( imageClient, imageId, imageservice.UpdateOpts{ imageservice.UpdateVisibility{ Visibility: config.ImageVisibility, }, }, ) if _, err = r.Extract(); err != nil { err = fmt.Errorf("Error updating image visibility: %s", err) state.Put("error", err) return multistep.ActionHalt } return multistep.ActionContinue } func (s *stepUpdateImageVisibility) Cleanup(multistep.StateBag) { // No cleanup... }
ricardclau/packer
builder/openstack/step_update_image_visibility.go
GO
mpl-2.0
1,429
package common import ( "context" "fmt" "log" "github.com/hashicorp/packer-plugin-sdk/multistep" packersdk "github.com/hashicorp/packer-plugin-sdk/packer" ) // This step suppresses any messages that VMware product might show. type StepSuppressMessages struct{} func (s *StepSuppressMessages) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { driver := state.Get("driver").(Driver) ui := state.Get("ui").(packersdk.Ui) vmxPath := state.Get("vmx_path").(string) log.Println("Suppressing messages in VMX") if err := driver.SuppressMessages(vmxPath); err != nil { err := fmt.Errorf("Error suppressing messages: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } return multistep.ActionContinue } func (s *StepSuppressMessages) Cleanup(state multistep.StateBag) {}
ricardclau/packer
builder/vmware/common/step_suppress_messages.go
GO
mpl-2.0
846
package org.playorm.nio.test; import java.io.IOException; import java.nio.ByteBuffer; import java.util.logging.Logger; import javax.net.ssl.SSLEngine; import junit.framework.TestCase; import org.playorm.nio.api.deprecated.ChannelServiceFactory; import org.playorm.nio.api.libs.AsyncSSLEngine; import org.playorm.nio.api.libs.BufferHelper; import org.playorm.nio.api.libs.FactoryCreator; import org.playorm.nio.api.libs.SSLEngineFactory; import org.playorm.nio.api.libs.SSLListener; import org.playorm.nio.api.testutil.CloneByteBuffer; import org.playorm.nio.api.testutil.HandlerForTests; import org.playorm.nio.api.testutil.MockSSLEngineFactory; import biz.xsoftware.mock.CalledMethod; import biz.xsoftware.mock.MockObject; import biz.xsoftware.mock.MockObjectFactory; /** * Normally I would not separate out one class for testing, but when this * is integrated with the ChanMgr, testing becomes non-deterministic with * packets being separated and such. This allows more deterministic * testing to fully test AsynchSSLEngine. * * @author dean.hiller */ public class TestNewAsynchSSLEngine2 extends TestCase { private static final Logger log = Logger.getLogger(TestNewAsynchSSLEngine2.class.getName()); private BufferHelper helper = ChannelServiceFactory.bufferHelper(null); private MockObject serverList = MockObjectFactory.createMock(SSLListener.class); private MockObject clientList = MockObjectFactory.createMock(SSLListener.class); private AsyncSSLEngine serverEngine; private AsyncSSLEngine clientEngine; @Override protected void setUp() throws Exception { HandlerForTests.setupLogging(); serverList.setDefaultBehavior("packetEncrypted", new CloneByteBuffer()); clientList.setDefaultBehavior("packetEncrypted", new CloneByteBuffer()); SSLEngineFactory sslEngineFactory = new MockSSLEngineFactory(); FactoryCreator creator = FactoryCreator.createFactory(null); SSLEngine wrappedSvr = sslEngineFactory.createEngineForServerSocket(); serverEngine = creator.createSSLEngine("[serverAsynch] ", wrappedSvr, null); serverEngine.setListener((SSLListener)serverList); SSLEngine wrappedClient = sslEngineFactory.createEngineForSocket(); clientEngine = creator.createSSLEngine("[clientEngine] ", wrappedClient, null); clientEngine.setListener((SSLListener)clientList); } @Override protected void tearDown() throws Exception { if(!clientEngine.isClosed()) closeWithExpects(clientEngine, clientList); if(!serverEngine.isClosed()) closeWithExpects(serverEngine, serverList); HandlerForTests.checkForWarnings(); clientList.expect(MockObject.NONE); serverList.expect(MockObject.NONE); } private void closeWithExpects(AsyncSSLEngine engine, MockObject sslListener) throws IOException { TestNewAsynchSSLEngine.closeWithExpects(engine, sslListener); // engine.close(); // // String[] methodNames = new String[2]; // methodNames[0] = "packetEncrypted"; // methodNames[1] = "closed"; // sslListener.expect(methodNames); } /** * This tests the Runnable task being run in between packets such that it * should not cause packet feeds to create new Runnables, and can * run before all packets are in. */ public void testDelayedRunTask() throws Exception { log.fine("B*******************************************"); clientEngine.beginHandshake(); CalledMethod m = clientList.expect("packetEncrypted"); ByteBuffer b = (ByteBuffer)m.getAllParams()[0]; serverEngine.feedEncryptedPacket(b, null); m = serverList.expect("runTask"); Runnable r = (Runnable)m.getAllParams()[0]; r.run(); m = serverList.expect("packetEncrypted"); b = (ByteBuffer)m.getAllParams()[0]; clientEngine.feedEncryptedPacket(b, null); m = clientList.expect("runTask"); r = (Runnable)m.getAllParams()[0]; r.run(); String[] methodNames = new String[3]; methodNames[0] = "packetEncrypted"; methodNames[1] = "packetEncrypted"; methodNames[2] = "packetEncrypted"; CalledMethod[] methods = clientList.expect(methodNames); ByteBuffer b0 = (ByteBuffer)methods[0].getAllParams()[0]; serverEngine.feedEncryptedPacket(b0, null); ByteBuffer b1 = (ByteBuffer)methods[1].getAllParams()[0]; m = serverList.expect("runTask"); r = (Runnable)m.getAllParams()[0]; serverEngine.feedEncryptedPacket(b1, null); ByteBuffer b2 = (ByteBuffer)methods[2].getAllParams()[0]; //THIS IS THE DELAYED RUN TASK run after second feed of data to sslEngine... r.run(); serverEngine.feedEncryptedPacket(b2, null); String[] methodNames1 = new String[3]; methodNames1[0] = "packetEncrypted"; methodNames1[1] = "packetEncrypted"; methodNames1[2] = "encryptedLinkEstablished"; CalledMethod[] methods1 = serverList.expect(methodNames1); ByteBuffer b01 = (ByteBuffer)methods1[0].getAllParams()[0]; clientEngine.feedEncryptedPacket(b01, null); ByteBuffer b11 = (ByteBuffer)methods1[1].getAllParams()[0]; clientEngine.feedEncryptedPacket(b11, null); clientList.expect("encryptedLinkEstablished"); log.fine("E*******************************************"); } /** * This tests the situation where the Runnable must tell the engine * to reprocess the buffer itself. */ public void testReallyDelayedRunTask() throws Exception { log.fine("B*******************************************"); clientEngine.beginHandshake(); CalledMethod m = clientList.expect("packetEncrypted"); ByteBuffer b = (ByteBuffer)m.getAllParams()[0]; serverEngine.feedEncryptedPacket(b, null); m = serverList.expect("runTask"); Runnable r = (Runnable)m.getAllParams()[0]; r.run(); m = serverList.expect("packetEncrypted"); b = (ByteBuffer)m.getAllParams()[0]; clientEngine.feedEncryptedPacket(b, null); m = clientList.expect("runTask"); r = (Runnable)m.getAllParams()[0]; r.run(); String[] methodNames = new String[3]; methodNames[0] = "packetEncrypted"; methodNames[1] = "packetEncrypted"; methodNames[2] = "packetEncrypted"; CalledMethod[] methods = clientList.expect(methodNames); ByteBuffer b0 = (ByteBuffer)methods[0].getAllParams()[0]; serverEngine.feedEncryptedPacket(b0, null); ByteBuffer b1 = (ByteBuffer)methods[1].getAllParams()[0]; m = serverList.expect("runTask"); r = (Runnable)m.getAllParams()[0]; serverEngine.feedEncryptedPacket(b1, null); ByteBuffer b2 = (ByteBuffer)methods[2].getAllParams()[0]; serverEngine.feedEncryptedPacket(b2, null); String[] methodNames1 = new String[3]; //THIS IS THE REALLY DELAYED RUN TASK run after all 3 packets are fed //to ssl engine r.run(); methodNames1[0] = "packetEncrypted"; methodNames1[1] = "packetEncrypted"; methodNames1[2] = "encryptedLinkEstablished"; CalledMethod[] methods1 = serverList.expect(methodNames1); ByteBuffer b01 = (ByteBuffer)methods1[0].getAllParams()[0]; clientEngine.feedEncryptedPacket(b01, null); ByteBuffer b11 = (ByteBuffer)methods1[1].getAllParams()[0]; clientEngine.feedEncryptedPacket(b11, null); clientList.expect("encryptedLinkEstablished"); log.fine("E*******************************************"); } public void testHalfPackets() throws Exception { clientEngine.beginHandshake(); CalledMethod m = clientList.expect("packetEncrypted"); ByteBuffer b = (ByteBuffer)m.getAllParams()[0]; feedPacket(serverEngine, b); m = serverList.expect("runTask"); Runnable r = (Runnable)m.getAllParams()[0]; r.run(); m = serverList.expect("packetEncrypted"); b = (ByteBuffer)m.getAllParams()[0]; log.fine("remain1="+b.remaining()); feedPacket(clientEngine, b); m = clientList.expect("runTask"); r = (Runnable)m.getAllParams()[0]; r.run(); String[] methodNames = new String[3]; methodNames[0] = "packetEncrypted"; methodNames[1] = "packetEncrypted"; methodNames[2] = "packetEncrypted"; CalledMethod[] methods = clientList.expect(methodNames); ByteBuffer b0 = (ByteBuffer)methods[0].getAllParams()[0]; feedPacket(serverEngine, b0); m = serverList.expect("runTask"); r = (Runnable)m.getAllParams()[0]; r.run(); ByteBuffer b1 = (ByteBuffer)methods[1].getAllParams()[0]; feedPacket(serverEngine, b1); ByteBuffer b2 = (ByteBuffer)methods[2].getAllParams()[0]; feedPacket(serverEngine, b2); methodNames = new String[3]; methodNames[0] = "packetEncrypted"; methodNames[1] = "packetEncrypted"; methodNames[2] = "encryptedLinkEstablished"; methods = serverList.expect(methodNames); b0 = (ByteBuffer)methods[0].getAllParams()[0]; feedPacket(clientEngine, b0); b1 = (ByteBuffer)methods[1].getAllParams()[0]; feedPacket(clientEngine, b1); clientList.expect("encryptedLinkEstablished"); } public void testCombinedPackets() throws Exception { clientEngine.beginHandshake(); CalledMethod m; ByteBuffer b; CalledMethod m1 = clientList.expect("packetEncrypted"); ByteBuffer b3 = (ByteBuffer)m1.getAllParams()[0]; serverEngine.feedEncryptedPacket(b3, null); m = serverList.expect("runTask"); Runnable r = (Runnable)m.getAllParams()[0]; r.run(); m = serverList.expect("packetEncrypted"); b = (ByteBuffer)m.getAllParams()[0]; clientEngine.feedEncryptedPacket(b, null); m = clientList.expect("runTask"); r = (Runnable)m.getAllParams()[0]; r.run(); String[] methodNames = new String[3]; methodNames[0] = "packetEncrypted"; methodNames[1] = "packetEncrypted"; methodNames[2] = "packetEncrypted"; CalledMethod[] methods = clientList.expect(methodNames); ByteBuffer b0 = (ByteBuffer)methods[0].getAllParams()[0]; ByteBuffer b1 = (ByteBuffer)methods[1].getAllParams()[0]; ByteBuffer b2 = (ByteBuffer)methods[2].getAllParams()[0]; int total = b0.remaining()+b1.remaining()+b2.remaining(); ByteBuffer combined = ByteBuffer.allocate(total); combined.put(b0); combined.put(b1); combined.put(b2); helper.doneFillingBuffer(combined); serverEngine.feedEncryptedPacket(combined, null); m = serverList.expect("runTask"); r = (Runnable)m.getAllParams()[0]; r.run(); methodNames = new String[3]; methodNames[0] = "packetEncrypted"; methodNames[1] = "packetEncrypted"; methodNames[2] = "encryptedLinkEstablished"; methods = serverList.expect(methodNames); b0 = (ByteBuffer)methods[0].getAllParams()[0]; b1 = (ByteBuffer)methods[1].getAllParams()[0]; total = b0.remaining()+b1.remaining(); combined = ByteBuffer.allocate(total); combined.put(b0); combined.put(b1); helper.doneFillingBuffer(combined); clientEngine.feedEncryptedPacket(combined, null); clientList.expect("encryptedLinkEstablished"); } public void testOneAndHalfPackets() throws Exception { clientEngine.beginHandshake(); CalledMethod m = clientList.expect("packetEncrypted"); ByteBuffer b = (ByteBuffer)m.getAllParams()[0]; serverEngine.feedEncryptedPacket(b, null); m = serverList.expect("runTask"); Runnable r = (Runnable)m.getAllParams()[0]; r.run(); m = serverList.expect("packetEncrypted"); b = (ByteBuffer)m.getAllParams()[0]; clientEngine.feedEncryptedPacket(b, null); m = clientList.expect("runTask"); r = (Runnable)m.getAllParams()[0]; r.run(); String[] methodNames = new String[3]; methodNames[0] = "packetEncrypted"; methodNames[1] = "packetEncrypted"; methodNames[2] = "packetEncrypted"; CalledMethod[] methods = clientList.expect(methodNames); ByteBuffer b0 = (ByteBuffer)methods[0].getAllParams()[0]; ByteBuffer b1 = (ByteBuffer)methods[1].getAllParams()[0]; ByteBuffer b2 = (ByteBuffer)methods[2].getAllParams()[0]; int total = b0.remaining()+b1.remaining()+b2.remaining(); ByteBuffer combined = ByteBuffer.allocate(total); combined.put(b0); int lim = b1.limit(); b1.limit(3); //we only want to put part of b1 in payload combined.put(b1); helper.doneFillingBuffer(combined); serverEngine.feedEncryptedPacket(combined, null); combined.clear(); b1.limit(lim); combined.put(b1); combined.put(b2); helper.doneFillingBuffer(combined); serverEngine.feedEncryptedPacket(combined, null); m = serverList.expect("runTask"); r = (Runnable)m.getAllParams()[0]; r.run(); methodNames = new String[3]; methodNames[0] = "packetEncrypted"; methodNames[1] = "packetEncrypted"; methodNames[2] = "encryptedLinkEstablished"; methods = serverList.expect(methodNames); b0 = (ByteBuffer)methods[0].getAllParams()[0]; b1 = (ByteBuffer)methods[1].getAllParams()[0]; total = b0.remaining()+b1.remaining(); combined = ByteBuffer.allocate(total); combined.put(b0); combined.put(b1); helper.doneFillingBuffer(combined); clientEngine.feedEncryptedPacket(combined, null); clientList.expect("encryptedLinkEstablished"); } public void testRunInMiddleOfPacket() throws Exception { log.fine("B*******************************************"); clientEngine.beginHandshake(); CalledMethod m = clientList.expect("packetEncrypted"); ByteBuffer b = (ByteBuffer)m.getAllParams()[0]; serverEngine.feedEncryptedPacket(b, null); m = serverList.expect("runTask"); Runnable r = (Runnable)m.getAllParams()[0]; r.run(); m = serverList.expect("packetEncrypted"); b = (ByteBuffer)m.getAllParams()[0]; clientEngine.feedEncryptedPacket(b, null); m = clientList.expect("runTask"); r = (Runnable)m.getAllParams()[0]; r.run(); String[] methodNames = new String[3]; methodNames[0] = "packetEncrypted"; methodNames[1] = "packetEncrypted"; methodNames[2] = "packetEncrypted"; CalledMethod[] methods = clientList.expect(methodNames); ByteBuffer b0 = (ByteBuffer)methods[0].getAllParams()[0]; ByteBuffer b1 = (ByteBuffer)methods[1].getAllParams()[0]; ByteBuffer b2 = (ByteBuffer)methods[2].getAllParams()[0]; serverEngine.feedEncryptedPacket(b0, null); m = serverList.expect("runTask"); r = (Runnable)m.getAllParams()[0]; int total = b1.remaining()+b2.remaining(); ByteBuffer combined = ByteBuffer.allocate(total); int lim = b1.limit(); b1.limit(3); //we only want to put part of b1 in payload combined.put(b1); helper.doneFillingBuffer(combined); serverEngine.feedEncryptedPacket(combined, null); //run the task after some of the previous packet fed, then feed rest of packet r.run(); combined.clear(); b1.limit(lim); combined.put(b1); combined.put(b2); helper.doneFillingBuffer(combined); serverEngine.feedEncryptedPacket(combined, null); String[] methodNames1 = new String[3]; methodNames1[0] = "packetEncrypted"; methodNames1[1] = "packetEncrypted"; methodNames1[2] = "encryptedLinkEstablished"; CalledMethod[] methods1 = serverList.expect(methodNames1); b0 = (ByteBuffer)methods1[0].getAllParams()[0]; clientEngine.feedEncryptedPacket(b0, null); b1 = (ByteBuffer)methods1[1].getAllParams()[0]; clientEngine.feedEncryptedPacket(b1, null); clientList.expect("encryptedLinkEstablished"); } private void feedPacket(AsyncSSLEngine engine, ByteBuffer b) throws Exception { TestNewAsynchSSLEngine.feedPacket(engine, b); } }
deanhiller/channelmanager2
input/javasrc/org/playorm/nio/test/TestNewAsynchSSLEngine2.java
Java
mpl-2.0
15,075
/*此标记表明此文件可被设计器更新,如果不允许此操作,请删除此行代码.design by:agebull designer date:2019/4/10 10:44:52*/ #region using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Configuration; using System.Data; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Runtime.Serialization; using System.IO; using Newtonsoft.Json; using System.Data.Sql; using Agebull.Common; using Agebull.Common.OAuth; using Agebull.EntityModel.Common; using Agebull.EntityModel.SqlServer; using Agebull.EntityModel.BusinessLogic.SqlServer; using HPC.Projects.DataAccess; #endregion namespace HPC.Projects.BusinessLogic { /// <summary> /// 用户 /// </summary> public sealed partial class UserBusinessLogic : UiBusinessLogicBase<UserData,UserDataAccess,HpcSqlServerDb> { /*// <summary> /// 保存前的操作 /// </summary> /// <param name="data">数据</param> /// <param name="isAdd">是否为新增</param> /// <returns>如果为否将阻止后续操作</returns> protected override bool OnSaving(UserData data, bool isAdd) { return base.OnSaving(data, isAdd); } /// <summary> /// 保存完成后的操作 /// </summary> /// <param name="data">数据</param> /// <param name="isAdd">是否为新增</param> /// <returns>如果为否将阻止后续操作</returns> protected override bool OnSaved(UserData data, bool isAdd) { return base.OnSaved(data, isAdd); } /// <summary> /// 被用户编辑的数据的保存前操作 /// </summary> /// <param name="data">数据</param> /// <param name="isAdd">是否为新增</param> /// <returns>如果为否将阻止后续操作</returns> protected override bool LastSavedByUser(UserData data, bool isAdd) { return base.LastSavedByUser(data, isAdd); } /// <summary> /// 被用户编辑的数据的保存前操作 /// </summary> /// <param name="data">数据</param> /// <param name="isAdd">是否为新增</param> /// <returns>如果为否将阻止后续操作</returns> protected override bool PrepareSaveByUser(UserData data, bool isAdd) { return base.PrepareSaveByUser(data, isAdd); }*/ } }
agebullhu/AgebullDesigner
demo/src/HPC/HpcUser/Model/Business/User/UserBusinessLogic.cs
C#
mpl-2.0
2,573
package services.ntr.pms.model.history; import java.sql.Timestamp; import services.ntr.pms.service.information.Nameable; public class TransactionHistory implements Nameable{ private int transactionId; private int amount; private String type; private long payoutTime; private long payerAccountId; private String payerNickname; //This does not come from the SQL public int getTransactionId() { return transactionId; } public void setTransactionId(int transactionId) { this.transactionId = transactionId; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } public String getType() { return type; } public void setType(String type) { this.type = type; } public long getPayoutTime() { return payoutTime; } public void setPayoutTime(long payoutTime) { this.payoutTime = payoutTime; } public long getPayerAccountId() { return payerAccountId; } public void setPayerAccountId(long payerAccountId) { this.payerAccountId = payerAccountId; } public String getPayerNickname() { return payerNickname; } public void setPayerNickname(String payerNickname) { this.payerNickname = payerNickname; } /* Helper Methods------------------------------------------------- */ public void setPayoutTimeUsingTimestamp(Timestamp timestamp) { long time = timestamp.getTime(); long payoutTime = time; this.payoutTime = payoutTime; } //Used for Namable interface @Override public void setNickname(String nickname) { this.payerNickname = nickname; } @Override public String getNickname() { return this.payerNickname; } @Override public long getAccountId() { return this.payerAccountId; } @Override public String toString() { return "TransactionHistory [transactionId=" + transactionId + ", amount=" + amount + ", type=" + type + ", payoutTime=" + payoutTime + ", payerAccountId=" + payerAccountId + "]"; } }
NYPD/pms
src/services/ntr/pms/model/history/TransactionHistory.java
Java
mpl-2.0
1,929
class A(object): def something(self): return 3
caterinaurban/Typpete
typpete/unittests/inference/explicit_object_superclass.py
Python
mpl-2.0
58
/** * Input Field for JSON-schema type:object. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This Source Code includes react-jsonschema-form * released under the Apache License 2.0. * https://github.com/mozilla-services/react-jsonschema-form * Date on whitch referred: Thu, Mar 08, 2018 1:08:52 PM */ 'use strict'; const SchemaUtils = require('./schema-utils'); const SchemaField = require('./schema-field'); const Utils = require('../utils'); class ObjectField { constructor(schema, formData, idSchema, name, definitions, onChange, required = false, disabled = false, readOnly = false) { this.retrievedSchema = SchemaUtils.retrieveSchema(schema, definitions, formData); this.schema = schema; this.formData = formData; this.idSchema = idSchema; this.name = name; this.definitions = definitions; this.onChange = onChange; this.required = required; this.disabled = disabled; this.readOnly = readOnly; } isRequired(name) { return ( Array.isArray(this.retrievedSchema.required) && this.retrievedSchema.required.includes(name) ); } sortObject(obj) { const keys = Object.keys(obj).sort(); const map = {}; keys.forEach((key) => { let val = obj[key]; if (typeof val === 'object') { val = this.sortObject(val); } map[key] = val; }); return map; } isSameSchema(schema1, schema2) { const json1 = JSON.stringify(this.sortObject(schema1)); const json2 = JSON.stringify(this.sortObject(schema2)); return json1 === json2; } onPropertyChange(name, field) { return (value) => { const schema = this.schema; const newFormData = {}; newFormData[name] = value; this.formData = Object.assign(this.formData, newFormData); // modify part of form based on form data. if (schema.hasOwnProperty('dependencies')) { const newRetrievedSchema = SchemaUtils.retrieveSchema(schema, this.definitions, this.formData); if (!this.isSameSchema(this.retrievedSchema, newRetrievedSchema)) { this.retrievedSchema = newRetrievedSchema; this.formData = SchemaUtils.getDefaultFormState(newRetrievedSchema, this.formData, this.definitions); this.renderField(field); } } if (this.onChange) { this.onChange(this.formData); } }; } renderField(field) { const id = Utils.escapeHtmlForIdClass(this.idSchema.$id); const description = this.retrievedSchema.description; let title = this.retrievedSchema.title ? this.retrievedSchema.title : this.name; if (typeof title !== 'undefined' && title !== null) { title = Utils.escapeHtml(title); title = this.required ? title + SchemaUtils.REQUIRED_FIELD_SYMBOL : title; } field.innerHTML = (title ? `<legend id="${`${id}__title`}">${title}</legend>` : '') + (description ? `<p id="${id}__description" class="field-description"> ${Utils.escapeHtml(description)}</p>` : ''); // TODO support to specific properties order const orderedProperties = Object.keys(this.retrievedSchema.properties); orderedProperties.forEach((name) => { const childSchema = this.retrievedSchema.properties[name]; const childIdPrefix = `${this.idSchema.$id}_${name}`; const childData = this.formData[name]; const childIdSchema = SchemaUtils.toIdSchema( childSchema, childIdPrefix, this.definitions, childData ); const child = new SchemaField( childSchema, childData, childIdSchema, name, this.definitions, this.onPropertyChange(name, field), this.isRequired(name), childSchema.disabled, childSchema.readOnly).render(); field.appendChild(child); }); } render() { const field = document.createElement('fieldset'); this.renderField(field); return field; } } module.exports = ObjectField;
mozilla-iot/gateway
static/js/schema-form/object-field.js
JavaScript
mpl-2.0
4,632
require 'test_helper' class ApplicationSettingTest < ActiveSupport::TestCase teardown do ApplicationSetting.update_settings ApplicationSetting.defaults ApplicationSetting.apply! end describe "class methods" do describe "::update_settings" do it "should update only known params" do ApplicationSetting.update_settings({'foo' => "asdf"}) assert_nil ApplicationSetting['foo'] end it "should transform devise.expire_password_after to days when > 0" do ApplicationSetting.update_settings({'devise.expire_password_after' => 3}) assert_equal 3.days, ApplicationSetting['devise.expire_password_after'] end it "should set devise.expire_password_after to false when 0 is specified" do ApplicationSetting.update_settings({'devise.expire_password_after' => 0}) assert_equal false, ApplicationSetting['devise.expire_password_after'] end it "should transform devise.timeout_in to minutes when > 0" do ApplicationSetting.update_settings({'devise.timeout_in' => 3}) assert_equal 3.minutes, ApplicationSetting['devise.timeout_in'] end it "should set devise.timeout_in to nil when 0 is specified" do ApplicationSetting.update_settings({'devise.timeout_in' => 0}) assert_nil ApplicationSetting['devise.timeout_in'] end it "should not change unspecified settings" do ApplicationSetting['devise.timeout_in'] = 3 ApplicationSetting.update_settings({'devise.expire_password_after' => 3}) assert_equal 3, ApplicationSetting['devise.timeout_in'] end end describe "::apply!" do it "should apply all currently saved settings to the application" do Devise.maximum_attempts = 99 Devise.password_archiving_count = 99 Devise.expire_password_after = 99 Devise.timeout_in = 99 ApplicationSetting['devise.maximum_attempts'] = 1 ApplicationSetting['devise.password_archiving_count'] = 2 ApplicationSetting['devise.expire_password_after'] = 3 ApplicationSetting['devise.timeout_in'] = 4 ApplicationSetting.apply! assert_equal 1, Devise.maximum_attempts assert_equal 2, Devise.password_archiving_count assert_equal 3, Devise.expire_password_after assert_equal 4, Devise.timeout_in end end end end
rideconnection/clearinghouse
test/unit/application_setting_test.rb
Ruby
agpl-3.0
2,462
# -*- coding: utf-8 -*- # (c) 2015 Incaser Informatica S.L. - Sergio Teruel # (c) 2015 Incaser Informatica S.L. - Carlos Dauden # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from openerp import models, fields, api from openerp.tools.float_utils import float_round import decimal tipo_articulo = {'product': 'M', 'consu': 'M', 'service': 'I'} codigo_empresa = 1 class AccountInvoice(models.Model): _inherit = 'account.invoice' sagelc_export = fields.Boolean(string='Exported', default=False) sagelc_code = fields.Char(string='SageLC Code', size=15) def sanitize_arg(self, val): if isinstance(val, decimal.Decimal): return eval(str(val)) / 10000000000.0 else: return val @api.multi def export_records(self): if self[0].type == 'out_invoice': self.export_records_customer() else: self.export_records_supplier() @api.multi def export_records_customer(self): db_obj = self.env['base.external.dbsource'] db_sage = db_obj.search([('name', '=', 'Logic')]) for invoice in self: dic_equiv = {} sql = 'SELECT * FROM CabeceraAlbaranCliente WHERE 1=?' cab_cols = db_sage.execute(sql, (2), True)['cols'] sql = 'SELECT * FROM LineasAlbaranCliente WHERE 1=?' lin_cols = db_sage.execute(sql, (2), True)['cols'] sql = 'SELECT * FROM Clientes WHERE CodigoEmpresa=? AND CodigoCliente=?' clientes = db_sage.execute(sql, (codigo_empresa, invoice.partner_id.sagelc_customer_ref)) cli = clientes[0] for pos in range(len(cli)): col = cli.cursor_description[pos][0] if col in cab_cols: dic_equiv['[%s]' % col] = self.sanitize_arg(cli[pos]) sql = 'SELECT * FROM ClientesConta WHERE CodigoEmpresa=? AND CodigoCuenta=?' clientes_conta = db_sage.execute(sql, (codigo_empresa, cli.CodigoContable)) cli_conta = clientes_conta[0] for pos in range(len(cli_conta)): col = cli_conta.cursor_description[pos][0] if col in cab_cols: dic_equiv['[%s]' % col] = self.sanitize_arg(cli_conta[pos]) sql = 'SELECT * FROM ClientesProveedores WHERE SiglaNacion=? AND CifDni=?' clientes_prov = db_sage.execute(sql, (cli.SiglaNacion, cli.CifDni)) cli_prov = clientes_prov[0] for pos in range(len(cli_prov)): col = cli_prov.cursor_description[pos][0] if col in cab_cols: dic_equiv['[%s]' % col] = self.sanitize_arg(cli_prov[pos]) dic_man = { '[CodigoEmpresa]': codigo_empresa, '[EjercicioAlbaran]': invoice.date_invoice[:4], '[SerieAlbaran]': 'OD', '[NumeroAlbaran]': invoice.id, '[IdDelegacion]': 'CAS', '[CodigoCliente]': invoice.partner_id.sagelc_customer_ref, '[FechaAlbaran]': invoice.date_invoice, '[NumeroLineas]': len(invoice.invoice_line), } dic_equiv.update(dic_man) print(dic_equiv) key_list = dic_equiv.keys() params = '?,' * len(dic_equiv) params = params[:-1] sql = 'INSERT INTO CabeceraAlbaranCliente (%s) VALUES (%s)' % ( ', '.join(key_list), params) param_list = tuple([dic_equiv[key] for key in key_list]) db_sage.execute_void(sql, param_list) vals = {'sagelc_export': True} invoice.write(vals) for line in invoice.invoice_line: dic_equiv = { '[CodigoEmpresa]': codigo_empresa, '[EjercicioAlbaran]': invoice.date_invoice[:4], '[SerieAlbaran]': 'OD', '[NumeroAlbaran]': invoice.id, '[Orden]': line.sequence, '[FechaAlbaran]': invoice.date_invoice, '[CodigoArticulo]': line.product_id.sagelc_code, '[CodigoAlmacen]': '1', '[DescripcionArticulo]': line.product_id.name and line.product_id.name[:40] or '', '[DescripcionLinea]': line.name and line.name.replace('\n', '\r\n') or '', '[FactorConversion_]': 1, '[AcumulaEstadistica_]': -1, '[CodigoTransaccion]': 1, '[GrupoIva]': 1, '[CodigoIva]': 21, '[UnidadesServidas]': line.quantity, '[Unidades]': line.quantity, '[Unidades2_]': line.quantity, '[Precio]': line.price_unit, '[PrecioRebaje]': line.price_unit, '[PrecioCoste]': line.product_id.standard_price, '[%Descuento]': line.discount, '[%Iva]': 21, '[TipoArticulo]': tipo_articulo[line.product_id.type], } print(dic_equiv) key_list = dic_equiv.keys() params = '?,' * len(dic_equiv) params = params[:-1] sql = 'INSERT INTO LineasAlbaranCliente (%s) VALUES (%s)' % ( ', '.join(key_list), params) param_list = tuple([dic_equiv[key] for key in key_list]) db_sage.execute_void(sql, param_list) @api.multi def export_records_supplier(self): db_obj = self.env['base.external.dbsource'] db_sage = db_obj.search([('name', '=', 'Logic')]) codigo_empresa = 1 for invoice in self: dic_equiv = {} sql = 'SELECT * FROM CabeceraAlbaranProveedor WHERE 1=?' cab_cols = db_sage.execute(sql, (2), True)['cols'] sql = 'SELECT * FROM LineasAlbaranProveedor WHERE 1=?' lin_cols = db_sage.execute(sql, (2), True)['cols'] sql = 'SELECT * FROM Proveedores WHERE CodigoEmpresa=? AND CodigoProveedor=?' proveedores = db_sage.execute(sql, (codigo_empresa, invoice.partner_id.sagelc_supplier_ref)) prov = proveedores[0] for pos in range(len(prov)): col = prov.cursor_description[pos][0] if col in cab_cols: dic_equiv['[%s]' % col] = self.sanitize_arg(prov[pos]) sql = 'SELECT * FROM ClientesConta WHERE CodigoEmpresa=? AND CodigoCuenta=?' clientes_conta = db_sage.execute(sql, (codigo_empresa, prov.CodigoContable)) cli_conta = clientes_conta[0] for pos in range(len(cli_conta)): col = cli_conta.cursor_description[pos][0] if col in cab_cols: dic_equiv['[%s]' % col] = self.sanitize_arg(cli_conta[pos]) sql = 'SELECT * FROM ClientesProveedores WHERE SiglaNacion=? AND CifDni=?' clientes_prov = db_sage.execute(sql, (prov.SiglaNacion, prov.CifDni)) cli_prov = clientes_prov[0] for pos in range(len(cli_prov)): col = cli_prov.cursor_description[pos][0] if col in cab_cols: dic_equiv['[%s]' % col] = self.sanitize_arg(cli_prov[pos]) dic_man = { '[CodigoEmpresa]': codigo_empresa, '[EjercicioAlbaran]': invoice.date_invoice[:4], '[SerieAlbaran]': 'OD', '[NumeroAlbaran]': invoice.id, '[IdDelegacion]': 'CAS', '[CodigoProveedor]': invoice.partner_id.sagelc_supplier_ref, '[FechaAlbaran]': invoice.date_invoice, '[NumeroLineas]': len(invoice.invoice_line), } dic_equiv.update(dic_man) print(dic_equiv) key_list = dic_equiv.keys() params = '?,' * len(dic_equiv) params = params[:-1] sql = 'INSERT INTO CabeceraAlbaranProveedor (%s) VALUES (%s)' % (', '.join(key_list), params) param_list = tuple([dic_equiv[key] for key in key_list]) db_sage.execute_void(sql, param_list) vals = {'sagelc_export': True} invoice.write(vals) for line in invoice.invoice_line: dic_equiv = { '[CodigoEmpresa]': codigo_empresa, '[EjercicioAlbaran]': invoice.date_invoice[:4], '[SerieAlbaran]': 'OD', '[NumeroAlbaran]': invoice.id, '[Orden]': line.sequence, '[FechaAlbaran]': invoice.date_invoice, '[CodigoArticulo]': line.product_id.sagelc_code, '[CodigoAlmacen]': '1', '[DescripcionArticulo]': line.product_id.name, '[DescripcionLinea]': line.name and line.name.replace('\n', '\r\n') or '', '[FactorConversion_]': 1, '[AcumulaEstadistica_]': -1, '[CodigoTransaccion]': 1, '[GrupoIva]': 1, '[CodigoIva]': 21, '[UnidadesRecibidas]': line.quantity, '[Unidades]': line.quantity, '[Unidades2_]': line.quantity, '[Precio]': line.price_unit, '[PrecioRebaje]': line.price_unit, '[%Descuento]': line.discount, '[%Iva]': 21, '[TipoArticulo]': tipo_articulo[line.product_id.type], } print(dic_equiv) key_list = dic_equiv.keys() params = '?,' * len(dic_equiv) params = params[:-1] sql = 'INSERT INTO LineasAlbaranProveedor (%s) VALUES (%s)' % (', '.join(key_list), params) param_list = tuple([dic_equiv[key] for key in key_list]) db_sage.execute_void(sql, param_list)
incaser/incaser-odoo-addons
export_sagelc/models/account_invoice.py
Python
agpl-3.0
10,115
/** */ package com.euclideanspace.casl.editor; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Var Decl</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link com.euclideanspace.casl.editor.VarDecl#getVar <em>Var</em>}</li> * <li>{@link com.euclideanspace.casl.editor.VarDecl#getVar2 <em>Var2</em>}</li> * <li>{@link com.euclideanspace.casl.editor.VarDecl#getSort <em>Sort</em>}</li> * </ul> * </p> * * @see com.euclideanspace.casl.editor.EditorPackage#getVarDecl() * @model * @generated */ public interface VarDecl extends EObject { /** * Returns the value of the '<em><b>Var</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Var</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Var</em>' containment reference. * @see #setVar(Var) * @see com.euclideanspace.casl.editor.EditorPackage#getVarDecl_Var() * @model containment="true" * @generated */ Var getVar(); /** * Sets the value of the '{@link com.euclideanspace.casl.editor.VarDecl#getVar <em>Var</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Var</em>' containment reference. * @see #getVar() * @generated */ void setVar(Var value); /** * Returns the value of the '<em><b>Var2</b></em>' containment reference list. * The list contents are of type {@link com.euclideanspace.casl.editor.Var}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Var2</em>' containment reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Var2</em>' containment reference list. * @see com.euclideanspace.casl.editor.EditorPackage#getVarDecl_Var2() * @model containment="true" * @generated */ EList<Var> getVar2(); /** * Returns the value of the '<em><b>Sort</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Sort</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Sort</em>' containment reference. * @see #setSort(Sort) * @see com.euclideanspace.casl.editor.EditorPackage#getVarDecl_Sort() * @model containment="true" * @generated */ Sort getSort(); /** * Sets the value of the '{@link com.euclideanspace.casl.editor.VarDecl#getSort <em>Sort</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Sort</em>' containment reference. * @see #getSort() * @generated */ void setSort(Sort value); } // VarDecl
martinbaker/caslEdit
com.euclideanspace.casl/src-gen/com/euclideanspace/casl/editor/VarDecl.java
Java
agpl-3.0
3,054
/* This file is part of VoltDB. * Copyright (C) 2008-2018 VoltDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb.compiler; import java.io.IOException; import java.io.Reader; import org.voltdb.utils.InMemoryJarfile; /** * Abstract base for readers used during catalog compile or upgrade. */ public abstract class VoltCompilerReader extends Reader { public abstract String getName(); public abstract String getPath(); public abstract void putInJar(InMemoryJarfile jarFile, String name) throws IOException; }
simonzhangsm/voltdb
src/frontend/org/voltdb/compiler/VoltCompilerReader.java
Java
agpl-3.0
1,169
from .sources import TestSources __all__ = ["TestSources"]
kaini/newslist
server/newslist/tests/__init__.py
Python
agpl-3.0
60
/* All emon_widgets code is released under the GNU General Public License v3. See COPYRIGHT.txt and LICENSE.txt. Part of the OpenEnergyMonitor project: http://openenergymonitor.org Author: Trystan Lea: trystan.lea@googlemail.com If you have any questions please get in touch, try the forums here: http://openenergymonitor.org/emon/forum */ function vis_widgetlist(){ var widgets = { "realtime": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["feedid","colour","initzoom"], "optionstype":["feedid","colour_picker","dropbox"], "optionsname":[_Tr("Feed"),_Tr("Colour"),_Tr("Zoom")], "optionshint":[_Tr("Feed source"),_Tr("Line colour in hex. Blank is use default."),_Tr("Default visible window interval")], "optionsdata": [ , , [["1", "1 "+_Tr("minute")],["5", "5 "+_Tr("minutes")],["15", "15 "+_Tr("minutes")],["30", "30 "+_Tr("minutes")],["60", "1 "+ _Tr("hour")]] ], "html":"" }, "rawdata": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["feedid","colour","units","dp","scale","fill","initzoom"], "optionstype":["feedid","colour_picker","value","value","value","value","dropbox"], "optionsname":[_Tr("Feed"),_Tr("Colour"),_Tr("units"),_Tr("dp"),_Tr("scale"),_Tr("Fill"),_Tr("Zoom")], "optionshint":[_Tr("Feed source"),_Tr("Line colour in hex. Blank is use default."),_Tr("units"),_Tr("Decimal points"),_Tr("Scale by"),_Tr("Fill value"),_Tr("Default visible window interval")], "optionsdata": [ , , , , , , [["1", _Tr("Day")],["7", _Tr("Week")],["30", _Tr("Month")],["365", _Tr("Year")]] ], "html":"" }, "bargraph": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["feedid","colour","interval","units","dp","scale","delta"], "optionstype":["feedid","colour_picker","value","value","value","value","boolean"], "optionsname":[_Tr("Feed"),_Tr("Colour"),_Tr("Interval"),_Tr("units"),_Tr("dp"),_Tr("scale"),_Tr("delta")], "optionshint":[_Tr("Feed source"),_Tr("Line colour in hex. Blank is use default."),_Tr("Interval (seconds)-you can set \"d\" for day, \"m\" for month, or \"y\" for year"),_Tr("Units"),_Tr("Decimal points"),_Tr("Scale by"),_Tr("Show difference between each bar")], "html":"" }, "timestoredaily": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["feedid","units","initzoom"], "optionstype":["feedid","value","dropbox"], "optionsname":[_Tr("Feed"),_Tr("Units"),_Tr("Zoom")], "optionshint":[_Tr("Feed source"),_Tr("Units to show"),_Tr("Default visible window interval")], "optionsdata": [ , , [["1", _Tr("Day")],["7", _Tr("Week")],["30", _Tr("Month")],["365", _Tr("Year")]] ], "html":"" }, "zoom": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["power","kwhd","currency","currency_after_val","pricekwh","delta"], "optionstype":["feedid","feedid","value","value","value","boolean"], "optionsname":[_Tr("Power"),_Tr("kwhd"),_Tr("Currency"),_Tr("Currency position"),_Tr("Kwh price"),_Tr("delta")], "optionshint":[_Tr("Power to show"),_Tr("kwhd source"),_Tr("Currency to show"),_Tr("0 = before value, 1 = after value"),_Tr("Set kwh price"),_Tr("Show difference between each bar")], "html":"" }, "simplezoom": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["power","kwhd","delta"], "optionstype":["feedid","feedid","boolean"], "optionsname":[_Tr("Power"),_Tr("kwhd"),_Tr("delta")], "optionshint":[_Tr("Power to show"),_Tr("kwhd source"),_Tr("Show difference between each bar")], "html":"" }, "histgraph": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["feedid"], "optionstype":["feedid"], "optionsname":[_Tr("Feed")], "optionshint":[_Tr("Feed source")], "html":"" }, "threshold": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["feedid","thresholdA","thresholdB","initzoom"], "optionstype":["feedid","value","value","dropbox"], "optionsname":[_Tr("Feed"),_Tr("Threshold A"),_Tr("Threshold B"),_Tr("Zoom")], "optionshint":[_Tr("Feed source"),_Tr("Threshold A used"),_Tr("Threshold B used"),_Tr("Default visible window interval")], "optionsdata": [ , , , [["1", _Tr("Day")],["7", _Tr("Week")],["30", _Tr("Month")],["365", _Tr("Year")]] ], "html":"" }, "orderthreshold": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["feedid","power","thresholdA","thresholdB"], "optionstype":["feedid","feedid","value","value"], "optionsname":[_Tr("Feed"),_Tr("Power"),_Tr("Threshold A"),_Tr("Threshold B")], "optionshint":[_Tr("Feed source"),_Tr("Power"),_Tr("Threshold A used"),_Tr("Threshold B used")], "html":"" }, "orderbars": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["feedid","delta"], "optionstype":["feedid","boolean"], "optionsname":[_Tr("Feed"),_Tr("delta")], "optionshint":[_Tr("Feed source"),_Tr("Show difference between each bar")], "html":"" }, "stacked": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["bottom","top","colourt","colourb","delta"], "optionstype":["feedid","feedid","colour_picker","colour_picker","boolean"], "optionsname":[_Tr("Bottom"),_Tr("Top"),_Tr("Top colour"),_Tr("Bottom colour"),_Tr("delta")], "optionshint":[_Tr("Bottom feed value"),_Tr("Top feed value"),_Tr("Top colour"),_Tr("Bottom colour"),_Tr("Show difference between each bar")], "html":"" }, "stackedsolar": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["solar","consumption","delta"], "optionstype":["feedid","feedid","boolean"], "optionsname":[_Tr("Solar"),_Tr("Consumption"),_Tr("delta")], "optionshint":[_Tr("Solar feed value"),_Tr("Consumption feed value"),_Tr("Show difference between each bar")], "html":"" }, "smoothie": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["feedid","ufac"], "optionstype":["feedid","value"], "optionsname":[_Tr("Feed"),_Tr("Ufac")], "optionshint":[_Tr("Feed source"),_Tr("Ufac value")], "html":"" }, "multigraph": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["mid"], "optionstype":["dropbox"], "optionsname":[_Tr("Multigraph")], "optionshint":[_Tr("Managed on Visualization module")], "optionsdata":[multigraphsDropBoxOptions], // Gets multigraphs from vis_widget.php multigraphsDropBoxOptions variable "html":"" }, "timecompare": { "offsetx":0,"offsety":0,"width":400,"height":300, "menu":"Visualisations", "options":["feedid","fill","depth","npoints","initzoom"], "optionstype":["feedid","value","value","value","dropbox"], "optionsname":[_Tr("Feed"),_Tr("Fill"),_Tr("Depth"),_Tr("Data points"),_Tr("Zoom")], "optionshint":[_Tr("Feed source"),_Tr("Fill under line"),_Tr("Number of lines"),_Tr("Default: 800"),_Tr("Default visible window interval")], "optionsdata": [ , , , , [["8", "8 " + _Tr("Hours")],["24", _Tr("Day")],["168", _Tr("Week")],["672", _Tr("Month")],["8760", _Tr("Year")]] ], "html":"" } } return widgets; } function vis_init(){ vis_draw(); } function vis_draw(){ var vislist = vis_widgetlist(); var visclasslist = ''; for (z in vislist) { visclasslist += '.'+z+','; } visclasslist = visclasslist.slice(0, -1); $(visclasslist).each(function(){ var id = $(this).attr("id"); var feed = $(this).attr("feed") || 0; var width = $(this).width(); var height = $(this).height(); var apikey_string = ""; if (apikey) apikey_string = "&apikey="+apikey; if (!$(this).html() || reloadiframe==id || reloadiframe==-1 || apikey){ var attrstring = ""; var target = $(this).get(0); var l = target.attributes.length; for (var i=0; i<l; i++){ var attr = target.attributes[i].name; if (attr!="id" && attr!="class" && attr!="style"){ attrstring += "&"+attr+"="+target.attributes[i].value; } } pathfix=path.substr(path.indexOf('://')+3); // remove protocol pathfix=pathfix.substr(pathfix.indexOf('/')); // remove hostname $(this).html('<iframe frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="'+pathfix+'vis/'+$(this).attr("class")+'?embed=1'+attrstring+apikey_string+'"></iframe>'); console.log('--> new relative url for iframe of '+ $(this).attr("class") + ': '+pathfix+'vis/'+$(this).attr("class")+'?embed=1'+attrstring+apikey_string); } var iframe = $(this).children('iframe'); iframe.width(width); iframe.height(height); }); reloadiframe = 0; } function vis_slowupdate() {} function vis_fastupdate() {}
thaipowertech/emoncms
Modules/vis/widget/vis_render.js
JavaScript
agpl-3.0
9,506
<?php /* * @author Anakeen * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License * @package FDL */ /** * Modify family preferences * * @author Anakeen 2007 * @version $Id: generic_modprefs.php,v 1.2 2007/05/04 16:11:40 eric Exp $ * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License * @package FDL * @subpackage */ /** */ include_once ("FDL/Class.Doc.php"); include_once ("GENERIC/generic_util.php"); function generic_modprefs(&$action) { $famid = GetHttpVars("famid"); // family id $dirid = GetHttpVars("dirid"); // last searched $dispo = GetHttpVars("dispo"); // last searched $letters = GetHttpVars("letters"); // want tab letters $inherit = GetHttpVars("inherit"); // search in inherit $dbaccess = $action->getParam("FREEDOM_DB"); $fdoc = new_doc($dbaccess, $famid); if (!$fdoc->isAlive()) { $action->exitError(sprintf(_("Family (#%s) not exists") , $famid)); } switch ($dispo) { case 1: $split = 'V'; $visu = 'abstract'; break; case 2: $split = 'H'; $visu = 'column'; break; case 3: $split = 'V'; $visu = 'column'; break; case 4: $split = 'H'; $visu = 'abstract'; break; } if ($dispo > 0) { setSplitMode($action, $famid, $split); setViewMode($action, $famid, $visu); } if ($letters == 1) setTabLetter($action, $famid, 'Y'); else setTabLetter($action, $famid, 'N'); if ($inherit == 1) setInherit($action, $famid, 'Y'); else setInherit($action, $famid, 'N'); $action->lay->set("famtitle", $fdoc->title); $action->lay->set("famid", $famid); $action->lay->set("dirid", $dirid); redirect($action, "GENERIC", "GENERIC_TAB&tab=0&dirid=$dirid&famid=$famid", $action->GetParam("CORE_STANDURL")); } ?>
Eric-Brison/dynacase-core
Action/Generic/generic_modprefs.php
PHP
agpl-3.0
2,008
/** * Copyright (C) 2001-2020 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.example; import java.util.Iterator; /** * Iterates over either only the regular attribute, only the special attributes, or over all all * attributes. * * @author Ingo Mierswa */ public class AttributeIterator implements Iterator<Attribute> { private Iterator<AttributeRole> parent; private int type = Attributes.REGULAR; private Attribute current = null; private boolean hasNextInvoked = false; private AttributeRole currentRole = null; public AttributeIterator(Iterator<AttributeRole> parent, int type) { this.parent = parent; this.type = type; } @Override public boolean hasNext() { this.hasNextInvoked = true; if (!parent.hasNext() && currentRole == null) { current = null; return false; } else { AttributeRole role; if (currentRole == null) { role = parent.next(); } else { role = currentRole; } switch (type) { case Attributes.REGULAR: if (!role.isSpecial()) { current = role.getAttribute(); currentRole = role; return true; } else { return hasNext(); } case Attributes.SPECIAL: if (role.isSpecial()) { current = role.getAttribute(); currentRole = role; return true; } else { return hasNext(); } case Attributes.ALL: current = role.getAttribute(); currentRole = role; return true; default: current = null; return false; } } } @Override public Attribute next() { if (!this.hasNextInvoked) { hasNext(); } this.hasNextInvoked = false; this.currentRole = null; return current; } @Override public void remove() { parent.remove(); this.currentRole = null; this.hasNextInvoked = false; } }
rapidminer/rapidminer-studio
src/main/java/com/rapidminer/example/AttributeIterator.java
Java
agpl-3.0
2,654
/* * Copyright (C) 2000 - 2021 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "https://www.silverpeas.org/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.silverpeas.core.contribution.attachment.util; import org.silverpeas.core.admin.component.model.SilverpeasComponent; import org.silverpeas.core.util.ResourceLocator; import org.silverpeas.core.util.SettingBundle; import org.silverpeas.core.util.StringUtil; import java.util.Optional; import java.util.stream.Stream; /** * Handled the settings around the attachments. * @author Yohann Chastagnier */ public class AttachmentSettings { public static final int DEFAULT_REORDER_START = 1; public static final int YOUNGEST_TO_OLDEST_MANUAL_REORDER_START = 200000; public static final int YOUNGEST_TO_OLDEST_MANUAL_REORDER_THRESHOLD = 100000; private static SettingBundle settings = ResourceLocator.getSettingBundle("org.silverpeas.util.attachment.Attachment"); private AttachmentSettings() { throw new IllegalStateException("Utility class"); } /** * Gets the delay in percent after which an alert MUST be sent to the owner in order to remind * it to release the reserved file. * @return an integer representing a percentage, -1 means no value. */ public static int getDelayInPercentAfterWhichReservedFileAlertMustBeSent() { return settings.getInteger("DelayReservedFile", -1); } /** * Indicates the order the methods in charge of returning list of documents must apply. * @return false to list from oldest to youngest, true to list from the youngest to the oldest. */ public static boolean listFromYoungestToOldestAdd() { final int order = settings.getInteger("attachment.list.order", 1); return order < 0; } /** * Indicates if metadata of a file, if any, can be used to fill data (title & description) of an * attachment. (defined in properties by attachment.data.fromMetadata) * @return true if they must be used, false otherwise. */ public static boolean isUseFileMetadataForAttachmentDataEnabled() { return settings.getBoolean("attachment.data.fromMetadata", false); } /** * Gets the stream of component name for which the the displaying as content is enabled. * @return {@link Stream} of component name as {@link String}. */ public static Stream<String> displayableAsContentComponentNames() { return Stream .of(settings.getString("attachmentsAsContent.component.names", StringUtil.EMPTY).split("[ ,;]")) .map(String::trim); } /** * Gets the default value of the JCR flag which indicates if a document is displayable as content. * @return true of displayable as content, false otherwise. */ public static boolean defaultValueOfDisplayableAsContentBehavior() { return settings.getBoolean("attachmentsAsContent.default.value", true); } /** * Indicates if the displaying as content is enabled for a component instance represented by * the given identifier. * @param componentInstanceId identifier of a component instance. * @return true if activated, false otherwise. */ public static boolean isDisplayableAsContentForComponentInstanceId( final String componentInstanceId) { return displayableAsContentComponentNames() .map(c -> { final Optional<SilverpeasComponent> component = SilverpeasComponent.getByInstanceId(componentInstanceId); return component.isPresent() && component.get().getName().equalsIgnoreCase(c.trim()); }) .filter(b -> b) .findFirst() .orElse(false); } /** * Gets the default value of the JCR flag which indicates if a document is editable simultaneously. * @return true if editable simultaneously, false otherwise. */ public static boolean defaultValueOfEditableSimultaneously() { return settings.getBoolean("attachment.onlineEditing.simultaneously.default", true); } }
SilverDav/Silverpeas-Core
core-library/src/main/java/org/silverpeas/core/contribution/attachment/util/AttachmentSettings.java
Java
agpl-3.0
4,900
class CreateAddressGroups < ActiveRecord::Migration def change create_table :address_groups do |t| t.string :name t.timestamps end end end
camsys/ridepilot
db/migrate/20170625200226_create_address_groups.rb
Ruby
agpl-3.0
164
/*////////////////////////////////////////////////////////////////// //// SKIRT -- an advanced radiative transfer code //// //// © Astronomical Observatory, Ghent University //// ///////////////////////////////////////////////////////////////// */ #include <cmath> #include "BrokenExpDiskGeometry.hpp" #include "FatalError.hpp" #include "Random.hpp" #include "NR.hpp" #include "SpecialFunctions.hpp" #include "Units.hpp" using namespace std; //////////////////////////////////////////////////////////////////// BrokenExpDiskGeometry::BrokenExpDiskGeometry() : _hinn(0), _hout(0), _hz(0), _Rb(0), _s(0), _beta(0), _rho0(0), _SigmaR(0), _Rv(0), _Xv(0) { } //////////////////////////////////////////////////////////////////// void BrokenExpDiskGeometry::setupSelfBefore() { SepAxGeometry::setupSelfBefore(); // verify property values if (_hinn <= 0) throw FATALERROR("The inner scale length should be positive"); if (_hout <= 0) throw FATALERROR("The outer scale length should be positive"); if (_hz <= 0) throw FATALERROR("The axial scale height should be positive"); if (_Rb <= 0) throw FATALERROR("The break radius should be positive"); if (_s <= 0) throw FATALERROR("The sharpness should be positive"); _beta = 1.0/_s*(_hout/_hinn-1.0); // create a radial array with the cumulative mass distribution. Use Ninn points in the // range between 0 and _Rb, and Nout points between _Rb and the outermost radius, // which we choose to be _Rb + 10*_hout. int Ninn = 200; int Nout = 400; int N = Ninn+Nout; _Rv.resize(N+1); _Xv.resize(N+1); double dRinn = _Rb/Ninn; for (int i=0; i<Ninn; i++) _Rv[i] = i*dRinn; double dRout = 10*_hout/Nout; for (int i=Ninn; i<=N; i++) _Rv[i] = _Rb + (i-Ninn)*dRout; _Xv[0] = 0.0; double intprev = 0.0; for (int i=1; i<=N; i++) { double RL = _Rv[i-1]; double RR = _Rv[i]; double intL = intprev; double intR = radialdensity(RR)*RR; intprev = intR; _Xv[i] = _Xv[i-1] + 0.5*(RR-RL)*(intL+intR); } double IR = _Xv[N-1]; _Xv /= IR; // calculate _rho0; _rho0 = 1.0/4.0/M_PI/_hz/IR; // calculate the radial surface density intprev = 0.0; double sum = 0.0; for (int i=1; i<=N; i++) { double RL = _Rv[i-1]; double RR = _Rv[i]; double intL = intprev; double intR = radialdensity(RR); intprev = intR; sum += 0.5*(RR-RL)*(intL+intR); } _SigmaR = sum*_rho0; } //////////////////////////////////////////////////////////////////// void BrokenExpDiskGeometry::setRadialScaleInner(double value) { _hinn = value; } //////////////////////////////////////////////////////////////////// double BrokenExpDiskGeometry::radialScaleInner() const { return _hinn; } //////////////////////////////////////////////////////////////////// void BrokenExpDiskGeometry::setRadialScaleOuter(double value) { _hout = value; } //////////////////////////////////////////////////////////////////// double BrokenExpDiskGeometry::radialScaleOuter() const { return _hout; } //////////////////////////////////////////////////////////////////// void BrokenExpDiskGeometry::setAxialScale(double value) { _hz = value; } //////////////////////////////////////////////////////////////////// double BrokenExpDiskGeometry::axialScale() const { return _hz; } //////////////////////////////////////////////////////////////////// void BrokenExpDiskGeometry::setBreakRadius(double value) { _Rb = value; } //////////////////////////////////////////////////////////////////// double BrokenExpDiskGeometry::breakRadius() const { return _Rb; } //////////////////////////////////////////////////////////////////// void BrokenExpDiskGeometry::setSharpness(double value) { _s = value; } //////////////////////////////////////////////////////////////////// double BrokenExpDiskGeometry::sharpness() const { return _s; } //////////////////////////////////////////////////////////////////// double BrokenExpDiskGeometry::radialdensity(double R) const { return exp(-R/_hinn) * pow( 1.0+exp(_s*(R-_Rb)/_hout) , _beta); } //////////////////////////////////////////////////////////////////// double BrokenExpDiskGeometry::density(double R, double z) const { return _rho0 * exp(-abs(z)/_hz) * radialdensity(R); } //////////////////////////////////////////////////////////////////// double BrokenExpDiskGeometry::randomR() const { return _random->cdf(_Rv,_Xv); } //////////////////////////////////////////////////////////////////// double BrokenExpDiskGeometry::randomz() const { double z, XX; XX = _random->uniform(); z = (XX<=0.5) ? _hz*log(2.0*XX) : -_hz*log(2.0*(1.0-XX)); return z; } ////////////////////////////////////////////////////////////////////// double BrokenExpDiskGeometry::SigmaR() const { return _SigmaR; } ////////////////////////////////////////////////////////////////////// double BrokenExpDiskGeometry::SigmaZ() const { return 2.0 * _rho0 * _hz * radialdensity(0.0); } //////////////////////////////////////////////////////////////////////
SKIRT/SKIRT
SKIRTcore/BrokenExpDiskGeometry.cpp
C++
agpl-3.0
5,220
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2017 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.krad.datadictionary.validation.constraint; import java.io.Serializable; import java.util.List; /** * This class is a direct copy of one that was in Kuali Student. Look up constraints are currently not implemented. * * @since 1.1 */ public class CommonLookup implements Serializable { private static final long serialVersionUID = 1L; private String id; // unique ID of this lookup private String name; // name of this search private String desc; private String searchTypeId; private String resultReturnKey; private String searchParamIdKey; private List<CommonLookupParam> params; public String getSearchTypeId() { return searchTypeId; } public void setSearchTypeId(String searchTypeId) { this.searchTypeId = searchTypeId; } public String getResultReturnKey() { return resultReturnKey; } public void setResultReturnKey(String resultReturnKey) { this.resultReturnKey = resultReturnKey; } public List<CommonLookupParam> getParams() { return params; } public void setParams(List<CommonLookupParam> params) { this.params = params; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getSearchParamIdKey() { return searchParamIdKey; } public void setSearchParamIdKey(String searchParamIdKey) { this.searchParamIdKey = searchParamIdKey; } }
quikkian-ua-devops/will-financials
kfs-kns/src/main/java/org/kuali/kfs/krad/datadictionary/validation/constraint/CommonLookup.java
Java
agpl-3.0
2,587
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2017 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.module.purap.fixture; import org.apache.commons.lang.StringUtils; import org.kuali.kfs.module.purap.businessobject.PurApAccountingLine; import org.kuali.kfs.module.purap.businessobject.PurApItem; import org.kuali.kfs.module.purap.businessobject.RequisitionAccount; import org.kuali.kfs.module.purap.businessobject.RequisitionItem; import org.kuali.kfs.sys.fixture.AccountingLineFixture; import org.kuali.rice.core.api.util.type.KualiDecimal; public enum RequisitionAccountingLineFixture { BASIC_REQ_ACCOUNT_1(PurApAccountingLineFixture.BASIC_ACCOUNT_1, // PurApAccountingLineFixture AccountingLineFixture.PURAP_LINE3 // AccountingLineFixture ), BASIC_REQ_ACCOUNT_2(PurApAccountingLineFixture.BASIC_ACCOUNT_1, // PurApAccountingLineFixture AccountingLineFixture.PURAP_LINE1 // AccountingLineFixture ), PERFORMANCE_ACCOUNT(PurApAccountingLineFixture.BASIC_ACCOUNT_1, // PurApAccountingLineFixture AccountingLineFixture.PURAP_PERFORMANCE_LINE // AccountingLineFixture ), APO_REQ_ACCOUNT_1(PurApAccountingLineFixture.BASIC_ACCOUNT_1, // PurApAccountingLineFixture AccountingLineFixture.APO_LINE1 // AccountingLineFixture ), APO_REQ_ACCOUNT_2(PurApAccountingLineFixture.ACCOUNT_50_PERCENT, // PurApAccountingLineFixture AccountingLineFixture.APO_LINE2 // AccountingLineFixture ), APO_REQ_ACCOUNT_3(PurApAccountingLineFixture.ACCOUNT_50_PERCENT, // PurApAccountingLineFixture AccountingLineFixture.APO_LINE3 // AccountingLineFixture ), APO_REQ_ACCOUNT_4(PurApAccountingLineFixture.BASIC_ACCOUNT_1, // PurApAccountingLineFixture AccountingLineFixture.APO_LINE4 // AccountingLineFixture ), REQ_ACCOUNT_NEGATIVE_AMOUNT(PurApAccountingLineFixture.BASIC_ACCOUNT_1, // PurApAccountingLineFixture AccountingLineFixture.PURAP_LINE_NEGATIVE_AMT // AccountingLineFixture ), REQ_ACCOUNT_MULTI_QUANTITY(PurApAccountingLineFixture.REQ_ACCOUNT_MULTI, // PurApAccountingLineFixture AccountingLineFixture.REQ_ACCOUNT_MULTI_QUANTITY // AccountingLineFixture ), REQ_ACCOUNT_MULTI_NON_QUANTITY(PurApAccountingLineFixture.REQ_ACCOUNT_MULTI, // PurApAccountingLineFixture AccountingLineFixture.REQ_ACCOUNT_MULTI_NON_QUANTITY // AccountingLineFixture ), APO_ACCOUNT_VALID_CAPITAL_ASSET_OBJECT_CODE(PurApAccountingLineFixture.BASIC_ACCOUNT_1, // PurApAccountingLineFixture AccountingLineFixture.APO_LINE2, // AccountingLineFixture "7001" // objectCode ), APO_ACCOUNT_VALID_CAPITAL_ASSET_OBJECT_CODE_50_PERCENT(PurApAccountingLineFixture.ACCOUNT_50_PERCENT, //PurApAccountingLineFixture AccountingLineFixture.APO_LINE4, // AccountingLineFixture "7001" // objectCode ), APO_ACCOUNT_VALID_EXPENSE_OBJECT_CODE_50_PERCENT(PurApAccountingLineFixture.ACCOUNT_50_PERCENT, //PurApAccountingLineFixture AccountingLineFixture.APO_LINE4, // AccountingLineFixture "5000" // objectCode ),; private PurApAccountingLineFixture purApAccountingLineFixture; private AccountingLineFixture accountingLineFixture; private String objectCode; private RequisitionAccountingLineFixture(PurApAccountingLineFixture purApAccountingLineFixture, AccountingLineFixture accountingLineFixture) { this.purApAccountingLineFixture = purApAccountingLineFixture; this.accountingLineFixture = accountingLineFixture; } private RequisitionAccountingLineFixture(PurApAccountingLineFixture purApAccountingLineFixture, AccountingLineFixture accountingLineFixture, String objectCode) { this.purApAccountingLineFixture = purApAccountingLineFixture; this.accountingLineFixture = accountingLineFixture; this.objectCode = objectCode; } public PurApAccountingLine createPurApAccountingLine(Class clazz, PurApAccountingLineFixture puralFixture, AccountingLineFixture alFixture) { PurApAccountingLine line = null; // TODO: what should this debit code really be line = puralFixture.createPurApAccountingLine(RequisitionAccount.class, alFixture); if (StringUtils.isNotBlank(objectCode)) { line.setFinancialObjectCode(objectCode); line.refreshReferenceObject("objectCode"); } return line; } public void addTo(RequisitionItem item) { PurApAccountingLine purApAccountingLine = createPurApAccountingLine(item.getAccountingLineClass(), purApAccountingLineFixture, accountingLineFixture); //fix item reference purApAccountingLine.setPurapItem(item); // fix amount purApAccountingLine.setAmount(item.calculateExtendedPrice().multiply(new KualiDecimal(purApAccountingLine.getAccountLinePercent())).divide(new KualiDecimal(100))); item.getSourceAccountingLines().add(purApAccountingLine); } /** * This method adds an account to an item * * @param document * @param purApItemFixture * @throws IllegalAccessException * @throws InstantiationException */ public void addTo(PurApItem item, PurApAccountingLineFixture purApaccountFixture, AccountingLineFixture alFixture) throws IllegalAccessException, InstantiationException { // purApaccountFixture.createPurApAccountingLine(RequisitionAccount.class, alFixture); if (0 == 0) { ; } } }
quikkian-ua-devops/will-financials
kfs-purap/src/test/java/org/kuali/kfs/module/purap/fixture/RequisitionAccountingLineFixture.java
Java
agpl-3.0
6,153
# -*- coding: utf-8 -*- ############################################################################## # # Product GTIN module for Odoo # Copyright (C) 2004-2011 Tiny SPRL (<http://tiny.be>). # Copyright (C) 2010-2011 Camptocamp (<http://www.camptocamp.at>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import logging _logger = logging.getLogger(__name__) from openerp.osv import orm, fields import operator CONSTRAINT_MESSAGE = 'Error: Invalid EAN/GTIN code' HELP_MESSAGE = ("EAN8 EAN13 UPC JPC GTIN \n" "http://en.wikipedia.org/wiki/Global_Trade_Item_Number") def is_pair(x): return not x % 2 def check_ean8(eancode): """Check if the given ean code answer ean8 requirements For more details: http://en.wikipedia.org/wiki/EAN-8 :param eancode: string, ean-8 code :return: boolean """ if not eancode or not eancode.isdigit(): return False if not len(eancode) == 8: _logger.warn('Ean8 code has to have a length of 8 characters.') return False sum = 0 ean_len = int(len(eancode)) for i in range(ean_len-1): if is_pair(i): sum += 3 * int(eancode[i]) else: sum += int(eancode[i]) check = 10 - operator.mod(sum, 10) if check == 10: check = 0 return check == int(eancode[-1]) def check_upc(upccode): """Check if the given code answers upc requirements For more details: http://en.wikipedia.org/wiki/Universal_Product_Code :param upccode: string, upc code :return: bool """ if not upccode or not upccode.isdigit(): return False if not len(upccode) == 12: _logger.warn('UPC code has to have a length of 12 characters.') return False sum_pair = 0 ean_len = int(len(upccode)) for i in range(ean_len-1): if is_pair(i): sum_pair += int(upccode[i]) sum = sum_pair * 3 for i in range(ean_len-1): if not is_pair(i): sum += int(upccode[i]) check = ((sum/10 + 1) * 10) - sum return check == int(upccode[-1]) def check_ean13(eancode): """Check if the given ean code answer ean13 requirements For more details: http://en.wikipedia.org/wiki/International_Article_Number_%28EAN%29 :param eancode: string, ean-13 code :return: boolean """ if not eancode or not eancode.isdigit(): return False if not len(eancode) == 13: _logger.warn('Ean13 code has to have a length of 13 characters.') return False sum = 0 ean_len = int(len(eancode)) for i in range(ean_len-1): pos = int(ean_len-2-i) if is_pair(i): sum += 3 * int(eancode[pos]) else: sum += int(eancode[pos]) check = 10 - operator.mod(sum, 10) if check == 10: check = 0 return check == int(eancode[-1]) def check_ean11(eancode): pass def check_gtin14(eancode): pass DICT_CHECK_EAN = {8: check_ean8, 11: check_ean11, 12: check_upc, 13: check_ean13, 14: check_gtin14, } def check_ean(eancode): if not eancode: return True if not len(eancode) in DICT_CHECK_EAN: return False try: int(eancode) except: return False return DICT_CHECK_EAN[len(eancode)](eancode) class product_product(orm.Model): _inherit = "product.product" def _check_ean_key(self, cr, uid, ids): for rec in self.browse(cr, uid, ids): if not check_ean(rec.ean13): return False return True _columns = { 'ean13': fields.char( 'EAN/GTIN', size=14, help="Code for %s" % HELP_MESSAGE), } _constraints = [(_check_ean_key, CONSTRAINT_MESSAGE, ['ean13'])] class product_packaging(orm.Model): _inherit = "product.packaging" def _check_ean_key(self, cr, uid, ids): for rec in self.browse(cr, uid, ids): if not check_ean(rec.ean): return False return True _columns = { 'ean': fields.char( 'EAN', size=14, help='Barcode number for %s' % HELP_MESSAGE), } _constraints = [(_check_ean_key, CONSTRAINT_MESSAGE, ['ean'])] class res_partner(orm.Model): _inherit = "res.partner" def _check_ean_key(self, cr, uid, ids): for rec in self.browse(cr, uid, ids): if not check_ean(rec.ean13): return False return True _columns = { 'ean13': fields.char( 'EAN', size=14, help="Code for %s" % HELP_MESSAGE), } _constraints = [(_check_ean_key, CONSTRAINT_MESSAGE, ['ean13'])]
cgstudiomap/cgstudiomap
main/parts/product-attribute/product_gtin/product_gtin.py
Python
agpl-3.0
5,465
import { combineReducers } from 'redux' const FETCH_ENTRIES = 'FETCH_ENTRIES' const RECEIVE_ENTRIES = 'RECEIVE_ENTRIES' const RECEIVE_MORE_ENTRIES = 'RECEIVE_MORE_ENTRIES' const RECEIVE_ERROR = 'RECEIVE_ERROR' const INSERT_ENTRIES = 'INSERT_ENTRIES' const UPDATE_ENTRIES = 'UPDATE_ENTRIES' const DELETE_ENTRY = 'DELETE_ENTRY' const EMIT_ERROR = 'EMIT_ERROR' const entries = (state = [], action) => { switch (action.type) { case RECEIVE_MORE_ENTRIES: return [...state, ...action.entries] case RECEIVE_ENTRIES: return action.entries case INSERT_ENTRIES: return [...action.entries, ...state] case UPDATE_ENTRIES: return state.map(entry => { let updatedEntry = action.entries.find( actionEntry => actionEntry._id === entry._id ) return updatedEntry || entry }) case DELETE_ENTRY: // TODO: quick and dirty fix for removeFromAlbum (we got IDs instead of photos) const id = typeof action.entity === 'object' ? action.entity.id || action.entity._id : action.entity // TODO: why is the back sending an id prop instead of a _id prop here??? const idx = state.findIndex(e => e._id === id) if (idx === -1) return state return [...state.slice(0, idx), ...state.slice(idx + 1)] default: return state } } const fetchStatus = (state = 'pending', action) => { switch (action.type) { case FETCH_ENTRIES: return 'loading' case RECEIVE_ENTRIES: return 'loaded' case RECEIVE_ERROR: return 'failed' default: return state } } const lastFetch = (state = null, action) => { switch (action.type) { case RECEIVE_ENTRIES: case RECEIVE_MORE_ENTRIES: return Date.now() default: return state } } const hasMore = (state = false, action) => { switch (action.type) { case RECEIVE_ENTRIES: case RECEIVE_MORE_ENTRIES: return action.next !== undefined ? action.next : state default: return state } } const index = (state = null, action) => { switch (action.type) { case RECEIVE_ENTRIES: return action.index !== undefined ? action.index : state default: return state } } const listReducer = combineReducers({ entries, fetchStatus, lastFetch, hasMore, index }) const listsReducer = (state = {}, action) => { switch (action.type) { case FETCH_ENTRIES: case RECEIVE_ENTRIES: case RECEIVE_MORE_ENTRIES: case RECEIVE_ERROR: case INSERT_ENTRIES: case UPDATE_ENTRIES: case DELETE_ENTRY: return Object.assign({}, state, { [action.name]: listReducer(state[action.name] || {}, action) }) default: return state } } export default listsReducer export const createFetchAction = (listName, saga) => { return (...args) => { return (dispatch, getState) => { let fetchingMoreEntries = false const existingList = getList(getState(), listName) if (existingList) { const { fetchStatus, hasMore } = existingList fetchingMoreEntries = fetchStatus === 'loaded' && hasMore === true } if (!fetchingMoreEntries) { dispatch({ type: FETCH_ENTRIES, name: listName }) } return saga(...args) .then(resp => { return fetchingMoreEntries && resp.skip !== 0 ? dispatch({ type: RECEIVE_MORE_ENTRIES, name: listName, ...resp }) : dispatch({ type: RECEIVE_ENTRIES, name: listName, ...resp }) }) .catch(error => dispatch({ type: RECEIVE_ERROR, name: listName, error }) ) } } } const shouldRefetch = list => { if (!list) { return true } // here we could add conditions so that we don't refetch a list fetched 30s ago return true } export const createFetchIfNeededAction = (listName, saga) => { return (...args) => { return (dispatch, getState) => { const existingList = getList(getState(), listName) if (existingList && !shouldRefetch(existingList)) { return Promise.resolve(existingList) } return dispatch(createFetchAction(listName, saga)(...args)) } } } export const createInsertAction = (listName, saga) => { return (...args) => { return (dispatch, getState) => { const existingList = getList(getState(), listName) return saga(...args).then(resp => { if (existingList) { return dispatch(insertAction(listName, resp)) } else { return resp } }) } } } export const createUpdateAction = (listName, saga) => { return (...args) => { return (dispatch, getState) => { const existingList = getList(getState(), listName) return saga(...args).then(resp => { if (existingList) { return dispatch(updateAction(listName, resp)) } else { return resp } }) } } } export const createDeleteAction = (listName, saga) => { return (...args) => { return (dispatch, getState) => { const existingList = getList(getState(), listName) return saga(...args).then(resp => { if (existingList) { resp.entries.forEach(e => dispatch(deleteAction(listName, e))) } return resp }) } } } export const errorAction = (listName, error) => ({ type: EMIT_ERROR, name: listName, error, alert: { message: error.message || error } }) // TODO: remove the discrepancy between insert and deleteAction inputs (full response with entries vs single entry) export const insertAction = (listName, resp) => ({ type: INSERT_ENTRIES, name: listName, ...resp }) export const updateAction = (listName, resp) => ({ type: UPDATE_ENTRIES, name: listName, ...resp }) export const deleteAction = (listName, entity) => ({ type: DELETE_ENTRY, name: listName, entity }) export const getList = (state, name) => state.lists[name]
enguerran/cozy-files-v3
src/photos/ducks/lists/index.js
JavaScript
agpl-3.0
5,918
class API::Logger def initialize(app) @app = app end def call(env) payload = { remote_addr: env['REMOTE_ADDR'], request_method: env['REQUEST_METHOD'], request_path: env['PATH_INFO'], request_query: env['QUERY_STRING'], x_organization: env['HTTP_X_ORGANIZATION'] } ActiveSupport::Notifications.instrument "grape.request", payload do @app.call(env).tap do |response| if env["api.endpoint"] && env["api.endpoint"].params.present? payload[:params] = env["api.endpoint"].params.to_hash payload[:params].delete("route_info") payload[:params].delete("format") end payload[:response_status] = response[0] end end end end
Loos/bike_index
app/controllers/api/logger.rb
Ruby
agpl-3.0
745
import { DataSourcePluginOptionsEditorProps, onUpdateDatasourceJsonDataOptionChecked, SelectableValue, updateDatasourcePluginJsonDataOption, } from '@grafana/data'; import { EventsWithValidation, InlineFormLabel, LegacyForms, regexValidation } from '@grafana/ui'; import React, { SyntheticEvent } from 'react'; import { PromOptions } from '../types'; import { ExemplarsSettings } from './ExemplarsSettings'; const { Select, Input, FormField, Switch } = LegacyForms; const httpOptions = [ { value: 'POST', label: 'POST' }, { value: 'GET', label: 'GET' }, ]; type Props = Pick<DataSourcePluginOptionsEditorProps<PromOptions>, 'options' | 'onOptionsChange'>; export const PromSettings = (props: Props) => { const { options, onOptionsChange } = props; // We are explicitly adding httpMethod so it is correctly displayed in dropdown. This way, it is more predictable for users. if (!options.jsonData.httpMethod) { options.jsonData.httpMethod = 'POST'; } return ( <> <div className="gf-form-group"> <div className="gf-form-inline"> <div className="gf-form"> <FormField label="Scrape interval" labelWidth={13} inputEl={ <Input className="width-6" value={options.jsonData.timeInterval} spellCheck={false} placeholder="15s" onChange={onChangeHandler('timeInterval', options, onOptionsChange)} validationEvents={promSettingsValidationEvents} /> } tooltip="Set this to the typical scrape and evaluation interval configured in Prometheus. Defaults to 15s." /> </div> </div> <div className="gf-form-inline"> <div className="gf-form"> <FormField label="Query timeout" labelWidth={13} inputEl={ <Input className="width-6" value={options.jsonData.queryTimeout} onChange={onChangeHandler('queryTimeout', options, onOptionsChange)} spellCheck={false} placeholder="60s" validationEvents={promSettingsValidationEvents} /> } tooltip="Set the Prometheus query timeout." /> </div> </div> <div className="gf-form"> <InlineFormLabel width={13} tooltip="You can use either POST or GET HTTP method to query your Prometheus data source. POST is the recommended method as it allows bigger queries. Change this to GET if you have a Prometheus version older than 2.1 or if POST requests are restricted in your network." > HTTP Method </InlineFormLabel> <Select aria-label="Select HTTP method" menuShouldPortal options={httpOptions} value={httpOptions.find((o) => o.value === options.jsonData.httpMethod)} onChange={onChangeHandler('httpMethod', options, onOptionsChange)} width={7} /> </div> </div> <h3 className="page-heading">Misc</h3> <div className="gf-form-group"> <div className="gf-form"> <Switch checked={options.jsonData.disableMetricsLookup ?? false} label="Disable metrics lookup" labelClass="width-14" onChange={onUpdateDatasourceJsonDataOptionChecked(props, 'disableMetricsLookup')} tooltip="Checking this option will disable the metrics chooser and metric/label support in the query field's autocomplete. This helps if you have performance issues with bigger Prometheus instances." /> </div> <div className="gf-form-inline"> <div className="gf-form max-width-30"> <FormField label="Custom query parameters" labelWidth={14} tooltip="Add Custom parameters to all Prometheus or Thanos queries." inputEl={ <Input className="width-25" value={options.jsonData.customQueryParameters} onChange={onChangeHandler('customQueryParameters', options, onOptionsChange)} spellCheck={false} placeholder="Example: max_source_resolution=5m&timeout=10" /> } /> </div> </div> </div> <ExemplarsSettings options={options.jsonData.exemplarTraceIdDestinations} onChange={(exemplarOptions) => updateDatasourcePluginJsonDataOption( { onOptionsChange, options }, 'exemplarTraceIdDestinations', exemplarOptions ) } /> </> ); }; export const promSettingsValidationEvents = { [EventsWithValidation.onBlur]: [ regexValidation( /^$|^\d+(ms|[Mwdhmsy])$/, 'Value is not valid, you can use number with time unit specifier: y, M, w, d, h, m, s' ), ], }; export const getValueFromEventItem = (eventItem: SyntheticEvent<HTMLInputElement> | SelectableValue<string>) => { if (!eventItem) { return ''; } if (eventItem.hasOwnProperty('currentTarget')) { return eventItem.currentTarget.value; } return (eventItem as SelectableValue<string>).value; }; const onChangeHandler = (key: keyof PromOptions, options: Props['options'], onOptionsChange: Props['onOptionsChange']) => (eventItem: SyntheticEvent<HTMLInputElement> | SelectableValue<string>) => { onOptionsChange({ ...options, jsonData: { ...options.jsonData, [key]: getValueFromEventItem(eventItem), }, }); };
grafana/grafana
public/app/plugins/datasource/prometheus/configuration/PromSettings.tsx
TypeScript
agpl-3.0
5,824
/*===================================================================== PIXHAWK Micro Air Vehicle Flying Robotics Toolkit (c) 2009, 2010 PIXHAWK PROJECT <http://pixhawk.ethz.ch> This file is part of the PIXHAWK project PIXHAWK 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. PIXHAWK 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 PIXHAWK. If not, see <http://www.gnu.org/licenses/>. ======================================================================*/ /** * @file * @brief Waypoint list widget * * @author Lorenz Meier <mavteam@student.ethz.ch> * @author Benjamin Knecht <mavteam@student.ethz.ch> * @author Petri Tanskanen <mavteam@student.ethz.ch> * */ #include "WaypointList.h" #include "ui_WaypointList.h" #include <UASInterface.h> #include <UASManager.h> #include <QDebug> #include <QFileDialog> #include <QMessageBox> #include <QMouseEvent> WaypointList::WaypointList(QWidget *parent, UASInterface* uas) : QWidget(parent), uas(NULL), mavX(0.0), mavY(0.0), mavZ(0.0), mavYaw(0.0), showOfflineWarning(false), m_ui(new Ui::WaypointList) { m_ui->setupUi(this); //EDIT TAB editableListLayout = new QVBoxLayout(m_ui->editableListWidget); editableListLayout->setSpacing(0); editableListLayout->setMargin(0); editableListLayout->setAlignment(Qt::AlignTop); m_ui->editableListWidget->setLayout(editableListLayout); // ADD WAYPOINT // Connect add action, set right button icon and connect action to this class connect(m_ui->addButton, SIGNAL(clicked()), m_ui->actionAddWaypoint, SIGNAL(triggered())); connect(m_ui->actionAddWaypoint, SIGNAL(triggered()), this, SLOT(addEditable())); // ADD WAYPOINT AT CURRENT POSITION connect(m_ui->positionAddButton, SIGNAL(clicked()), this, SLOT(addCurrentPositionWaypoint())); // SEND WAYPOINTS connect(m_ui->transmitButton, SIGNAL(clicked()), this, SLOT(transmit())); // DELETE ALL WAYPOINTS connect(m_ui->clearWPListButton, SIGNAL(clicked()), this, SLOT(clearWPWidget())); // REQUEST WAYPOINTS connect(m_ui->readButton, SIGNAL(clicked()), this, SLOT(read())); // SAVE/LOAD WAYPOINTS connect(m_ui->saveButton, SIGNAL(clicked()), this, SLOT(saveWaypoints())); connect(m_ui->loadButton, SIGNAL(clicked()), this, SLOT(loadWaypoints())); //connect(UASManager::instance(), SIGNAL(activeUASSet(UASInterface*)), this, SLOT(setUAS(UASInterface*))); //VIEW TAB viewOnlyListLayout = new QVBoxLayout(m_ui->viewOnlyListWidget); viewOnlyListLayout->setSpacing(0); viewOnlyListLayout->setMargin(0); viewOnlyListLayout->setAlignment(Qt::AlignTop); m_ui->viewOnlyListWidget->setLayout(viewOnlyListLayout); // REFRESH VIEW TAB connect(m_ui->refreshButton, SIGNAL(clicked()), this, SLOT(refresh())); // SET UAS AFTER ALL SIGNALS/SLOTS ARE CONNECTED if (uas) { WPM = uas->getWaypointManager(); //setUAS(uas); } else { // Hide buttons, which don't make sense without valid UAS m_ui->positionAddButton->hide(); m_ui->transmitButton->hide(); m_ui->readButton->hide(); m_ui->refreshButton->hide(); //FIXME: The whole "Onboard Waypoints"-tab should be hidden, instead of "refresh" button UnconnectedUASInfoWidget* inf = new UnconnectedUASInfoWidget(this); viewOnlyListLayout->insertWidget(0, inf); //insert a "NO UAV" info into the Onboard Tab showOfflineWarning = true; WPM = new UASWaypointManager(NULL); } setUAS(uas); // STATUS LABEL updateStatusLabel(""); this->setVisible(false); loadFileGlobalWP = false; readGlobalWP = false; centerMapCoordinate.setX(0.0); centerMapCoordinate.setY(0.0); } WaypointList::~WaypointList() { delete m_ui; } void WaypointList::updatePosition(UASInterface* uas, double x, double y, double z, quint64 usec) { Q_UNUSED(uas); Q_UNUSED(usec); mavX = x; mavY = y; mavZ = z; } void WaypointList::updateAttitude(UASInterface* uas, double roll, double pitch, double yaw, quint64 usec) { Q_UNUSED(uas); Q_UNUSED(usec); Q_UNUSED(roll); Q_UNUSED(pitch); mavYaw = yaw; } void WaypointList::setUAS(UASInterface* uas) { //if (this->uas == NULL && uas != NULL) if (this->uas == NULL) { this->uas = uas; connect(WPM, SIGNAL(updateStatusString(const QString &)), this, SLOT(updateStatusLabel(const QString &))); connect(WPM, SIGNAL(waypointEditableListChanged(void)), this, SLOT(waypointEditableListChanged(void))); connect(WPM, SIGNAL(waypointEditableChanged(int,Waypoint*)), this, SLOT(updateWaypointEditable(int,Waypoint*))); connect(WPM, SIGNAL(waypointViewOnlyListChanged(void)), this, SLOT(waypointViewOnlyListChanged(void))); connect(WPM, SIGNAL(waypointViewOnlyChanged(int,Waypoint*)), this, SLOT(updateWaypointViewOnly(int,Waypoint*))); connect(WPM, SIGNAL(currentWaypointChanged(quint16)), this, SLOT(currentWaypointViewOnlyChanged(quint16))); if (uas != NULL) { connect(uas, SIGNAL(localPositionChanged(UASInterface*,double,double,double,quint64)), this, SLOT(updatePosition(UASInterface*,double,double,double,quint64))); connect(uas, SIGNAL(attitudeChanged(UASInterface*,double,double,double,quint64)), this, SLOT(updateAttitude(UASInterface*,double,double,double,quint64))); } //connect(WPM,SIGNAL(loadWPFile()),this,SLOT(setIsLoadFileWP())); //connect(WPM,SIGNAL(readGlobalWPFromUAS(bool)),this,SLOT(setIsReadGlobalWP(bool))); } } void WaypointList::saveWaypoints() { QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "./waypoints.txt", tr("Waypoint File (*.txt)")); WPM->saveWaypoints(fileName); } void WaypointList::loadWaypoints() { //create a popup notifying the user about the limitations of offline editing if (showOfflineWarning == true) { QMessageBox msgBox; msgBox.setIcon(QMessageBox::Warning); msgBox.setText("Offline editor!"); msgBox.setInformativeText("You are using the offline mission editor. Please don't forget to save your mission plan before connecting the UAV, otherwise it will be lost."); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.setDefaultButton(QMessageBox::Ok); int ret = msgBox.exec(); showOfflineWarning = false; } QString fileName = QFileDialog::getOpenFileName(this, tr("Load File"), ".", tr("Waypoint File (*.txt)")); WPM->loadWaypoints(fileName); } void WaypointList::transmit() { if (uas) { WPM->writeWaypoints(); } } void WaypointList::read() { if (uas) { WPM->readWaypoints(true); } } void WaypointList::refresh() { if (uas) { WPM->readWaypoints(false); } } void WaypointList::addEditable() { const QVector<Waypoint *> &waypoints = WPM->getWaypointEditableList(); Waypoint *wp; if (waypoints.size() > 0) { // Create waypoint with last frame Waypoint *last = waypoints.at(waypoints.size()-1); wp = new Waypoint(0, last->getX(), last->getY(), last->getZ(), last->getParam1(), last->getParam2(), last->getParam3(), last->getParam4(), last->getAutoContinue(), false, last->getFrame(), last->getAction()); WPM->addWaypointEditable(wp); } else { if (uas) { // Create first waypoint at current MAV position addCurrentPositionWaypoint(); } else { //Since no UAV available, create first default waypoint. updateStatusLabel(tr("No UAV. Added default LOCAL (NED) waypoint")); wp = new Waypoint(0, 0, 0, -0.50, 0, 0.20, 0, 0,true, true, MAV_FRAME_LOCAL_NED, MAV_CMD_NAV_WAYPOINT); WPM->addWaypointEditable(wp); //create a popup notifying the user about the limitations of offline editing if (showOfflineWarning == true) { QMessageBox msgBox; msgBox.setIcon(QMessageBox::Warning); msgBox.setText("Offline editor!"); msgBox.setInformativeText("You are using the offline mission editor. Please don't forget to save your mission plan before connecting the UAV, otherwise it will be lost."); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.setDefaultButton(QMessageBox::Ok); int ret = msgBox.exec(); showOfflineWarning = false; } } } } void WaypointList::addCurrentPositionWaypoint() { if (uas) { const QVector<Waypoint *> &waypoints = WPM->getWaypointEditableList(); Waypoint *wp; Waypoint *last = 0; if (waypoints.size() > 0) { last = waypoints.at(waypoints.size()-1); } if (uas->globalPositionKnown()) { float acceptanceRadiusGlobal = 10.0f; float holdTime = 0.0f; float yawGlobal = 0.0f; if (last) { acceptanceRadiusGlobal = last->getAcceptanceRadius(); holdTime = last->getHoldTime(); yawGlobal = last->getYaw(); } // Create global frame waypoint per default wp = new Waypoint(0, uas->getLatitude(), uas->getLongitude(), uas->getAltitude(), 0, acceptanceRadiusGlobal, holdTime, yawGlobal, true, false, MAV_FRAME_GLOBAL_RELATIVE_ALT, MAV_CMD_NAV_WAYPOINT); WPM->addWaypointEditable(wp); updateStatusLabel(tr("Added GLOBAL, ALTITUDE OVER GROUND waypoint")); } else if (uas->localPositionKnown()) { float acceptanceRadiusLocal = 0.2f; float holdTime = 0.5f; if (last) { acceptanceRadiusLocal = last->getAcceptanceRadius(); holdTime = last->getHoldTime(); } // Create local frame waypoint as second option wp = new Waypoint(0, uas->getLocalX(), uas->getLocalY(), uas->getLocalZ(), uas->getYaw(), acceptanceRadiusLocal, holdTime, 0.0, true, false, MAV_FRAME_LOCAL_NED, MAV_CMD_NAV_WAYPOINT); WPM->addWaypointEditable(wp); updateStatusLabel(tr("Added LOCAL (NED) waypoint")); } else { // Do nothing updateStatusLabel(tr("Not adding waypoint, no position of MAV known yet.")); } } } void WaypointList::updateStatusLabel(const QString &string) { // Status label in write widget m_ui->statusLabel->setText(string); // Status label in read only widget m_ui->viewStatusLabel->setText(string); } // Request UASWaypointManager to send the SET_CURRENT message to UAV void WaypointList::changeCurrentWaypoint(quint16 seq) { if (uas) { WPM->setCurrentWaypoint(seq); } } // Request UASWaypointManager to set the new "current" and make sure all other waypoints are not "current" void WaypointList::currentWaypointEditableChanged(quint16 seq) { WPM->setCurrentEditable(seq); const QVector<Waypoint *> &waypoints = WPM->getWaypointEditableList(); if (seq < waypoints.size()) { for(int i = 0; i < waypoints.size(); i++) { WaypointEditableView* widget = wpEditableViews.find(waypoints[i]).value(); if (waypoints[i]->getId() == seq) { widget->setCurrent(true); } else { widget->setCurrent(false); } } } } // Update waypointViews to correctly indicate the new current waypoint void WaypointList::currentWaypointViewOnlyChanged(quint16 seq) { const QVector<Waypoint *> &waypoints = WPM->getWaypointViewOnlyList(); if (seq < waypoints.size()) { for(int i = 0; i < waypoints.size(); i++) { WaypointViewOnlyView* widget = wpViewOnlyViews.find(waypoints[i]).value(); if (waypoints[i]->getId() == seq) { widget->setCurrent(true); } else { widget->setCurrent(false); } } } } void WaypointList::updateWaypointEditable(int uas, Waypoint* wp) { Q_UNUSED(uas); WaypointEditableView *wpv = wpEditableViews.value(wp); wpv->updateValues(); } void WaypointList::updateWaypointViewOnly(int uas, Waypoint* wp) { Q_UNUSED(uas); WaypointViewOnlyView *wpv = wpViewOnlyViews.value(wp); wpv->updateValues(); } void WaypointList::waypointViewOnlyListChanged() { // Prevent updates to prevent visual flicker this->setUpdatesEnabled(false); const QVector<Waypoint *> &waypoints = WPM->getWaypointViewOnlyList(); if (!wpViewOnlyViews.empty()) { QMapIterator<Waypoint*,WaypointViewOnlyView*> viewIt(wpViewOnlyViews); viewIt.toFront(); while(viewIt.hasNext()) { viewIt.next(); Waypoint *cur = viewIt.key(); int i; for (i = 0; i < waypoints.size(); i++) { if (waypoints[i] == cur) { break; } } if (i == waypoints.size()) { WaypointViewOnlyView* widget = wpViewOnlyViews.find(cur).value(); widget->hide(); viewOnlyListLayout->removeWidget(widget); wpViewOnlyViews.remove(cur); } } } // then add/update the views for each waypoint in the list for(int i = 0; i < waypoints.size(); i++) { Waypoint *wp = waypoints[i]; if (!wpViewOnlyViews.contains(wp)) { WaypointViewOnlyView* wpview = new WaypointViewOnlyView(wp, this); wpViewOnlyViews.insert(wp, wpview); connect(wpview, SIGNAL(changeCurrentWaypoint(quint16)), this, SLOT(changeCurrentWaypoint(quint16))); viewOnlyListLayout->insertWidget(i, wpview); } WaypointViewOnlyView *wpv = wpViewOnlyViews.value(wp); //check if ordering has changed if(viewOnlyListLayout->itemAt(i)->widget() != wpv) { viewOnlyListLayout->removeWidget(wpv); viewOnlyListLayout->insertWidget(i, wpv); } wpv->updateValues(); // update the values of the ui elements in the view } this->setUpdatesEnabled(true); loadFileGlobalWP = false; } void WaypointList::waypointEditableListChanged() { // Prevent updates to prevent visual flicker this->setUpdatesEnabled(false); const QVector<Waypoint *> &waypoints = WPM->getWaypointEditableList(); if (!wpEditableViews.empty()) { QMapIterator<Waypoint*,WaypointEditableView*> viewIt(wpEditableViews); viewIt.toFront(); while(viewIt.hasNext()) { viewIt.next(); Waypoint *cur = viewIt.key(); int i; for (i = 0; i < waypoints.size(); i++) { if (waypoints[i] == cur) { break; } } if (i == waypoints.size()) { WaypointEditableView* widget = wpEditableViews.find(cur).value(); widget->hide(); editableListLayout->removeWidget(widget); wpEditableViews.remove(cur); } } } // then add/update the views for each waypoint in the list for(int i = 0; i < waypoints.size(); i++) { Waypoint *wp = waypoints[i]; if (!wpEditableViews.contains(wp)) { WaypointEditableView* wpview = new WaypointEditableView(wp, this); wpEditableViews.insert(wp, wpview); connect(wpview, SIGNAL(moveDownWaypoint(Waypoint*)), this, SLOT(moveDown(Waypoint*))); connect(wpview, SIGNAL(moveUpWaypoint(Waypoint*)), this, SLOT(moveUp(Waypoint*))); connect(wpview, SIGNAL(removeWaypoint(Waypoint*)), this, SLOT(removeWaypoint(Waypoint*))); //connect(wpview, SIGNAL(currentWaypointChanged(quint16)), this, SLOT(currentWaypointChanged(quint16))); connect(wpview, SIGNAL(changeCurrentWaypoint(quint16)), this, SLOT(currentWaypointEditableChanged(quint16))); editableListLayout->insertWidget(i, wpview); } WaypointEditableView *wpv = wpEditableViews.value(wp); //check if ordering has changed if(editableListLayout->itemAt(i)->widget() != wpv) { editableListLayout->removeWidget(wpv); editableListLayout->insertWidget(i, wpv); } wpv->updateValues(); // update the values of the ui elements in the view } this->setUpdatesEnabled(true); loadFileGlobalWP = false; } void WaypointList::moveUp(Waypoint* wp) { const QVector<Waypoint *> &waypoints = WPM->getWaypointEditableList(); //get the current position of wp in the local storage int i; for (i = 0; i < waypoints.size(); i++) { if (waypoints[i] == wp) break; } // if wp was found and its not the first entry, move it if (i < waypoints.size() && i > 0) { WPM->moveWaypoint(i, i-1); } } void WaypointList::moveDown(Waypoint* wp) { const QVector<Waypoint *> &waypoints = WPM->getWaypointEditableList(); //get the current position of wp in the local storage int i; for (i = 0; i < waypoints.size(); i++) { if (waypoints[i] == wp) break; } // if wp was found and its not the last entry, move it if (i < waypoints.size()-1) { WPM->moveWaypoint(i, i+1); } } void WaypointList::removeWaypoint(Waypoint* wp) { WPM->removeWaypoint(wp->getId()); } void WaypointList::changeEvent(QEvent *e) { switch (e->type()) { case QEvent::LanguageChange: m_ui->retranslateUi(this); break; default: break; } } void WaypointList::on_clearWPListButton_clicked() { if (uas) { emit clearPathclicked(); const QVector<Waypoint *> &waypoints = WPM->getWaypointEditableList(); while(!waypoints.isEmpty()) { //for(int i = 0; i <= waypoints.size(); i++) WaypointEditableView* widget = wpEditableViews.find(waypoints[0]).value(); widget->remove(); } } else { // if(isGlobalWP) // { // emit clearPathclicked(); // } } } ///** @brief The MapWidget informs that a waypoint global was changed on the map */ //void WaypointList::waypointGlobalChanged(QPointF coordinate, int indexWP) //{ // if (uas) // { // const QVector<Waypoint *> &waypoints = WPM->getWaypointEditableList(); // if (waypoints.size() > 0) // { // Waypoint *temp = waypoints.at(indexWP); // temp->setX(coordinate.x()); // temp->setY(coordinate.y()); // //WaypointGlobalView* widget = wpGlobalViews.find(waypoints[indexWP]).value(); // //widget->updateValues(); // } // } //} ///** @brief The MapWidget informs that a waypoint global was changed on the map */ //void WaypointList::waypointGlobalPositionChanged(Waypoint* wp) //{ // QPointF coordinate; // coordinate.setX(wp->getX()); // coordinate.setY(wp->getY()); // emit ChangeWaypointGlobalPosition(wp->getId(), coordinate); //} void WaypointList::clearWPWidget() { const QVector<Waypoint *> &waypoints = WPM->getWaypointEditableList(); while(!waypoints.isEmpty()) { //for(int i = 0; i <= waypoints.size(); i++) WaypointEditableView* widget = wpEditableViews.find(waypoints[0]).value(); widget->remove(); } } //void WaypointList::setIsLoadFileWP() //{ // loadFileGlobalWP = true; //} //void WaypointList::setIsReadGlobalWP(bool value) //{ // // FIXME James Check this // Q_UNUSED(value); // // readGlobalWP = value; //}
josephlewis42/UDenverQGC
src/ui/WaypointList.cc
C++
agpl-3.0
20,720
<?php // created: 2013-02-07 16:25:26 $sugar_config = array ( 'admin_access_control' => false, 'admin_export_only' => false, 'cache_dir' => 'cache/', 'calculate_response_time' => true, 'calendar' => array ( 'default_view' => 'week', 'show_calls_by_default' => true, 'show_tasks_by_default' => true, 'editview_width' => 990, 'editview_height' => 485, 'day_timestep' => 15, 'week_timestep' => 30, 'items_draggable' => true, 'items_resizable' => true, 'enable_repeat' => true, 'max_repeat_count' => 1000, ), 'chartEngine' => 'Jit', 'common_ml_dir' => '', 'create_default_user' => false, 'cron' => array ( 'max_cron_jobs' => 10, 'max_cron_runtime' => 30, 'min_cron_interval' => 30, ), 'currency' => '', 'dashlet_display_row_options' => array ( 0 => '1', 1 => '3', 2 => '5', 3 => '10', ), 'date_formats' => array ( 'Y-m-d' => '2010-12-23', 'm-d-Y' => '12-23-2010', 'd-m-Y' => '23-12-2010', 'Y/m/d' => '2010/12/23', 'm/d/Y' => '12/23/2010', 'd/m/Y' => '23/12/2010', 'Y.m.d' => '2010.12.23', 'd.m.Y' => '23.12.2010', 'm.d.Y' => '12.23.2010', ), 'datef' => 'm/d/Y', 'dbconfig' => array ( 'db_host_name' => 'localhost', 'db_host_instance' => 'SQLEXPRESS', 'db_user_name' => 'root', 'db_password' => 'sa', 'db_name' => 'rrd', 'db_type' => 'mysql', 'db_port' => '', 'db_manager' => 'MysqliManager', ), 'dbconfigoption' => array ( 'persistent' => true, 'autofree' => false, 'debug' => 0, 'ssl' => false, ), 'default_action' => 'index', 'default_charset' => 'UTF-8', 'default_currencies' => array ( 'AUD' => array ( 'name' => 'Australian Dollars', 'iso4217' => 'AUD', 'symbol' => '$', ), 'BRL' => array ( 'name' => 'Brazilian Reais', 'iso4217' => 'BRL', 'symbol' => 'R$', ), 'GBP' => array ( 'name' => 'British Pounds', 'iso4217' => 'GBP', 'symbol' => '£', ), 'CAD' => array ( 'name' => 'Canadian Dollars', 'iso4217' => 'CAD', 'symbol' => '$', ), 'CNY' => array ( 'name' => 'Chinese Yuan', 'iso4217' => 'CNY', 'symbol' => '¥', ), 'EUR' => array ( 'name' => 'Euro', 'iso4217' => 'EUR', 'symbol' => '€', ), 'HKD' => array ( 'name' => 'Hong Kong Dollars', 'iso4217' => 'HKD', 'symbol' => '$', ), 'INR' => array ( 'name' => 'Indian Rupees', 'iso4217' => 'INR', 'symbol' => '₨', ), 'KRW' => array ( 'name' => 'Korean Won', 'iso4217' => 'KRW', 'symbol' => '₩', ), 'YEN' => array ( 'name' => 'Japanese Yen', 'iso4217' => 'JPY', 'symbol' => '¥', ), 'MXM' => array ( 'name' => 'Mexican Pesos', 'iso4217' => 'MXM', 'symbol' => '$', ), 'SGD' => array ( 'name' => 'Singaporean Dollars', 'iso4217' => 'SGD', 'symbol' => '$', ), 'CHF' => array ( 'name' => 'Swiss Franc', 'iso4217' => 'CHF', 'symbol' => 'SFr.', ), 'THB' => array ( 'name' => 'Thai Baht', 'iso4217' => 'THB', 'symbol' => '฿', ), 'USD' => array ( 'name' => 'US Dollars', 'iso4217' => 'USD', 'symbol' => '$', ), ), 'default_currency_iso4217' => 'USD', 'default_currency_name' => 'US Dollars', 'default_currency_significant_digits' => 2, 'default_currency_symbol' => '$', 'default_date_format' => 'm/d/Y', 'default_decimal_seperator' => '.', 'default_email_charset' => 'UTF-8', 'default_email_client' => 'sugar', 'default_email_editor' => 'html', 'default_export_charset' => 'UTF-8', 'default_language' => 'en_us', 'default_locale_name_format' => 's f l', 'default_max_tabs' => '7', 'default_module' => 'Home', 'default_navigation_paradigm' => 'gm', 'default_number_grouping_seperator' => ',', 'default_password' => '', 'default_permissions' => array ( 'dir_mode' => 1528, 'file_mode' => 432, 'user' => '', 'group' => '', ), 'default_subpanel_links' => false, 'default_subpanel_tabs' => true, 'default_swap_last_viewed' => false, 'default_swap_shortcuts' => false, 'default_theme' => 'VTPL', 'default_time_format' => 'h:ia', 'default_user_is_admin' => false, 'default_user_name' => '', 'demoData' => 'yes', 'disable_convert_lead' => false, 'disable_export' => false, 'disable_persistent_connections' => 'false', 'display_email_template_variable_chooser' => false, 'display_inbound_email_buttons' => false, 'dump_slow_queries' => false, 'email_address_separator' => ',', 'email_default_client' => 'sugar', 'email_default_delete_attachments' => true, 'email_default_editor' => 'html', 'export_delimiter' => ',', 'history_max_viewed' => 50, 'host_name' => 'localhost', 'import_max_execution_time' => 3600, 'import_max_records_per_file' => 100, 'import_max_records_total_limit' => '', 'installer_locked' => true, 'jobs' => array ( 'min_retry_interval' => 30, 'max_retries' => 5, 'timeout' => 86400, ), 'js_custom_version' => 1, 'js_lang_version' => 4, 'languages' => array ( 'en_us' => 'English (US)', ), 'large_scale_test' => false, 'lead_conv_activity_opt' => 'donothing', 'list_max_entries_per_page' => 20, 'list_max_entries_per_subpanel' => 10, 'lock_default_user_name' => false, 'lock_homepage' => false, 'lock_subpanels' => false, 'log_dir' => '.', 'log_file' => 'sugarcrm.log', 'log_memory_usage' => false, 'logger' => array ( 'level' => 'fatal', 'file' => array ( 'ext' => '.log', 'name' => 'sugarcrm', 'dateFormat' => '%c', 'maxSize' => '10MB', 'maxLogs' => 10, 'suffix' => '', ), ), 'max_dashlets_homepage' => '15', 'name_formats' => array ( 's f l' => 's f l', 'f l' => 'f l', 's l' => 's l', 'l, s f' => 'l, s f', 'l, f' => 'l, f', 's l, f' => 's l, f', 'l s f' => 'l s f', 'l f s' => 'l f s', ), 'passwordsetting' => array ( 'SystemGeneratedPasswordON' => true, 'generatepasswordtmpl' => '9bcfa05d-3288-034a-0f5a-5111e6e7b8cc', 'lostpasswordtmpl' => 'c636a422-a241-ab44-c071-5111e69d04b3', 'forgotpasswordON' => true, 'linkexpiration' => true, 'linkexpirationtime' => 24, 'linkexpirationtype' => 60, 'systexpiration' => 1, 'systexpirationtime' => 7, 'systexpirationtype' => '0', 'systexpirationlogin' => '', 'minpwdlength' => 6, 'oneupper' => true, 'onelower' => true, 'onenumber' => true, ), 'portal_view' => 'single_user', 'require_accounts' => true, 'resource_management' => array ( 'special_query_limit' => 50000, 'special_query_modules' => array ( 0 => 'Reports', 1 => 'Export', 2 => 'Import', 3 => 'Administration', 4 => 'Sync', ), 'default_limit' => 1000, ), 'rss_cache_time' => '10800', 'save_query' => 'all', 'search_wildcard_char' => '%', 'search_wildcard_infront' => false, 'session_dir' => '', 'showDetailData' => true, 'showThemePicker' => true, 'site_url' => 'http://localhost/rrd', 'slow_query_time_msec' => '100', 'sugar_version' => '6.5.8', 'sugarbeet' => true, 'time_formats' => array ( 'H:i' => '23:00', 'h:ia' => '11:00pm', 'h:iA' => '11:00PM', 'h:i a' => '11:00 pm', 'h:i A' => '11:00 PM', 'H.i' => '23.00', 'h.ia' => '11.00pm', 'h.iA' => '11.00PM', 'h.i a' => '11.00 pm', 'h.i A' => '11.00 PM', ), 'timef' => 'H:i', 'tmp_dir' => 'cache/xml/', 'tracker_max_display_length' => 15, 'translation_string_prefix' => false, 'unique_key' => 'c724c99c34ff308b7a7d08f6c3b728f0', 'upload_badext' => array ( 0 => 'php', 1 => 'php3', 2 => 'php4', 3 => 'php5', 4 => 'pl', 5 => 'cgi', 6 => 'py', 7 => 'asp', 8 => 'cfm', 9 => 'js', 10 => 'vbs', 11 => 'html', 12 => 'htm', ), 'upload_dir' => 'upload/', 'upload_maxsize' => 120000000, 'use_common_ml_dir' => false, 'use_real_names' => true, 'vcal_time' => '2', 'verify_client_ip' => true, 'email_xss' => 'YToxMzp7czo2OiJhcHBsZXQiO3M6NjoiYXBwbGV0IjtzOjQ6ImJhc2UiO3M6NDoiYmFzZSI7czo1OiJlbWJlZCI7czo1OiJlbWJlZCI7czo0OiJmb3JtIjtzOjQ6ImZvcm0iO3M6NToiZnJhbWUiO3M6NToiZnJhbWUiO3M6ODoiZnJhbWVzZXQiO3M6ODoiZnJhbWVzZXQiO3M6NjoiaWZyYW1lIjtzOjY6ImlmcmFtZSI7czo2OiJpbXBvcnQiO3M6ODoiXD9pbXBvcnQiO3M6NToibGF5ZXIiO3M6NToibGF5ZXIiO3M6NDoibGluayI7czo0OiJsaW5rIjtzOjY6Im9iamVjdCI7czo2OiJvYmplY3QiO3M6MzoieG1wIjtzOjM6InhtcCI7czo2OiJzY3JpcHQiO3M6Njoic2NyaXB0Ijt9', 'disabled_themes' => '', 'addAjaxBannedModules' => array ( 0 => 'Home', 1 => 'Tasks', 2 => 'Meetings', 3 => 'Notes', 4 => 'Leads', 5 => 'ProspectLists', 6 => 'Opportunities', 7 => 'Contacts', 8 => 'Bugs', 9 => 'Accounts', 10 => 'Cases', 11 => 'Prospects', 12 => 'Calls', ), );
harish-patel/rrd
config.php
PHP
agpl-3.0
9,128
<?php /** * Data class for happenings * * PHP version 5 * * @category Data * @package StatusNet * @author Evan Prodromou <evan@status.net> * @license http://www.fsf.org/licensing/licenses/agpl.html AGPLv3 * @link http://status.net/ * * StatusNet - the distributed open-source microblogging tool * Copyright (C) 2011, StatusNet, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ if (!defined('STATUSNET')) { exit(1); } /** * Data class for userpoints * * There's already an Event class in lib/event.php, so we couldn't * call this an Event without causing a hole in space-time. * * "UserPoints" seemed good enough. * * @category Event * @package StatusNet * @author Evan Prodromou <evan@status.net> * @license http://www.fsf.org/licensing/licenses/agpl.html AGPLv3 * @link http://status.net/ * * @see Managed_DataObject */ class UserPoints extends Managed_DataObject { const OBJECT_TYPE = 'http://activitystrea.ms/schema/1.0/event'; public $__table = 'user_points'; // table name public $profile_id; // int public $cumulative_points; public $available_points; public $points_index; public $nickname; /** * Get an instance by key * * @param string $k Key to use to lookup (usually 'id' for this class) * @param mixed $v Value to lookup * * @return Happening object found, or null for no hits * */ function staticGet($k, $v=null) { return Memcached_DataObject::staticGet('UserPoints', $k, $v); } /** * The One True Thingy that must be defined and declared. */ public static function schemaDef() { return array( 'description' => 'A real-world happening', 'fields' => array( 'profile_id' => array('type' => 'int', 'not null' => true), 'nickname' => array('type' => 'varchar', 'length' => 64), 'cumulative_points' => array('type' => 'int', 'not null' => true), 'available_points' => array('type' => 'int', 'not null' => true), 'points_index' => array('type' => 'int', 'not null' => true), ), 'primary key' => array('profile_id'), ); } static function getPoints($profile_id) { return UserPoints::staticGet('profile_id', $profile_id); } }
gayathri6/stepstream_salute
plugins/Event/UserPoints.php
PHP
agpl-3.0
3,036
<?php /********************************************************************************* * Zurmo is a customer relationship management program developed by * Zurmo, Inc. Copyright (C) 2013 Zurmo Inc. * * Zurmo is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * Zurmo is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive * Suite 370 Chicago, IL 60606. or at email address contact@zurmo.com. * * The interactive user interfaces in original and modified versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the Zurmo * logo and Zurmo copyright notice. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display the words * "Copyright Zurmo Inc. 2013. All rights reserved". ********************************************************************************/ /** * Model for storing currency attribute values on other models. */ class CurrencyValue extends OwnedModel { protected function constructDerived($bean, $setDefaults) { assert('$bean === null || $bean instanceof RedBean_OODBBean'); assert('is_bool($setDefaults)'); parent::constructDerived($bean, $setDefaults); if ($bean === null && $setDefaults) { $currentUser = Yii::app()->user->userModel; if (!$currentUser instanceof User) { throw new NoCurrentUserSecurityException(); } $this->currency = Yii::app()->currencyHelper->getActiveCurrencyForCurrentUser(); } } public function __toString() { if (trim($this->value) == '') { return Zurmo::t('Core', '(None)'); } return strval($this->value); } public static function getDefaultMetadata() { $metadata = parent::getDefaultMetadata(); $metadata[__CLASS__] = array( 'members' => array( 'rateToBase', 'value', ), 'relations' => array( 'currency' => array(static::HAS_ONE, 'Currency'), ), 'rules' => array( array('currency', 'required'), array('rateToBase', 'required'), array('rateToBase', 'type', 'type' => 'float'), array('value', 'required'), array('value', 'type', 'type' => 'float'), array('value', 'default', 'value' => 0), array('value', 'numerical', 'min' => 0, 'on' => 'positiveValue'), ), 'defaultSortAttribute' => 'value' ); return $metadata; } public static function isTypeDeletable() { return true; } /** * Given an id of a currency model, determine if any currency values are using this currency. * @return true if at least one currency value model is using this currency. * @param integer $currencyId */ public static function isCurrencyInUseById($currencyId) { assert('is_int($currencyId)'); $columnName = static::getForeignKeyName('CurrencyValue', 'currency'); $quote = DatabaseCompatibilityUtil::getQuote(); $where = "{$quote}{$columnName}{$quote} = '{$currencyId}'"; $count = CurrencyValue::getCount(null, $where); if ($count > 0) { return true; } return false; } /** * Get the rateToBase from the currency model. If the scenario is importModel, then having a rateToBase * manually set is ok. * @return true to signal success and that validate can proceed. */ public function beforeValidate() { if (!parent::beforeValidate()) { return false; } if ($this->currency->rateToBase !== null && ($this->rateToBase === null || array_key_exists('value', $this->originalAttributeValues) || array_key_exists('currency', $this->originalAttributeValues)) && !($this->getScenario() == 'importModel' && $this->rateToBase != null)) { $this->rateToBase = $this->currency->rateToBase; assert('$this->rateToBase !== null'); } return true; } protected static function translatedAttributeLabels($language) { return array_merge(parent::translatedAttributeLabels($language), array( 'currency' => Zurmo::t('ZurmoModule', 'Currency', array(), null, $language), 'rateToBase' => Zurmo::t('ZurmoModule', 'Rate To Base', array(), null, $language), 'value' => Zurmo::t('Core', 'Value', array(), null, $language), ) ); } } ?>
jhuymaier/zurmo
app/protected/modules/zurmo/models/CurrencyValue.php
PHP
agpl-3.0
6,523
/* * Copyright (C) 2015 DECOIT GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.decoit.siemgui.domain.rules; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * * @author Thomas Rix (rix@decoit.de) */ @Getter @Setter @EqualsAndHashCode @ToString @JsonIgnoreProperties(ignoreUnknown = true) public class CorrelationRule { private long entityId; private long dtoId; private String name; private String description; private CorrelationRuleCondition condition; private CorrelationRuleAction action; }
decoit/siem-gui-imonitor
src/main/java/de/decoit/siemgui/domain/rules/CorrelationRule.java
Java
agpl-3.0
1,269
(function () { 'use strict'; var WindowSize = Class.create({ width: function() { var myWidth = 0; if (typeof(window.innerWidth) == 'number') { //Non-IE myWidth = window.innerWidth; } else if (document.documentElement && document.documentElement.clientWidth) { //IE 6+ in 'standards compliant mode' myWidth = document.documentElement.clientWidth; } else if (document.body && document.body.clientWidth) { //IE 4 compatible myWidth = document.body.clientWidth; } return myWidth; }, height: function() { var myHeight = 0; if (typeof(window.innerHeight) == 'number') { //Non-IE myHeight = window.innerHeight; } else if (document.documentElement && document.documentElement.clientHeight) { //IE 6+ in 'standards compliant mode' myHeight = document.documentElement.clientHeight; } else if (document.body && document.body.clientHeight) { //IE 4 compatible myHeight = document.body.clientHeight; } return myHeight; }, scrollTop: function (){ return document.viewport.getScrollOffsets()['top']; } }); var dateTimePicker = function (element, options){ var picker = {}, date, viewDate, unset = true, input, component = false, widget = false, use24Hours, minViewModeNumber = 0, actualFormat, parseFormats, currentViewMode, datePickerModes = [ { clsName: 'days', navFnc: 'M', navStep: 1 }, { clsName: 'months', navFnc: 'y', navStep: 1 }, { clsName: 'years', navFnc: 'y', navStep: 10 }, { clsName: 'decades', navFnc: 'y', navStep: 100 } ], viewModes = ['days', 'months', 'years', 'decades'], verticalModes = ['top', 'bottom', 'auto'], horizontalModes = ['left', 'right', 'auto'], toolbarPlacements = ['default', 'top', 'bottom'], keyMap = { 'up': 38, 38: 'up', 'down': 40, 40: 'down', 'left': 37, 37: 'left', 'right': 39, 39: 'right', 'tab': 9, 9: 'tab', 'escape': 27, 27: 'escape', 'enter': 13, 13: 'enter', 'pageUp': 33, 33: 'pageUp', 'pageDown': 34, 34: 'pageDown', 'shift': 16, 16: 'shift', 'control': 17, 17: 'control', 'space': 32, 32: 'space', 't': 84, 84: 't', 'delete': 46, 46: 'delete' }, keyState = {}, /******************************************************************************** * * Private functions * ********************************************************************************/ hasTimeZone = function () { return moment.tz !== undefined && options.timeZone !== undefined && options.timeZone !== null && options.timeZone !== ''; }, getMoment = function (d) { var returnMoment; if (d === undefined || d === null) { returnMoment = moment(); //TODO should this use format? and locale? } else if (moment.isDate(d) || moment.isMoment(d)) { // If the date that is passed in is already a Date() or moment() object, // pass it directly to moment. returnMoment = moment(d); } else if (hasTimeZone()) { // There is a string to parse and a default time zone // parse with the tz function which takes a default time zone if it is not in the format string returnMoment = moment.tz(d, parseFormats, options.useStrict, options.timeZone); } else { returnMoment = moment(d, parseFormats, options.useStrict); } if (hasTimeZone()) { returnMoment.tz(options.timeZone); } return returnMoment; }, isEnabled = function (granularity) { if (typeof granularity !== 'string' || granularity.length > 1) { throw new TypeError('isEnabled expects a single character string parameter'); } switch (granularity) { case 'y': return actualFormat.indexOf('Y') !== -1; case 'M': return actualFormat.indexOf('M') !== -1; case 'd': return actualFormat.toLowerCase().indexOf('d') !== -1; case 'h': case 'H': return actualFormat.toLowerCase().indexOf('h') !== -1; case 'm': return actualFormat.indexOf('m') !== -1; case 's': return actualFormat.indexOf('s') !== -1; default: return false; } }, hasTime = function () { return (isEnabled('h') || isEnabled('m') || isEnabled('s')); }, hasDate = function () { return (isEnabled('y') || isEnabled('M') || isEnabled('d')); }, getDatePickerTemplate = function () { var headTemplate = [ '<thead>', '<tr>', '<th class="prev" data-action="previous">', '<span class="'+options.icons.previous+'"/>', '</th>', '<th class="picker-switch" data-action="pickerSwitch" colspan="'+(options.calendarWeeks?'6':'5')+'"></th>', '<th class="next" data-action="next">', '<span class="'+options.icons.next+'"/>', '</th>', '</tr>', '</thead>' ].join(''), contTemplate = [ '<tbody>', '<tr>', '<td colspan="'+(options.calendarWeeks?'8':'7')+'"/>', '</tr>', '<tbody>' ].join(''); return [ new Element('div', {className:'datepicker-days'}).update([ '<table class="table-condensed">', headTemplate, '<tbody/>', '</table>' ].join('')), new Element('div', {className:'datepicker-months'}).update([ '<table class="table-condensed">', headTemplate, contTemplate, '</table>' ].join('')), new Element('div', {className:'datepicker-years'}).update([ '<table class="table-condensed">', headTemplate, contTemplate, '</table>' ].join('')), new Element('div', {className:'datepicker-decades'}).update([ '<table class="table-condensed">', headTemplate, contTemplate, '</table>' ].join('')) ]; }, getTimePickerMainTemplate = function (){ var topRow = ['<tr>'], middleRow = ['<tr>'], bottomRow = ['<tr>']; if (isEnabled('h')) { topRow.splice(topRow.length, 0, '<td>', '<a class="btn" href="#" tabindex="-1" title="'+options.tooltips.incrementHour+'" data-action="incrementHours">', '<span class="'+options.icons.up+'"/>', '</a>', '</td>'); middleRow.splice(middleRow.length, 0, '<td>', '<span class="timepicker-hour" data-time-component="hours" title="'+options.tooltips.pickHour+'" data-action="showHours"/>', '</td>'); bottomRow.splice(bottomRow.length, 0, '<td>', '<a class="btn" href="#" tab-index="-1" title="'+options.tooltips.decrementHour+'" data-action="decrementHours"/>', '<span class="'+options.icons.down+'"/>', '</a>', '</td>'); } if (isEnabled('m')) { if (isEnabled('h')) { topRow.push('<td class="separator"></td>'); middleRow.push('<td class="separator">:</td>'); bottomRow.push('<td class="separator"></td>'); } topRow.splice(topRow.length, 0, '<td>', '<a class="btn" href="#" tabindex="-1" title="'+options.tooltips.incrementMinute+'" data-action="incrementMinutes">', '<span class="'+options.icons.up+'"/>', '</a>', '</td>'); middleRow.splice(middleRow.length, 0, '<td>', '<span class="timepicker-minute" data-time-component="minute" title="'+options.tooltips.pickMinute+'" data-action="showMinutes"/>', '</td>'); bottomRow.splice(bottomRow.length, 0, '<td>', '<a class="btn" href="#" tab-index="-1" title="'+options.tooltips.decrementMinute+'" data-action="decrementMinutes"/>', '<span class="'+options.icons.down+'"/>', '</a>', '</td>'); } if (isEnabled('s')) { if (isEnabled('m')) { topRow.push('<td class="separator"></td>'); middleRow.push('<td class="separator">:</td>'); bottomRow.push('<td class="separator"></td>'); } topRow.splice(topRow.length, 0, '<td>', '<a class="btn" href="#" tabindex="-1" title="'+options.tooltips.incrementSecond+'" data-action="incrementSeconds">', '<span class="'+options.icons.up+'"/>', '</a>', '</td>'); middleRow.splice(middleRow.length, 0, '<td>', '<span class="timepicker-second" data-time-component="seconds" title="'+options.tooltips.pickSecond+'" data-action="showSeconds"/>', '</td>'); bottomRow.splice(bottomRow.length, 0, '<td>', '<a class="btn" href="#" tab-index="-1" title="'+options.tooltips.decrementSecond+'" data-action="decrementSeconds"/>', '<span class="'+options.icons.down+'"/>', '</a>', '</td>'); } if (!use24Hours){ topRow.push('<td class="separator"/>'); middleRow.splice(middleRow.length, 0, '<td>', '<button class="btn btn-primary" data-action="togglePeriod" tabindex="-1"', ' title="'+options.tooltips.togglePeriod+'"/>', '</td>'); bottomRow.push('<td class="separator"/>'); } topRow.push('</tr>') middleRow.push('</tr>') bottomRow.push('</tr>') var content = [ '<table class="table-condensed">', topRow.join(''), middleRow.join(''), bottomRow.join(''), '</table>' ].join(''); return new Element('div', {className:'timepicker-picker'}).update(content); }, getTimePickerTemplate = function () { var hoursView = new Element('div', {className:'timepicker-hours'}).update('<table class="table-condensed"></table>'), minutesView = new Element('div', {className:'timepicker-minutes'}).update('<table class="table-condensed"></table>'), secondsView = new Element('div', {className:'timepicker-seconds'}).update('<table class="table-condensed"></table>'), ret = [getTimePickerMainTemplate()]; if (isEnabled('h')) { ret.push(hoursView); } if (isEnabled('m')) { ret.push(minutesView); } if (isEnabled('s')) { ret.push(secondsView); } return ret; }, getToolbar = function () { var row = ['<tbody><tr>']; if (options.showTodayButton) { row.splice(row.length, 0, '<td>', '<a data-action="today" title="'+options.tooltips.today+'">', '<span class="'+options.icons.today+'"/>', '</a>', '</td>' ); } if (!options.sideBySide && hasDate() && hasTime()){ row.splice(row.length, 0, '<td>', '<a data-action="togglePicker" title="'+options.tooltips.selectTime+'">', '<span class="'+options.icons.time+'"/>', '</a>', '</td>' ); } if (options.showClear) { row.splice(row.length, 0, '<td>', '<a data-action="clear" title="'+options.tooltips.clear+'">', '<span class="'+options.icons.clear+'"/>', '</a>', '</td>' ); } if (options.showClose) { row.splice(row.length, 0, '<td>', '<a data-action="close" title="'+options.tooltips.close+'">', '<span class="'+options.icons.close+'"/>', '</a>', '</td>' ); } row.push('</tr></tbody>') return new Element('table', { className: 'table-condensed' }).update(row.join('')); }, getTemplate = function () { var template = new Element('div', {className: 'bootstrap-datetimepicker-widget dropdown-menu'}), dateView = new Element('div', {className: 'datepicker'}), timeView = new Element('div', {className: 'timepicker'}), content = new Element('ul', {className: 'list-unstyled'}), toolbar = new Element('li', {className: 'picker-switch' + (options.collapse ? ' accordion-toggle' : '')}).update(getToolbar()); $A(getDatePickerTemplate()).each(function(el){ dateView.insert(el); }); $A(getTimePickerTemplate()).each(function(el){ timeView.insert(el); }); if (options.inline) { template.removeClassName('dropdown-menu'); } if (use24Hours) { template.addClassName('usetwentyfour'); } if (isEnabled('s') && !use24Hours) { template.addClassName('wider'); } if (options.sideBySide && hasDate() && hasTime()){ template.addClassName('timepicker-sbs'); if (options.toolbarPlacement === 'top') { template.insert(toolbar); } template.insert( new Element('div', {className:'row'}) .insert(dateView.addClassName('col-md-6')) .insert(timeView.addClassName('col-md-6')) ); if (options.toolbarPlacement === 'bottom'){ template.insert(toolbar); } return template; } if (options.toolbarPlacement === 'top'){ content.insert(toolbar); } if (hasDate()){ content.insert(new Element('li', {className: (options.collapse && hasTime() ? 'collapse in' : '')}).update(dateView)); } if (options.toolbarPlacement === 'default'){ content.insert(toolbar); } if (hasTime()){ content.insert(new Element('li', {className: (options.collapse && hasDate() ? 'collapse' : '')}).update(timeView)); } if (options.toolbarPlacement === 'bottom'){ content.insert(toolbar); } return template.insert(content); }, dataToOptions = function(){ var dateOptions, dataOptions = {}; if (element.match('input') || options.inline) { dateOptions = element.retrieve('dateoptions'); } else { dateOptions = element.select('input').first().retrieve('dateoptions'); } if (dateOptions && dateOptions instanceof Object) { dataOptions = Object.extend(dataOptions, dateOptions); } $A(options).each(function (key){ var attributeName = 'date' + key.charAt(0).toUpperCase() + key.slice(1); if (dateOptions[attributeName] !== undefined) { dataOptions[key] = dateOptions[attributeName]; } }); return dataOptions; }, hasFocus = function (elem){ return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, falseFn = function (e){ e.stop(); return false; }, place = function () { var eLayout = (component || element).getLayout(true), position = { top: eLayout.get('top'), left: eLayout.get('left') }, offset = (component || element).cumulativeOffset(), vertical = options.widgetPositioning.vertical, horizontal = options.widgetPositioning.horizontal, parent; /*if (options.widgetParent) { parent = options.widgetParent.insert(widget); } else if (element.match('input')) { parent = element.insert({after: widget}).up(); } else if (options.inline) { parent = element.insert(widget); return; } else { parent = element; element.childElements().first().insert({after: widget}); }*/ component.insert(widget); parent = component; var windowSize = new WindowSize(); var wLayout = widget.getLayout(true); var eOuterHeight = eLayout.get('height') + eLayout.get('border-box-height'); var eOuterWidth = eLayout.get('width') + eLayout.get('border-box-width'); // Top and bottom logic if (vertical === 'auto'){ if (offset.top + wLayout.get('height') * 1.5 >= windowSize.height() + windowSize.scrollTop() && wLayout.get('height') + eOuterHeight < offset.top){ vertical = 'top'; } else { vertical = 'bottom'; } } var pLayout = parent.getLayout(true); var pOuterHeight = pLayout.get('height') + pLayout.get('border-box-height'); var pOuterWidth = pLayout.get('width') + pLayout.get('border-box-width'); // Left and right logic if (horizontal === 'auto'){ var outerWidth = wLayout.get('width') + wLayout.get('border-box-width'); if (pLayout.get('width') < offset.left + outerWidth / 2 && offset.left + outerWidth > windowSize.width()){ horizontal = 'right'; } else { horizontal = 'left'; } } widget.addClassName('bottom'); /*if (vertical === 'top') { widget.addClassName('top').removeClassName('bottom'); } else { widget.addClassName('bottom').removeClassName('top'); }*/ widget.removeClassName('pull-right'); /* if (horizontal === 'right') { widget.addClassName('pull-right'); } else { widget.removeClassName('pull-right'); }*/ // find the first parent element that has a non-static css positioning if (parent.getStyle('position') === 'static'){ parent = parent.ancestors().filter(function (it) { return $(it).getStyle('position') !== 'static'; }).first(); } if (!parent) { throw new Error('datetimepicker component should be placed within a non-static positioned container'); } var parentsZindex = [0]; widget.ancestors().each(function(a){ var itemZIndex = $(a).getStyle('z-index'); if (itemZIndex !== 'auto' && Number(itemZIndex) !== 0) parentsZindex.push(Number(itemZIndex)); }); var zIndex = Math.max.apply(Math, parentsZindex) + 10; //console.log([vertical, horizontal, position, eOuterHeight, pOuterHeight, pOuterWidth]); /*ToDo: Correct this to properly calculate positioning var style = { top: vertical === 'top' ? 'auto' : (position.top + eOuterHeight)+'px', bottom: vertical === 'top' ? (pOuterHeight - (parent === element ? 0 : position.top))+'px' : 'auto', left: horizontal === 'left' ? (parent === element ? 0 : position.left)+'px' : 'auto', right: horizontal === 'left' ? 'auto' : (pOuterWidth - eOuterWidth - (parent === element ? 0 : position.left))+'px', zIndex: zIndex };*/ var style = { top: '26px', left: 0, right: 'auto', bottom: 'auto', zIndex: zIndex }; //console.log(style); widget.setStyle(style); }, notifyEvent = function (e) { if (e.type === 'dp:change' && ((e.date && e.date.isSame(e.oldDate)) || (!e.date && !e.oldDate))) { return; } element.fire(e.type, e); }, viewUpdate = function (e) { if (e === 'y') { e = 'YYYY'; } notifyEvent({ type: 'dp:update', change: e, viewDate: viewDate.clone() }); }, showMode = function (dir) { if (!widget) { return; } if (dir){ currentViewMode = Math.max(minViewModeNumber, Math.min(3, currentViewMode + dir)); } widget.select('.datepicker > div').each(function(el){ el.hide(); if (el.match('.datepicker-' + datePickerModes[currentViewMode].clsName)){ el.setStyle({display: 'block'}); } }); }, fillDow = function () { var row = new Element('tr'), currentDate = viewDate.clone().startOf('w').startOf('d'); if (options.calendarWeeks === true) { row.insert(new Element('th', {className: 'cw'}).update('#')); } while (currentDate.isBefore(viewDate.clone().endOf('w'))) { row.insert(new Element('th', {className: 'dow'}).update(currentDate.format('dd'))); currentDate.add(1, 'd'); } widget.select('.datepicker-days thead').first().insert(row); }, isInDisabledDates = function (testDate) { return options.disabledDates[testDate.format('YYYY-MM-DD')] === true; }, isInEnabledDates = function (testDate) { return options.enabledDates[testDate.format('YYYY-MM-DD')] === true; }, isInDisabledHours = function (testDate) { return options.disabledHours[testDate.format('H')] === true; }, isInEnabledHours = function (testDate) { return options.enabledHours[testDate.format('H')] === true; }, isValid = function (targetMoment, granularity) { if (!targetMoment.isValid()) { return false; } if (options.disabledDates && granularity === 'd' && isInDisabledDates(targetMoment)) { return false; } if (options.enabledDates && granularity === 'd' && !isInEnabledDates(targetMoment)) { return false; } if (options.minDate && targetMoment.isBefore(options.minDate, granularity)) { return false; } if (options.maxDate && targetMoment.isAfter(options.maxDate, granularity)) { return false; } if (options.daysOfWeekDisabled && granularity === 'd' && options.daysOfWeekDisabled.indexOf(targetMoment.day()) !== -1) { return false; } if (options.disabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && isInDisabledHours(targetMoment)) { return false; } if (options.enabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && !isInEnabledHours(targetMoment)) { return false; } if (options.disabledTimeIntervals && (granularity === 'h' || granularity === 'm' || granularity === 's')) { var found = false; $A(options.disabledTimeIntervals).each(function (it) { if (targetMoment.isBetween(it[0], it[1])) { found = true; return false; } }); if (found) { return false; } } return true; }, fillMonths = function () { var spans = [], monthsShort = viewDate.clone().startOf('y').startOf('d'), tdMonths = widget.select('.datepicker-months td').first(); tdMonths.update(''); while (monthsShort.isSame(viewDate, 'y')) { //spans.push($('<span>').attr('data-action', 'selectMonth').addClassName('month').text(monthsShort.format('MMM'))); tdMonths.insert(new Element('span', {'data-action':'selectMonth', className: 'month'}).update(monthsShort.format('MMM'))); monthsShort.add(1, 'M'); } //widget.find('.datepicker-months td').empty().append(spans); }, updateMonths = function () { var monthsView = widget.select('.datepicker-months').first(), monthsViewHeader = monthsView.select('th'), months = monthsView.select('tbody').first().select('span'); var mvh0 = Prototype.Selector.find(monthsViewHeader, 'th', 0); if (mvh0 && mvh0.down('span')) mvh0.down('span').writeAttribute('title', options.tooltips.prevYear); var mvh1 = Prototype.Selector.find(monthsViewHeader, 'th', 1); if (mvh1 && mvh1.down('span')) mvh1.down('span').writeAttribute('title', options.tooltips.selectYear); var mvh2 = Prototype.Selector.find(monthsViewHeader, 'th', 2); if (mvh2 && mvh2.down('span')) mvh2.down('span').writeAttribute('title', options.tooltips.nextYear); monthsView.select('.disabled').each(function(el){el.removeClassName('disabled');}); if (!isValid(viewDate.clone().subtract(1, 'y'), 'y')) { mvh0.addClassName('disabled'); } mvh1.update(viewDate.year()); if (!isValid(viewDate.clone().add(1, 'y'), 'y')) { mvh2.addClassName('disabled'); } months.each(function (el){el.removeClassName('active');}); if (date.isSame(viewDate, 'y') && !unset) { Prototype.Selector.find(months, 'span', date.month()).addClassName('active'); } months.each(function (month, index) { if (!isValid(viewDate.clone().month(index), 'M')) { month.addClassName('disabled'); } }); }, updateYears = function () { var yearsView = widget.select('.datepicker-years').first(), yearsViewHeader = yearsView.select('th'), startYear = viewDate.clone().subtract(5, 'y'), endYear = viewDate.clone().add(6, 'y'), html = ''; var yvh0 = Prototype.Selector.find(yearsViewHeader, 'th', 0); if (yvh0 && yvh0.down('span')) yvh0.down('span').writeAttribute('title', options.tooltips.prevDecade); var yvh1 = Prototype.Selector.find(yearsViewHeader, 'th', 1); if (yvh1 && yvh1.down('span')) yvh1.down('span').writeAttribute('title', options.tooltips.selectDecade); var yvh2 = Prototype.Selector.find(yearsViewHeader, 'th', 2); if (yvh1 && yvh2.down('span')) yvh2.down('span').writeAttribute('title', options.tooltips.nextDecade); yearsView.select('.disabled').each(function(el){el.removeClassName('disabled');}); if (options.minDate && options.minDate.isAfter(startYear, 'y')) { yvh0.addClassName('disabled'); } yvh1.update(startYear.year() + '-' + endYear.year()); if (options.maxDate && options.maxDate.isBefore(endYear, 'y')) { yvh2.addClassName('disabled'); } while (!startYear.isAfter(endYear, 'y')) { html += '<span data-action="selectYear" class="year' + (startYear.isSame(date, 'y') && !unset ? ' active' : '') + (!isValid(startYear, 'y') ? ' disabled' : '') + '">' + startYear.year() + '</span>'; startYear.add(1, 'y'); } yearsView.select('td').each(function(td){ td.update(html);}); }, updateDecades = function () { var decadesView = widget.select('.datepicker-decades').first(), decadesViewHeader = decadesView.select('th'), startDecade = moment({ y: viewDate.year() - (viewDate.year() % 100) - 1 }), endDecade = startDecade.clone().add(100, 'y'), startedAt = startDecade.clone(), minDateDecade = false, maxDateDecade = false, endDecadeYear, html = ''; var dvh0 = Prototype.Selector.find(decadesViewHeader, 'th', 0); if (dvh0 && dvh0.down('span')) dvh0.down('span').writeAttribute('title', options.tooltips.prevCentury); var dvh1 = Prototype.Selector.find(decadesViewHeader, 'th', 1); var dvh2 = Prototype.Selector.find(decadesViewHeader, 'th', 2); if (dvh2 && dvh2.down('span')) dvh2.down('span').writeAttribute('title', options.tooltips.nextCentury); decadesView.select('.disabled').each(function(el){el.removeClassName('disabled');}); if (startDecade.isSame(moment({ y: 1900 })) || (options.minDate && options.minDate.isAfter(startDecade, 'y'))) { dvh0.addClassName('disabled'); } dvh1.update(startDecade.year() + '-' + endDecade.year()); if (startDecade.isSame(moment({ y: 2000 })) || (options.maxDate && options.maxDate.isBefore(endDecade, 'y'))) { dvh2.addClassName('disabled'); } while (!startDecade.isAfter(endDecade, 'y')) { endDecadeYear = startDecade.year() + 12; minDateDecade = options.minDate && options.minDate.isAfter(startDecade, 'y') && options.minDate.year() <= endDecadeYear; maxDateDecade = options.maxDate && options.maxDate.isAfter(startDecade, 'y') && options.maxDate.year() <= endDecadeYear; html += '<span data-action="selectDecade" class="decade' + (date.isAfter(startDecade) && date.year() <= endDecadeYear ? ' active' : '') + (!isValid(startDecade, 'y') && !minDateDecade && !maxDateDecade ? ' disabled' : '') + '" data-selection="' + (startDecade.year() + 6) + '">' + (startDecade.year() + 1) + ' - ' + (startDecade.year() + 12) + '</span>'; startDecade.add(12, 'y'); } html += '<span></span><span></span><span></span>'; //push the dangling block over, at least this way it's even decadesView.select('td').each(function(td){td.update(html);}); dvh1.update((startedAt.year() + 1) + '-' + (startDecade.year())); }, fillDate = function () { var daysView = widget.select('.datepicker-days').first(), daysViewHeader = daysView.select('th'), currentDate, html = [], row, clsNames = [], i; if (!hasDate()) { return; } var dvh0 = Prototype.Selector.find(daysViewHeader, 'th', 0); if (dvh0 && dvh0.down('span')) dvh0.down('span').writeAttribute('title', options.tooltips.prevMonth); var dvh1 = Prototype.Selector.find(daysViewHeader, 'th', 1); if (dvh1 && dvh1.down('span')) dvh1.down('span').writeAttribute('title', options.tooltips.selectMonth); var dvh2 = Prototype.Selector.find(daysViewHeader, 'th', 2); if (dvh2 && dvh2.down('span')) dvh2.down('span').writeAttribute('title', options.tooltips.nextMonth); daysView.select('.disabled').each(function(el) { el.removeClassName('disabled');}); dvh1.update(viewDate.format(options.dayViewHeaderFormat)); if (!isValid(viewDate.clone().subtract(1, 'M'), 'M')) { dvh0.addClassName('disabled'); } if (!isValid(viewDate.clone().add(1, 'M'), 'M')) { dvh2.addClassName('disabled'); } currentDate = viewDate.clone().startOf('M').startOf('w').startOf('d'); for (i = 0; i < 42; i++) { //always display 42 days (should show 6 weeks) if (currentDate.weekday() === 0) { row = new Element('tr'); if (options.calendarWeeks) { row.insert('<td class="cw">' + currentDate.week() + '</td>'); } html.push(row); } clsNames = ['day']; if (currentDate.isBefore(viewDate, 'M')) { clsNames.push('old'); } if (currentDate.isAfter(viewDate, 'M')) { clsNames.push('new'); } if (currentDate.isSame(date, 'd') && !unset) { clsNames.push('active'); } if (!isValid(currentDate, 'd')) { clsNames.push('disabled'); } if (currentDate.isSame(getMoment(), 'd')) { clsNames.push('today'); } if (currentDate.day() === 0 || currentDate.day() === 6) { clsNames.push('weekend'); } notifyEvent({ type: 'dp:classify', date: currentDate, classNames: clsNames }); row.insert('<td data-action="selectDay" data-day="' + currentDate.format('L') + '" class="' + clsNames.join(' ') + '">' + currentDate.date() + '</td>'); currentDate.add(1, 'd'); } var tbody = daysView.select('tbody').first().update(''); $A(html).each(function (it){ tbody.insert(it); }) updateMonths(); updateYears(); updateDecades(); }, fillHours = function () { var table = widget.select('.timepicker-hours table').first(), currentHour = viewDate.clone().startOf('d'), html = [], row = new Element('tr'); if (viewDate.hour() > 11 && !use24Hours) { currentHour.hour(12); } while (currentHour.isSame(viewDate, 'd') && (use24Hours || (viewDate.hour() < 12 && currentHour.hour() < 12) || viewDate.hour() > 11)) { if (currentHour.hour() % 4 === 0) { row = new Element('tr'); html.push(row); } row.insert('<td data-action="selectHour" class="hour' + (!isValid(currentHour, 'h') ? ' disabled' : '') + '">' + currentHour.format(use24Hours ? 'HH' : 'hh') + '</td>'); currentHour.add(1, 'h'); } table.update(''); $A(html).each(function (r){table.insert(r);}); }, fillMinutes = function () { var table = widget.select('.timepicker-minutes table').first(), currentMinute = viewDate.clone().startOf('h'), html = [], row = new Element('tr'), step = options.stepping === 1 ? 5 : options.stepping; while (viewDate.isSame(currentMinute, 'h')) { if (currentMinute.minute() % (step * 4) === 0) { row = new Element('tr'); html.push(row); } row.insert('<td data-action="selectMinute" class="minute' + (!isValid(currentMinute, 'm') ? ' disabled' : '') + '">' + currentMinute.format('mm') + '</td>'); currentMinute.add(step, 'm'); } table.update(''); $A(html).each(function(r){table.insert(r);}); }, fillSeconds = function () { var table = widget.select('.timepicker-seconds table').first(), currentSecond = viewDate.clone().startOf('m'), html = [], row = new Element('tr'); if (!table) return; while (viewDate.isSame(currentSecond, 'm')) { if (currentSecond.second() % 20 === 0) { row = new Element('tr'); html.push(row); } row.insert('<td data-action="selectSecond" class="second' + (!isValid(currentSecond, 's') ? ' disabled' : '') + '">' + currentSecond.format('ss') + '</td>'); currentSecond.add(5, 's'); } table.update(''); $A(html).each(function(r){table.insert(r);}); }, fillTime = function () { var toggle, newDate, timeComponents = widget.select('.timepicker span[data-time-component]'); if (!use24Hours) { toggle = widget.select('.timepicker [data-action=togglePeriod]').first(); newDate = date.clone().add((date.hours() >= 12) ? -12 : 12, 'h'); toggle.update(date.format('A')); if (isValid(newDate, 'h')) { toggle.removeClassName('disabled'); } else { toggle.addClassName('disabled'); } } timeComponents.each(function(tc){ if (tc.match('[data-time-component=hours]')){ tc.update(date.format(use24Hours ? 'HH' : 'hh')); } if (tc.match('[data-time-component=minute]')){ tc.update(date.format('mm')); } if (tc.match('[data-time-component=seconds]')){ tc.update(date.format(date.format('ss'))); } }) if (isEnabled('h')) fillHours(); if (isEnabled('m')) fillMinutes(); if (isEnabled('s')) fillSeconds(); }, update = function () { if (!widget) { return; } fillDate(); fillTime(); }, setValue = function (targetMoment) { var oldDate = unset ? null : date; // case of calling setValue(null or false) if (!targetMoment) { unset = true; input.setValue(''); input.store(date, ''); element.store('date', ''); notifyEvent({ type: 'dp:change', date: false, oldDate: oldDate }); update(); return; } targetMoment = targetMoment.clone().locale(options.locale); if (hasTimeZone()) { targetMoment.tz(options.timeZone); } if (options.stepping !== 1) { targetMoment.minutes((Math.round(targetMoment.minutes() / options.stepping) * options.stepping)).seconds(0); while (options.minDate && targetMoment.isBefore(options.minDate)) { targetMoment.add(options.stepping, 'minutes'); } } if (isValid(targetMoment)) { date = targetMoment; viewDate = date.clone(); input.setValue(date.format(actualFormat)); element.store('date', date.format(actualFormat)); input.store('date', date.toISOString()); unset = false; update(); notifyEvent({ type: 'dp:change', date: date.clone(), oldDate: oldDate }); } else { if (!options.keepInvalid) { Form.Element.setValue(input, unset ? '' : date.format(actualFormat)); } else { notifyEvent({ type: 'dp:change', date: targetMoment, oldDate: oldDate }); } notifyEvent({ type: 'dp:error', date: targetMoment, oldDate: oldDate }); } }, /// // Hides the widget. Possibly will emit dp:hide // hide = function () { var transitioning = false; if (!widget) { return picker; } // Ignore event if in the middle of a picker transition widget.select('.collapse').each(function (it) { var collapseData = it.retrieve('collapse'); if (collapseData && collapseData.transitioning) { transitioning = true; return false; } return true; }); if (transitioning) { return picker; } if (component && component.hasClassName('btn')) { component.toggleClassName('active'); } widget.hide(); Event.stopObserving(window, 'resize', place); widget.stopObserving('click', doAction); widget.stopObserving('mousedown', falseFn); widget.remove(); widget = false; notifyEvent({ type: 'dp:hide', date: date.clone() }); input.blur(); viewDate = date.clone(); return picker; }, clear = function () { setValue(null); }, parseInputDate = function (inputDate) { if (options.parseInputDate === undefined) { if (!moment.isMoment(inputDate) || inputDate instanceof Date) { inputDate = getMoment(inputDate); } } else { inputDate = options.parseInputDate(inputDate); } //inputDate.locale(options.locale); return inputDate; }, /******************************************************************************** * * Widget UI interaction functions * ********************************************************************************/ actions = { next: function () { var navFnc = datePickerModes[currentViewMode].navFnc; viewDate.add(datePickerModes[currentViewMode].navStep, navFnc); fillDate(); viewUpdate(navFnc); }, previous: function () { var navFnc = datePickerModes[currentViewMode].navFnc; viewDate.subtract(datePickerModes[currentViewMode].navStep, navFnc); fillDate(); viewUpdate(navFnc); }, pickerSwitch: function () { showMode(1); }, selectMonth: function (e) { //var month = $(e.target).closest('tbody').find('span').index($(e.target)); var month = $(e.target).previousSiblings().size(); viewDate.month(month); if (currentViewMode === minViewModeNumber) { setValue(date.clone().year(viewDate.year()).month(viewDate.month())); if (!options.inline) { hide(); } } else { showMode(-1); fillDate(); } viewUpdate('M'); }, selectYear: function (e) { var year = parseInt($(e.target).innerText, 10) || 0; viewDate.year(year); if (currentViewMode === minViewModeNumber) { setValue(date.clone().year(viewDate.year())); if (!options.inline) { hide(); } } else { showMode(-1); fillDate(); } viewUpdate('YYYY'); }, selectDecade: function (e) { var year = parseInt($(e.target).readAttribute('data-selection'), 10) || 0; viewDate.year(year); if (currentViewMode === minViewModeNumber) { setValue(date.clone().year(viewDate.year())); if (!options.inline) { hide(); } } else { showMode(-1); fillDate(); } viewUpdate('YYYY'); }, selectDay: function (e) { var day = viewDate.clone(); if ($(e.target).match('.old')) { day.subtract(1, 'M'); } if ($(e.target).match('.new')) { day.add(1, 'M'); } setValue(day.date(parseInt($(e.target).innerText, 10))); if (!hasTime() && !options.keepOpen && !options.inline) { hide(); } }, incrementHours: function () { var newDate = date.clone().add(1, 'h'); if (isValid(newDate, 'h')) { setValue(newDate); } }, incrementMinutes: function () { var newDate = date.clone().add(options.stepping, 'm'); if (isValid(newDate, 'm')) { setValue(newDate); } }, incrementSeconds: function () { var newDate = date.clone().add(1, 's'); if (isValid(newDate, 's')) { setValue(newDate); } }, decrementHours: function () { var newDate = date.clone().subtract(1, 'h'); if (isValid(newDate, 'h')) { setValue(newDate); } }, decrementMinutes: function () { var newDate = date.clone().subtract(options.stepping, 'm'); if (isValid(newDate, 'm')) { setValue(newDate); } }, decrementSeconds: function () { var newDate = date.clone().subtract(1, 's'); if (isValid(newDate, 's')) { setValue(newDate); } }, togglePeriod: function () { setValue(date.clone().add((date.hours() >= 12) ? -12 : 12, 'h')); }, togglePicker: function (e) { var $this = $(e.target), $parent = $this.up('ul'), expanded = $parent.select('.in').first(), closed = $parent.select('.collapse:not(.in)').first(), collapseData; if (expanded) { collapseData = expanded.retrieve('collapse'); if (collapseData && collapseData.transitioning) { return; } expanded.removeClassName('in'); closed.addClassName('in'); if ($this.match('span')) { $this.toggleClassName(options.icons.time + ' ' + options.icons.date); } else { $this.down('span').toggleClassName(options.icons.time + ' ' + options.icons.date); } // NOTE: uncomment if toggled state will be restored in show() //if (component) { // component.find('span').toggleClass(options.icons.time + ' ' + options.icons.date); //} } }, showPicker: function () { widget.select('.timepicker > div:not(.timepicker-picker)').each(function(el){el.hide();}); widget.down('.timepicker .timepicker-picker').show(); }, showHours: function () { widget.down('.timepicker .timepicker-picker').hide(); widget.down('.timepicker .timepicker-hours').show(); }, showMinutes: function () { widget.down('.timepicker .timepicker-picker').hide(); widget.down('.timepicker .timepicker-minutes').show(); }, showSeconds: function () { widget.down('.timepicker .timepicker-picker').hide(); widget.down('.timepicker .timepicker-seconds').show(); }, selectHour: function (e) { var hour = parseInt($(e.target).innerText, 10); if (!use24Hours) { if (date.hours() >= 12) { if (hour !== 12) { hour += 12; } } else { if (hour === 12) { hour = 0; } } } setValue(date.clone().hours(hour)); actions.showPicker.call(picker); }, selectMinute: function (e) { setValue(date.clone().minutes(parseInt($(e.target).innerText, 10))); actions.showPicker.call(picker); }, selectSecond: function (e) { setValue(date.clone().seconds(parseInt($(e.target).innerText, 10))); actions.showPicker.call(picker); }, clear: clear, today: function () { var todaysDate = getMoment(); if (isValid(todaysDate, 'd')) { setValue(todaysDate); } }, close: hide }, doAction = function (e) { Event.stop(e); var actionEl = e.findElement('[data-action]'); if (!actionEl) return false; if ($(e.target).match('.disabled')){ return false; } actions[actionEl.readAttribute('data-action')].apply(picker, arguments); return false; }, /// // Shows the widget. Possibly will emit dp:show and dp:change /// show = function () { var currentMoment, useCurrentGranularity = { 'year': function (m) { return m.month(0).date(1).hours(0).seconds(0).minutes(0); }, 'month': function (m) { return m.date(1).hours(0).seconds(0).minutes(0); }, 'day': function (m) { return m.hours(0).seconds(0).minutes(0); }, 'hour': function (m) { return m.seconds(0).minutes(0); }, 'minute': function (m) { return m.seconds(0); } }; if (input.readAttribute('disabled') || (!options.ignoreReadonly && input.readAttribute('readonly')) || widget) { return picker; } var val = input.retrieve('date'); if (!val){ val = $F(input); val = moment(val.trim(), actualFormat); } else { val = moment(val.trim()); } if (val !== undefined) { //} && val.trim().length !== 0) { setValue(parseInputDate(val)); } else if (unset && options.useCurrent && (options.inline || (input.match('input') && val.trim().length === 0))) { currentMoment = getMoment(); if (typeof options.useCurrent === 'string') { currentMoment = useCurrentGranularity[options.useCurrent](currentMoment); } setValue(currentMoment); } widget = getTemplate(); fillDow(); fillMonths(); widget.down('.timepicker-hours') && widget.down('.timepicker-hours').hide(); widget.down('.timepicker-minutes') && widget.down('.timepicker-minutes').hide(); widget.down('.timepicker-seconds') && widget.down('.timepicker-seconds').hide(); //ToDo: Enable this when safe update(); showMode(); Event.observe(window, 'resize', place); widget.observe('click', doAction); // this handles clicks on the widget widget.observe('mousedown', falseFn); if (component && component.hasClassName('btn')) { component.toggleClassName('active'); } place(); if (options.focusOnShow && !hasFocus(input)) { //return elem === document.activeElement && ( elem.type || elem.href ); input.focus(); } notifyEvent({ type: 'dp:show' }); return picker; }, /// // Shows or hides the widget /// toggle = function () { if (input.match('[disabled]')) return; return (widget ? hide() : show()); }, keydown = function (e) { var handler = null, index, index2, pressedKeys = [], pressedModifiers = {}, currentKey = e.which, keyBindKeys, allModifiersPressed, pressed = 'p'; keyState[currentKey] = pressed; for (index in keyState) { if (keyState.hasOwnProperty(index) && keyState[index] === pressed) { pressedKeys.push(index); if (parseInt(index, 10) !== currentKey) { pressedModifiers[index] = true; } } } for (index in options.keyBinds) { if (options.keyBinds.hasOwnProperty(index) && typeof (options.keyBinds[index]) === 'function') { keyBindKeys = index.split(' '); if (keyBindKeys.length === pressedKeys.length && keyMap[currentKey] === keyBindKeys[keyBindKeys.length - 1]) { allModifiersPressed = true; for (index2 = keyBindKeys.length - 2; index2 >= 0; index2--) { if (!(keyMap[keyBindKeys[index2]] in pressedModifiers)) { allModifiersPressed = false; break; } } if (allModifiersPressed) { handler = options.keyBinds[index]; break; } } } } if (handler) { handler.call(picker, widget); e.stopPropagation(); e.preventDefault(); } }, keyup = function (e) { keyState[e.which] = 'r'; e.stopPropagation(); e.preventDefault(); }, change = function (e) { var val = $F($(e.target)).trim(), parsedDate = val ? parseInputDate(val) : null; setValue(parsedDate); e.stopImmediatePropagation(); return false; }, attachDatePickerElementEvents = function () { input.observe('change', change); input.observe('blur', options.debug ? Prototype.emptyFunction : hide); input.observe('keydown', keydown); input.observe('keyup', keyup); input.observe('focus', options.allowInputToggle ? show : Prototype.emptyFunction); if (element.match('input')) { input.observe('focus', show); } else if (component) { component.observe('click', toggle); component.observe('mousedown', falseFn); } },/* detachDatePickerElementEvents = function () { input.off({ 'change': change, 'blur': blur, 'keydown': keydown, 'keyup': keyup, 'focus': options.allowInputToggle ? hide : '' }); if (element.is('input')) { input.off({ 'focus': show }); } else if (component) { component.off('click', toggle); component.off('mousedown', false); } }, indexGivenDates = function (givenDatesArray) { // Store given enabledDates and disabledDates as keys. // This way we can check their existence in O(1) time instead of looping through whole array. // (for example: options.enabledDates['2014-02-27'] === true) var givenDatesIndexed = {}; $.each(givenDatesArray, function () { var dDate = parseInputDate(this); if (dDate.isValid()) { givenDatesIndexed[dDate.format('YYYY-MM-DD')] = true; } }); return (Object.keys(givenDatesIndexed).length) ? givenDatesIndexed : false; }, indexGivenHours = function (givenHoursArray) { // Store given enabledHours and disabledHours as keys. // This way we can check their existence in O(1) time instead of looping through whole array. // (for example: options.enabledHours['2014-02-27'] === true) var givenHoursIndexed = {}; $.each(givenHoursArray, function () { givenHoursIndexed[this] = true; }); return (Object.keys(givenHoursIndexed).length) ? givenHoursIndexed : false; },*/ initFormatting = function () { var format = options.format || 'L LT'; actualFormat = format.replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, function (formatInput) { var newinput = date.localeData().longDateFormat(formatInput) || formatInput; return newinput.replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, function (formatInput2) { //temp fix for #740 return date.localeData().longDateFormat(formatInput2) || formatInput2; }); }); parseFormats = options.extraFormats ? options.extraFormats.slice() : []; if (parseFormats.indexOf(format) < 0 && parseFormats.indexOf(actualFormat) < 0){ parseFormats.push(actualFormat); } use24Hours = (actualFormat.toLowerCase().indexOf('a') < 1 && actualFormat.replace(/\[.*?\]/g, '').indexOf('h') < 1); if (isEnabled('y')){ minViewModeNumber = 2; } if (isEnabled('M')){ minViewModeNumber = 1; } if (isEnabled('d')){ minViewModeNumber = 0; } currentViewMode = Math.max(minViewModeNumber, currentViewMode); if (!unset) { setValue(date); } }; /******************************************************************************** * * Public API functions * ===================== * * Important: Do not expose direct references to private objects or the options * object to the outer world. Always return a clone when returning values or make * a clone when setting a private variable. * ********************************************************************************/ picker.destroy = function () { ///<summary>Destroys the widget and removes all attached event listeners</summary> hide(); detachDatePickerElementEvents(); //element.removeData('DateTimePicker'); //element.removeData('date'); }; picker.toggle = toggle; picker.show = show; picker.hide = hide; picker.disable = function () { ///<summary>Disables the input element, the component is attached to, by adding a disabled="true" attribute to it. ///If the widget was visible before that call it is hidden. Possibly emits dp:hide</summary> hide(); if (component && component.hasClassName('btn')) { component.addClassName('disabled'); } input.prop('disabled', true); return picker; }; picker.enable = function () { ///<summary>Enables the input element, the component is attached to, by removing disabled attribute from it.</summary> if (component && component.hasClassName('btn')) { component.removeClassName('disabled'); } input.prop('disabled', false); return picker; }; picker.ignoreReadonly = function (ignoreReadonly) { if (arguments.length === 0) { return options.ignoreReadonly; } if (typeof ignoreReadonly !== 'boolean') { throw new TypeError('ignoreReadonly () expects a boolean parameter'); } options.ignoreReadonly = ignoreReadonly; return picker; }; picker.options = function (newOptions) { if (arguments.length === 0) { return Object.extend({}, options); } if (!(newOptions instanceof Object)) { throw new TypeError('options() options parameter should be an object'); } Object.extend(options, newOptions); $H(options).each(function (pair) { if (picker[pair.key] !== undefined) { picker[pair.key](pair.value); } else { throw new TypeError('option ' + key + ' is not recognized!'); } }); return picker; }; picker.date = function (newDate) { ///<signature helpKeyword="$.fn.datetimepicker.date"> ///<summary>Returns the component's model current date, a moment object or null if not set.</summary> ///<returns type="Moment">date.clone()</returns> ///</signature> ///<signature> ///<summary>Sets the components model current moment to it. Passing a null value unsets the components model current moment. Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration.</summary> ///<param name="newDate" locid="$.fn.datetimepicker.date_p:newDate">Takes string, Date, moment, null parameter.</param> ///</signature> if (arguments.length === 0) { if (unset) { return null; } return date.clone(); } if (newDate !== null && typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) { throw new TypeError('date() parameter must be one of [null, string, moment or Date]'); } setValue(newDate === null ? null : parseInputDate(newDate)); return picker; }; picker.format = function (newFormat) { ///<summary>test su</summary> ///<param name="newFormat">info about para</param> ///<returns type="string|boolean">returns foo</returns> if (arguments.length === 0) { return options.format; } if ((typeof newFormat !== 'string') && ((typeof newFormat !== 'boolean') || (newFormat !== false))) { throw new TypeError('format() expects a string or boolean:false parameter ' + newFormat); } options.format = newFormat; if (actualFormat) { initFormatting(); // reinit formatting } return picker; }; picker.timeZone = function (newZone) { if (arguments.length === 0) { return options.timeZone; } if (typeof newZone !== 'string') { throw new TypeError('newZone() expects a string parameter'); } options.timeZone = newZone; return picker; }; picker.dayViewHeaderFormat = function (newFormat) { if (arguments.length === 0) { return options.dayViewHeaderFormat; } if (typeof newFormat !== 'string') { throw new TypeError('dayViewHeaderFormat() expects a string parameter'); } options.dayViewHeaderFormat = newFormat; return picker; }; picker.extraFormats = function (formats) { if (arguments.length === 0) { return options.extraFormats; } if (formats !== false && !(formats instanceof Array)) { throw new TypeError('extraFormats() expects an array or false parameter'); } options.extraFormats = formats; if (parseFormats) { initFormatting(); // reinit formatting } return picker; }; picker.disabledDates = function (dates) { ///<signature helpKeyword="$.fn.datetimepicker.disabledDates"> ///<summary>Returns an array with the currently set disabled dates on the component.</summary> ///<returns type="array">options.disabledDates</returns> ///</signature> ///<signature> ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of ///options.enabledDates if such exist.</summary> ///<param name="dates" locid="$.fn.datetimepicker.disabledDates_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param> ///</signature> if (arguments.length === 0) { return (options.disabledDates ? Object.extend({}, options.disabledDates) : options.disabledDates); } if (!dates) { options.disabledDates = false; update(); return picker; } if (!(dates instanceof Array)) { throw new TypeError('disabledDates() expects an array parameter'); } options.disabledDates = indexGivenDates(dates); options.enabledDates = false; update(); return picker; }; picker.enabledDates = function (dates) { ///<signature helpKeyword="$.fn.datetimepicker.enabledDates"> ///<summary>Returns an array with the currently set enabled dates on the component.</summary> ///<returns type="array">options.enabledDates</returns> ///</signature> ///<signature> ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of options.disabledDates if such exist.</summary> ///<param name="dates" locid="$.fn.datetimepicker.enabledDates_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param> ///</signature> if (arguments.length === 0) { return (options.enabledDates ? Object.extend({}, options.enabledDates) : options.enabledDates); } if (!dates) { options.enabledDates = false; update(); return picker; } if (!(dates instanceof Array)) { throw new TypeError('enabledDates() expects an array parameter'); } options.enabledDates = indexGivenDates(dates); options.disabledDates = false; update(); return picker; }; picker.daysOfWeekDisabled = function (daysOfWeekDisabled) { if (arguments.length === 0) { return options.daysOfWeekDisabled.splice(0); } if ((typeof daysOfWeekDisabled === 'boolean') && !daysOfWeekDisabled) { options.daysOfWeekDisabled = false; update(); return picker; } if (!(daysOfWeekDisabled instanceof Array)) { throw new TypeError('daysOfWeekDisabled() expects an array parameter'); } options.daysOfWeekDisabled = daysOfWeekDisabled.reduce(function (previousValue, currentValue) { currentValue = parseInt(currentValue, 10); if (currentValue > 6 || currentValue < 0 || isNaN(currentValue)) { return previousValue; } if (previousValue.indexOf(currentValue) === -1) { previousValue.push(currentValue); } return previousValue; }, []).sort(); if (options.useCurrent && !options.keepInvalid) { var tries = 0; while (!isValid(date, 'd')) { date.add(1, 'd'); if (tries === 31) { throw 'Tried 31 times to find a valid date'; } tries++; } setValue(date); } update(); return picker; }; picker.maxDate = function (maxDate) { if (arguments.length === 0) { return options.maxDate ? options.maxDate.clone() : options.maxDate; } if ((typeof maxDate === 'boolean') && maxDate === false) { options.maxDate = false; update(); return picker; } if (typeof maxDate === 'string') { if (maxDate === 'now' || maxDate === 'moment') { maxDate = getMoment(); } } var parsedDate = parseInputDate(maxDate); if (!parsedDate.isValid()) { throw new TypeError('maxDate() Could not parse date parameter: ' + maxDate); } if (options.minDate && parsedDate.isBefore(options.minDate)) { throw new TypeError('maxDate() date parameter is before options.minDate: ' + parsedDate.format(actualFormat)); } options.maxDate = parsedDate; if (options.useCurrent && !options.keepInvalid && date.isAfter(maxDate)) { setValue(options.maxDate); } if (viewDate.isAfter(parsedDate)) { viewDate = parsedDate.clone().subtract(options.stepping, 'm'); } update(); return picker; }; picker.minDate = function (minDate) { if (arguments.length === 0) { return options.minDate ? options.minDate.clone() : options.minDate; } if ((typeof minDate === 'boolean') && minDate === false) { options.minDate = false; update(); return picker; } if (typeof minDate === 'string') { if (minDate === 'now' || minDate === 'moment') { minDate = getMoment(); } } var parsedDate = parseInputDate(minDate); if (!parsedDate.isValid()) { throw new TypeError('minDate() Could not parse date parameter: ' + minDate); } if (options.maxDate && parsedDate.isAfter(options.maxDate)) { throw new TypeError('minDate() date parameter is after options.maxDate: ' + parsedDate.format(actualFormat)); } options.minDate = parsedDate; if (options.useCurrent && !options.keepInvalid && date.isBefore(minDate)) { setValue(options.minDate); } if (viewDate.isBefore(parsedDate)) { viewDate = parsedDate.clone().add(options.stepping, 'm'); } update(); return picker; }; picker.defaultDate = function (defaultDate) { ///<signature helpKeyword="$.fn.datetimepicker.defaultDate"> ///<summary>Returns a moment with the options.defaultDate option configuration or false if not set</summary> ///<returns type="Moment">date.clone()</returns> ///</signature> ///<signature> ///<summary>Will set the picker's inital date. If a boolean:false value is passed the options.defaultDate parameter is cleared.</summary> ///<param name="defaultDate" locid="$.fn.datetimepicker.defaultDate_p:defaultDate">Takes a string, Date, moment, boolean:false</param> ///</signature> if (arguments.length === 0) { return options.defaultDate ? options.defaultDate.clone() : options.defaultDate; } if (!defaultDate) { options.defaultDate = false; return picker; } if (typeof defaultDate === 'string') { if (defaultDate === 'now' || defaultDate === 'moment') { defaultDate = getMoment(); } else { defaultDate = getMoment(defaultDate); } } var parsedDate = parseInputDate(defaultDate); if (!parsedDate.isValid()) { throw new TypeError('defaultDate() Could not parse date parameter: ' + defaultDate); } if (!isValid(parsedDate)) { throw new TypeError('defaultDate() date passed is invalid according to component setup validations'); } options.defaultDate = parsedDate; if ((options.defaultDate && options.inline) || input.val().trim() === '') { setValue(options.defaultDate); } return picker; }; picker.locale = function (locale) { if (arguments.length === 0) { return options.locale; } if (!moment.localeData(locale)) { throw new TypeError('locale() locale ' + locale + ' is not loaded from moment locales!'); } options.locale = locale; options.tooltips = localeTooltips[locale] || options.locale; date.locale(options.locale); viewDate.locale(options.locale); if (actualFormat) { initFormatting(); // reinit formatting } if (widget) { hide(); show(); } return picker; }; picker.stepping = function (stepping) { if (arguments.length === 0) { return options.stepping; } stepping = parseInt(stepping, 10); if (isNaN(stepping) || stepping < 1) { stepping = 1; } options.stepping = stepping; return picker; }; picker.useCurrent = function (useCurrent) { var useCurrentOptions = ['year', 'month', 'day', 'hour', 'minute']; if (arguments.length === 0) { return options.useCurrent; } if ((typeof useCurrent !== 'boolean') && (typeof useCurrent !== 'string')) { throw new TypeError('useCurrent() expects a boolean or string parameter'); } if (typeof useCurrent === 'string' && useCurrentOptions.indexOf(useCurrent.toLowerCase()) === -1) { throw new TypeError('useCurrent() expects a string parameter of ' + useCurrentOptions.join(', ')); } options.useCurrent = useCurrent; return picker; }; picker.collapse = function (collapse) { if (arguments.length === 0) { return options.collapse; } if (typeof collapse !== 'boolean') { throw new TypeError('collapse() expects a boolean parameter'); } if (options.collapse === collapse) { return picker; } options.collapse = collapse; if (widget) { hide(); show(); } return picker; }; picker.icons = function (icons) { if (arguments.length === 0) { return Object.extend({}, options.icons); } if (!(icons instanceof Object)) { throw new TypeError('icons() expects parameter to be an Object'); } Object.extend(options.icons, icons); if (widget) { hide(); show(); } return picker; }; picker.tooltips = function (tooltips) { if (arguments.length === 0) { return Object.extend({}, options.tooltips); } if (!(tooltips instanceof Object)) { throw new TypeError('tooltips() expects parameter to be an Object'); } Object.extend(options.tooltips, tooltips); if (widget) { hide(); show(); } return picker; }; picker.useStrict = function (useStrict) { if (arguments.length === 0) { return options.useStrict; } if (typeof useStrict !== 'boolean') { throw new TypeError('useStrict() expects a boolean parameter'); } options.useStrict = useStrict; return picker; }; picker.sideBySide = function (sideBySide) { if (arguments.length === 0) { return options.sideBySide; } if (typeof sideBySide !== 'boolean') { throw new TypeError('sideBySide() expects a boolean parameter'); } options.sideBySide = sideBySide; if (widget) { hide(); show(); } return picker; }; picker.viewMode = function (viewMode) { if (arguments.length === 0) { return options.viewMode; } if (typeof viewMode !== 'string') { throw new TypeError('viewMode() expects a string parameter'); } if (viewModes.indexOf(viewMode) === -1) { throw new TypeError('viewMode() parameter must be one of (' + viewModes.join(', ') + ') value'); } options.viewMode = viewMode; currentViewMode = Math.max(viewModes.indexOf(viewMode), minViewModeNumber); showMode(); return picker; }; picker.toolbarPlacement = function (toolbarPlacement) { if (arguments.length === 0) { return options.toolbarPlacement; } if (typeof toolbarPlacement !== 'string') { throw new TypeError('toolbarPlacement() expects a string parameter'); } if (toolbarPlacements.indexOf(toolbarPlacement) === -1) { throw new TypeError('toolbarPlacement() parameter must be one of (' + toolbarPlacements.join(', ') + ') value'); } options.toolbarPlacement = toolbarPlacement; if (widget) { hide(); show(); } return picker; }; picker.widgetPositioning = function (widgetPositioning) { if (arguments.length === 0) { return Object.extend({}, options.widgetPositioning); } if (({}).toString.call(widgetPositioning) !== '[object Object]') { throw new TypeError('widgetPositioning() expects an object variable'); } if (widgetPositioning.horizontal) { if (typeof widgetPositioning.horizontal !== 'string') { throw new TypeError('widgetPositioning() horizontal variable must be a string'); } widgetPositioning.horizontal = widgetPositioning.horizontal.toLowerCase(); if (horizontalModes.indexOf(widgetPositioning.horizontal) === -1) { throw new TypeError('widgetPositioning() expects horizontal parameter to be one of (' + horizontalModes.join(', ') + ')'); } options.widgetPositioning.horizontal = widgetPositioning.horizontal; } if (widgetPositioning.vertical) { if (typeof widgetPositioning.vertical !== 'string') { throw new TypeError('widgetPositioning() vertical variable must be a string'); } widgetPositioning.vertical = widgetPositioning.vertical.toLowerCase(); if (verticalModes.indexOf(widgetPositioning.vertical) === -1) { throw new TypeError('widgetPositioning() expects vertical parameter to be one of (' + verticalModes.join(', ') + ')'); } options.widgetPositioning.vertical = widgetPositioning.vertical; } update(); return picker; }; picker.calendarWeeks = function (calendarWeeks) { if (arguments.length === 0) { return options.calendarWeeks; } if (typeof calendarWeeks !== 'boolean') { throw new TypeError('calendarWeeks() expects parameter to be a boolean value'); } options.calendarWeeks = calendarWeeks; update(); return picker; }; picker.showTodayButton = function (showTodayButton) { if (arguments.length === 0) { return options.showTodayButton; } if (typeof showTodayButton !== 'boolean') { throw new TypeError('showTodayButton() expects a boolean parameter'); } options.showTodayButton = showTodayButton; if (widget) { hide(); show(); } return picker; }; picker.showClear = function (showClear) { if (arguments.length === 0) { return options.showClear; } if (typeof showClear !== 'boolean') { throw new TypeError('showClear() expects a boolean parameter'); } options.showClear = showClear; if (widget) { hide(); show(); } return picker; }; picker.widgetParent = function (widgetParent) { if (arguments.length === 0) { return options.widgetParent; } if (typeof widgetParent === 'string') { widgetParent = $(widgetParent); } if (widgetParent !== null && (typeof widgetParent !== 'string' && !(widgetParent instanceof Element))) { throw new TypeError('widgetParent() expects a string or a Element object parameter'); } options.widgetParent = widgetParent; if (widget) { hide(); show(); } return picker; }; picker.keepOpen = function (keepOpen) { if (arguments.length === 0) { return options.keepOpen; } if (typeof keepOpen !== 'boolean') { throw new TypeError('keepOpen() expects a boolean parameter'); } options.keepOpen = keepOpen; return picker; }; picker.focusOnShow = function (focusOnShow) { if (arguments.length === 0) { return options.focusOnShow; } if (typeof focusOnShow !== 'boolean') { throw new TypeError('focusOnShow() expects a boolean parameter'); } options.focusOnShow = focusOnShow; return picker; }; picker.inline = function (inline) { if (arguments.length === 0) { return options.inline; } if (typeof inline !== 'boolean') { throw new TypeError('inline() expects a boolean parameter'); } options.inline = inline; return picker; }; picker.clear = function () { clear(); return picker; }; picker.keyBinds = function (keyBinds) { if (arguments.length === 0) { return options.keyBinds; } options.keyBinds = keyBinds; return picker; }; picker.getMoment = function (d) { return getMoment(d); }; picker.debug = function (debug) { if (typeof debug !== 'boolean') { throw new TypeError('debug() expects a boolean parameter'); } options.debug = debug; return picker; }; picker.allowInputToggle = function (allowInputToggle) { if (arguments.length === 0) { return options.allowInputToggle; } if (typeof allowInputToggle !== 'boolean') { throw new TypeError('allowInputToggle() expects a boolean parameter'); } options.allowInputToggle = allowInputToggle; return picker; }; picker.showClose = function (showClose) { if (arguments.length === 0) { return options.showClose; } if (typeof showClose !== 'boolean') { throw new TypeError('showClose() expects a boolean parameter'); } options.showClose = showClose; return picker; }; picker.keepInvalid = function (keepInvalid) { if (arguments.length === 0) { return options.keepInvalid; } if (typeof keepInvalid !== 'boolean') { throw new TypeError('keepInvalid() expects a boolean parameter'); } options.keepInvalid = keepInvalid; return picker; }; picker.datepickerInput = function (datepickerInput) { if (arguments.length === 0) { return options.datepickerInput; } if (typeof datepickerInput !== 'string') { throw new TypeError('datepickerInput() expects a string parameter'); } options.datepickerInput = datepickerInput; return picker; }; picker.parseInputDate = function (parseInputDate) { if (arguments.length === 0) { return options.parseInputDate; } if (typeof parseInputDate !== 'function') { throw new TypeError('parseInputDate() sholud be as function'); } options.parseInputDate = parseInputDate; return picker; }; picker.disabledTimeIntervals = function (disabledTimeIntervals) { ///<signature helpKeyword="$.fn.datetimepicker.disabledTimeIntervals"> ///<summary>Returns an array with the currently set disabled dates on the component.</summary> ///<returns type="array">options.disabledTimeIntervals</returns> ///</signature> ///<signature> ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of ///options.enabledDates if such exist.</summary> ///<param name="dates" locid="$.fn.datetimepicker.disabledTimeIntervals_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param> ///</signature> if (arguments.length === 0) { return (options.disabledTimeIntervals ? Object.extend({}, options.disabledTimeIntervals) : options.disabledTimeIntervals); } if (!disabledTimeIntervals) { options.disabledTimeIntervals = false; update(); return picker; } if (!(disabledTimeIntervals instanceof Array)) { throw new TypeError('disabledTimeIntervals() expects an array parameter'); } options.disabledTimeIntervals = disabledTimeIntervals; update(); return picker; }; picker.disabledHours = function (hours) { ///<signature helpKeyword="$.fn.datetimepicker.disabledHours"> ///<summary>Returns an array with the currently set disabled hours on the component.</summary> ///<returns type="array">options.disabledHours</returns> ///</signature> ///<signature> ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of ///options.enabledHours if such exist.</summary> ///<param name="hours" locid="$.fn.datetimepicker.disabledHours_p:hours">Takes an [ int ] of values and disallows the user to select only from those hours.</param> ///</signature> if (arguments.length === 0) { return (options.disabledHours ? Object.extend({}, options.disabledHours) : options.disabledHours); } if (!hours) { options.disabledHours = false; update(); return picker; } if (!(hours instanceof Array)) { throw new TypeError('disabledHours() expects an array parameter'); } options.disabledHours = indexGivenHours(hours); options.enabledHours = false; if (options.useCurrent && !options.keepInvalid) { var tries = 0; while (!isValid(date, 'h')) { date.add(1, 'h'); if (tries === 24) { throw 'Tried 24 times to find a valid date'; } tries++; } setValue(date); } update(); return picker; }; picker.enabledHours = function (hours) { ///<signature helpKeyword="$.fn.datetimepicker.enabledHours"> ///<summary>Returns an array with the currently set enabled hours on the component.</summary> ///<returns type="array">options.enabledHours</returns> ///</signature> ///<signature> ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of options.disabledHours if such exist.</summary> ///<param name="hours" locid="$.fn.datetimepicker.enabledHours_p:hours">Takes an [ int ] of values and allows the user to select only from those hours.</param> ///</signature> if (arguments.length === 0) { return (options.enabledHours ? Object.extend({}, options.enabledHours) : options.enabledHours); } if (!hours) { options.enabledHours = false; update(); return picker; } if (!(hours instanceof Array)) { throw new TypeError('enabledHours() expects an array parameter'); } options.enabledHours = indexGivenHours(hours); options.disabledHours = false; if (options.useCurrent && !options.keepInvalid) { var tries = 0; while (!isValid(date, 'h')) { date.add(1, 'h'); if (tries === 24) { throw 'Tried 24 times to find a valid date'; } tries++; } setValue(date); } update(); return picker; }; /** * Returns the component's model current viewDate, a moment object or null if not set. Passing a null value unsets the components model current moment. Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration. * @param {Takes string, viewDate, moment, null parameter.} newDate * @returns {viewDate.clone()} */ picker.viewDate = function (newDate) { if (arguments.length === 0) { return viewDate.clone(); } if (!newDate) { viewDate = date.clone(); return picker; } if (typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) { throw new TypeError('viewDate() parameter must be one of [string, moment or Date]'); } viewDate = parseInputDate(newDate); viewUpdate(); return picker; }; // initializing element and component attributes if (element.match('input')) { input = element; } else { input = element.select(options.datepickerInput); if (input.length === 0) { input = element.select('input').first(); } else if (!input.match('input')) { throw new Error('CSS class "' + options.datepickerInput + '" cannot be applied to non input element'); } } if (element.hasClassName('input-group')) { // in case there is more then one 'input-group-addon' Issue #48 if (element.select('.datepickerbutton').length === 0) { component = element.select('.input-group-addon').first(); } else { component = element.select('.datepickerbutton').first(); } } if (!options.inline && !input.match('input')) { throw new Error('Could not initialize DateTimePicker without an input element'); } // Set defaults for date here now instead of in var declaration date = getMoment(); viewDate = date.clone(); Object.extend(options, dataToOptions()); picker.options(options); initFormatting(); attachDatePickerElementEvents(); if (input.readAttribute('disabled')) { picker.disable(); } var val = input.retrieve('date'); if (!val) val = $F(input).trim(); else val = moment(val); if (input.match('input') && val.length !== 0) { setValue(parseInputDate(val)); } else if (options.defaultDate && (input.readAttribute('placeholder') === undefined || input.readAttribute('placeholder') === null)) { setValue(options.defaultDate); } if (options.inline) { show(); } return picker; }; /******************************************************************************** * * jQuery plugin constructor and defaults object * ********************************************************************************/ /** * See (http://jquery.com/). * @name jQuery * @class * See the jQuery Library (http://jquery.com/) for full details. This just * documents the function and classes that are added to jQuery by this plug-in. */ /** * See (http://jquery.com/) * @name fn * @class * See the jQuery Library (http://jquery.com/) for full details. This just * documents the function and classes that are added to jQuery by this plug-in. * @memberOf jQuery */ /** * Show comments * @class datetimepicker * @memberOf jQuery.fn */ var dpDefaults = { timeZone: '', format: false, dayViewHeaderFormat: 'MMMM YYYY', extraFormats: false, stepping: 1, minDate: false, maxDate: false, useCurrent: true, collapse: true, locale: moment.locale(), defaultDate: false, disabledDates: false, enabledDates: false, icons: { time: 'glyphicon glyphicon-time', date: 'glyphicon glyphicon-calendar', up: 'glyphicon glyphicon-chevron-up', down: 'glyphicon glyphicon-chevron-down', previous: 'glyphicon glyphicon-chevron-left', next: 'glyphicon glyphicon-chevron-right', today: 'glyphicon glyphicon-screenshot', clear: 'glyphicon glyphicon-trash', close: 'glyphicon glyphicon-remove' }, tooltips: { today: 'Go to today', clear: 'Clear selection', close: 'Close the picker', selectMonth: 'Select Month', prevMonth: 'Previous Month', nextMonth: 'Next Month', selectYear: 'Select Year', prevYear: 'Previous Year', nextYear: 'Next Year', selectDecade: 'Select Decade', prevDecade: 'Previous Decade', nextDecade: 'Next Decade', prevCentury: 'Previous Century', nextCentury: 'Next Century', pickHour: 'Pick Hour', incrementHour: 'Increment Hour', decrementHour: 'Decrement Hour', pickMinute: 'Pick Minute', incrementMinute: 'Increment Minute', decrementMinute: 'Decrement Minute', pickSecond: 'Pick Second', incrementSecond: 'Increment Second', decrementSecond: 'Decrement Second', togglePeriod: 'Toggle Period', selectTime: 'Select Time' }, useStrict: false, sideBySide: false, daysOfWeekDisabled: false, calendarWeeks: false, viewMode: 'days', toolbarPlacement: 'default', showTodayButton: true, showClear: false, showClose: false, widgetPositioning: { horizontal: 'auto', vertical: 'auto' }, widgetParent: null, ignoreReadonly: false, keepOpen: false, focusOnShow: true, inline: false, keepInvalid: false, datepickerInput: '.datepickerinput', keyBinds: { up: function (widget) { if (!widget) { return; } var d = this.date() || this.getMoment(); if (widget.down('.datepicker').visible()) { this.date(d.clone().subtract(7, 'd')); } else { this.date(d.clone().add(this.stepping(), 'm')); } }, down: function (widget) { if (!widget) { this.show(); return; } var d = this.date() || this.getMoment(); if (widget.down('.datepicker').visible()) { this.date(d.clone().add(7, 'd')); } else { this.date(d.clone().subtract(this.stepping(), 'm')); } }, 'control up': function (widget) { if (!widget) { return; } var d = this.date() || this.getMoment(); if (widget.down('.datepicker').visible()) { this.date(d.clone().subtract(1, 'y')); } else { this.date(d.clone().add(1, 'h')); } }, 'control down': function (widget) { if (!widget) { return; } var d = this.date() || this.getMoment(); if (widget.down('.datepicker').visible()) { this.date(d.clone().add(1, 'y')); } else { this.date(d.clone().subtract(1, 'h')); } }, left: function (widget) { if (!widget) { return; } var d = this.date() || this.getMoment(); if (widget.down('.datepicker').visible()) { this.date(d.clone().subtract(1, 'd')); } }, right: function (widget) { if (!widget) { return; } var d = this.date() || this.getMoment(); if (widget.down('.datepicker').visible()) { this.date(d.clone().add(1, 'd')); } }, pageUp: function (widget) { if (!widget) { return; } var d = this.date() || this.getMoment(); if (widget.down('.datepicker').visible()) { this.date(d.clone().subtract(1, 'M')); } }, pageDown: function (widget) { if (!widget) { return; } var d = this.date() || this.getMoment(); if (widget.down('.datepicker').visible()) { this.date(d.clone().add(1, 'M')); } }, enter: function () { this.hide(); }, escape: function () { this.hide(); }, //tab: function (widget) { //this break the flow of the form. disabling for now // var toggle = widget.find('.picker-switch a[data-action="togglePicker"]'); // if(toggle.length > 0) toggle.click(); //}, 'control space': function (widget) { if (!widget) { return; } if (widget.down('.timepicker').visible()) { widget.down('.btn[data-action="togglePeriod"]').click(); } }, t: function () { this.date(this.getMoment()); }, 'delete': function () { this.clear(); } }, debug: false, allowInputToggle: false, disabledTimeIntervals: false, disabledHours: false, enabledHours: false, viewDate: false }; var localeTooltips = { es: { today: 'Hoy', clear: 'Limpiar selección', close: 'Cerrar', selectMonth: 'Seleccionar mes', prevMonth: 'Mes anterior', nextMonth: 'Mes siguiente', selectYear: 'Seleccionar año', prevYear: 'Año anterior', nextYear: 'Año siguiente', selectDecade: 'Seleccionar década', prevDecade: 'Década anterior', nextDecade: 'Década siguiente', prevCentury: 'Siglo siguiente', nextCentury: 'Siglo anterior', pickHour: 'Seleccionar hora', incrementHour: 'Aumentar hora', decrementHour: 'Disminuir hora', pickMinute: 'Seleccionar minuto', incrementMinute: 'Aumentar minuto', decrementMinute: 'Disminuir minuto', pickSecond: 'Seleccionar segundo', incrementSecond: 'Aumentar segundo', decrementSecond: 'Disminuir segundo', togglePeriod: 'Toggle Period', selectTime: 'Select Time' } }; Class.create('DateTimePicker', { picker: null, initialize: function (element, options) { var thisOptions = Object.extend({}, dpDefaults); thisOptions = Object.extend(thisOptions, options || {}); thisOptions.tooltips = localeTooltips[thisOptions.locale] || thisOptions.tooltips; this.picker = dateTimePicker(element, thisOptions); } }); })();
boa-project/boa
src/boa/plugins/gui.ajax/res/js/core/DateTimePicker.class.js
JavaScript
agpl-3.0
113,199
importPackage(Packages.tools); var returnTo = new Array(103000100, 103000310); var rideTo = new Array(103000310, 103000100); var trainRide = new Array(103000301, 103000302); var myRide; var returnMap; var exitMap; var map; var onRide; //Time Setting is in millisecond var rideTime = 10 * 1000; function init() { rideTime = em.getTransportationTime(rideTime); } function setup(level, lobbyid) { var eim = em.newInstance("KerningTrain_" + lobbyid); return eim; } function afterSetup(eim) {} function playerEntry(eim, player) { if (player.getMapId() == returnTo[0]) { myRide = 0; } else { myRide = 1; } exitMap = eim.getEm().getChannelServer().getMapFactory().getMap(rideTo[myRide]); returnMap = eim.getMapFactory().getMap(returnTo[myRide]); onRide = eim.getMapFactory().getMap(trainRide[myRide]); player.changeMap(onRide, onRide.getPortal(0)); player.getClient().announce(MaplePacketCreator.getClock(rideTime / 1000)); player.getClient().announce(MaplePacketCreator.earnTitleMessage("The next stop is at Kerning " + (myRide == 0 ? "Square" : "Subway") + " Station. The exit is to your left.")); eim.schedule("timeOut", rideTime); } function timeOut(eim) { end(eim); } function playerUnregistered(eim, player) {} function playerExit(eim, player, success) { eim.unregisterPlayer(player); player.changeMap(success ? exitMap.getId() : returnMap.getId(), 0); } function end(eim) { var party = eim.getPlayers(); for (var i = 0; i < party.size(); i++) { playerExit(eim, party.get(i), true); } eim.dispose(); } function playerDisconnected(eim, player) { playerExit(eim, player, false); } function cancelSchedule() {} function dispose(eim) {} // ---------- FILLER FUNCTIONS ---------- function monsterValue(eim, mobid) {return 0;} function disbandParty(eim, player) {} function monsterKilled(mob, eim) {} function scheduledTimeout(eim) {} function changedLeader(eim, leader) {} function leftParty(eim, player) {} function clearPQ(eim) {} function allMonstersDead(eim) {}
ronancpl/MapleSolaxiaV2
scripts/event/KerningTrain.js
JavaScript
agpl-3.0
2,133
// TriangleCanvas.js import React from 'react'; import Trianglify from 'trianglify'; import './TriangleCanvas.scss'; /** Canvas with Trianglify styling applied, equal in size to current window, can be used as a sweet background. Will automatically size to window's width and height. @prop cellSize: cell_size option for Trianglify @prop xColors: x_colors option for Trianglify @prop yColors: y_colors option for Trianglify note: more Trianglify options available https://github.com/qrohlf/trianglify */ const TriangleCanvas = React.createClass({ getDefaultProps() { return { cellSize: Trianglify.defaults.cell_size, xColors: Trianglify.defaults.x_colors, yColors: Trianglify.defaults.cell_size, }; }, componentDidMount() { this.renderCanvas(); }, renderCanvas() { const canvas = document.getElementById('daCanvas'); const pattern = Trianglify({ width: window.innerWidth, height: window.innerHeight, cell_size: this.props.cellSize, x_colors: this.props.xColors, }); pattern.canvas(canvas); }, render() { return ( <div className="triangleCanvas"> <canvas className="canvasCanvas" id="daCanvas" /> <div className="canvasContent">{this.props.children}</div> </div> ); }, }); export default TriangleCanvas;
uclaradio/uclaradio
client/react/frontpage/components/TriangleCanvas.js
JavaScript
agpl-3.0
1,331
<?php namespace App\Services\Immoware24; use App\Models\RentDefinition; use Carbon\Carbon; use Exception; class RentalContractsMapper extends Mapper { protected $tenants; protected $phones; protected $faxs; protected $emails; protected $SEPAMandate; protected $unit; protected $start, $end; public function __construct($model, & $config) { parent::__construct($model, $config); $this->tenants = $this->model->mieter; $this->phones = $this->tenants->pluck('phones')->collapse()->unique(); $this->faxs = $this->tenants->pluck('faxs')->collapse()->unique(); $this->emails = $this->tenants->pluck('emails')->collapse()->unique(); $this->SEPAMandate = $this->currentSEPAMandate(); $this->unit = $this->model->einheit; $this->start = $this->start($this->model->MIETVERTRAG_VON, $this->model->MIETVERTRAG_BIS); $this->end = $this->end($this->model->MIETVERTRAG_VON, $this->model->MIETVERTRAG_BIS); } protected function currentSEPAMandate() { $until = $this->model->BIS; if ($until === '0000-00-00') { return $this->model->SEPAMandates()->active('=', Carbon::today())->first(); } else { return $this->model->SEPAMandates()->active('=', $until)->first(); } } public function getOBJ_ID() { return $this->unit->haus->objekt->OBJEKT_ID; } public function getVE_ID() { return $this->unit->EINHEIT_ID; } public function getK_ID() { $tenantsId = implode(':', $this->tenants->pluck('id')->sort()->values()->all()); if (array_has($this->config['person-to-contact-ids'], $tenantsId)) { return $this->config['person-to-contact-ids'][$tenantsId]; } else { throw new Exception(); } } public function getTyp() { return "M"; } public function getvon() { return $this->date($this->model->MIETVERTRAG_VON); } public function getbis() { if ($this->model->MIETVERTRAG_BIS === '0000-00-00') { return ""; } return $this->date($this->model->MIETVERTRAG_BIS); } public function getGewerbe() { $type = $this->unit->TYP; switch ($type) { case "Gewerbe": return "G"; default: return "N"; } } public function getLastschrift() { if (!empty($this->SEPAMandate)) { return "1"; } return "0"; } public function getMahnsperre() { return ""; } public function getUmlAusfWagnis() { return ""; } public function getNotizen() { return ""; } public function getSV_Brutto() { return ""; } public function getSV_Fälligkeit() { return ""; } public function getZ_Miete() { $basicRentDefinitions = $this->model->basicRentDefinitions($this->start, $this->end) ->where('KOSTENKATEGORIE', '!=', 'Untermieter Zuschlag') ->where('KOSTENKATEGORIE', '!=', 'Garagenmiete') ->where('KOSTENKATEGORIE', '!=', 'Stellplatzmiete'); $basicRent = RentDefinition::sumDefinitions( $basicRentDefinitions, $this->start, $this->end ); $basicRentDeductionDefinitions = $this->model->basicRentDeductionDefinitions($this->start, $this->end); $basicRentDeduction = RentDefinition::sumDefinitions( $basicRentDeductionDefinitions, $this->start, $this->end ); return number_format($basicRent + $basicRentDeduction, 2, ',', '.'); } public function getZ_BKV() { $operatingCostAdvanceDefinitions = $this->model->operatingCostAdvanceDefinitions($this->start, $this->end) ->where('KOSTENKATEGORIE', '!=', 'Kabel TV'); $operatingCostAdvances = RentDefinition::sumDefinitions( $operatingCostAdvanceDefinitions, $this->start, $this->end ); return number_format($operatingCostAdvances, 2, ',', '.'); } public function getZ_HKV() { $heatingExpenseAdvanceDefinitions = $this->model->heatingExpenseAdvanceDefinitions($this->start, $this->end); $heatingExpenseAdvances = RentDefinition::sumDefinitions( $heatingExpenseAdvanceDefinitions, $this->start, $this->end ); return number_format($heatingExpenseAdvances, 2, ',', '.'); } public function getZ_Garage() { $garageRentDefinitions = $this->model->rentDefinitions($this->start, $this->end) ->where('KOSTENKATEGORIE', '=', 'Garagenmiete'); $garageRent = RentDefinition::sumDefinitions( $garageRentDefinitions, $this->start, $this->end ); return number_format($garageRent, 2, ',', '.'); } public function getZ_Stellplatz() { $parkingSpaceRentDefinitions = $this->model->rentDefinitions($this->start, $this->end) ->where('KOSTENKATEGORIE', '=', 'Stellplatzmiete'); $parkingSpaceRent = RentDefinition::sumDefinitions( $parkingSpaceRentDefinitions, $this->start, $this->end ); return number_format($parkingSpaceRent, 2, ',', '.'); } public function getZ_sonstMiete() { $miscRentDefinitions = $this->model->rentDefinitions($this->start, $this->end) ->where(function ($query) { $query->where('KOSTENKATEGORIE', '=', 'Untermieter Zuschlag') ->orWhere('KOSTENKATEGORIE', '=', 'Kabel TV'); }); $miscRent = RentDefinition::sumDefinitions( $miscRentDefinitions, $this->start, $this->end ); return number_format($miscRent, 2, ',', '.'); } public function getZ_Hausgeld() { return ""; } public function getZ_Rücklage1() { return ""; } public function getZ_Rücklage2() { return ""; } public function getU_Wohnfläche() { if (!empty($this->unit)) { return number_format(trim($this->unit->EINHEIT_QM), 2, ',', '.'); } return ""; } public function getU_Heizfläche() { if (!empty($this->unit)) { return number_format(trim($this->unit->EINHEIT_QM), 2, ',', '.'); } return ""; } public function getU_KabelTV() { return ""; } public function getU_Personen() { return $this->tenants->count(); } public function getU_Einheiten() { return ""; } public function getU_Garagen() { return ""; } public function getU_Stellplätze() { return ""; } public function getU_MEA() { return ""; } public function getBK_ID() { if (!empty($this->SEPAMandate)) { $id = 'sepa:' . implode(':', $this->tenants->pluck('id')->sort()->values()->all()) . '|' . $this->SEPAMandate->M_ID; if (array_has($this->config['bank-account-ids'], $id)) { return $this->config['bank-account-ids'][$id]; } else { $this->logger->error( 'Missing BK_ID for contract (id: ' . $this->model->MIETVERTRAG_ID . ' unit: ' . $this->model->einheit->EINHEIT_KURZNAME . ').' ); throw new Exception(); } } return ""; } public function getGläubigerID() { if (!empty($this->SEPAMandate)) { return trim($this->SEPAMandate->GLAEUBIGER_ID); } return ""; } public function getMandatRef() { if (!empty($this->SEPAMandate)) { return trim($this->SEPAMandate->M_REFERENZ); } return ""; } public function getMandatVon() { if (!empty($this->SEPAMandate)) { return $this->date($this->SEPAMandate->M_ADATUM); } return ""; } public function getMandatBis() { if (!empty($this->SEPAMandate) && $this->SEPAMandate->M_EDATUM !== '9999-12-31') { return $this->date($this->SEPAMandate->M_EDATUM); } return ""; } public function getMandatUnterschrift() { if (!empty($this->SEPAMandate)) { return $this->date($this->SEPAMandate->M_UDATUM); } return ""; } }
BerlusGmbH/Berlussimo
app/Services/Immoware24/RentalContractsMapper.php
PHP
agpl-3.0
8,701
OC.L10N.register( "workflowengine", { "Saved" : "Bewaard", "Saving failed:" : "Opslaan mislukt:", "File MIME type" : "Mimetype bestand", "is" : "is", "is not" : "is niet", "matches" : "komt overeen", "does not match" : "komt niet overeen", "Example: {placeholder}" : "Bijvoorbeeld: {placeholder}", "File size (upload)" : "Bestandsgrootte (upload)", "less" : "minder", "less or equals" : "minder of gelijk", "greater or equals" : "groter of gelijk", "greater" : "groter", "File system tag" : "Bestandssysteem markering", "is tagged with" : "is gemarkeerd met", "is not tagged with" : "is niet gemarkeerd met", "Select tag…" : "Selecteer markering...", "Request remote address" : "Vraag extern adres aan", "matches IPv4" : "komt overeen met IPv4", "does not match IPv4" : "komt niet overeen met IPv4", "matches IPv6" : "komt overeen met IPv6", "does not match IPv6" : "komt niet overeen met IPv6", "Request time" : "Vraag tijd aan", "between" : "tussen", "not between" : "niet tussen", "Start" : "Begin", "End" : "Einde", "Select timezone…" : "Selecteer tijdzone...", "Request URL" : "Vraag URL aan", "Predefined URLs" : "Voorgedefinieerde URL's", "Files WebDAV" : "Bestanden WebDAV", "Request user agent" : "Vraag gebruikersagent aan", "Sync clients" : "Synchroniseer clients", "Android client" : "Android client", "iOS client" : "iOS client", "Desktop client" : "Desktop client", "User group membership" : "Gebruikersgroep lidmaatschap", "is member of" : "is lid van", "is not member of" : "is geen lid van", "The given operator is invalid" : "De opgegeven operator is ongeldig", "The given regular expression is invalid" : "De opgegeven reguliere expressie is ongeldig", "The given file size is invalid" : "De opgegeven bestandsgrootte is ongeldig", "The given tag id is invalid" : "De opgegeven markerings-id is ongeldig", "The given IP range is invalid" : "De opgegeven IP-range is ongeldig", "The given IP range is not valid for IPv4" : "De opgegeven IP-range is niet geldig voor IPv4", "The given IP range is not valid for IPv6" : "De opgegeven IP-range is niet geldig voor IPv6", "The given time span is invalid" : "De opgegeven tijdspanne is ongeldig", "The given start time is invalid" : "De opgegeven begintijd is ongeldig", "The given end time is invalid" : "De opgegeven eindtijd is ongeldig", "The given group does not exist" : "De opgegeven groep bestaat niet", "Check %s is invalid or does not exist" : "Controleer: %s is ongeldig of bestaat niet", "Operation #%s does not exist" : "Bewerking #%s bestaat niet", "Operation %s does not exist" : "Bewerking %s bestaat niet", "Operation %s is invalid" : "Bewerking %s is ongeldig", "Check %s does not exist" : "Controleer: %s bestaat niet", "Check %s is invalid" : "Controleer: %s is ongeldig", "Check #%s does not exist" : "Controleer: #%s bestaat niet", "Workflow" : "Workflow", "Files workflow engine" : "Betand workflow engine", "Open documentation" : "Open documentatie", "Add rule group" : "Groepsrol toevoegen", "Short rule description" : "Korte rolbeschrijving", "Add rule" : "Voeg rol toe", "Reset" : "Reset", "Save" : "Opslaan", "Saving…" : "Opslaan...", "Loading…" : "Laden...", "Successfully saved" : "Succesvol opgeslagen", "File mime type" : "Bestand mime type" }, "nplurals=2; plural=(n != 1);");
pixelipo/server
apps/workflowengine/l10n/nl.js
JavaScript
agpl-3.0
3,565
/* * PHEX - The pure-java Gnutella-servent. * Copyright (C) 2001 - 2007 Phex Development Group * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * --- SVN Information --- * $Id: Range.java 3933 2007-09-21 18:35:24Z gregork $ */ package phex.http; public class Range { public static final int NOT_SET = -1; private long suffixLength; /** * The start offset of the download. */ private long startOffset; /** * The end offset of the download (inclusive) */ private long endOffset; /** * Creates a HTTPRange object for suffix lengths like '-500' which requests * the last 500 bytes of a file. * * @param suffixLength the suffix length. */ public Range(long suffixLength) { this.startOffset = NOT_SET; this.endOffset = NOT_SET; this.suffixLength = suffixLength; } /** * Creates a HTTPRange object with a start and end offset. The end offset * can be NOT_SET to form request like '100-' * * @param startOffset the start offset. * @param endOffset the end offset. * @param rating the rating */ public Range(long startOffset, long endOffset) { this.startOffset = startOffset; this.endOffset = endOffset; this.suffixLength = NOT_SET; } /** * Updates a HTTPRange object for suffix lengths like '-500' which requests * the last 500 bytes of a file. * * @param suffixLength the suffix length. */ public void update(long suffix) { this.startOffset = NOT_SET; this.endOffset = NOT_SET; this.suffixLength = suffix; } /** * Updats a HTTPRange object with a start and end offset. The end offset * can be NOT_SET to form request like '100-' * * @param startOffset the start offset. * @param endOffset the end offset. */ public void update(long startOffset, long endOffset) { this.startOffset = startOffset; this.endOffset = endOffset; this.suffixLength = NOT_SET; } @Override public String toString() { StringBuffer buf = new StringBuffer("[Range: " + startOffset + '-' + endOffset + ']'); return buf.toString(); } /** * Returns the start offset of the download. * * @param fileSize the file size is needed in case of suffix byte range * requests. * @return */ public long getStartOffset(long fileSize) { if (suffixLength == NOT_SET) {// we have absolute ranges. return Math.min(startOffset, fileSize - 1); } else { return fileSize - suffixLength; } } /** * Returns the end offset (inclusive) of the download. * * @param fileSize the file size is needed in case of suffix byte range * requests. * @return */ public long getEndOffset(long fileSize) { if (suffixLength == NOT_SET && endOffset != NOT_SET) {// we have absolut ranges. return Math.min(endOffset, fileSize - 1); } else { return fileSize - 1; } } public boolean isRangeSatisfiable(Range range, long fileSize) { // a------a // r--r // r--r // r--r // r--r long rangeStart = range.getStartOffset(fileSize); return getStartOffset(fileSize) <= rangeStart && rangeStart <= getEndOffset(fileSize); } public String buildHTTPRangeString() { if (suffixLength == NOT_SET) { return String.valueOf(startOffset) + '-' + String.valueOf( endOffset); } else { return '-' + String.valueOf(suffixLength); } } public enum RangeAvailability { /** * Indicates that the range is available */ RANGE_AVAILABLE, /** * Indicates that the range is not available */ RANGE_NOT_AVAILABLE, /** * Indicates that the range is available */ RANGE_NOT_SATISFIABLE } }
deepstupid/phex
src/main/java/phex/http/Range.java
Java
agpl-3.0
4,812
using System.Collections.Generic; namespace galaxy.core.misc.figuredata.types { class FigureSet { public SetType Type { get; set; } public int PalletId { get; set; } private Dictionary<int, Set> _sets; public FigureSet(SetType type, int palletId) { this.Type = type; this.PalletId = palletId; this._sets = new Dictionary<int, Set>(); } public Dictionary<int, Set> Sets { get { return this._sets; } set { this._sets = value; } } } }
helloimcasper/GalaxyEmulator
galaxy.core/misc/figuredata/types/FigureSet.cs
C#
agpl-3.0
583
/* * Copyright (c) 2012 - 2020 Splice Machine, Inc. * * This file is part of Splice Machine. * Splice Machine is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either * version 3, or (at your option) any later version. * Splice Machine is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License along with Splice Machine. * If not, see <http://www.gnu.org/licenses/>. */ package com.splicemachine.access.api; import com.splicemachine.db.iapi.store.access.conglomerate.Conglomerate; import com.splicemachine.storage.Partition; import java.io.IOException; import java.util.concurrent.Future; /** * @author Scott Fines * Date: 12/28/15 */ public interface PartitionCreator{ PartitionCreator withName(String name); PartitionCreator withName(String name, Conglomerate.Priority priority); PartitionCreator withDisplayNames(String[] displayNames); /** * Set the maximum size of a given subpartition for this overall partition, * if the underlying architecture supports table-specific partition sizes. * * If the architecture does not support table-specific partition sizes, then * this is a no-op. * * @param partitionSize the size of a partition * @return a creator */ PartitionCreator withPartitionSize(long partitionSize); PartitionCreator withCoprocessor(String coprocessor) throws IOException; PartitionCreator withTransactionId(long txnId) throws IOException; PartitionCreator withSplitKeys(byte[][] splitKeys); PartitionCreator withCatalogVersion(String version); Partition create() throws IOException; Future<Partition> createAsync() throws IOException; }
splicemachine/spliceengine
splice_access_api/src/main/java/com/splicemachine/access/api/PartitionCreator.java
Java
agpl-3.0
2,043
<?php /** * zCorrecteurs.fr est le logiciel qui fait fonctionner www.zcorrecteurs.fr * * Copyright (C) 2012-2019 Corrigraphie * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ namespace Zco\Bundle\ContentBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Zco\Bundle\ContentBundle\Domain\CategoryDAO; use Zco\Bundle\ContentBundle\Search\Searchable\BlogSearchable; use Zco\Bundle\ContentBundle\Search\Searchable\ForumSearchable; use Zco\Bundle\ContentBundle\Search\SearchQuery; use Symfony\Bundle\FrameworkBundle\Controller\Controller; /** * Contrôleur gérant la recherche sur le site. * * @author mwsaz <mwsaz@zcorrecteurs.fr> */ class SearchController extends Controller { /** * Affichage du formulaire complet de recherche et des résultats. * * @param Request $request HTTP request. * @return Response */ public function indexAction(Request $request) { $section = $request->query->get('section', 'forum'); $page = $request->query->get('page', 1); // Configuration pour les trois actions (avant et après la recherche) $CatsForum = CategoryDAO::ListerEnfants(CategoryDAO::GetIDCategorie('forum'), true, true); $CatsBlog = CategoryDAO::ListerEnfants(CategoryDAO::GetIDCategorie('blog'), true, true); \Page::$titre = 'Recherche'; $this->get('zco_core.resource_manager')->requireResources(array( '@ZcoContentBundle/Resources/public/css/forum.css', '@ZcoCoreBundle/Resources/public/css/tableaux_messages.css', '@ZcoCoreBundle/Resources/public/css/zcode.css', )); $_flags = array(); // Section du site concernée par la recherche if ('forum' === $section) { $searchable = new ForumSearchable(); } elseif ('blog' === $section) { $searchable = new BlogSearchable(); } else { return redirect( 'Votre catégorie de recherche est invalide.', $this->generateUrl('zco_search_index'), MSG_ERROR ); } if (!$request->query->has('recherche')) { return $this->render('ZcoContentBundle:Search:index.html.php', compact( 'CatsForum', 'CatsBlog', '_flags' )); } $query = new SearchQuery(); $_flags['recherche'] = $request->query->get('recherche'); $query->setSearch($_flags['recherche']); // Pagination. $_flags['nb_resultats'] = $resultats = (int)$request->query->get('nb_resultats', 20); $resultats = ($resultats <= 50 && $resultats >= 5) ? $resultats : 20; $page = max(1, $page); $_flags['nb_resultats'] = $resultats; $query->setPage($page, $resultats); // Mode de recherche. $modes = [ 'tous' => SearchQuery::MATCH_ALL, 'un' => SearchQuery::MATCH_ANY, 'phrase' => SearchQuery::MATCH_PHRASE ]; $mode = $request->query->get('mode', current($modes)); $mode = isset($modes[$mode]) ? $mode : current($modes); $_flags['mode'] = $mode; $query->setMatchMode($mode); // Restriction de catégorie. if ($request->query->has('categories')) { $categoryIds = $request->query->get('categories') ?: []; $query->setCategories($categoryIds); $_flags['categories'] = $categoryIds; } // Critères de recherche spécifiques à une section. if ($section == 'forum') { $flags = array('ferme', 'resolu', 'postit'); foreach ($flags as $flg) { if ($request->query->has($flg)) { $_flags[$flg] = (bool)$request->query->get($flg); if ($_flags[$flg]) { $query->includeFlag('sujet_' . $flg); } else { $query->excludeFlag('sujet_' . $flg); } } } $_flags['auteur'] = $request->query->get('auteur', ''); if ($_flags['auteur']) { $query->setAuthor($_flags['auteur']); } } elseif ($section == 'blog') { // … } elseif ($section == 'twitter') { $_flags['auteur'] = $request->query->get('auteur', ''); if ($_flags['auteur']) { $query->setAuthor($_flags['auteur']); } } // Récupération des résultats $pages = $Resultats = $CompterResultats = null; try { $res = $this->get('zco_search.search_service')->execute($query, $searchable); $Resultats = $res->getResults(); $CompterResultats = $res->getTotalCount(); //TODO: fix pagination here. $url = str_replace('91919191', '%s', $this->generateUrl('zco_search_index', array_merge(['section' => $section, 'page' => 91919191], $_flags))); $pages = liste_pages($page, ceil($CompterResultats / $_flags['nb_resultats']), $url); } catch (\Exception $e) { $this->get('logger')->warn($e->getMessage()); $_SESSION['erreur'][] = 'Une erreur est survenue pendant la recherche. Merci de réessayer dans quelques instants.'; } return $this->render('ZcoContentBundle:Search:index.html.php', compact( 'CatsForum', 'CatsBlog', '_flags', 'pages', 'CompterResultats', 'Resultats', 'section' )); } }
zcorrecteurs/monolith-www
src/Zco/Bundle/ContentBundle/Controller/SearchController.php
PHP
agpl-3.0
6,183
/* * _ _ _ * | | | | | | * | | __ _| |__ ___ ___ __ _| |_ Labcoat (R) * | |/ _` | '_ \ / __/ _ \ / _` | __| Powerful development environment for Quirrel. * | | (_| | |_) | (_| (_) | (_| | |_ Copyright (C) 2010 - 2013 SlamData, Inc. * |_|\__,_|_.__/ \___\___/ \__,_|\__| All Rights Reserved. * * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version * 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See * the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this * program. If not, see <http://www.gnu.org/licenses/>. * */ /* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2010, Ajax.org B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Ajax.org B.V. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ***** END LICENSE BLOCK ***** */ define(function(require, exports, module) { "use strict"; var oop = require("ace/lib/oop"); var EventEmitter = require("ace/lib/event_emitter").EventEmitter; var Editor = exports.Editor = function() { this._buffers = []; this._windows = []; }; (function() { oop.implement(this, EventEmitter); this.addBuffer = function(buffer) { this._buffers.push(buffer); return this._buffers.length-1; }; this.addWindow = function(win) { this._windows.push(win); return this._windows.length-1; }; this.openInWindow = function(bufferId, winId) { this._windows[winId || 0].setBuffer(this._buffers[bufferId]); }; }).call(Editor.prototype); });
precog/labcoat-legacy
js/ace/model/editor.js
JavaScript
agpl-3.0
3,492
/*************************************************************************** helpaboutform.cpp - description ------------------- begin : Tue Apr 22 2003 copyright : (C) 2003 by Lalescu Liviu email : Please see https://lalescu.ro/liviu/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address) ***************************************************************************/ /*************************************************************************** * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of the * * License, or (at your option) any later version. * * * ***************************************************************************/ #include <QCoreApplication> #include <QString> #include "helpaboutform.h" #include "timetable_defs.h" #include "centerwidgetonscreen.h" HelpAboutForm::HelpAboutForm(QWidget* parent): QDialog(parent) { setupUi(this); closePushButton->setDefault(true); aboutTextBrowser->setReadOnly(true); authorsTextBrowser->setReadOnly(true); translatorsTextBrowser->setReadOnly(true); referencesTextBrowser->setReadOnly(true); thanksToTextBrowser->setReadOnly(true); connect(closePushButton, SIGNAL(clicked()), this, SLOT(close())); centerWidgetOnScreen(this); restoreFETDialogGeometry(this); tabWidget->setCurrentIndex(0); aboutTextBrowser->setOpenExternalLinks(true); referencesTextBrowser->setOpenExternalLinks(true); //Trick to have the translations handy for future releases QString monthJan=QCoreApplication::translate("MonthsNames", "January"); Q_UNUSED(monthJan); QString monthFeb=QCoreApplication::translate("MonthsNames", "February"); Q_UNUSED(monthFeb); QString monthMar=QCoreApplication::translate("MonthsNames", "March"); Q_UNUSED(monthMar); QString monthApr=QCoreApplication::translate("MonthsNames", "April"); Q_UNUSED(monthApr); QString monthMay=QCoreApplication::translate("MonthsNames", "May"); Q_UNUSED(monthMay); QString monthJun=QCoreApplication::translate("MonthsNames", "June"); Q_UNUSED(monthJun); QString monthJul=QCoreApplication::translate("MonthsNames", "July"); Q_UNUSED(monthJul); QString monthAug=QCoreApplication::translate("MonthsNames", "August"); Q_UNUSED(monthAug); QString monthSep=QCoreApplication::translate("MonthsNames", "September"); Q_UNUSED(monthSep); QString monthOct=QCoreApplication::translate("MonthsNames", "October"); Q_UNUSED(monthOct); QString monthNov=QCoreApplication::translate("MonthsNames", "November"); Q_UNUSED(monthNov); QString monthDec=QCoreApplication::translate("MonthsNames", "December"); Q_UNUSED(monthDec); QString about=QString(""); about+=tr("FET is free software for automatically scheduling the timetable of a school, high-school or university."); about+="<br /><br />"; about+=tr("Copyright (C) %1-%2 %3.", "%1 is the year of the first FET release, %2 is the current release year, %3 are the FET authors") .arg(2002).arg(2019).arg("Liviu Lalescu, Volker Dirr"); about+="<br /><br />"; about+=tr("Version: %1 (%2 %3).", "%1 is the current FET version, %2 is the current release month, %3 is the current release year").arg(FET_VERSION) .arg(QCoreApplication::translate("MonthsNames", "January")).arg(2019); about+="<br /><br />"; about+=tr("Licensed under the GNU Affero General Public License version 3 or later."); about+="<br /><br />"; about+=tr("FET homepage: %1", "%1 is the FET homepage").arg("<a href=\"https://lalescu.ro/liviu/fet/\">https://lalescu.ro/liviu/fet/</a>"); about+="<br />"; aboutTextBrowser->setHtml(about); QString authors=QString(""); authors+=QString("Liviu Lalescu (https://lalescu.ro/liviu/)"); authors+="<br /><br />"; authors+=QString("Volker Dirr (https://www.timetabling.de/)"); authors+="<br />"; authors+=QString("&nbsp;&nbsp;&nbsp;&nbsp;- ")+tr("XHTML timetable export."); authors+="<br />"; authors+=QString("&nbsp;&nbsp;&nbsp;&nbsp;- ")+tr("CSV import and export."); authors+="<br />"; authors+=QString("&nbsp;&nbsp;&nbsp;&nbsp;- ")+tr("Advanced statistics print/export."); authors+="<br />"; authors+=QString("&nbsp;&nbsp;&nbsp;&nbsp;- ")+tr("Speed improvements in the timetable generation."); authors+="<br />"; authors+=QString("&nbsp;&nbsp;&nbsp;&nbsp;- ")+tr("Locking the activities."); authors+="<br />"; authors+=QString("&nbsp;&nbsp;&nbsp;&nbsp;- ")+tr("Activity planning dialog."); authors+="<br />"; authors+=QString("&nbsp;&nbsp;&nbsp;&nbsp;- ")+tr("Print timetable dialog."); authors+="<br />"; authorsTextBrowser->setHtml(authors); QString translators=QString(""); translators+=QString("ar - ")+tr("Arabic translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("former translator: %1 (to contact %2 visit FET forum - %3, " "section about Arabic translation, or contact forum user %4)", "%1 is the translator, %2 is his short name, %3 is the FET forum address, " "%4 is the username of the translator").arg("Silver").arg("Silver").arg("https://lalescu.ro/liviu/fet/forum/").arg("Silver"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("current translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Benahmed Abdelkrim").arg("pmg9.81 AT gmail.com"); translators+=QString("<br /><br /><br />"); translators+=QString("ca - ")+tr("Catalan translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("former translator: %1 (to contact %2 visit FET forum - %3, " "section about Catalan translation, or contact forum user %4)", "%1 is the translator, %2 is his short name, %3 is the FET forum address, " "%4 is the username of the translator").arg(QString::fromUtf8("Sílvia Lag")).arg(QString::fromUtf8("Sílvia")).arg("https://lalescu.ro/liviu/fet/forum/").arg("silvia"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("current translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Innocent De Marchi").arg("tangram.peces AT gmail.com"); translators+=QString("<br /><br /><br />"); translators+=QString("cs - ")+tr("Czech translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Pavel Fric").arg("pavelfric AT seznam.cz"); translators+=QString("<br /><br /><br />"); translators+=QString("da - ")+tr("Danish translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("David Lamhauge").arg("davidlamhauge AT gmail.com"); translators+=QString("<br /><br /><br />"); translators+=QString("de - ")+tr("German translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("former translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Volker Dirr").arg("https://www.timetabling.de/"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("current translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Robert Hairgrove").arg("code AT roberthairgrove.com"); translators+=QString("<br /><br /><br />"); translators+=QString("el - ")+tr("Greek translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("former translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Dimitrios Ropokis").arg("wamy80s AT gmail.com"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("former translator: %1 (to contact %2 visit FET forum - %3, " "section about Greek translation, or contact forum user %4)", "%1 is the translator, %2 is his short name, %3 is the FET forum address, " "%4 is the username of the translator").arg("Dimitris Kanatas").arg("Dimitris Kanatas").arg("https://lalescu.ro/liviu/fet/forum/").arg("Dimitris Kanatas"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("current translator: %1 (to contact %2 visit FET forum - %3, " "section about Greek translation, or contact forum user %4)" ,"%1 is the translator, %2 is his short name, %3 is the FET forum address, " "%4 is the username of the translator").arg("Vangelis Karafillidis").arg("Vangelis Karafillidis").arg("https://lalescu.ro/liviu/fet/forum/").arg("Vangelis Karafillidis"); translators+=QString(" - ")+tr("rewrote the translation from zero"); translators+=QString("<br /><br /><br />"); translators+=QString("es - ")+tr("Spanish translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("former translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address") .arg(QString::fromUtf8("José César Fernández López")).arg("cesar.fernandez.lopez AT gmail.com"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("current translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address") .arg(QString::fromUtf8("Emiliano Llano Díaz")).arg("compuvtt AT hotmail.com"); translators+=QString(" - ")+tr("rewrote the translation from zero"); translators+=QString("<br /><br /><br />"); translators+=QString("eu - ")+tr("Basque translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Asier Urio Larrea").arg("asieriko AT gmail.com"); translators+=QString("<br /><br /><br />"); translators+=QString("fa - ")+tr("Persian translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("former translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Hamed SadeghiNeshat").arg("ha_sadeghi AT ce.sharif.edu"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("current translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("sally sat").arg("soory63 AT gmail.com"); translators+=QString("<br /><br /><br />"); translators+=QString("fr - ")+tr("French translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("former translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Jerome Durand").arg("fetfr AT free.fr"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("former translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Patrick Fox").arg("patrick.fox AT laposte.net"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("former translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address") .arg(QString::fromUtf8("Régis Bouguin")).arg("regis.bouguin AT laposte.net"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("current translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Pascal Cohen").arg("pacohen AT laposte.net"); translators+=QString(" - ")+tr("rewrote the translation from zero"); translators+=QString("<br /><br /><br />"); translators+=QString("gl - ")+tr("Galician translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("%1 (to contact %2 visit FET forum - %3, " "section about Galician translation, or contact forum user %4)", "%1 is the translator, %2 is his short name, %3 is the FET forum address, " "%4 is the username of the translator").arg("Juan Marcos Filgueira Gomis").arg("marcos.filgueira").arg("https://lalescu.ro/liviu/fet/forum/").arg("marcos.filgueira"); translators+=QString("<br /><br /><br />"); translators+=QString("he - ")+tr("Hebrew translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Yotam Medini").arg("yotam.medini AT gmail.com"); translators+=QString("<br /><br /><br />"); translators+=QString("hu - ")+tr("Hungarian translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Ferenczi Viktor").arg("cx AT cx.hu"); translators+=QString("<br /><br /><br />"); translators+=QString("id - ")+tr("Indonesian translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Nirwan Yus").arg("ny.unpar AT gmail.com"); translators+=QString("<br /><br /><br />"); translators+=QString("it - ")+tr("Italian translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Marco Barsotti").arg("mbarsan AT gmail.com"); translators+=QString("<br /><br /><br />"); translators+=QString("ja - ")+tr("Japanese translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("%1 (to contact %2 visit FET forum - %3, " "section about Japanese translation, or contact forum user %4)", "%1 is the translator, %2 is his short name, %3 is the FET forum address, " "%4 is the username of the translator").arg("Taro Tada").arg("Taro Tada").arg("https://lalescu.ro/liviu/fet/forum/").arg("Taro Tada"); translators+=QString("<br /><br /><br />"); translators+=QString("lt - ")+tr("Lithuanian translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Darius Staigys").arg("darius AT e-servisas.lt"); translators+=QString("<br /><br /><br />"); translators+=QString("mk - ")+tr("Macedonian translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Zoran Zdravkovski").arg("zoran AT pmf.ukim.edu.mk"); translators+=QString("<br /><br /><br />"); translators+=QString("ms - ")+tr("Malay translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Abdul Hadi Kamel").arg("hadikamel AT perlis.uitm.edu.my"); translators+=QString("<br /><br /><br />"); translators+=QString("nl - ")+tr("Dutch translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Niels Fikse").arg("k.fikse AT student.utwente.nl"); translators+=QString("<br /><br /><br />"); translators+=QString("pl - ")+tr("Polish translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Radoslaw Pasiok").arg("zapala AT konto.pl"); translators+=QString("<br /><br /><br />"); translators+=QString("pt_BR - ")+tr("Brazilian Portuguese translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("former translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Werner Bruns").arg("werner.bruns AT gmail.com"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("former translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address") .arg(QString::fromUtf8("Frank Mártin")).arg("drfarofa AT gmail.com"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("former translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Cloves das Neves").arg("clovesneves AT gmail.com"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("current translator: %1 (%2). (Alternatively, to contact %3 visit FET forum - %4, " "section about Brazilian Portuguese translation, or contact forum user %5)", "%1 is the name of the translator, %2 is his email or web address, " "%3 is the short name of the translator, %4 is the address of the forum, %5 is forum user name of the translator") .arg("Alexandre R. Soares").arg("alexrsoares AT zoho.com").arg("Alexandre R. Soares").arg("https://lalescu.ro/liviu/fet/forum/").arg("khemis"); translators+=QString("<br /><br /><br />"); translators+=QString("ro - ")+tr("Romanian translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Liviu Lalescu").arg("https://lalescu.ro/liviu/"); translators+=QString("<br /><br /><br />"); translators+=QString("ru - ")+tr("Russian translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Ilya V. Paramonov").arg("ivparamonov AT gmail.com"); translators+=QString("<br /><br /><br />"); translators+=QString("si - ")+tr("Sinhala translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Achini Duisna").arg("duisna1012 AT gmail.com"); translators+=QString("<br /><br /><br />"); translators+=QString("sk - ")+tr("Slovak translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("%1 (to contact %2 visit FET forum - %3, " "section about Slovak translation, or contact forum user %4)", "%1 is the translator, %2 is his short name, %3 is the FET forum address, " "%4 is the username of the translator").arg("Ondrej Gregor").arg("Ondrej").arg("https://lalescu.ro/liviu/fet/forum/").arg("Ondrej"); translators+=QString("<br /><br /><br />"); translators+=QString("sq - ")+tr("Albanian translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Artur Lugu").arg("ciaoartur AT yahoo.it"); translators+=QString("<br /><br /><br />"); translators+=QString("sr - ")+tr("Serbian translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Ivan Starchevicy").arg("ivanstar61 AT gmail.com"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Radan Putnik").arg("srastral AT gmail.com"); translators+=QString("<br /><br /><br />"); translators+=QString("tr - ")+tr("Turkish translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("former translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Mehmet Gezmisoglu").arg("m_gezmisoglu AT hotmail.com"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("former translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Mahir Nacar").arg("mahirnacar AT email.com"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("current translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Yakup Kadri Demirci").arg("yakup AT engineer.com"); translators+=QString("<br /><br /><br />"); translators+=QString("uk - ")+tr("Ukrainian translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("Andriy Melnyk").arg("melnyk.andriy AT gmail.com"); translators+=QString("<br /><br /><br />"); translators+=QString("uz - ")+tr("Uzbek translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("%1 (%2, or visit FET forum - %3, " "section about Uzbek translation, or contact forum user %4)", "%1 is the current translator, %2 is his email or web address, %3 is the FET forum address, " "%4 is the username of the translator").arg("Orzubek Eraliyev").arg("o.eraliyev AT gmail.com").arg("https://lalescu.ro/liviu/fet/forum/").arg("sarkor"); translators+=QString("<br /><br /><br />"); translators+=QString("vi - ")+tr("Vietnamese translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("former translator: %1 (to contact %2 visit FET forum - %3, " "section about Vietnamese translation, or contact forum user %4)", "%1 is the translator, %2 is his short name, %3 is the FET forum address, " "%4 is the username of the translator").arg("Nguyen Truong Thang").arg("Thang").arg("https://lalescu.ro/liviu/fet/forum/").arg("NTThang"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("current translator: %1 (%2)", "%1 is the name of the translator, %2 is his email or web address") .arg(QString::fromUtf8("Nguyễn Hữu Duyệt")).arg("nguyenhuuduyet AT gmail.com"); translators+=QString("<br /><br /><br />"); translators+=QString("zh_CN - ")+tr("Chinese Simplified translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("orange").arg("112260085 AT qq.com"); translators+=QString("<br /><br /><br />"); translators+=QString("zh_TW - ")+tr("Chinese Traditional translation"); translators+=QString("<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;"); translators+=tr("%1 (%2)", "%1 is the name of the translator, %2 is his email or web address").arg("James").arg("james AT cc.shu.edu.tw"); translators+=QString("<br />"); translatorsTextBrowser->setHtml(translators); QString references=QString(""); references+=tr("You may find references for the algorithms and techniques used in this program on the FET documentation web page, %1") .arg("<a href=\"https://lalescu.ro/liviu/fet/doc/\">https://lalescu.ro/liviu/fet/doc/</a>"); references+="<br />"; referencesTextBrowser->setHtml(references); QString thanksTo=QString(""); thanksTo+=QString("(")+tr("chronologically")+QString("):"); thanksTo+=QString("<br /><br />"); thanksTo+=QString::fromUtf8("Costin Bădică"); thanksTo+=QString("<br />"); thanksTo+=QString("Carsten Niehaus"); thanksTo+=QString("<br />"); thanksTo+=QString("Imre Nagy"); thanksTo+=QString("<br />"); thanksTo+=QString("Sajith V. K."); thanksTo+=QString("<br />"); thanksTo+=QString("Michael Towers"); thanksTo+=QString("<br />"); thanksTo+=QString("Antti Leppik"); thanksTo+=QString("<br />"); thanksTo+=QString("Ian Fantom"); thanksTo+=QString("<br />"); thanksTo+=QString("Simon Ghetti"); thanksTo+=QString("<br />"); thanksTo+=QString("Gibbon Tamba"); thanksTo+=QString("<br />"); thanksTo+=QString("Jerome Durand"); thanksTo+=QString("<br />"); thanksTo+=QString("Marek Jaszuk"); thanksTo+=QString("<br />"); thanksTo+=QString("Ramanathan Srinivasan"); thanksTo+=QString("<br />"); thanksTo+=QString("Vimal Joseph"); thanksTo+=QString("<br />"); thanksTo+=QString("Cristian Gherman"); thanksTo+=QString("<br />"); thanksTo+=QString("Nicholas Robinson"); thanksTo+=QString("<br />"); thanksTo+=QString("Radu Spineanu"); thanksTo+=QString("<br />"); thanksTo+=QString("Morten Piil"); thanksTo+=QString("<br />"); thanksTo+=QString("Sebastian Canagaratna"); thanksTo+=QString("<br />"); thanksTo+=QString("Abdul Hadi Kamel"); thanksTo+=QString("<br />"); thanksTo+=QString("Miguel Gea Milvaques"); thanksTo+=QString("<br />"); thanksTo+=QString("Frans de Bruijn"); thanksTo+=QString("<br />"); thanksTo+=QString("Radoslaw Pasiok"); thanksTo+=QString("<br />"); thanksTo+=QString("Daan Huntjens"); thanksTo+=QString("<br />"); thanksTo+=QString("Yush Yuen"); thanksTo+=QString("<br />"); thanksTo+=QString("Scott Sweeting"); thanksTo+=QString("<br />"); thanksTo+=QString::fromUtf8("Dragoș Petrașcu"); thanksTo+=QString("<br />"); thanksTo+=QString("Daniel S."); thanksTo+=QString("<br />"); thanksTo+=QString("Gianluca Salvo"); thanksTo+=QString("<br />"); thanksTo+=QString("Sebastian O'Halloran"); thanksTo+=QString("<br />"); thanksTo+=QString("Mehmet Gezmisoglu"); thanksTo+=QString("<br />"); thanksTo+=QString("Tom Hosty"); thanksTo+=QString("<br />"); thanksTo+=QString("Niels Fikse"); thanksTo+=QString("<br />"); thanksTo+=QString("Simon Bohlin"); thanksTo+=QString("<br />"); thanksTo+=QString("Volker Dirr"); thanksTo+=QString("<br />"); thanksTo+=QString("Les Richardson"); thanksTo+=QString("<br />"); thanksTo+=QString("Gabi Danon"); thanksTo+=QString("<br />"); thanksTo+=QString("Manolo Par"); thanksTo+=QString("<br />"); thanksTo+=QString("Viktor Ferenczi"); thanksTo+=QString("<br />"); thanksTo+=QString("Patrick Fox"); thanksTo+=QString("<br />"); thanksTo+=QString("Andres Chandia"); thanksTo+=QString("<br />"); thanksTo+=QString("Zoran Zdravkovski"); thanksTo+=QString("<br />"); thanksTo+=QString("Constantin Romulus"); thanksTo+=QString("<br />"); thanksTo+=QString("L. W. Johnstone"); thanksTo+=QString("<br />"); thanksTo+=QString("Zsolt Udvari"); thanksTo+=QString("<br />"); thanksTo+=QString("mantas"); thanksTo+=QString("<br />"); thanksTo+=QString("moryus"); thanksTo+=QString("<br />"); thanksTo+=QString("bb"); thanksTo+=QString("<br />"); thanksTo+=QString("Maciej Deorowicz"); thanksTo+=QString("<br />"); thanksTo+=QString::fromUtf8("José César Fernández López"); thanksTo+=QString("<br />"); thanksTo+=QString("Daniel Chiriac"); thanksTo+=QString("<br />"); thanksTo+=QString("Dimitrios Ropokis"); thanksTo+=QString("<br />"); thanksTo+=QString("Danail"); thanksTo+=QString("<br />"); thanksTo+=QString("Peter Ambroz"); thanksTo+=QString("<br />"); thanksTo+=QString("Nirwan Yus"); thanksTo+=QString("<br />"); thanksTo+=QString("Marco Barsotti"); thanksTo+=QString("<br />"); thanksTo+=QString("Silver"); thanksTo+=QString("<br />"); thanksTo+=QString::fromUtf8("Horațiu Hălmăjan"); thanksTo+=QString("<br />"); thanksTo+=QString("kdsayang"); thanksTo+=QString("<br />"); thanksTo+=QString("didit"); thanksTo+=QString("<br />"); thanksTo+=QString("Bobby Wise"); thanksTo+=QString("<br />"); thanksTo+=QString("Willy Henckert"); thanksTo+=QString("<br />"); thanksTo+=QString("Wilfred"); thanksTo+=QString("<br />"); thanksTo+=QString("W. D. John"); thanksTo+=QString("<br />"); thanksTo+=QString("Darius Staigys"); thanksTo+=QString("<br />"); thanksTo+=QString("George Miliotis [Ionio]"); thanksTo+=QString("<br />"); thanksTo+=QString::fromUtf8("Sílvia"); thanksTo+=QString("<br />"); thanksTo+=QString("Chafik Graiguer"); thanksTo+=QString("<br />"); thanksTo+=QString("Niels Stargardt"); thanksTo+=QString("<br />"); thanksTo+=QString("Cristian Balint"); thanksTo+=QString("<br />"); thanksTo+=QString("sherman"); thanksTo+=QString("<br />"); thanksTo+=QString("Azu Boba"); thanksTo+=QString("<br />"); thanksTo+=QString("Thomas Schwartz"); thanksTo+=QString("<br />"); thanksTo+=QString::fromUtf8("Cătălin Maican"); thanksTo+=QString("<br />"); thanksTo+=QString("Ilya V. Paramonov"); thanksTo+=QString("<br />"); thanksTo+=QString("Hamed SadeghiNeshat"); thanksTo+=QString("<br />"); thanksTo+=QString("Joan de Gracia"); thanksTo+=QString("<br />"); thanksTo+=QString("Massimo Mancini"); thanksTo+=QString("<br />"); thanksTo+=QString("Regina V. Kryvakovska"); thanksTo+=QString("<br />"); thanksTo+=QString::fromUtf8("ßingen"); thanksTo+=QString("<br />"); thanksTo+=QString("Angela"); thanksTo+=QString("<br />"); thanksTo+=QString("T. Renganathan"); thanksTo+=QString("<br />"); thanksTo+=QString("Marco"); thanksTo+=QString("<br />"); thanksTo+=QString("sally sat"); thanksTo+=QString("<br />"); thanksTo+=QString("sstt2"); thanksTo+=QString("<br />"); thanksTo+=QString("Nikos Koutsoukos"); thanksTo+=QString("<br />"); thanksTo+=QString("pinco"); thanksTo+=QString("<br />"); thanksTo+=QString("Ben Bauer"); thanksTo+=QString("<br />"); thanksTo+=QString("Rodica Lalescu"); thanksTo+=QString("<br />"); thanksTo+=QString("Gigica Nedelcu"); thanksTo+=QString("<br />"); thanksTo+=QString("Paolo Cataldi"); thanksTo+=QString("<br />"); thanksTo+=QString("Gerrit Jan Veltink"); thanksTo+=QString("<br />"); thanksTo+=QString("Soyeb Aswat"); thanksTo+=QString("<br />"); thanksTo+=QString("Andriy Melnyk"); thanksTo+=QString("<br />"); thanksTo+=QString("Frans"); thanksTo+=QString("<br />"); thanksTo+=QString("m"); thanksTo+=QString("<br />"); thanksTo+=QString("Christoph Schilling"); thanksTo+=QString("<br />"); thanksTo+=QString::fromUtf8("Frank Mártin"); thanksTo+=QString("<br />"); thanksTo+=QString("Werner Bruns"); thanksTo+=QString("<br />"); thanksTo+=QString("aliponte"); thanksTo+=QString("<br />"); thanksTo+=QString("David Lamhauge"); thanksTo+=QString("<br />"); thanksTo+=QString("murad"); thanksTo+=QString("<br />"); thanksTo+=QString("Achini Duisna"); thanksTo+=QString("<br />"); thanksTo+=QString("Ondrej Gregor"); thanksTo+=QString("<br />"); thanksTo+=QString::fromUtf8("Karel Rodríguez Varona"); thanksTo+=QString("<br />"); thanksTo+=QString("Remus Turea"); thanksTo+=QString("<br />"); thanksTo+=QString("Joachim"); thanksTo+=QString("<br />"); thanksTo+=QString("Chichi Lalescu"); thanksTo+=QString("<br />"); thanksTo+=QString("Iftekhar Ahmad"); thanksTo+=QString("<br />"); thanksTo+=QString("DT"); thanksTo+=QString("<br />"); thanksTo+=QString("Yotam Medini"); thanksTo+=QString("<br />"); thanksTo+=QString("mohd"); thanksTo+=QString("<br />"); thanksTo+=QString("Dimitris Kanatas"); thanksTo+=QString("<br />"); thanksTo+=QString("waleed"); thanksTo+=QString("<br />"); thanksTo+=QString("aang"); thanksTo+=QString("<br />"); thanksTo+=QString("M K Lohumi"); thanksTo+=QString("<br />"); thanksTo+=QString::fromUtf8("Régis Bouguin"); thanksTo+=QString("<br />"); thanksTo+=QString("Ivan Starchevicy"); thanksTo+=QString("<br />"); thanksTo+=QString("Radan Putnik"); thanksTo+=QString("<br />"); thanksTo+=QString("Asti Widayanti"); thanksTo+=QString("<br />"); thanksTo+=QString("uni_instructor"); thanksTo+=QString("<br />"); thanksTo+=QString("liquid"); thanksTo+=QString("<br />"); thanksTo+=QString("Juan Marcos Filgueira Gomis"); thanksTo+=QString("<br />"); thanksTo+=QString("llantones"); thanksTo+=QString("<br />"); thanksTo+=QString("Christian Kemmer"); thanksTo+=QString("<br />"); thanksTo+=QString("Davide G. M. Salvetti"); thanksTo+=QString("<br />"); thanksTo+=QString("lalloso"); thanksTo+=QString("<br />"); thanksTo+=QString("drew"); thanksTo+=QString("<br />"); thanksTo+=QString("Fabio Piedimonte"); thanksTo+=QString("<br />"); thanksTo+=QString("K"); thanksTo+=QString("<br />"); thanksTo+=QString("skinkone"); thanksTo+=QString("<br />"); thanksTo+=QString("Jonathan Block"); thanksTo+=QString("<br />"); thanksTo+=QString("Nguyen Truong Thang"); thanksTo+=QString("<br />"); thanksTo+=QString("kdrosos"); thanksTo+=QString("<br />"); thanksTo+=QString("Ian Holden"); thanksTo+=QString("<br />"); thanksTo+=QString("Sarwan Bangar"); thanksTo+=QString("<br />"); thanksTo+=QString("Petros Nouvakis"); thanksTo+=QString("<br />"); thanksTo+=QString("mma"); thanksTo+=QString("<br />"); thanksTo+=QString("Orzubek Eraliyev"); thanksTo+=QString("<br />"); thanksTo+=QString("k1aas"); thanksTo+=QString("<br />"); thanksTo+=QString("nomad"); thanksTo+=QString("<br />"); thanksTo+=QString("Robert Sutcliffe"); thanksTo+=QString("<br />"); thanksTo+=QString("rjmillett"); thanksTo+=QString("<br />"); thanksTo+=QString("yasin dehghan"); thanksTo+=QString("<br />"); thanksTo+=QString("Daniel"); thanksTo+=QString("<br />"); thanksTo+=QString("Pietro"); thanksTo+=QString("<br />"); thanksTo+=QString("arivasm"); thanksTo+=QString("<br />"); thanksTo+=QString("AZ"); thanksTo+=QString("<br />"); thanksTo+=QString("Etlau"); thanksTo+=QString("<br />"); thanksTo+=QString("Nemo"); thanksTo+=QString("<br />"); thanksTo+=QString("Anton Anthofer"); thanksTo+=QString("<br />"); thanksTo+=QString("Danny Zitzman"); thanksTo+=QString("<br />"); thanksTo+=QString("geaplanet"); thanksTo+=QString("<br />"); thanksTo+=QString("Leandro Bueno"); thanksTo+=QString("<br />"); thanksTo+=QString("Laid Messaoudi"); thanksTo+=QString("<br />"); thanksTo+=QString("karim"); thanksTo+=QString("<br />"); thanksTo+=QString("hicham_idrissi"); thanksTo+=QString("<br />"); thanksTo+=QString("Davide Cottignoli"); thanksTo+=QString("<br />"); thanksTo+=QString("agemagician"); thanksTo+=QString("<br />"); thanksTo+=QString::fromUtf8("Vlăduț Frățiman"); thanksTo+=QString("<br />"); thanksTo+=QString("vlad2005"); thanksTo+=QString("<br />"); thanksTo+=QString("mouiata"); thanksTo+=QString("<br />"); thanksTo+=QString("rapsy"); thanksTo+=QString("<br />"); thanksTo+=QString("clouds"); thanksTo+=QString("<br />"); thanksTo+=QString("MarioMic"); thanksTo+=QString("<br />"); thanksTo+=QString("Cloves das Neves"); thanksTo+=QString("<br />"); thanksTo+=QString("pedrobordon"); thanksTo+=QString("<br />"); thanksTo+=QString("Tony Chan"); thanksTo+=QString("<br />"); thanksTo+=QString("Artur Lugu"); thanksTo+=QString("<br />"); thanksTo+=QString("plaldw"); thanksTo+=QString("<br />"); thanksTo+=QString("jimmyjim"); thanksTo+=QString("<br />"); thanksTo+=QString("Curtis Wilson"); thanksTo+=QString("<br />"); thanksTo+=QString("Mohamed Bahaj"); thanksTo+=QString("<br />"); thanksTo+=QString("Thomas Klausner"); thanksTo+=QString("<br />"); thanksTo+=QString::fromUtf8("Jörg Sonnenberger"); thanksTo+=QString("<br />"); thanksTo+=QString("Boubker"); thanksTo+=QString("<br />"); thanksTo+=QString("Alexey Loginov"); thanksTo+=QString("<br />"); thanksTo+=QString("_indianajones"); thanksTo+=QString("<br />"); thanksTo+=QString("russell"); thanksTo+=QString("<br />"); thanksTo+=QString("Nguyen Huu Tuyen"); thanksTo+=QString("<br />"); thanksTo+=QString("fromturkey"); thanksTo+=QString("<br />"); thanksTo+=QString("orange"); thanksTo+=QString("<br />"); thanksTo+=QString("nguyenhuuduyet"); thanksTo+=QString("<br />"); thanksTo+=QString("Vanyo Georgiev"); thanksTo+=QString("<br />"); thanksTo+=QString("bharatstank"); thanksTo+=QString("<br />"); thanksTo+=QString("alxgudea"); thanksTo+=QString("<br />"); thanksTo+=QString("andrealva"); thanksTo+=QString("<br />"); thanksTo+=QString("dotosouza"); thanksTo+=QString("<br />"); thanksTo+=QString("Bob Hairgrove"); thanksTo+=QString("<br />"); thanksTo+=QString("James"); thanksTo+=QString("<br />"); thanksTo+=QString("Khalilullah Yosufi"); thanksTo+=QString("<br />"); thanksTo+=QString("mercurialuser"); thanksTo+=QString("<br />"); thanksTo+=QString("azaer"); thanksTo+=QString("<br />"); thanksTo+=QString("chintu"); thanksTo+=QString("<br />"); thanksTo+=QString("khalafi"); thanksTo+=QString("<br />"); thanksTo+=QString("jillali elghazoui"); thanksTo+=QString("<br />"); thanksTo+=QString("Mohamed NAJARI"); thanksTo+=QString("<br />"); thanksTo+=QString("youssouf"); thanksTo+=QString("<br />"); thanksTo+=QString("Pascal Cohen"); thanksTo+=QString("<br />"); thanksTo+=QString("Asier Urio Larrea"); thanksTo+=QString("<br />"); thanksTo+=QString("Pavel Fric"); thanksTo+=QString("<br />"); thanksTo+=QString("Michel"); thanksTo+=QString("<br />"); thanksTo+=QString("MilesM"); thanksTo+=QString("<br />"); thanksTo+=QString("adso"); thanksTo+=QString("<br />"); thanksTo+=QString("locutusofborg"); thanksTo+=QString("<br />"); thanksTo+=QString("Maouhoub"); thanksTo+=QString("<br />"); thanksTo+=QString("flauta"); thanksTo+=QString("<br />"); thanksTo+=QString("Marco Vassura"); thanksTo+=QString("<br />"); thanksTo+=QString("Luigi Valbonesi"); thanksTo+=QString("<br />"); thanksTo+=QString("fernandolordao"); thanksTo+=QString("<br />"); thanksTo+=QString("Wizard"); thanksTo+=QString("<br />"); thanksTo+=QString("ant7"); thanksTo+=QString("<br />"); thanksTo+=QString("Lizio"); thanksTo+=QString("<br />"); thanksTo+=QString("Omar Ben Ali"); thanksTo+=QString("<br />"); thanksTo+=QString("Nguyen Trong Hieu"); thanksTo+=QString("<br />"); thanksTo+=QString("Arsenio Stabile"); thanksTo+=QString("<br />"); thanksTo+=QString("Vangelis Karafillidis"); thanksTo+=QString("<br />"); thanksTo+=QString("Handaya"); thanksTo+=QString("<br />"); thanksTo+=QString("Sudharshan K M"); thanksTo+=QString("<br />"); thanksTo+=QString("Nataraj Urs H D"); thanksTo+=QString("<br />"); thanksTo+=QString("Alexandre R. Soares"); thanksTo+=QString("<br />"); thanksTo+=QString("hudrea"); thanksTo+=QString("<br />"); thanksTo+=QString::fromUtf8("Udo Schütz"); thanksTo+=QString("<br />"); thanksTo+=QString("Jijo Jose"); thanksTo+=QString("<br />"); thanksTo+=QString("Fernando Poblete"); thanksTo+=QString("<br />"); thanksTo+=QString("Benahmed Abdelkrim"); thanksTo+=QString("<br />"); thanksTo+=QString("math user"); thanksTo+=QString("<br />"); thanksTo+=QString("ChicagoPianoTuner"); thanksTo+=QString("<br />"); thanksTo+=QString("MING-KIAN JONATHAN CEDRIC LEE KIM GNOK"); thanksTo+=QString("<br />"); thanksTo+=QString("daltinkurt"); thanksTo+=QString("<br />"); thanksTo+=QString::fromUtf8("Léo-Paul Roch"); thanksTo+=QString("<br />"); thanksTo+=QString::fromUtf8("Matthias Söllner"); thanksTo+=QString("<br />"); thanksTo+=QString("auriolar"); thanksTo+=QString("<br />"); thanksTo+=QString("dmcdonald"); thanksTo+=QString("<br />"); thanksTo+=QString("wahyuamin"); thanksTo+=QString("<br />"); thanksTo+=QString("abautu"); thanksTo+=QString("<br />"); thanksTo+=QString("Jan Losinski"); thanksTo+=QString("<br />"); thanksTo+=QString("mrtvillaret"); thanksTo+=QString("<br />"); thanksTo+=QString("alienglow"); thanksTo+=QString("<br />"); thanksTo+=QString("noddy11"); thanksTo+=QString("<br />"); thanksTo+=QString("JBoss"); thanksTo+=QString("<br />"); thanksTo+=QString("thanhnambkhn"); thanksTo+=QString("<br />"); thanksTo+=QString("Malamojka"); thanksTo+=QString("<br />"); thanksTo+=QString("canhathuongnhau"); thanksTo+=QString("<br />"); thanksTo+=QString("rodolforg"); thanksTo+=QString("<br />"); thanksTo+=QString("dasa"); thanksTo+=QString("<br />"); thanksTo+=QString::fromUtf8("Julio González Gil"); thanksTo+=QString("<br />"); thanksTo+=QString("Abou"); thanksTo+=QString("<br />"); thanksTo+=QString("Matsumoto"); thanksTo+=QString("<br />"); thanksTo+=QString("bart.leyen"); thanksTo+=QString("<br />"); thanksTo+=QString("math"); thanksTo+=QString("<br />"); thanksTo+=QString("s.lanore"); thanksTo+=QString("<br />"); thanksTo+=QString("Robinson A. Lemos"); thanksTo+=QString("<br />"); thanksTo+=QString("Maurino C. Maria"); thanksTo+=QString("<br />"); thanksTo+=QString("Valdo"); thanksTo+=QString("<br />"); thanksTo+=QString("sigit_yuwono"); thanksTo+=QString("<br />"); thanksTo+=QString("S Chandrasekar"); thanksTo+=QString("<br />"); thanksTo+=QString("utismetis"); thanksTo+=QString("<br />"); thanksTo+=QString("chernous"); thanksTo+=QString("<br />"); thanksTo+=QString("Roberto Bergonzini"); thanksTo+=QString("<br />"); thanksTo+=QString("sln_rj"); thanksTo+=QString("<br />"); thanksTo+=QString::fromUtf8("Emiliano Llano Díaz"); thanksTo+=QString("<br />"); thanksTo+=QString("mohammed"); thanksTo+=QString("<br />"); thanksTo+=QString("Taro Tada"); thanksTo+=QString("<br />"); thanksTo+=QString("V Paul C Charlesraj"); thanksTo+=QString("<br />"); thanksTo+=QString("Innocent De Marchi"); thanksTo+=QString("<br />"); thanksTo+=QString("Yakup Kadri Demirci"); thanksTo+=QString("<br />"); thanksTo+=QString("bachiri401"); thanksTo+=QString("<br />"); thanksTo+=QString("francescotorres"); thanksTo+=QString("<br />"); thanksTo+=QString("aisse"); thanksTo+=QString("<br />"); thanksTo+=QString("svenvanhal"); thanksTo+=QString("<br />"); thanksTo+=QString("Coralie"); thanksTo+=QString("<br />"); thanksTo+=QString("Diego Froner"); thanksTo+=QString("<br />"); thanksTo+=QString("pg788"); thanksTo+=QString("<br />"); thanksTo+=QString("Dietmar Deuster"); thanksTo+=QString("<br />"); thanksTo+=QString("Ahmed Ben Hassan"); thanksTo+=QString("<br />"); thanksTo+=QString("amin"); thanksTo+=QString("<br />"); thanksTo+=QString("Anthony Siaudeau"); thanksTo+=QString("<br />"); thanksTo+=QString("satellite2"); thanksTo+=QString("<br />"); thanksTo+=QString("Jude G"); thanksTo+=QString("<br />"); thanksToTextBrowser->setHtml(thanksTo); } HelpAboutForm::~HelpAboutForm() { saveFETDialogGeometry(this); }
rodolforg/fet
src/interface/helpaboutform.cpp
C++
agpl-3.0
41,583
import { t } from '@lingui/macro'; import { formatPercentage } from 'common/format'; import SPELLS from 'common/SPELLS'; import { SpellIcon } from 'interface'; import { SpellLink } from 'interface'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events from 'parser/core/Events'; import { ThresholdStyle } from 'parser/core/ParseResults'; import BoringValue from 'parser/ui/BoringValueText'; import Statistic from 'parser/ui/Statistic'; import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER'; import React from 'react'; import { SPELLS_WHICH_REMOVE_BOC } from '../../constants'; const debug = false; const BOC_DURATION = 15000; class BlackoutCombo extends Analyzer { get dpsWasteThreshold() { return { actual: this.spellsBOCWasUsedOn[SPELLS.TIGER_PALM.id] / this.blackoutComboBuffs, isLessThan: { minor: 0.95, average: 0.9, major: 0.85, }, style: ThresholdStyle.PERCENTAGE, }; } blackoutComboConsumed = 0; blackoutComboBuffs = 0; lastBlackoutComboCast = 0; spellsBOCWasUsedOn = {}; statisticOrder = STATISTIC_ORDER.OPTIONAL(); constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.BLACKOUT_COMBO_TALENT.id); this.addEventListener( Events.applybuff.by(SELECTED_PLAYER).spell(SPELLS.BLACKOUT_COMBO_BUFF), this.onApplyBuff, ); this.addEventListener( Events.refreshbuff.by(SELECTED_PLAYER).spell(SPELLS.BLACKOUT_COMBO_BUFF), this.onRefreshBuff, ); this.addEventListener( Events.cast.by(SELECTED_PLAYER).spell(SPELLS_WHICH_REMOVE_BOC), this.onCast, ); } onApplyBuff(event) { debug && console.log('Blackout combo applied'); this.blackoutComboBuffs += 1; this.lastBlackoutComboCast = event.timestamp; } onRefreshBuff(event) { debug && console.log('Blackout combo refreshed'); this.blackoutComboBuffs += 1; this.lastBlackoutComboCast = event.timestamp; } onCast(event) { const spellId = event.ability.guid; // BOC should be up if ( this.lastBlackoutComboCast > 0 && this.lastBlackoutComboCast + BOC_DURATION > event.timestamp ) { this.blackoutComboConsumed += 1; if (this.spellsBOCWasUsedOn[spellId] === undefined) { this.spellsBOCWasUsedOn[spellId] = 0; } this.spellsBOCWasUsedOn[spellId] += 1; } this.lastBlackoutComboCast = 0; } suggestions(when) { const wastedPerc = (this.blackoutComboBuffs - this.blackoutComboConsumed) / this.blackoutComboBuffs; when(wastedPerc) .isGreaterThan(0.1) .addSuggestion((suggest, actual, recommended) => suggest( <span> You wasted {formatPercentage(actual)}% of your{' '} <SpellLink id={SPELLS.BLACKOUT_COMBO_BUFF.id} /> procs. Try to use the procs as soon as you get them so they are not overwritten. </span>, ) .icon(SPELLS.BLACKOUT_COMBO_BUFF.icon) .actual( t({ id: 'monk.brewmaster.suggestions.blackoutCombo.wasted', message: `${formatPercentage(actual)}% unused`, }), ) .recommended(`${Math.round(formatPercentage(recommended))}% or less is recommended`) .regular(recommended + 0.1) .major(recommended + 0.2), ); } statistic() { const wastedPerc = (this.blackoutComboBuffs - this.blackoutComboConsumed) / this.blackoutComboBuffs; return ( <Statistic position={STATISTIC_ORDER.OPTIONAL()} size="flexible" tooltip={ <> You got total <strong>{this.blackoutComboBuffs}</strong> Blackout Combo procs and used{' '} <strong>{this.blackoutComboConsumed}</strong> of them. <br /> Blackout combo buff usage: <ul> {Object.keys(this.spellsBOCWasUsedOn) .sort((a, b) => this.spellsBOCWasUsedOn[b] - this.spellsBOCWasUsedOn[a]) .map((type) => ( <li key={type}> <em>{SPELLS[type].name || 'Unknown'}</em> was used{' '} {this.spellsBOCWasUsedOn[type]} time {this.spellsBOCWasUsedOn[type] === 1 ? '' : 's'} ( {formatPercentage(this.spellsBOCWasUsedOn[type] / this.blackoutComboConsumed)}%) </li> ))} </ul> </> } > <BoringValue label={ <> <SpellIcon id={SPELLS.BLACKOUT_COMBO_BUFF.id} /> Wasted Blackout Combo </> } > <>{formatPercentage(wastedPerc)}%</> </BoringValue> </Statistic> ); } } export default BlackoutCombo;
anom0ly/WoWAnalyzer
analysis/monkbrewmaster/src/modules/spells/BlackoutCombo.js
JavaScript
agpl-3.0
4,812
/* * Claudia Project * http://claudia.morfeo-project.org * * (C) Copyright 2010 Telefonica Investigacion y Desarrollo * S.A.Unipersonal (Telefonica I+D) * * See CREDITS file for info about members and contributors. * * This program is free software; you can redistribute it and/or modify * it under the terms of the Affero GNU General Public License (AGPL) 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 Affero GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * If you want to use this software an plan to distribute a * proprietary application in any way, and you are not licensing and * distributing your source code under AGPL, you probably need to * purchase a commercial license of the product. Please contact * claudia-support@lists.morfeo-project.org for more information. */ package com.telefonica.claudia.slm.deployment.hwItems; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import org.hibernate.annotations.CollectionOfElements; import com.telefonica.claudia.slm.deployment.VEEReplica; import com.telefonica.claudia.slm.naming.DirectoryEntry; import com.telefonica.claudia.slm.naming.FQN; import com.telefonica.claudia.slm.naming.ReservoirDirectory; @Entity public class NIC implements DirectoryEntry { @Id @GeneratedValue public long internalId; private int id = 0; private int throughput = 0; @CollectionOfElements private List<String> ipAddresses = new ArrayList<String>(); private byte[] macAddress = null; @OneToOne(cascade={CascadeType.REFRESH, CascadeType.MERGE, CascadeType.PERSIST}) private NICConf nicConf = null; @ManyToOne private VEEReplica veeReplica = null; @OneToOne(cascade={CascadeType.REFRESH, CascadeType.MERGE, CascadeType.PERSIST}) private FQN nicFQN = null; public NIC() {} public NIC(int id, NICConf nicConf, VEEReplica veeReplica) { if(veeReplica == null) throw new IllegalArgumentException("VEE replica cannot be null"); if(nicConf == null) throw new IllegalArgumentException("NIC conf cannot be null"); this.id = id; this.veeReplica = veeReplica; this.nicConf = nicConf; } public int getId() { return id; } public void setId(int id) { this.id = id; } public List<String> getIPAddresses() { return ipAddresses; } public void addIPAddress(String ipAddress) { this.ipAddresses.add(ipAddress); } public byte[] getMacAddress() { return macAddress; } public void setMacAddress(byte[] macAddress) { this.macAddress = macAddress; } public int getThroughput() { return throughput; } public void setThroughput(int throughput) { this.throughput = throughput; } public VEEReplica getVEEReplica() { return veeReplica; } public NICConf getNICConf() { return nicConf; } public FQN getFQN() { if(nicFQN == null) nicFQN = ReservoirDirectory.getInstance().buildFQN(this); return nicFQN; } @Override public String toString() { return getFQN().toString(); } @Override public int hashCode() { return getFQN().hashCode(); } @Override public boolean equals(Object object) { if(object == null) return false; if(!(object instanceof NIC)) return false; return ((NIC)object).getFQN().equals(getFQN()); } }
StratusLab/claudia
clotho/src/main/java/com/telefonica/claudia/slm/deployment/hwItems/NIC.java
Java
agpl-3.0
4,281
$(document).ready(function () { var pathArray = window.location.pathname.split( '/' ); var targetname = pathArray[pathArray.length -1]; $('#targetloglist').DataTable({ 'paging' : true, 'lengthChange': false, 'searching' : true, 'ordering' : true, 'order' : [[0, "desc"]], 'info' : true, 'autoWidth' : true, 'deferRender' : true, "language": { "emptyTable": "No connection history for this target" }, 'ajax' : { url : '/ajax/target/lastconnections/' + targetname, dataSrc : 'data' } }) })
LibrIT/passhport
passhweb/app/static/librit/scripts/target_lastconnections.js
JavaScript
agpl-3.0
682
// Copyright (c) 2012, 2013 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <cstdlib> #include "openMVG/sfm/sfm.hpp" #include "openMVG/system/timer.hpp" #include "openMVG/cameras/Cameras_Common_command_line_helper.hpp" #include <openMVG/geometry/box.hpp> #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" using namespace openMVG; using namespace openMVG::cameras; using namespace openMVG::sfm; /// From 2 given image file-names, find the two corresponding index in the View list bool computeIndexFromImageNames( const SfM_Data & sfm_data, const std::pair<std::string,std::string>& initialPairName, Pair& initialPairIndex) { if (initialPairName.first == initialPairName.second) { std::cerr << "\nInvalid image names. You cannot use the same image to initialize a pair." << std::endl; return false; } initialPairIndex = Pair(UndefinedIndexT, UndefinedIndexT); /// List views filenames and find the one that correspond to the user ones: for (Views::const_iterator it = sfm_data.GetViews().begin(); it != sfm_data.GetViews().end(); ++it) { const View * v = it->second.get(); const std::string filename = stlplus::filename_part(v->s_Img_path); if (filename == initialPairName.first) { initialPairIndex.first = v->id_view; } else{ if (filename == initialPairName.second) { initialPairIndex.second = v->id_view; } } } return (initialPairIndex.first != UndefinedIndexT && initialPairIndex.second != UndefinedIndexT); } bool saveIntrinsics(const SfM_Data & data, const std::string & path){ // Check and create path if necessary if (!stlplus::folder_exists(path) && !stlplus::folder_create(path)) { std::cerr << "\nCannot create output directory to write 'intrinsics_OpenMVG.txt'" << std::endl; return false; } bool checkIntrinsics = false; unsigned i = 0; while (i < data.views.size() && checkIntrinsics == false){ const View & view = *(data.views.at(i)); if(data.IsPoseAndIntrinsicDefined(&view)){ // Get intrinsics from SfM data const IntrinsicBase * baseintrinsics = data.intrinsics.at(view.id_intrinsic).get(); const Pinhole_Intrinsic_Radial_K3 & intrinsics = *(dynamic_cast<const Pinhole_Intrinsic_Radial_K3*>(baseintrinsics)); const std::vector<double> params = intrinsics.getParams(); if ( !checkIntrinsics ){ // Create the stream and check it is ok std::ofstream stream(stlplus::create_filespec(path, "intrinsics_OpenMVG.txt").c_str(), std::ios::binary | std::ios::out); if (!stream.is_open()) return false; // Write intrinsics_OpenMVG.txt stream << intrinsics.K() << std::endl; stream << params[params.size()-3] << " " << params[params.size()-2] << " " << params[params.size()-1] << " " << std::endl; stream.close(); checkIntrinsics = true; } } i++; } return true; } bool saveSFM(const SfM_Data & data, const std::string & path){ // Check and create path if necessary if (!stlplus::folder_exists(path) && !stlplus::folder_create(path)) { std::cerr << "\nCannot create output sfm directory" << std::endl; return false; } ///// Camera files for (unsigned i = 0; i < data.views.size(); ++i){ const View & view = *(data.views.at(i)); if(data.IsPoseAndIntrinsicDefined(&view)){ // Get current camera intrinsics and extrinsics from SfM data const IntrinsicBase * baseintrinsics = data.intrinsics.at(view.id_intrinsic).get(); const Pinhole_Intrinsic_Radial_K3 & intrinsics = *(dynamic_cast<const Pinhole_Intrinsic_Radial_K3*>(baseintrinsics)); const geometry::Pose3 & extrinsics = data.poses.at(view.id_pose); const std::vector<double> params = intrinsics.getParams(); // Pinhole_Intrinsic_Radial_K3 model format // params[0] = focal // params[1] = ppx // params[2] = ppy // params[3] = K1 // params[4] = K2 // params[5] = K3 // Set filename and path std::ostringstream filename; std::string fullname = data.views.at(i)->s_Img_path; size_t lastindex = fullname.find_last_of("."); std::string rawname = fullname.substr(0, lastindex); filename << rawname + "_cam.txt"; // Create the stream and check it is ok std::ofstream stream(stlplus::create_filespec(path, filename.str()), std::ios::binary | std::ios::out); if (!stream.is_open()) return false; // Write current camera file stream << "1" << std::endl; stream << intrinsics.w_ << " " << intrinsics.h_ << std::endl; stream << intrinsics.K() << std::endl; stream << extrinsics.rotation() << std::endl; stream << extrinsics.translation() << std::endl; stream << params[params.size()-3] << " " << params[params.size()-2] << " " << params[params.size()-1] << " " << std::endl; stream.close(); } } ///// Structure { // Create the stream and check it is ok std::ofstream stream(stlplus::create_filespec(path, "structure_raw.ply").c_str(), std::ios::binary | std::ios::out); if (!stream.is_open()) return false; // Write structure in a ply file stream << "ply" << std::endl; stream << "format ascii 1.0" << std::endl; stream << "element vertex " << data.structure.size() << std::endl; stream << "property float x" << std::endl; stream << "property float y" << std::endl; stream << "property float z" << std::endl; stream << "end_header" << std::endl; Landmarks::const_iterator it; for (it = data.structure.begin(); it != data.structure.end(); ++it) { const Vec3 & P = it->second.X; stream << P[0] << " " << P[1] << " " << P[2] << std::endl; } stream.close(); } ///// Bounding box { // Compute bounding box Vec3 BBmin(1e10,1e10,1e10), BBmax(-1e10,-1e10,-1e10); Landmarks::const_iterator it; for (it = data.structure.begin(); it != data.structure.end(); ++it) { const Vec3 & P = it->second.X; for (unsigned i = 0; i < 3; ++i) { if (P[i] < BBmin[i]) BBmin[i] = P[i]; else if (P[i] > BBmax[i]) BBmax[i] = P[i]; } } // Create the stream and check it is ok std::ofstream stream(stlplus::create_filespec(path, "bbox_raw.txt").c_str(), std::ios::binary | std::ios::out); if (!stream.is_open()) return false; // Write bbox in a txt file stream << BBmin[0] << " " << BBmin[1] << " " << BBmin[2] << "\n" << BBmax[0] << " " << BBmax[1] << " " << BBmax[2] << std::endl; stream.close(); } return true; } int main(int argc, char **argv) { using namespace std; std::cout << "Sequential/Incremental reconstruction" << std::endl << " Perform incremental SfM (Initial Pair Essential + Resection)." << std::endl << std::endl; CmdLine cmd; std::string sSfM_Data_Filename; std::string sMatchesDir; std::string sOutDir = ""; std::pair<std::string,std::string> initialPairString("",""); std::string sIntrinsic_refinement_options = "ADJUST_ALL"; int i_User_camera_model = PINHOLE_CAMERA_RADIAL3; bool b_use_motion_priors = false; cmd.add( make_option('i', sSfM_Data_Filename, "input_file") ); cmd.add( make_option('m', sMatchesDir, "matchdir") ); cmd.add( make_option('o', sOutDir, "outdir") ); cmd.add( make_option('a', initialPairString.first, "initialPairA") ); cmd.add( make_option('b', initialPairString.second, "initialPairB") ); cmd.add( make_option('c', i_User_camera_model, "camera_model") ); cmd.add( make_option('f', sIntrinsic_refinement_options, "refineIntrinsics") ); cmd.add( make_switch('P', "prior_usage") ); try { if (argc == 1) throw std::string("Invalid parameter."); cmd.process(argc, argv); } catch(const std::string& s) { std::cerr << "Usage: " << argv[0] << '\n' << "[-i|--input_file] path to a SfM_Data scene\n" << "[-m|--matchdir] path to the matches that corresponds to the provided SfM_Data scene\n" << "[-o|--outdir] path where the output data will be stored\n" << "\n[Optional]\n" << "[-a|--initialPairA] filename of the first image (without path)\n" << "[-b|--initialPairB] filename of the second image (without path)\n" << "[-c|--camera_model] Camera model type for view with unknown intrinsic:\n" << "\t 1: Pinhole \n" << "\t 2: Pinhole radial 1\n" << "\t 3: Pinhole radial 3 (default)\n" << "\t 4: Pinhole radial 3 + tangential 2\n" << "\t 5: Pinhole fisheye\n" << "[-f|--refineIntrinsics] Intrinsic parameters refinement option\n" << "\t ADJUST_ALL -> refine all existing parameters (default) \n" << "\t NONE -> intrinsic parameters are held as constant\n" << "\t ADJUST_FOCAL_LENGTH -> refine only the focal length\n" << "\t ADJUST_PRINCIPAL_POINT -> refine only the principal point position\n" << "\t ADJUST_DISTORTION -> refine only the distortion coefficient(s) (if any)\n" << "\t -> NOTE: options can be combined thanks to '|'\n" << "\t ADJUST_FOCAL_LENGTH|ADJUST_PRINCIPAL_POINT\n" << "\t\t-> refine the focal length & the principal point position\n" << "\t ADJUST_FOCAL_LENGTH|ADJUST_DISTORTION\n" << "\t\t-> refine the focal length & the distortion coefficient(s) (if any)\n" << "\t ADJUST_PRINCIPAL_POINT|ADJUST_DISTORTION\n" << "\t\t-> refine the principal point position & the distortion coefficient(s) (if any)\n" << "[-P|--prior_usage] Enable usage of motion priors (i.e GPS positions) (default: false)\n" << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } if (i_User_camera_model < PINHOLE_CAMERA || i_User_camera_model > PINHOLE_CAMERA_FISHEYE ) { std::cerr << "\n Invalid camera type" << std::endl; return EXIT_FAILURE; } const cameras::Intrinsic_Parameter_Type intrinsic_refinement_options = cameras::StringTo_Intrinsic_Parameter_Type(sIntrinsic_refinement_options); // Load input SfM_Data scene SfM_Data sfm_data; if (!Load(sfm_data, sSfM_Data_Filename, ESfM_Data(VIEWS|INTRINSICS))) { std::cerr << std::endl << "The input SfM_Data file \""<< sSfM_Data_Filename << "\" cannot be read." << std::endl; return EXIT_FAILURE; } // Init the regions_type from the image describer file (used for image regions extraction) using namespace openMVG::features; const std::string sImage_describer = stlplus::create_filespec(sMatchesDir, "image_describer", "json"); std::unique_ptr<Regions> regions_type = Init_region_type_from_file(sImage_describer); if (!regions_type) { std::cerr << "Invalid: " << sImage_describer << " regions type file." << std::endl; return EXIT_FAILURE; } // Features reading std::shared_ptr<Features_Provider> feats_provider = std::make_shared<Features_Provider>(); if (!feats_provider->load(sfm_data, sMatchesDir, regions_type)) { std::cerr << std::endl << "Invalid features." << std::endl; return EXIT_FAILURE; } // Matches reading std::shared_ptr<Matches_Provider> matches_provider = std::make_shared<Matches_Provider>(); if // Try to read the two matches file formats ( !(matches_provider->load(sfm_data, stlplus::create_filespec(sMatchesDir, "matches.f.txt")) || matches_provider->load(sfm_data, stlplus::create_filespec(sMatchesDir, "matches.f.bin"))) ) { std::cerr << std::endl << "Invalid matches file." << std::endl; return EXIT_FAILURE; } if (sOutDir.empty()) { std::cerr << "\nIt is an invalid output directory" << std::endl; return EXIT_FAILURE; } if (!stlplus::folder_exists(sOutDir)) { if (!stlplus::folder_create(sOutDir)) { std::cerr << "\nCannot create the output directory" << std::endl; } } //--------------------------------------- // Sequential reconstruction process //--------------------------------------- openMVG::system::Timer timer; SequentialSfMReconstructionEngine sfmEngine( sfm_data, sOutDir, stlplus::create_filespec(sOutDir, "Reconstruction_Report.html")); // Configure the features_provider & the matches_provider sfmEngine.SetFeaturesProvider(feats_provider.get()); sfmEngine.SetMatchesProvider(matches_provider.get()); // Configure reconstruction parameters sfmEngine.Set_Intrinsics_Refinement_Type(intrinsic_refinement_options); sfmEngine.SetUnknownCameraType(EINTRINSIC(i_User_camera_model)); b_use_motion_priors = cmd.used('P'); sfmEngine.Set_Use_Motion_Prior(b_use_motion_priors); // Handle Initial pair parameter if (!initialPairString.first.empty() && !initialPairString.second.empty()) { Pair initialPairIndex; if(!computeIndexFromImageNames(sfm_data, initialPairString, initialPairIndex)) { std::cerr << "Could not find the initial pairs <" << initialPairString.first << ", " << initialPairString.second << ">!\n"; return EXIT_FAILURE; } sfmEngine.setInitialPair(initialPairIndex); } if (sfmEngine.Process()) { std::cout << std::endl << " Total Ac-Sfm took (s): " << timer.elapsed() << std::endl; std::cout << "...Generating SfM_Report.html" << std::endl; Generate_SfM_Report(sfmEngine.Get_SfM_Data(), stlplus::create_filespec(sOutDir, "SfMReconstruction_Report.html")); //-- Export to disk computed scene (data & visualizable results) std::cout << "...Export SfM_Data to disk." << std::endl; Save(sfmEngine.Get_SfM_Data(), stlplus::create_filespec(sOutDir, "sfm_data", ".bin"), ESfM_Data(ALL)); Save(sfmEngine.Get_SfM_Data(), stlplus::create_filespec(sOutDir, "cloud_and_poses", ".ply"), ESfM_Data(ALL)); //-- Save sfm files for 3D reconstruction saveIntrinsics(sfmEngine.Get_SfM_Data(), sOutDir); saveSFM(sfmEngine.Get_SfM_Data(), stlplus::create_filespec(sOutDir, "sfm")); return EXIT_SUCCESS; } return EXIT_FAILURE; }
rogermm14/rec3D
modifications_openmvg/main_IncrementalSfM.cpp
C++
agpl-3.0
14,201
<?php /** * plentymarkets shopware connector * Copyright © 2013 plentymarkets GmbH * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License, supplemented by an additional * permission, and of our proprietary license can be found * in the LICENSE file you have received along with this program. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * "plentymarkets" is a registered trademark of plentymarkets GmbH. * "shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, titles and interests in the * above trademarks remain entirely with the trademark owners. * * @copyright Copyright (c) 2013, plentymarkets GmbH (http://www.plentymarkets.com) * @author Daniel Bächtle <daniel.baechtle@plentymarkets.com> */ /** * I am a generated class and am required for communicating with plentymarkets. */ class PlentySoapResponse_AddItemAttributeValueSets { /** * @var ArrayOfPlentysoapresponsemessage */ public $ResponseMessages; /** * @var boolean */ public $Success; }
k-30/plentymarkets-shopware-connector
Components/Soap/Models/PlentySoapResponse/AddItemAttributeValueSets.php
PHP
agpl-3.0
1,498
# -*- coding: utf-8 -*- import minimongo import osm import pymongo.collection import logging import re import stitch def is_area(way): return len(way.nodes)\ and way.nodes[0] == way.nodes[-1]\ and ('area' in way.tags and way.tags['area'] == 'yes'\ or (not 'highway' in way.tags\ and not 'barrier' in way.tags)) def get_poly(nodes): """Get poly from a list of node ids""" poly = [] for nodeid in nodes: for node in osm.Node.collection.find({"_id": nodeid}): poly.append((node.lon, node.lat)) return poly def truish(x): return x == "yes" or x == "true" or x == "1" def falsish(x): return x == "no" or x == "false" or x == "0" class Sink(object): def processWay(self, way): poly = get_poly(way.nodes) if is_area(way): if Area.connection.planet.multipolygon_ways.find({"_id": way._id}).count(): #logging.debug("Skipping way %d as it belongs to a multipolygon relation", way._id) return parea = Area() parea.id = way._id parea.outer = poly parea.tags = way.tags parea.save() else: typ = Way.type_from_tags(way.tags) if not typ is None: pway = Way(way._id, poly, typ) pway.attr_from_tags(way.tags) pway.save() else: pline = Line(way._id, poly, way.tags) pline.save() def processNode(self, node): pass def processRelation(self, relation): typ = relation.tags.get('type', None) if typ == 'multipolygon': self.processRelationMultiPolygon(relation) def processRelationMultiPolygon(self, rel): """http://wiki.openstreetmap.org/wiki/Relation:multipolygon""" memids = [] #logging.debug("%d members", len(rel.members)) #logging.debug("relation %d", rel._id) #if len(rel.members)> 50: # logging.debug('processRelationMultiPolygon: big rel') # logging.debug("processing %d members", len(rel.members)) # logging.debug(rel._id) # logging.debug(rel.tags) outer_stitch = stitch.Stitch(rel['_id'], True) inner_stitch = stitch.Stitch(rel['_id'], True) for m in rel.members: try: if m['type'] == 'way': way = osm.Way.collection.find_one({"_id": m['ref']}) if way: #logging.debug(way._id) try: if m['role'] == 'outer': outer_stitch.add_id(get_poly(way.nodes), way._id) elif m['role'] == 'inner': inner_stitch.add_id(get_poly(way.nodes), way._id) except RuntimeError,e: print e, 'way id: ', way['_id'], 'relation id', rel['_id'] memids.append(way['_id']) try: Area.connection.planet.multipolygon_ways.insert({"_id": way._id}, safe=True) except pymongo.errors.DuplicateKeyError: pass else: logging.debug("cound't find way id: %d in multipolygon relation id %d", m['ref'], rel._id) if m['role'] == 'outer': outer_stitch.dontClose() elif m['role'] == 'inner': inner_stitch.autoClose() except KeyError: logging.warn("processRelationMultiPolygon: KeyError") return parea = Area() parea.id = rel._id try: parea.outer = outer_stitch.getPolygons() except RuntimeError, e: logging.warn("processRelationMultiPolygon exception: rel {0}: {1}".format(rel["_id"], e)) logging.warn(memids) try: parea.inner = inner_stitch.getPolygons() except RuntimeError, e: logging.warn("processRelationMultiPolygon exception: rel {0}: {1}".format(rel["_id"], e)) logging.warn(memids) parea.tags = rel.tags parea.memids = memids parea.save() #logging.debug("done") def processMember(self, member): pass class Area(minimongo.Model): class Meta: database = 'planet' # def __init__(self, initial=None, **kw): # super(Area, self).__init__(initial, **kw) # # def __init__(self, id, outer, inner, tags): # # might not be unique, can't use _id as we save areas from Ways and from Relations # self.id = id # self.outer = outer # self.inner = inner # self.tags = tags # class Line(minimongo.Model): class Meta: database = 'planet' def __init__(self, id, poly, tags): self._id = id self.poly = poly self.tags = tags class Way(minimongo.Model): class Meta: database = 'planet' HW_MOTORWAY = 0 HW_MOTORWAY_LINK = 1 HW_TRUNK = 2 HW_TRUNK_LINK = 3 HW_PRIMARY = 4 HW_PRIMARY_LINK = 5 HW_SECONDARY = 6 HW_SECONDARY_LINK = 7 HW_TERTIARY = 8 HW_TERTIARY_LINK = 9 HW_LIVING_STREET = 10 HW_PEDESTRIAN = 11 HW_RESIDENTIAL = 12 HW_UNCLASSIFIED = 13 HW_SERVICE = 14 HW_TRACK = 15 HW_BUS_GUIDEWAY = 16 HW_RACEWAY = 17 HW_ROAD = 18 HW_PATH = 19 HW_FOOTWAY = 20 HW_CYCLEWAY = 21 HW_BRIDLEWAY = 22 HW_STEPS = 23 HW_PROPOSED = 24 HW_CONSTRUCTION = 25 def __init__(self, id, poly, typ): self._id = id self.poly = poly self.t = typ @staticmethod def type_from_tags(tags): if tags.has_key('highway'): try: val = tags['highway'] attr = 'HW_{0}'.format(val.upper()) hw = getattr(Way, attr) return hw except AttributeError: pass except UnicodeEncodeError: pass return None def attr_from_tags(self, tags): self.car_forward = True self.car_backward = True self.bike = True if tags.has_key('oneway'): ow = tags['oneway'] if truish(ow): self.car_backward = False elif ow == "-1": self.car_backward = True #elif falsish(ow): # pass if tags.has_key('roundabout'): self.roundabout = True if not tags.has_key('oneway'): self.car_backward = False if self.t == Way.HW_MOTORWAY or self.t == Way.HW_MOTORWAY_LINK and not tags.has_key('oneway'): self.car_forward = True self.car_backward = False if tags.has_key('maxspeed'): s = tags['maxspeed'] m = re.match('\s*(\d+)\s*(\w*)\s*', s) if m: self.speedlimit = float(m.group(1)) if m.group(2) == 'mph': self.speedlimit *= 1.609344 # TODO: no_thru if self.t >= Way.HW_PATH: self.car_forward = False self.car_backward = False # bikes if self.t <= Way.HW_MOTORWAY_LINK\ or self.t == Way.HW_FOOTWAY\ or self.t == Way.HW_STEPS: self.bike = False if truish(tags.get('bicycle', False)): self.bike = True
larroy/osmtransform
planet/__init__.py
Python
agpl-3.0
7,567
<?php /* * Fusio * A web-application to create dynamically RESTful APIs * * Copyright (C) 2015-2020 Christoph Kappestein <christoph.kappestein@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ namespace Fusio\Impl\Event\Plan\Contract; use Fusio\Impl\Authorization\UserContext; use Fusio\Impl\Event\EventAbstract; use Fusio\Model\Backend\Plan_Contract_Update; use PSX\Record\RecordInterface; /** * UpdatedEvent * * @author Christoph Kappestein <christoph.kappestein@gmail.com> * @license http://www.gnu.org/licenses/agpl-3.0 * @link http://fusio-project.org */ class UpdatedEvent extends EventAbstract { /** * @var Plan_Contract_Update */ private $contract; /** * @var RecordInterface */ private $existing; /** * @param Plan_Contract_Update $contract * @param RecordInterface $existing * @param UserContext $context */ public function __construct(Plan_Contract_Update $contract, RecordInterface $existing, UserContext $context) { parent::__construct($context); $this->contract = $contract; $this->existing = $existing; } /** * @return Plan_Contract_Update */ public function getContract(): Plan_Contract_Update { return $this->contract; } /** * @return RecordInterface */ public function getExisting(): RecordInterface { return $this->existing; } }
k42b3/fusio-impl
src/Event/Plan/Contract/UpdatedEvent.php
PHP
agpl-3.0
2,052
# Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013 The Collaborative Software Foundation # # This file is part of TriSano. # # TriSano is free software: you can redistribute it and/or modify it under the # terms of the GNU Affero General Public License as published by the # Free Software Foundation, either version 3 of the License, # or (at your option) any later version. # # TriSano is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with TriSano. If not, see http://www.gnu.org/licenses/agpl-3.0.txt. Then /^the encounter should be struck\-through$/ do @browser.is_element_present("//table[@id='encounters']//td[@class='struck-through'][text()='#{@encounter.participations_encounter.user.uid}']").should be_true end When /^I click the encounter parent link$/ do parent_event_name = @encounter.parent_event.party.full_name @browser.click("link=#{parent_event_name}") wait_for_element_present(:text, "Demographic") end When /^I click the "([^\"]*)" link and accept the confirmation$/ do |link| @browser.click("link=#{link}") get_confirmation() wait_for_element_present(:text, "uccessfully") end
JayBoyer/new-trisano
webapp/features/enhanced_step_definitions/event_encounter_delete_steps.rb
Ruby
agpl-3.0
1,391
<?php /* * FUPS: Forum user-post scraper. An extensible PHP framework for scraping and * outputting the posts of a specified user from a specified forum/board * running supported forum software. Can be run as either a web app or a * commandline script. * * Copyright (C) 2013-2015 Laird Shaw. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ /* File : common.php. * Description: Contains defines and functions shared between FUPS scripts. */ // These are not defines because we want it to be possible to override them // in settings.php, and this is also why they occur before the require of // settings.php. if (isset($_SERVER['REQUEST_URI'])) { list($tmp) = explode('?', $_SERVER['REQUEST_URI'], 2); $fups_url_base = ($tmp[strlen($tmp)-1] == '/' ? $tmp : dirname($tmp)); if ($fups_url_base[strlen($fups_url_base)-1] != '/') { $fups_url_base .= '/'; } } else $fups_url_base = ''; $fups_url_homepage = $fups_url_base; $fups_url_ajax_get_status = $fups_url_base.'ajax-get-status.php'; $fups_url_cancel = $fups_url_base.'cancel.php'; $fups_url_delete_files = $fups_url_base.'delete-files.php'; $fups_url_enter_options = $fups_url_base.'enter-options.php'; $fups_url_notify_email_address = $fups_url_base.'notify-email-address.php'; $fups_url_run = $fups_url_base.'run.php'; require_once __DIR__.'/settings.php'; // Check before doing anything else that FUPS_CMDLINE_PHP_PATH is valid. // This is especially important under Windows because if we supply an invalid command // to "start" (generated by make_php_exec_cmd() below), it pops up an invisible // error message which causes a hang until PHP timeout. // If not Windows, assume a UNIX-like "which" command is present, otherwise use // a custom batch file. $cmd = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? __DIR__.'\\would_run.bat' : 'which').' '.escapeshellarg(FUPS_CMDLINE_PHP_PATH); exec($cmd, $dummy, $res); if ($res !== 0) { exit('Fatal error: The value defined in settings.php for FUPS_CMDLINE_PHP_PATH, "'.FUPS_CMDLINE_PHP_PATH.'", does not appear to be runnable given the current working directory and your path. Exiting.'); } define('FUPS_DONE_STR' , 'DONE' ); define('FUPS_FAILED_STR' , 'EXITING' ); define('FUPS_CANCELLED_STR' , 'CANCELLED'); define('FUPS_MAX_TOKEN_ATTEMPTS' , 10); define('FUPS_FALLBACK_FUPS_CHAIN_DURATION', 1200); function format_html($html) { $flags = defined('ENT_SUBSTITUTE') ? ENT_SUBSTITUTE : (ENT_COMPAT | ENT_HTML401); return str_replace("\n", "<br />\n", htmlspecialchars($html, $flags)); } function make_cancellation_filename($token) { return FUPS_DATADIR.$token.'.cancel.txt'; } function make_cookie_filename($token_or_settings_filename) { return FUPS_DATADIR.sanitise_filename($token_or_settings_filename).'.cookies.txt'; } function make_errs_filename($token) { return FUPS_DATADIR.$token.'.errs.txt'; } function make_errs_admin_filename($token) { return FUPS_DATADIR.$token.'.errs.admin.txt'; } function make_output_dirname($token, $for_web = false, $appendix = '') { return ($for_web ? FUPS_OUTPUTDIR_WEB : FUPS_OUTPUTDIR).$token.$appendix.'/'; } // $output_dirname must end in a slash function make_output_filename($output_dirname, $appendix) { return $output_dirname.'fups.output'.$appendix; } function make_output_info_filename($token) { return FUPS_DATADIR.$token.'.output-info.json'; } function make_php_exec_cmd($params) { $args = ''; $prefix = ''; $redirect = '1>/dev/null'; $bg_token = '&'; if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { $prefix = 'start /b '; $redirect = '1>NUL'; $bg_token = ''; } if (isset($params['token'])) { if ($args) $args .= ' '; $args .= '-t '.escapeshellarg($params['token']); $errs_fname = make_errs_filename($params['token']); $redirect = ' 1>>'.$errs_fname.' 2>&1'; } if (isset($params['settings_filename'])) { if ($args) $args .= ' '; $args .= '-i '.escapeshellarg($params['settings_filename']); } if (isset($params['output_filename'])) { if ($args) $args .= ' '; $args .= '-o '.escapeshellarg($params['output_filename']); } if (isset($params['chained']) && $params['chained'] == true) { if ($args) $args .= ' '; $args .= '-c'; } if (isset($params['quiet']) && $params['quiet'] == true) { if ($args) $args .= ' '; $args .= '-q'; } $fups_path = realpath(__DIR__.'/fups.php'); if ($fups_path === false) { $fups_path = 'fups.php'; } // Early return possible return $prefix.FUPS_CMDLINE_PHP_PATH.' -d max_execution_time=0 '.$fups_path.' '.$args.' '.$redirect.' '.$bg_token; } function try_run_bg_proc($cmd) { $res = popen($cmd, 'r'); $ret = $res !== false; pclose($res); return $ret; } function sanitise_filename($filename) { $tmp = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $filename); $sanitised = ($tmp !== null ? $tmp : $filename); $sanitised2 = str_replace('..', '__', $sanitised); return $sanitised2; } function make_serialize_filename($token_or_settings_filename) { return FUPS_DATADIR.sanitise_filename($token_or_settings_filename).'.serialize.txt'; } function make_settings_filename($token) { return FUPS_DATADIR.$token.'.settings.txt'; } function make_status_filename($token) { return FUPS_DATADIR.$token.'.status.txt'; } function validate_token($token, &$err) { $err = ''; if (strlen($token) <> 32) { $err = 'A fatal error occurred: token is malformed (length).'; } else { $malformed_char = false; for ($i = 0; $i < strlen($token); $i++) { $ch = $token[$i]; if (!($ch >= '0' && $ch <= '9') && !($ch >= 'a' && $ch <= 'z')) { $malformed_char = true; break; } } if ($malformed_char) { $err = 'A fatal error occurred: token is malformed (character).'; } } return $err == ''; } function get_failed_done_cancelled($status, &$done, &$cancelled, &$failed) { $failed = (substr($status, -strlen(FUPS_FAILED_STR)) == FUPS_FAILED_STR); $done = (substr($status, -strlen(FUPS_DONE_STR)) == FUPS_DONE_STR); $cancelled = (substr($status, -strlen(FUPS_CANCELLED_STR)) == FUPS_CANCELLED_STR); } function show_delete($token, $had_success = false) { global $fups_url_delete_files; ?> <p>For your privacy, you might wish to delete from this web server all session and output files associated with this request, especially if you have supplied a login username and password (files that store your username and password details are not publicly visible, but it is wise to delete them anyway).<?php echo FUPS_ROUTINE_DELETION_POLICY; ?></p> <?php if ($had_success) { ?> <p>Be sure to do this only <strong>after</strong> you have clicked the above "View result" link, and saved the contents at that page, because they will no longer be accessible after clicking the following link.</p> <?php } ?> <p><a href="<?php echo $fups_url_delete_files; ?>?token=<?php echo htmlspecialchars(urlencode($token)); ?>">Delete all files</a> associated with your scrape from my web server - this includes your settings, including your password if you entered one.</p> <?php } function output_update_html($token, $status, $done, $cancelled, $failed, $err, $errs, $errs_admin = false, $ajax = false) { global $fups_url_cancel, $fups_url_notify_email_address, $fups_url_run; if ($err) { ?> <div class="fups_error"><?php echo format_html($err); ?></div> <?php return; } ?> <h3>Status</h3> <div id="fups_div_status"> <?php echo htmlspecialchars($status); ?> </div> <?php if ($done) { $output_info = json_decode(file_get_contents(make_output_info_filename($token)), true); if ($output_info == null) { ?> <p>We are sorry, but an unexpected error occurred. The scraping process completed, and the output was created, however we were unable to decode the list of output files. Please feel free to <a href="<?php echo FUPS_CONTACT_URL; ?>">contact me</a> for help with accessing your output files, quoting token "<?php echo $token; ?>".</p> <?php } else { ?> <p>Success! Your posts were retrieved and the output is ready. The following output files are available:</p> <table style="border-collapse: collapse;"> <tr><th style="border: 1px solid black;">Description</th><th style="border: 1px solid black;">View/download file (opens in a new window)</th><th style="border: 1px solid black;">File size</th></tr> <?php foreach ($output_info as $opv) { ?> <tr><td style="border: 1px solid black;"><?php echo $opv['description']; ?></td><td style="border: 1px solid black;"><a target="_blank" href="<?php echo $opv['url']; ?>">View/download file</a></td><td style="border: 1px solid black;"><?php echo number_format($opv['size']).' bytes'; ?></td></tr> <?php } ?> </table> <p>If you're wondering what to do next, here are some possible steps:</p> <ol> <li>Click on the "View/download file" link beside the HTML file which is sorted according to your preference. This will open up a new window/tab for that file. Switch to this window/tab if necessary, and then save the page, e.g. in Firefox click the "File" menu option and under that click "Save Page As". Select the directory/folder and filename you wish to save this output as (remember this location for the next step).</li> <li>Start up a word processor such as LibreOffice/OpenOffice or Microsoft Word. Open up in that word processor the HTML file that you saved in the previous step, e.g. click the "File" menu option and under that click "Open", then select the file you saved in the previous step. You are now free to edit the file as you like. You can now (if you so desire) save the file in a friendlier format than HTML, a format such as your editor's default format, e.g. in LibreOffice, click the "File" menu option and then click "Save As" or "Export", and choose the format you desire.</li> </ol> <?php show_delete($token, true); } } else if ($cancelled) { ?> <p>Cancelled by your request.</p> <?php show_delete($token, false); } else if ($failed) { ?> <p>The script appears to have exited due to an error; the error message is shown below. I have been notified of this error by email; if you would like me to get back to you if/when I have fixed the error, then please enter your email address into the following box and press the button to notify me of it.</p> <div> <form method="post" action="<?php echo $fups_url_notify_email_address; ?>"> <input type="hidden" name="token" value="<?php echo $token; ?>" /> <label for="email_address.id">Your contact email address:</label><br /> <input type="text" name="email_address" id="email_address.id" /><br /> <label for="message.id">Any message you'd like to include (leaving this blank is fine):</label><br /> <textarea rows="5" cols="80" name="message" id="message.id"></textarea><br /> <input type="submit" value="Notify the FUPS maintainer" /> </form> </div> <p>Alternatively, feel free to retry or to <a href="<?php echo FUPS_CONTACT_URL; ?>">contact me</a> manually about this error, quoting your run token of "<?php echo $token; ?>".</p> <?php show_delete($token, false); } else { $same_status = (isset($_GET['last_status']) && $status == $_GET['last_status']); ?> <p> <a href="<?php echo $fups_url_run.'?token='.$token.($same_status ? '&amp;last_status='.htmlspecialchars(urlencode($status)) : '').($ajax ? '&amp;ajax=yes' : ''); ?>"><?php echo ($ajax ? 'Refresh page' : 'Check progress'); ?></a><?php if ($ajax): echo ' (it should not be necessary to click this link unless something goes wrong)'; endif; ?>. <?php if ($same_status) { ?> (It appears that progress has halted unexpectedly - the current status is the same as the previous status. It is likely that an error has caused the process to exit before finishing. We are sorry about this failure. In case you want to be sure that progress has indeed halted, you are welcome to click the preceding link, but otherwise, this page will no longer automatically refresh.) <?php show_delete($token, false); } else { ?> <?php echo (!$ajax ? 'Your browser should automatically refresh this page every '.FUPS_META_REDIRECT_DELAY.' seconds or so to update progress, but if you don\'t want to wait, you\'re welcome to click the link. ' : ''); ?>If you have changed your mind about wanting to run this script through to the end, <strong>please</strong> click this <a href="<?php echo $fups_url_cancel; ?>?token=<?php echo $token.($ajax ? '&amp;ajax=yes' : ''); ?>">cancel</a> link rather than just closing this page - clicking the cancel link will free up the resources (in particular a background process) associated with your task. <?php } ?> </p> <?php } $paren_msg_will_be_emailed = '(Unless a mailing error occurs, these will be emailed to me as-is if/when FUPS finishes running, with your token, "'.htmlspecialchars($token).'", included in the email\'s subject)'; $paren_msg_emailed = '(Unless a mailing error occurred, these have been emailed to me as-is, with your token, "'.htmlspecialchars($token).'", included in the email\'s subject)'; if ($errs) { ?> <h3>Errors</h3> <p><?php echo ($done || $failed ? $paren_msg_emailed : $paren_msg_will_be_emailed); ?></p> <?php $len = strlen($errs); if ($len > FUPS_MAX_ERROR_FILE_EMAIL_LENGTH) { $errs = substr($errs, 0, FUPS_MAX_ERROR_FILE_EMAIL_LENGTH); $trunc_msg = '[Truncated from '.number_format($len).' bytes to '.number_format(FUPS_MAX_ERROR_FILE_EMAIL_LENGTH).' bytes]'; ?> <p><?php echo $trunc_msg; ?></p> <?php } ?> <div class="fups_error"> <?php echo format_html($errs); ?> </div> <?php if ($errs_admin && ($done || $failed)) { // The toggle_ext_errs() Javascript function below is defined in run.php ?> <p><a href="javascript:toggle_ext_errs();">Show/hide extended error messages</a> <?php echo $paren_msg_emailed; ?></p> <div id="id_ext_err" style="display: none;"> <h3>Extended error messages</h3> <?php $len = strlen($errs_admin); if ($len > FUPS_MAX_ADMIN_FILE_EMAIL_LENGTH) { $errs_admin = substr($errs_admin, 0, FUPS_MAX_ADMIN_FILE_EMAIL_LENGTH); $trunc_msg = '[Truncated from '.number_format($len).' bytes to '.number_format(FUPS_MAX_ADMIN_FILE_EMAIL_LENGTH).' bytes]'; ?> <p><?php echo $trunc_msg; ?></p> <?php } ?> <div class="fups_error"><?php echo format_html($errs_admin); ?></div> </div> <?php } } // Early return possible } // Utility functions follow // Helper function for arrays_combos() function get_arrays_combos_r($arrays, $depth, $combo, &$combos) { foreach ($arrays[$depth] as $item) { $combo[$depth] = $item; if ($depth == count($arrays) - 1) { $combos[] = $combo; } else get_arrays_combos_r($arrays, $depth + 1, $combo, $combos); } } // Returns an array of all array combinations generated // by taking a single element from each of the arrays // in $arrays. function arrays_combos($arrays) { $ret = array(); $combo = array_fill(0, count($arrays), null); get_arrays_combos_r($arrays, 0, $combo, $ret); return $ret; }
ezeql/fups
common.php
PHP
agpl-3.0
15,661
<?php //***************************************************************************** // This will allow occurrences of a database table to be deleted. // The identity of the selected occurrence(s) is passed from the previous screen. //***************************************************************************** $table_id = 'mnu_role'; // table id $screen = 'mnu_role.detail.screen.inc'; // file identifying screen structure require 'std.delete1.inc'; // activate page controller ?>
apmuthu/radicore
radicore/menu/mnu_role(del1).php
PHP
agpl-3.0
526
<?php include_once "lib/functions.php"; include_once "colpr-config.php"; if (!isset($_SESSION["usuario"])){ header( 'Location: login.php' ); }else{ $user=autentificado(); // Propuestas en orden cronológico del usuario $consultaPropuestasUsuario = 'SELECT u.nombre, u.apellidos, p.id, p.titulo, p.comentarios, p.sum_likes, p.positivos, p.negativos, p.sector, p.barrio FROM users AS u join prog_propuestas AS p ON (`autor_id` = u.id) WHERE `autor_id` = :usuario_id ORDER BY p.id;'; $arrayusuario = array(':usuario_id'=>$user['id']); // Propuestas votadas en orden cronológico del usuario $consultaVotadasUsuario = 'SELECT u.nombre, u.apellidos, p.id, p.titulo, p.comentarios, p.sum_likes, p.positivos, p.negativos, p.sector, p.barrio FROM users AS u join prog_propuestas AS p ON (`autor_id` = u.id) JOIN prog_likes_propuesta AS lp ON (p.id = lp.propuesta_id) WHERE lp.usuario_id = :usuario_id ORDER BY p.id DESC;'; /*echo $consultaVotadasUsuario; return;*/ $datos = array('user'=>$user, 'propusuario'=>listarpreparada($arrayusuario, $consultaPropuestasUsuario), 'votosusuario'=>listarpreparada($arrayusuario, $consultaVotadasUsuario), 'openProps'=>$openProps, // Indica si se pueden hacer nuevas propuestas 'ipr'=>getRealIpAddr(), // La IP desde la que se ha hecho la consulta 'lang'=>$lang); //FIXME: Mirar si el lang se puede leer desde la plantilla twig /*foreach($datos as $key => $value) { echo $key." has the value ***". $value."***<br />\n"; var_dump($value); } return;*/ $template = $twig->loadTemplate('perfil.html'); echo $template->render($datos); }
mperezfr/collaborative-documents
perfil.php
PHP
agpl-3.0
1,691
# -*- coding: utf-8 -*- # # # Copyright 2015 Camptocamp SA # Author: Alexandre Fayolle # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # from openerp import models, api class SaleOrder(models.Model): _inherit = 'sale.order' @api.multi def over_budget(self): self.ensure_one() if self.order_type == 'donation': return False else: return super(SaleOrder, self).over_budget() @api.multi def has_budget_holder(self): self.ensure_one() if self.order_type == 'donation': return True else: return super(SaleOrder, self).has_budget_holder()
jorsea/vertical-ngo
logistic_order_donation_budget/model/sale_order.py
Python
agpl-3.0
1,300
/* * Copyright 2012 McEvoy Software Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.milton.http; import io.milton.resource.Resource; import io.milton.http.exceptions.BadRequestException; import io.milton.http.exceptions.ConflictException; import io.milton.http.exceptions.NotAuthorizedException; import io.milton.http.exceptions.NotFoundException; /** * * @author brad */ public interface ExistingEntityHandler extends ResourceHandler { public void processExistingResource( HttpManager manager, Request request, Response response, Resource resource ) throws NotAuthorizedException, BadRequestException, ConflictException, NotFoundException; }
FullMetal210/milton2
milton-server/src/main/java/io/milton/http/ExistingEntityHandler.java
Java
agpl-3.0
1,310
from fabric.api import run, cd, env from fabric import state DISTANT_PATH = '/www-data/click-and-deploy' def pull(): with cd(DISTANT_PATH): run('git pull') def restart_services(): run('sudo supervisorctl restart click-and-deploy') def deploy(): pull() restart_services()
Cerkinfo/click-and-deploy
apps/recipies/self.py
Python
agpl-3.0
299
"""Offer Utility Methods. """ import logging import string # pylint: disable=W0402 from decimal import Decimal from urllib.parse import urlencode import bleach import waffle from django.conf import settings from django.template.loader import render_to_string from django.utils.translation import ugettext as _ from ecommerce_worker.sailthru.v1.tasks import send_offer_assignment_email, send_offer_update_email from oscar.core.loading import get_model from ecommerce.core.constants import ENABLE_BRAZE from ecommerce.core.url_utils import absolute_redirect from ecommerce.extensions.checkout.utils import add_currency from ecommerce.extensions.offer.constants import OFFER_ASSIGNED logger = logging.getLogger(__name__) def _remove_exponent_and_trailing_zeros(decimal): """ Remove exponent and trailing zeros. Arguments: decimal (Decimal): Decimal number that needs to be modified Returns: decimal (Decimal): Modified decimal number without exponent and trailing zeros. """ return decimal.quantize(Decimal(1)) if decimal == decimal.to_integral() else decimal.normalize() def get_discount_percentage(discount_value, product_price): """ Get discount percentage of discount value applied to a product price. Arguments: discount_value (float): Discount value product_price (float): Price of a product the discount is used on Returns: float: Discount percentage """ return discount_value / product_price * 100 if product_price > 0 else 0.0 def get_discount_value(discount_percentage, product_price): """ Get discount value of discount percentage applied to a product price. Arguments: discount_percentage (float): Discount percentage product_price (float): Price of a product the discount is used on Returns: float: Discount value """ return discount_percentage * product_price / 100.0 def get_benefit_type(benefit): """ Returns type of benefit using 'type' or 'proxy_class' attributes of Benefit object""" _type = benefit.type if not _type: _type = getattr(benefit.proxy(), 'benefit_class_type', None) return _type def get_quantized_benefit_value(benefit): """ Returns the rounded value of the given benefit, without any decimal points. """ value = getattr(benefit.proxy(), 'benefit_class_value', benefit.value) return _remove_exponent_and_trailing_zeros(Decimal(str(value))) def format_benefit_value(benefit): """ Format benefit value for display based on the benefit type Arguments: benefit (Benefit): Benefit to be displayed Returns: benefit_value (str): String value containing formatted benefit value and type. """ Benefit = get_model('offer', 'Benefit') benefit_value = get_quantized_benefit_value(benefit) benefit_type = get_benefit_type(benefit) if benefit_type == Benefit.PERCENTAGE: benefit_value = _('{benefit_value}%').format(benefit_value=benefit_value) else: converted_benefit = add_currency(Decimal(benefit.value)) benefit_value = _('${benefit_value}').format(benefit_value=converted_benefit) return benefit_value def get_redirect_to_email_confirmation_if_required(request, offer, product): """ Render the email confirmation template if email confirmation is required to redeem the offer. We require email confirmation via account activation before an offer can be redeemed if the site is configured to require account activation or if the offer is restricted for use to learners with a specific email domain. The learner needs to activate their account before we allow them to redeem email domain-restricted offers, otherwise anyone could create an account using an email address with a privileged domain and use the coupon code associated with the offer. Arguments: request (HttpRequest): The current HttpRequest. offer (ConditionalOffer): The offer to be redeemed. product (Product): The Returns: HttpResponse or None: An HttpResponse that redirects to the email confirmation view if required. """ require_account_activation = request.site.siteconfiguration.require_account_activation or offer.email_domains if require_account_activation and not request.user.account_details(request).get('is_active'): response = absolute_redirect(request, 'offers:email_confirmation') course_id = product.course and product.course.id if course_id: response['Location'] += '?{params}'.format(params=urlencode({'course_id': course_id})) return response return None def format_assigned_offer_email(greeting, closing, learner_email, code, redemptions_remaining, code_expiration_date): """ Arguments: greeting (String): Email greeting (prefix) closing (String): Email closing (suffix) learner_email (String): Email of the customer who will receive the code. code (String): Code for the user. redemptions_remaining (Integer): Number of times the code can be redeemed. code_expiration_date(Datetime): Date till code is valid. Return the formatted email body for offer assignment. """ email_template = settings.OFFER_ASSIGNMENT_EMAIL_TEMPLATE placeholder_dict = SafeDict( REDEMPTIONS_REMAINING=redemptions_remaining, USER_EMAIL=learner_email, CODE=code, EXPIRATION_DATE=code_expiration_date ) return format_email(email_template, placeholder_dict, greeting, closing) def send_assigned_offer_email( subject, greeting, closing, offer_assignment_id, learner_email, code, redemptions_remaining, code_expiration_date, sender_alias, base_enterprise_url=''): """ Arguments: *subject* The email subject *email_greeting* The email greeting (prefix) *email_closing* The email closing (suffix) *offer_assignment_id* Primary key of the entry in the offer_assignment model. *learner_email* Email of the customer who will receive the code. *code* Code for the user. *redemptions_remaining* Number of times the code can be redeemed. *code_expiration_date* Date till code is valid. """ email_body = format_assigned_offer_email( greeting, closing, learner_email, code, redemptions_remaining, code_expiration_date ) if settings.DEBUG: # pragma: no cover # Avoid breaking devstack when no such service is available. logger.warning("Skipping Sailthru task 'send_offer_assignment_email' because DEBUG=true.") # pragma: no cover return # pragma: no cover send_offer_assignment_email.delay(learner_email, offer_assignment_id, subject, email_body, sender_alias, None, base_enterprise_url) def send_revoked_offer_email( subject, greeting, closing, learner_email, code, sender_alias, ): """ Arguments: *subject* The email subject *email_greeting* The email greeting (prefix) *email_closing* The email closing (suffix) *learner_email* Email of the customer who will receive the code. *code* Code for the user. """ email_template = settings.OFFER_REVOKE_EMAIL_TEMPLATE placeholder_dict = SafeDict( USER_EMAIL=learner_email, CODE=code, ) email_body = format_email(email_template, placeholder_dict, greeting, closing) send_offer_update_email.delay(learner_email, subject, email_body, sender_alias) def send_assigned_offer_reminder_email( subject, greeting, closing, learner_email, code, redeemed_offer_count, total_offer_count, code_expiration_date, sender_alias, base_enterprise_url=''): """ Arguments: *subject* The email subject *email_greeting* The email greeting (prefix) *email_closing* The email closing (suffix) *learner_email* Email of the customer who will receive the code. *code* Code for the user. *redeemed_offer_count* Number of times the code has been redeemed. *total_offer_count* Total number of offer assignments for this (code,email) pair *code_expiration_date* Date till code is valid. *sender_alias* Enterprise customer sender alias. *base_enterprise_url* Url for the enterprise's learner portal """ email_template = settings.OFFER_REMINDER_EMAIL_TEMPLATE placeholder_dict = SafeDict( REDEEMED_OFFER_COUNT=redeemed_offer_count, TOTAL_OFFER_COUNT=total_offer_count, USER_EMAIL=learner_email, CODE=code, EXPIRATION_DATE=code_expiration_date ) email_body = format_email(email_template, placeholder_dict, greeting, closing) send_offer_update_email.delay(learner_email, subject, email_body, sender_alias, base_enterprise_url) def format_email(template, placeholder_dict, greeting, closing): """ Arguments: template (String): Email template body placeholder_dict (SafeDict): Safe dictionary of placeholders and their values greeting (String): Email greeting (prefix) closing (String): Email closing (suffix) Apply placeholders to the email template. Safely handle placeholders in the template without matching tokens (just emit the placeholders). Reference: https://stackoverflow.com/questions/17215400/python-format-string-unused-named-arguments """ if greeting is None: greeting = '' if closing is None: closing = '' greeting = bleach.clean(greeting) closing = bleach.clean(closing) email_body = string.Formatter().vformat(template, SafeTuple(), placeholder_dict) if waffle.switch_is_active(ENABLE_BRAZE): email_body = (greeting + email_body + closing).replace('\"', '\'') return render_to_string('coupons/offer_email.html', {'body': email_body}) # \n\n is being treated as single line except of two lines in HTML template, # so separating them with &nbsp; tag to render them as expected. return (greeting + email_body + closing).replace('\n', '<br/>') class SafeDict(dict): """ Safely handle missing placeholder values. """ def __missing__(self, key): return '{' + key + '}' class SafeTuple(tuple): """ Safely handle missing unnamed placeholder values in python3. """ def __getitem__(self, value): return '{}' def update_assignments_for_multi_use_per_customer(voucher): """ Update `OfferAssignment` records for MULTI_USE_PER_CUSTOMER coupon type when max_uses changes for a coupon. """ if voucher.usage == voucher.MULTI_USE_PER_CUSTOMER: OfferAssignment = get_model('offer', 'OfferAssignment') offer = voucher.enterprise_offer existing_offer_assignments = OfferAssignment.objects.filter(code=voucher.code, offer=offer).count() if existing_offer_assignments == 0: return if existing_offer_assignments < offer.max_global_applications: user_email = OfferAssignment.objects.filter(code=voucher.code, offer=offer).first().user_email offer_assignments_available = offer.max_global_applications - existing_offer_assignments assignments = [ OfferAssignment(offer=offer, code=voucher.code, user_email=user_email, status=OFFER_ASSIGNED) for __ in range(offer_assignments_available) ] OfferAssignment.objects.bulk_create(assignments)
eduNEXT/edunext-ecommerce
ecommerce/extensions/offer/utils.py
Python
agpl-3.0
12,022
# -*- coding: utf-8 -*- ############################################################################## # # Author: Alessandro Camilli (a.camilli@yahoo.it) # Copyright (C) 2014 # Associazione OpenERP Italia (<http://www.openerp-italia.org>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from osv import fields, orm from openerp.tools.translate import _ import decimal_precision as dp import datetime, time class res_country(orm.Model): _inherit = "res.country" _columns = { 'codice_stato_agenzia_entrate': fields.char('Codice stato Agenzia Entrate', size=3) } class account_tax_code(orm.Model): _inherit = "account.tax.code" _columns = { 'spesometro_escludi': fields.boolean('Escludi dalla dichiarazione'), } _defaults = { 'spesometro_escludi' : False, } class account_journal(orm.Model): _inherit = "account.journal" _columns = { 'spesometro': fields.boolean('Da includere'), 'spesometro_operazione': fields.selection((('FA','Operazioni documentate da fattura'), ('SA','Operazioni senza fattura'), ('BL1','Operazioni con paesi con fiscalità privilegiata'), ('BL2','Operazioni con soggetti non residenti'), ('BL3','Acquisti di servizi da soggetti non residenti'), ('DR','Documento Riepilogativo')), 'Operazione' ), 'spesometro_segno': fields.selection((('attiva','Attiva'), ('passiva','Passiva')), 'Segno operaz.' ), 'spesometro_IVA_non_esposta': fields.boolean('IVA non esposta') } class res_partner(orm.Model): _inherit = "res.partner" _columns = { 'spesometro_escludi': fields.boolean('Escludi'), 'spesometro_operazione': fields.selection((('FA','Operazioni documentate da fattura'), ('SA','Operazioni senza fattura'), ('BL1','Operazioni con paesi con fiscalità privilegiata'), ('BL2','Operazioni con soggetti non residenti'), ('BL3','Acquisti di servizi da soggetti non residenti'), ('DR','Documento Riepilogativo')), 'Operazione' ), 'spesometro_IVA_non_esposta': fields.boolean('IVA non esposta'), 'spesometro_leasing': fields.selection((('A','Autovettura'), ('B','Caravan'), ('C','Altri veicoli'), ('D','Unità da diporto'), ('E','Aeromobili')), 'Tipo Leasing' ), 'spesometro_tipo_servizio': fields.selection((('cessione','Cessione Beni'), ('servizi','Prestazione di servizi')), 'Tipo servizio', help="Specificare per 'Operazioni con paesi con fiscalità privilegiata' "), 'spesometro_indirizzo_estero': fields.many2one('res.partner.address', 'Indirizzo non residente'), } _defaults = { 'spesometro_escludi' : False, } class spesometro_configurazione(orm.Model): def _check_one_year(self, cr, uid, ids, context=None): for element in self.browse(cr, uid, ids, context=context): element_ids = self.search(cr, uid, [('anno','=', element.anno)], context=context) if len(element_ids) > 1: return False return True _name = "spesometro.configurazione" _description = "Spesometro - Configurazione" _columns = { 'anno': fields.integer('Anno', size=4, required=True ), 'stato_san_marino': fields.many2one('res.country', 'Stato San Marino', required=True), 'quadro_fa_limite_importo': fields.float('Quadro FA - Limite importo'), 'quadro_fa_limite_importo_line': fields.float('Quadro FA - Limite importo singola operaz.'), 'quadro_sa_limite_importo': fields.float('Quadro SA - Limite importo'), 'quadro_sa_limite_importo_line': fields.float('Quadro SA - Limite importo singola operaz.'), 'quadro_bl_limite_importo': fields.float('Quadro BL - Limite importo'), 'quadro_bl_limite_importo_line': fields.float('Quadro BL - Limite importo singola operaz.'), 'quadro_se_limite_importo_line': fields.float('Quadro SE - Limite importo singola operaz.'), } _constraints = [ (_check_one_year, 'Error! Config for this year already exists.', ['anno']), ] class spesometro_comunicazione(orm.Model): _name = "spesometro.comunicazione" _description = "Spesometro - Comunicazione " def _tot_operation_number(self, cr, uid, ids, field_names, args, context=None): res = {} for com in self.browse(cr, uid, ids): # Aggregate tot_FA = len(com.line_FA_ids) tot_SA = len(com.line_SA_ids) tot_BL1 = 0 tot_BL2 = 0 tot_BL3 = 0 for line in com.line_BL_ids: if line.operazione_fiscalita_privilegiata: tot_BL1 += 1 elif line.operazione_con_soggetti_non_residenti: tot_BL2 += 1 elif line.Acquisto_servizi_da_soggetti_non_residenti: tot_BL3 += 1 #Analitiche tot_FE = 0 # Fatture emesse tot_FE_R = 0 # Doc riepilogativi for line in com.line_FE_ids: if line.documento_riepilogativo: tot_FE_R += 1 else: tot_FE += 1 tot_FR = 0 # Fatture ricevute tot_FR_R = 0 # Doc riepilogativi ricevuti for line in com.line_FR_ids: if line.documento_riepilogativo: tot_FR_R += 1 else: tot_FR += 1 tot_NE = len(com.line_NE_ids) tot_NR = len(com.line_NR_ids) tot_DF = len(com.line_DF_ids) tot_FN = len(com.line_FN_ids) tot_SE = len(com.line_SE_ids) tot_TU = len(com.line_TU_ids) res[com.id] = { 'totale_FA' : tot_FA, 'totale_SA' : tot_SA, 'totale_BL1' : tot_BL1, 'totale_BL2' : tot_BL2, 'totale_BL3' : tot_BL3, 'totale_FE' : tot_FE, 'totale_FE_R' : tot_FE_R, 'totale_FR' : tot_FR, 'totale_FR_r' : tot_FR_R, 'totale_NE' : tot_NE, 'totale_NR' : tot_NR, 'totale_DF' : tot_DF, 'totale_FN' : tot_FN, 'totale_SE' : tot_SE, 'totale_TU' : tot_TU, } return res _columns = { 'company_id': fields.many2one('res.company', 'Azienda', required=True ), 'periodo': fields.selection((('anno','Annuale'), ('trimestre','Trimestrale'), ('mese','Mensile')), 'Periodo', required=True), 'anno' : fields.integer('Anno', size=4, required=True), 'trimestre' : fields.integer('Trimestre', size=1 ), 'mese' : fields.selection((('1','Gennaio'), ('2','Febbraio'), ('3','Marzo'), ('4','Aprile'), ('5','Maggio'), ('6','Giugno'), ('7','Luglio'), ('8','Agosto'), ('9','Settembre'), ('10','Ottobre'), ('11','Novembre'), ('12','Dicembre'), ),'Mese'), 'tipo': fields.selection((('ordinaria','Ordinaria'), ('sostitutiva','Sostitutiva'), ('annullamento','Annullamento')), 'Tipo comunicazione', required=True), 'comunicazione_da_sostituire_annullare': fields.integer('Protocollo comunicaz. da sostituire/annullare'), 'documento_da_sostituire_annullare': fields.integer('Protocollo documento da sostituire/annullare'), 'formato_dati': fields.selection((('aggregati','Dati Aggregati'), ('analitici','Dati Analitici')), 'Formato dati', readonly=True ), 'codice_fornitura': fields.char('Codice fornitura', readonly=True, size=5, help='Impostare a "NSP00" '), 'tipo_fornitore': fields.selection((('01','Invio propria comunicazione'), ('10','Intermediario')), 'Tipo fornitore' ), 'codice_fiscale_fornitore': fields.char('Codice fiscale Fornitore', size=16, help="Deve essere uguale al Codice fiscale dell'intermediario (campo 52 del record B) se presente, altrimenti al Codice fiscale del soggetto tenuto alla comunicazione (campo 41 del record B) se presente, altrimenti al Codice fiscale del soggetto obbligato (campo 2 del record B)"), # # Valori per comunicazione su più invii (non gestito) 'progressivo_telematico': fields.integer('Progressivo telematico', readonly=True), 'numero_totale_invii': fields.integer('Numero totale invii telematici', readonly=True), # # Soggetto a cui si riferisce la comunicazione # 'soggetto_codice_fiscale': fields.char('Codice fiscale soggetto obbligato', size=16, help="Soggetto cui si riferisce la comunicazione"), 'soggetto_partitaIVA': fields.char('Partita IVA', size=11), 'soggetto_codice_attivita': fields.char('Codice attività', size=6, help="Codice ATECO 2007"), 'soggetto_telefono': fields.char('Telefono', size=12), 'soggetto_fax': fields.char('Fax', size=12), 'soggetto_email': fields.char('E-mail', size=50), 'soggetto_forma_giuridica': fields.selection((('persona_giuridica','Persona Giuridica'), ('persona_fisica','Persona Fisica')), 'Forma Giuridica'), 'soggetto_pf_cognome': fields.char('Cognome', size=24, help=""), 'soggetto_pf_nome': fields.char('Nome', size=20, help=""), 'soggetto_pf_sesso': fields.selection((('M','M'), ('F','F')),'Sesso'), 'soggetto_pf_data_nascita': fields.date('Data di nascita'), 'soggetto_pf_comune_nascita': fields.char('Comune o stato estero di nascita', size=40), 'soggetto_pf_provincia_nascita': fields.char('Provincia', size=2), 'soggetto_pg_denominazione': fields.char('Denominazione', size=60), # Soggetto tenuto alla comunicazione 'soggetto_cm_forma_giuridica': fields.selection((('persona_giuridica','Persona Giuridica'), ('persona_fisica','Persona Fisica')), 'Forma Giuridica'), 'soggetto_cm_codice_fiscale': fields.char('Codice Fiscale', size=16, help="Soggetto che effettua la comunicazione se diverso dal soggetto tenuto alla comunicazione"), 'soggetto_cm_pf_cognome': fields.char('Cognome', size=24, help=""), 'soggetto_cm_pf_nome': fields.char('Nome', size=20, help=""), 'soggetto_cm_pf_sesso': fields.selection((('M','M'), ('F','F')),'Sesso'), 'soggetto_cm_pf_data_nascita': fields.date('Data di nascita'), 'soggetto_cm_pf_comune_nascita': fields.char('Comune o stato estero di nascita', size=40), 'soggetto_cm_pf_provincia_nascita': fields.char('Provincia', size=2), 'soggetto_cm_pf_codice_carica': fields.integer('Codice Fiscale', size=2, help=""), 'soggetto_cm_pf_data_inizio_procedura': fields.date('Data inizio procedura'), 'soggetto_cm_pf_data_fine_procedura': fields.date('Data fine procedura'), 'soggetto_cm_pg_denominazione': fields.char('Denominazione', size=60), # Soggetto incaricato alla trasmissione 'soggetto_trasmissione_codice_fiscale': fields.char('Codice Fiscale', size=16, help="Intermediario che effettua la trasmissione telematica"), 'soggetto_trasmissione_numero_CAF': fields.integer('Nr iscrizione albo del C.A.F.', size=5, help="Intermediario che effettua la trasmissione telematica"), 'soggetto_trasmissione_impegno': fields.selection((('1','Soggetto obbligato'), ('2','Intermediario')),'Impegno trasmissione'), 'soggetto_trasmissione_data_impegno': fields.date('Data data impegno'), 'line_FA_ids': fields.one2many('spesometro.comunicazione.line.fa', 'comunicazione_id', 'Quadri FA' ), 'line_SA_ids': fields.one2many('spesometro.comunicazione.line.sa', 'comunicazione_id', 'Quadri SA' ), 'line_BL_ids': fields.one2many('spesometro.comunicazione.line.bl', 'comunicazione_id', 'Quadri BL' ), 'line_FE_ids': fields.one2many('spesometro.comunicazione.line.fe', 'comunicazione_id', 'Quadri FE' ), 'line_FR_ids': fields.one2many('spesometro.comunicazione.line.fr', 'comunicazione_id', 'Quadri FR' ), 'line_NE_ids': fields.one2many('spesometro.comunicazione.line.ne', 'comunicazione_id', 'Quadri NE' ), 'line_NR_ids': fields.one2many('spesometro.comunicazione.line.nr', 'comunicazione_id', 'Quadri NR' ), 'line_DF_ids': fields.one2many('spesometro.comunicazione.line.df', 'comunicazione_id', 'Quadri DF' ), 'line_FN_ids': fields.one2many('spesometro.comunicazione.line.fn', 'comunicazione_id', 'Quadri FN' ), 'line_SE_ids': fields.one2many('spesometro.comunicazione.line.se', 'comunicazione_id', 'Quadri SE' ), 'line_TU_ids': fields.one2many('spesometro.comunicazione.line.tu', 'comunicazione_id', 'Quadri TU' ), 'totale_FA': fields.function(_tot_operation_number, string='Tot operazioni FA', type='integer', multi='operation_number'), 'totale_SA': fields.function(_tot_operation_number, string='Tot operazioni SA', type='integer', multi='operation_number'), 'totale_BL1': fields.function(_tot_operation_number, string='Tot operazioni BL - Paesi con fiscalita privilegiata', type='integer', multi='operation_number'), 'totale_BL2': fields.function(_tot_operation_number, string='Tot operazioni BL - Soggetti non residenti', type='integer', multi='operation_number'), 'totale_BL3': fields.function(_tot_operation_number, string='Tot operazioni BL - Acquisti servizi non soggetti non residenti', type='integer', multi='operation_number'), 'totale_FE': fields.function(_tot_operation_number, string='Tot operazioni FE', type='integer', multi='operation_number'), 'totale_FE_R': fields.function(_tot_operation_number, string='Tot operazioni FE doc riepil.', type='integer', multi='operation_number'), 'totale_FR': fields.function(_tot_operation_number, string='Tot operazioni FR', type='integer', multi='operation_number'), 'totale_FR_R': fields.function(_tot_operation_number, string='Tot operazioni FR doc riepil.', type='integer', multi='operation_number'), 'totale_NE': fields.function(_tot_operation_number, string='Tot operazioni NE', type='integer', multi='operation_number'), 'totale_NR': fields.function(_tot_operation_number, string='Tot operazioni NR', type='integer', multi='operation_number'), 'totale_DF': fields.function(_tot_operation_number, string='Tot operazioni DF', type='integer', multi='operation_number'), 'totale_FN': fields.function(_tot_operation_number, string='Tot operazioni FN', type='integer', multi='operation_number'), 'totale_SE': fields.function(_tot_operation_number, string='Tot operazioni SE', type='integer', multi='operation_number'), 'totale_TU': fields.function(_tot_operation_number, string='Tot operazioni TU', type='integer', multi='operation_number'), } _default ={ 'codice_fornitura': 'NSP00', 'tipo_fornitore': '01', 'formato_dati': 'aggregati', } def onchange_trasmissione_impegno(self, cr, uid, ids, type, context=None): res = {} fiscalcode = False if type == '1': # soggetto obbligato fiscalcode = context.get('soggetto_codice_fiscale', False) res = { 'value' : {'soggetto_trasmissione_codice_fiscale' : fiscalcode} } return res def partner_is_from_san_marino(self, cr, uid, move, invoice, arg): # configurazione anno_competenza = datetime.datetime.strptime(move.period_id.date_start, "%Y-%m-%d").year configurazione_ids = self.pool.get('spesometro.configurazione').search(cr, uid, \ [('anno', '=', anno_competenza)]) if not configurazione_ids: raise orm.except_orm(_('Configurazione mancante!'),_("Configurare l'anno relativo alla comunicazione") ) configurazione = self.pool.get('spesometro.configurazione').browse(cr, uid, configurazione_ids[0]) stato_estero = False address = self._get_partner_address_obj(cr, uid, move, invoice, arg) if address and address.country_id and configurazione.stato_san_marino.id == address.country_id.id: return True else: return False def _get_partner_address_obj(self, cr, uid, move, invoice, arg): address = False if move.partner_id.spesometro_indirizzo_estero: address = move.partner_id.spesometro_indirizzo_estero elif move.partner_id.address[0]: address = move.partner_id.address[0] return address def compute_invoice_amounts(self, cr, uid, move, invoice, arg): ''' Calcolo totali documento. Dall'imponibile vanno esclusi gli importi assoggettati ad un'imposta che ha l'esclusione sulla "Comunicazione art.21" ''' res ={ 'amount_untaxed' : 0, 'amount_tax' : 0, 'amount_total' : 0, } for line in invoice.tax_line: if not line.tax_code_id.spesometro_escludi: res['amount_untaxed'] += line.base res['amount_tax'] += line.amount res['amount_total'] += round(line.base + line.amount, 2) return res def truncate_values(self, cr, uid, ids, context=None): for com in self.browse(cr, uid, ids): for line in com.line_FA_ids: vals = { 'attive_imponibile_non_esente': int(line.attive_imponibile_non_esente), 'attive_imposta': int(line.attive_imposta), 'attive_operazioni_iva_non_esposta': int(line.attive_operazioni_iva_non_esposta), 'attive_note_variazione': int(line.attive_note_variazione), 'attive_note_variazione_imposta': int(line.attive_note_variazione_imposta), 'passive_imponibile_non_esente': int(line.passive_imponibile_non_esente), 'passive_imposta': int(line.passive_imposta), 'passive_operazioni_iva_non_esposta': int(line.passive_operazioni_iva_non_esposta), 'passive_note_variazione': int(line.passive_note_variazione), 'passive_note_variazione_imposta': int(line.passive_note_variazione_imposta), } self.pool.get('spesometro.comunicazione.line.fa').write(cr, uid, [line.id], vals) for line in com.line_SA_ids: vals = { 'importo_complessivo': int(line.importo_complessivo), } self.pool.get('spesometro.comunicazione.line.sa').write(cr, uid, [line.id], vals) for line in com.line_BL_ids: vals = { 'attive_importo_complessivo': int(line.attive_importo_complessivo), 'attive_imposta': int(line.attive_imposta), 'attive_non_sogg_cessione_beni': int(line.attive_non_sogg_cessione_beni), 'attive_non_sogg_servizi': int(line.attive_non_sogg_servizi), 'attive_note_variazione': int(line.attive_note_variazione), 'attive_note_variazione_imposta': int(line.attive_note_variazione_imposta), 'passive_importo_complessivo': int(line.passive_importo_complessivo), 'passive_imposta': int(line.passive_imposta), 'passive_non_sogg_importo_complessivo': int(line.passive_non_sogg_importo_complessivo), 'passive_note_variazione': int(line.passive_note_variazione), 'passive_note_variazione_imposta': int(line.passive_note_variazione_imposta), } self.pool.get('spesometro.comunicazione.line.bl').write(cr, uid, [line.id], vals) return True def validate_lines(self, cr, uid, ids, context=None): for com in self.browse(cr, uid, ids): # configurazione configurazione_ids = self.pool.get('spesometro.configurazione').search(cr, uid, \ [('anno', '=', com.anno)]) if not configurazione_ids: raise orm.except_orm(_('Configurazione mancante!'),_("Configurare l'anno relativo alla comunicazione") ) configurazione = self.pool.get('spesometro.configurazione').browse(cr, uid, configurazione_ids[0]) for line in com.line_FA_ids: if configurazione.quadro_fa_limite_importo : if line.attive_imponibile_non_esente and \ line.attive_imponibile_non_esente < configurazione.quadro_fa_limite_importo: self.pool.get('spesometro.comunicazione.line.fa').unlink(cr, uid, [line.id]) for line in com.line_SA_ids: if configurazione.quadro_sa_limite_importo : if line.importo_complessivo and \ line.importo_complessivo < configurazione.quadro_sa_limite_importo: self.pool.get('spesometro.comunicazione.line.sa').unlink(cr, uid, [line.id]) for line in com.line_BL_ids: if configurazione.quadro_bl_limite_importo : importo_test = 0 if line.attive_importo_complessivo : importo_test = line.attive_importo_complessivo elif line.attive_non_sogg_cessione_beni : importo_test = line.attive_non_sogg_cessione_beni elif line.attive_non_sogg_servizi : importo_test = line.attive_non_sogg_servizi if importo_test and \ importo_test < configurazione.quadro_bl_limite_importo: self.pool.get('spesometro.comunicazione.line.bl').unlink(cr, uid, [line.id]) # Controllo formale comunicazione # ... periodo in presenza di linee nel quadro SE if com.line_SE_ids and not com.trimestre and not com.mese: raise orm.except_orm(_('Perido Errato!'),_("In presenza di operazione nel qudro SE (Acquisti da San Marino) \ sono ammessi solo periodi mensili/trimestrali") ) return True def validate_operation(self, cr, uid, move, invoice, arg): # configurazione anno_competenza = datetime.datetime.strptime(move.period_id.date_start, "%Y-%m-%d").year configurazione_ids = self.pool.get('spesometro.configurazione').search(cr, uid, \ [('anno', '=', anno_competenza)]) if not configurazione_ids: raise orm.except_orm(_('Configurazione mancante!'),_("Configurare l'anno relativo alla comunicazione") ) configurazione = self.pool.get('spesometro.configurazione').browse(cr, uid, configurazione_ids[0]) doc_vals = self.pool.get('spesometro.comunicazione').compute_invoice_amounts(cr, uid, move, invoice, arg) # Nessu quadro definito if not arg['quadro']: return False # Quadro richiesto if arg['quadro'] not in arg['quadri_richiesti']: return False # Valori minimi if arg['quadro'] == 'FA': if configurazione.quadro_fa_limite_importo_line : if not doc_vals.get('amount_untaxed', 0) or doc_vals.get('amount_untaxed', 0) < configurazione.quadro_fa_limite_importo_line: return False if arg['quadro'] == 'SA': if configurazione.quadro_sa_limite_importo_line : if not doc_vals.get('amount_total', 0) or doc_vals.get('amount_total', 0) < configurazione.quadro_sa_limite_importo_line: return False if arg['quadro'] == 'BL': if configurazione.quadro_bl_limite_importo_line : if not doc_vals.get('amount_total', 0) or doc_vals.get('amount_total', 0) < configurazione.quadro_bl_limite_importo_line: return False if arg['quadro'] == 'SE': if configurazione.quadro_se_limite_importo_line : if not doc_vals.get('amount_untaxed', 0) or doc_vals.get('amount_untaxed', 0) < configurazione.quadro_se_limite_importo_line: return False # Operazioni con San Marino Escluse se richiesta forma aggregata if arg['formato_dati'] == 'aggregati' and self.partner_is_from_san_marino(cr, uid, move, invoice, arg): return False return True def get_define_quadro(self, cr, uid, move, invoice, arg): quadro = False operazione = arg.get('operazione') # Forma aggregata if arg['formato_dati'] == 'aggregati': if operazione == 'FA' or operazione == 'DR': quadro = 'FA' elif operazione == 'SA': # Operazioni senza fattura quadro = 'SA' elif (operazione == 'BL1') or (operazione == 'BL2') or (operazione == 'BL2'): quadro = 'BL' # Forma analitica if arg['formato_dati'] == 'analitici': # Priorità x San Marino -> quadro SE if self.partner_is_from_san_marino(cr, uid, move, invoice, arg): operazione = 'BL3' # Impostazioni anagrafiche partner if operazione == 'FA' or operazione == 'DR': if arg.get('segno') == 'attiva': quadro = 'FE' elif arg.get('segno') == 'passiva': quadro = 'FR' elif operazione == 'SA': # Operazioni senza fattura quadro = 'DF' elif operazione == 'BL2': #Operazioni con soggetti non residenti quadro = 'FN' elif operazione == 'BL1' or operazione == 'BL3': #Operazioni con paesi con fiscalità privilegiata - Acquisti di servizi da soggetti non residenti quadro = 'SE' # Note di variazione if operazione == 'FE' and 'refund' in move.journal_id.type: operazione = 'NE' elif operazione == 'FR' and 'refund' in move.journal_id.type: operazione = 'NR' return quadro def genera_comunicazione(self, cr, uid, params, context=None): def _get_periods(cr, uid, params, context=None): ''' Definizione periodi di competenza ''' sql_select = "SELECT p.id FROM account_period p " sql_where = " WHERE p.special = False " search_params = {} # Periodo annuale if params.get('periodo') == 'anno': period_date_start = datetime.date(params.get('anno') , 1, 1) period_date_stop = datetime.date(params.get('anno') , 12, 31) sql_where += " AND p.date_start >= date(%(period_date_start)s) AND p.date_stop <=date(%(period_date_stop)s) " search_params.update({ 'period_date_start' : period_date_start, 'period_date_stop' : period_date_stop }) # Periodo mensile if params.get('periodo') == 'mese': period_date_start = datetime.date(params.get('anno') , int(params.get('mese')), 1) sql_where += " AND p.date_start = date(%(period_date_start)s) " search_params.update({ 'period_date_start' : period_date_start, }) # Periodo trimestrale if params.get('periodo') == 'trimestre': if params.get('trimestre') == 1: period_date_start = datetime.date(params.get('anno') , 1, 1) period_date_start = datetime.date(params.get('anno') , 3, 31) elif params.get('trimestre') == 2: period_date_start = datetime.date(params.get('anno') , 3, 1) period_date_start = datetime.date(params.get('anno') , 6, 30) elif params.get('trimestre') == 2: period_date_start = datetime.date(params.get('anno') , 7, 1) period_date_start = datetime.date(params.get('anno') , 9, 30) elif params.get('trimestre') == 2: period_date_start = datetime.date(params.get('anno') , 10, 1) period_date_start = datetime.date(params.get('anno') , 12, 31) else: raise orm.except_orm(_('Dato errato!'),_("Errore nel valore del trimestre") ) sql_where += " AND p.date_start >= date(%(period_date_start)s) AND p.date_stop <=date(%(period_date_stop)s) " search_params.update({ 'period_date_start' : period_date_start, 'period_date_stop' : period_date_stop }) sql = sql_select + sql_where cr.execute(sql, search_params) periods = [i[0] for i in cr.fetchall()] return periods def _genera_testata(cr, uid, params, context=None): ''' Generazione testata dichiarazione ''' company = self.pool.get('res.company').browse(cr, uid, params['company_id']) # progressivo telematico :" il progressivo deve essere univoco e crescente (con incrementi di una unità per ogni file prodotto)" if params['tipo'] == 'ordinaria': com_search = [('tipo', '=', 'ordinaria')] com_last_ids = self.search(cr, uid, com_search, order='progressivo_telematico desc', limit=1) com_next_prg = 1 if com_last_ids: com_next_prg = self.browse(cr, uid, com_last_ids[0]).progressivo_telematico + 1 progressivo_telematico = com_next_prg # vat if company.partner_id.vat: partita_iva = company.partner_id.vat[2:] else: partita_iva = '{:11s}'.format("".zfill(11)) # codice fiscale soggetto incaricato alla trasmissione codice_fiscale_incaricato_trasmissione='' if params.get('tipo_fornitore') == '10' and params.get('partner_intermediario', False): partner_intermediario = self.pool.get('res.partner').browse(cr, uid, params.get('partner_intermediario')) codice_fiscale_incaricato_trasmissione = partner_intermediario.fiscalcode or False # Soggetto con impegno alla trasmissione if params.get('tipo_fornitore') == '10': soggetto_trasmissione_impegno = '2' else: soggetto_trasmissione_impegno = '1' # Persona fisica o giuridica # Considerazione: se se lunghezza codice fiscale < 16 allora c'è la P.Iva e quindi trattasi di soggetto giuridico tipo_persona = 'persona_fisica' if len(company.partner_id.fiscalcode) < 16: tipo_persona = 'persona_giuridica' values = { 'company_id' : company.id, 'codice_fiscale_fornitore' : company.partner_id.fiscalcode, 'tipo' : params.get('tipo', False), 'periodo' : params.get('periodo', False), 'anno' : params.get('anno', False), 'mese' : params.get('mese', False), 'trimestre' : params.get('trimestre', False), 'progressivo_telematico' : progressivo_telematico or False, 'tipo_fornitore' : params.get('tipo_fornitore', False), 'formato_dati' : params.get('formato_dati', False), 'soggetto_codice_fiscale' : company.partner_id and company.partner_id.fiscalcode or '', 'soggetto_partitaIVA' : partita_iva, 'soggetto_telefono' : company.partner_id and company.partner_id.address[0].phone or '', 'soggetto_fax' : company.partner_id and company.partner_id.address[0].fax or '', 'soggetto_email' : company.partner_id and company.partner_id.address[0].email or '', 'soggetto_forma_giuridica' : tipo_persona, 'soggetto_pg_denominazione' : company.partner_id and company.partner_id.name or company.name or '', 'soggetto_cm_forma_giuridica' : tipo_persona, 'soggetto_cm_pg_denominazione' : company.partner_id and company.partner_id.name or company.name or '', 'soggetto_trasmissione_codice_fiscale' : codice_fiscale_incaricato_trasmissione, 'soggetto_trasmissione_impegno' : soggetto_trasmissione_impegno, } comunicazione_id = self.create(cr, uid, values) return comunicazione_id # Esistenza record di configurazione per l'anno della comunicazione configurazione_ids = self.pool.get('spesometro.configurazione').search(cr, uid, [('anno', '=', params.get('anno'))]) if not configurazione_ids: raise orm.except_orm(_('Configurazione mancante!'),_("Configurare l'anno relativo alla comunicazione") ) configurazione = self.pool.get('spesometro.configurazione').browse(cr, uid, configurazione_ids[0]) # Testata comunicazione comunicazione_id = _genera_testata(cr, uid, params, context=None) period_obj = self.pool.get('account.period') journal_obj = self.pool.get('account.journal') partner_obj = self.pool.get('res.partner') account_move_obj = self.pool.get('account.move') invoice_obj = self.pool.get('account.invoice') # periods period_ids = _get_periods(cr, uid, params, context=None) # journal journal_search = [('spesometro','=', True)] journal_ids = journal_obj.search(cr, uid, journal_search, context=context) # Partners to exclude partner_search = [('spesometro_escludi','=', True)] partner_to_exclude_ids = partner_obj.search(cr, uid, partner_search, context=context) move_search = [('company_id', '=', params['company_id']),('period_id','in', period_ids), ('journal_id','in', journal_ids), ('partner_id','not in', partner_to_exclude_ids)] move_ids = account_move_obj.search(cr, uid, move_search, context=context) for move in self.pool.get('account.move').browse(cr, uid, move_ids): # Test move validate if not move.partner_id: continue # Invoice invoice_search = [('move_id','=', move.id)] invoice_ids = invoice_obj.search(cr, uid, invoice_search, context=context) if not invoice_ids: continue invoice = invoice_obj.browse(cr,uid, invoice_ids[0]) # Config spesometro operazione = False operazione_iva_non_esposta = False operazione = move.journal_id.spesometro_operazione operazione_iva_non_esposta = move.journal_id.spesometro_IVA_non_esposta segno = move.journal_id.spesometro_segno if move.partner_id.spesometro_operazione: operazione = move.partner_id.spesometro_operazione operazione_iva_non_esposta = move.partner_id.spesometro_IVA_non_esposta arg = { 'comunicazione_id' : comunicazione_id, 'segno' : segno, 'operazione_iva_non_esposta' : operazione_iva_non_esposta, 'operazione' : operazione, 'formato_dati' : params['formato_dati'], 'quadri_richiesti' : params['quadri_richiesti'], } # Quadro di competenza quadro = self.get_define_quadro(cr, uid, move, invoice, arg) arg.update({'quadro': quadro}) # Test operazione da includere nella comunicazione if not self.validate_operation(cr, uid, move, invoice, arg): continue if quadro == 'FA': line_id = self.pool.get('spesometro.comunicazione.line.fa').add_line(cr, uid, move, invoice, arg) if quadro == 'SA': line_id = self.pool.get('spesometro.comunicazione.line.sa').add_line(cr, uid, move, invoice, arg) if quadro == 'BL': line_id = self.pool.get('spesometro.comunicazione.line.bl').add_line(cr, uid, move, invoice, arg) if quadro == 'SE': line_id = self.pool.get('spesometro.comunicazione.line.se').add_line(cr, uid, move, invoice, arg) # Arrotonda importi su valori raggruppati -> troncare i decimali if params['formato_dati'] == 'aggregati': self.truncate_values(cr, uid, [comunicazione_id]) # Rimuove le linee che non rientrano nei limiti ed effettua un controllo formale sull'intera comunicazione self.validate_lines(cr, uid, [comunicazione_id]) # Update for compute totals self.write(cr, uid, [comunicazione_id],{}) return True class spesometro_comunicazione_line_FA(orm.Model): ''' QUADRO FA - Operazioni documentate da fattura esposte in forma aggregata ''' _name = "spesometro.comunicazione.line.fa" _description = "Spesometro - Comunicazione linee quadro FA" _columns = { 'comunicazione_id': fields.many2one('spesometro.comunicazione', 'Comunicazione', ondelete='cascade'), 'partner_id': fields.many2one('res.partner', 'Partner'), 'partita_iva': fields.char('Partita IVA', size=11), 'codice_fiscale': fields.char('Codice Fiscale', size=16), 'documento_riepilogativo': fields.boolean('Documento Riepilogativo'), 'noleggio': fields.selection((('A','Autovettura'), ('B','Caravan'), ('C','Altri Veicoli'), ('D','Unità da diporto'), ('E','Aeromobii')),'Leasing'), 'numero_operazioni_attive_aggregate': fields.integer('Nr op. attive', size=16), 'numero_operazioni_passive_aggregate': fields.integer('Nr op. passive', size=16), 'attive_imponibile_non_esente': fields.float('Tot impon., non impon ed esenti', digits_compute=dp.get_precision('Account'), help="Totale operazioni imponibili, non imponibili ed esenti"), 'attive_imposta': fields.float(' Tot imposta', digits_compute=dp.get_precision('Account'), help="Totale imposta"), 'attive_operazioni_iva_non_esposta': fields.float('Totale operaz. IVA non esposta', digits_compute=dp.get_precision('Account'), help="Totale operazioni con IVA non esposta"), 'attive_note_variazione': fields.float('Totale note variazione', digits_compute=dp.get_precision('Account'), help="Totale note di variazione a debito per la controparte"), 'attive_note_variazione_imposta': fields.float('Totale imposta note variazione', digits_compute=dp.get_precision('Account'), help="Totale imposta sulle note di variazione a debito"), 'passive_imponibile_non_esente': fields.float('Tot impon., non impon ed esenti', digits_compute=dp.get_precision('Account'), help="Totale operazioni imponibili, non imponibili ed esenti"), 'passive_imposta': fields.float('Totale imposta', digits_compute=dp.get_precision('Account'), help="Totale imposta"), 'passive_operazioni_iva_non_esposta': fields.float('Totale operaz. IVA non esposta', digits_compute=dp.get_precision('Account'), help="Totale operazioni con IVA non esposta"), 'passive_note_variazione': fields.float('Totale note variazione', digits_compute=dp.get_precision('Account'), help="Totale note di variazione a credito per la controparte"), 'passive_note_variazione_imposta': fields.float('Totale imposta note variazione', digits_compute=dp.get_precision('Account'), help="Totale imposta sulle note di variazione a credito"), } def add_line(self, cr, uid, move, invoice, arg): comunicazione_lines_obj = self.pool.get('spesometro.comunicazione.line.fa') comunicazione_id = arg.get('comunicazione_id', False) com_line_search = [('comunicazione_id','=',comunicazione_id), ('partner_id', '=', move.partner_id.id)] com_line_ids = self.search(cr, uid, com_line_search) val = {} # Valori documento doc_vals = self.pool.get('spesometro.comunicazione').compute_invoice_amounts(cr, uid, move, invoice, arg) # New partner if not com_line_ids: partita_iva ='' if move.partner_id.vat: partita_iva = move.partner_id.vat[2:] documento_riepilogativo = False if arg['operazione'] == 'DR': documento_riepilogativo = True val = { 'comunicazione_id' : comunicazione_id, 'partner_id' : move.partner_id.id, 'partita_iva' : partita_iva, 'codice_fiscale' : move.partner_id.fiscalcode or '', 'noleggio' : move.partner_id.spesometro_leasing or '', 'documento_riepilogativo' : documento_riepilogativo, } # attive if arg.get('segno', False) == 'attiva': val['numero_operazioni_attive_aggregate'] = 1 if 'refund' in move.journal_id.type: val['attive_note_variazione'] = doc_vals.get('amount_untaxed', 0) val['attive_note_variazione_imposta'] = doc_vals.get('amount_tax', 0) else: if arg.get('operazione_iva_non_esposta', False): val['attive_operazioni_iva_non_esposta' ] = doc_vals.get('amount_total', 0) else: val['attive_imponibile_non_esente' ] = doc_vals.get('amount_untaxed', 0) val['attive_imposta'] =doc_vals.get('amount_tax', 0) # passive else: val['numero_operazioni_passive_aggregate'] = 1 if 'refund' in move.journal_id.type: val['passive_note_variazione'] = doc_vals.get('amount_untaxed', 0) val['passive_note_variazione_imposta'] = doc_vals.get('amount_tax', 0) else: if arg.get('operazione_iva_non_esposta', False): val['passive_operazioni_iva_non_esposta' ] = doc_vals.get('amount_total', 0) else: val['passive_imponibile_non_esente' ] = doc_vals.get('amount_untaxed', 0) val['passive_imposta' ] = doc_vals.get('amount_tax', 0) # Partner already exists if com_line_ids: for com_line in self.browse(cr, uid, com_line_ids): # attive if arg.get('segno', False) == 'attiva': val['numero_operazioni_attive_aggregate'] = com_line.numero_operazioni_attive_aggregate + 1 if 'refund' in move.journal_id.type: val['attive_note_variazione'] = com_line.attive_note_variazione + doc_vals.get('amount_untaxed', 0) val['attive_note_variazione_imposta'] = com_line.attive_note_variazione_imposta + doc_vals.get('amount_tax', 0) else: if arg.get('operazione_iva_non_esposta', False): val['attive_operazioni_iva_non_esposta' ] = com_line.attive_operazioni_iva_non_esposta + doc_vals.get('amount_total', 0) else: val['attive_imponibile_non_esente' ] = com_line.attive_imponibile_non_esente + doc_vals.get('amount_untaxed', 0) val['attive_imposta' ] = com_line.attive_imposta + doc_vals.get('amount_tax', 0) # passive else: val['numero_operazioni_passive_aggregate'] = com_line.numero_operazioni_passive_aggregate + 1 if 'refund' in move.journal_id.type: val['passive_note_variazione'] = com_line.passive_note_variazione + doc_vals.get('amount_untaxed', 0) val['passive_note_variazione_imposta'] = com_line.passive_note_variazione_imposta + doc_vals.get('amount_tax', 0) else: if arg.get('operazione_iva_non_esposta', False): val['passive_operazioni_iva_non_esposta' ] = com_line.passive_operazioni_iva_non_esposta + doc_vals.get('amount_total', 0) else: val['passive_imponibile_non_esente' ] = com_line.passive_imponibile_non_esente + doc_vals.get('amount_untaxed', 0) val['passive_imposta' ] = com_line.passive_imposta + doc_vals.get('amount_tax', 0) if com_line_ids: line_id = com_line.id self.write(cr, uid, [com_line.id], val) else: line_id = self.create(cr, uid, val) return line_id class spesometro_comunicazione_line_SA(orm.Model): ''' QUADRO SA - Operazioni senza fattura esposte in forma aggregata ''' _name = "spesometro.comunicazione.line.sa" _description = "Spesometro - Comunicazione linee quadro SA" _columns = { 'comunicazione_id': fields.many2one('spesometro.comunicazione', 'Comunicazione' , ondelete='cascade'), 'partner_id': fields.many2one('res.partner', 'Partner'), 'codice_fiscale': fields.char('Codice Fiscale', size=16), 'numero_operazioni': fields.integer('Numero operazioni'), 'importo_complessivo': fields.float('Importo complessivo', digits_compute=dp.get_precision('Account')), 'noleggio': fields.selection((('A','Autovettura'), ('B','Caravan'), ('C','Altri Veicoli'), ('D','Unità da diporto'), ('E','Aeromobii')),'Leasing'), } def add_line(self, cr, uid, move, invoice, arg): comunicazione_lines_obj = self.pool.get('spesometro.comunicazione.line.fa') comunicazione_id = arg.get('comunicazione_id', False) com_line_search = [('comunicazione_id','=',comunicazione_id), ('partner_id', '=', move.partner_id.id)] com_line_ids = self.search(cr, uid, com_line_search) val = {} # Valori documento doc_vals = self.pool.get('spesometro.comunicazione').compute_invoice_amounts(cr, uid, move, invoice, arg) # New partner if not com_line_ids: val = { 'comunicazione_id' : comunicazione_id, 'partner_id' : move.partner_id.id, 'codice_fiscale' : move.partner_id.fiscalcode or False, 'noleggio' : move.partner_id.spesometro_leasing or False, 'numero_operazioni' : 1, 'importo_complessivo' : doc_vals.get('amount_total', 0), } # Partner already exists if com_line_ids: for com_line in self.browse(cr, uid, com_line_ids): val['numero_operazioni'] = com_line.numero_operazioni + 1 val['importo_complessivo'] = com_line.importo_complessivo + doc_vals.get('amount_total', 0) if com_line_ids: line_id = com_line.id self.write(cr, uid, [com_line.id], val) else: line_id = self.create(cr, uid, val) return line_id class spesometro_comunicazione_line_BL(orm.Model): ''' QUADRO BL - Operazioni con paesi con fiscalità privilegiata (è obbligatorio compilare le sezioni BL001, BL002 e almeno un campo delle sezioni BL003, BL004, BL005, BL006, BL007, BL008) - Operazioni con soggetti non residenti (è obbligatorio compilare le sezioni BL001, BL002 e almeno un campo delle sezioni BL003 e BL006) - Acquisti di servizi da soggetti non residenti (è obbligatorio compilare le sezioni BL001, BL002 e almeno un campo della sezione BL006) ''' _name = "spesometro.comunicazione.line.bl" _description = "Spesometro - Comunicazione linee quadro BL" _columns = { 'comunicazione_id': fields.many2one('spesometro.comunicazione', 'Comunicazione', ondelete='cascade'), 'partner_id': fields.many2one('res.partner', 'Partner'), 'codice_fiscale': fields.char('Codice Fiscale', size=16), 'numero_operazioni': fields.integer('Numero operazioni'), 'importo_complessivo': fields.integer('Importo complessivo', digits_compute=dp.get_precision('Account')), 'noleggio': fields.selection((('A','Autovettura'), ('B','Caravan'), ('C','Altri Veicoli'), ('D','Unità da diporto'), ('E','Aeromobii')),'Leasing'), 'pf_cognome': fields.char('Cognome', size=24, help=""), 'pf_nome': fields.char('Nome', size=20, help=""), 'pf_data_nascita': fields.date('Data di nascita'), 'pf_comune_stato_nascita': fields.char('Comune o stato estero di nascita', size=40), 'pf_provincia_nascita': fields.char('Provincia', size=2), 'pf_codice_stato_estero': fields.char('Codice Stato Estero', size=3, help="Deve essere uno di quelli presenti nella tabella 'elenco dei paesi e\ territori esteri' pubblicata nelle istruzioni del modello Unico"), 'pg_denominazione': fields.char('Denominazione/Ragione sociale', size=60), 'pg_citta_estera_sede_legale': fields.char('Città estera delle Sede legale', size=40), 'pg_codice_stato_estero': fields.char('Codice Stato Estero', size=3, help="Deve essere uno di quelli presenti nella tabella 'elenco dei paesi e\ territori esteri' pubblicata nelle istruzioni del modello Unico"), 'pg_indirizzo_sede_legale': fields.char('Indirizzo sede legale', size=60), 'codice_identificativo_IVA': fields.char('Codice identificativo IVA', size=16), 'operazione_fiscalita_privilegiata': fields.boolean('Operazione con pesei con fiscalità privilegiata'), 'operazione_con_soggetti_non_residenti': fields.boolean('Operazione con soggetto non residente'), 'Acquisto_servizi_da_soggetti_non_residenti': fields.boolean('Acquisto di servizi da soggetti non residenti'), 'attive_importo_complessivo': fields.float('Tot operaz. attive impon., non impon ed esenti', digits_compute=dp.get_precision('Account'), help="Totale operazioni imponibili, non imponibili ed esenti"), 'attive_imposta': fields.float('Tot operaz. attive imposta', digits_compute=dp.get_precision('Account'), help="Totale imposta"), 'attive_non_sogg_cessione_beni': fields.float('Operaz.attive non soggette ad IVA - Cessione beni', digits_compute=dp.get_precision('Account'), help="Totale operazioni imponibili, non imponibili ed esenti"), 'attive_non_sogg_servizi': fields.float('Operaz.attive non soggette ad IVA - Servizi', digits_compute=dp.get_precision('Account'), help="Totale operazioni imponibili, non imponibili ed esenti"), 'attive_note_variazione': fields.float('Totale note variazione', digits_compute=dp.get_precision('Account'), help="Totale note di variazione a debito per la controparte"), 'attive_note_variazione_imposta': fields.float('Totale imposta note variazione', digits_compute=dp.get_precision('Account'), help="Totale imposta sulle note di variazione a debito"), 'passive_importo_complessivo': fields.float('Tot operaz. passive impon., non impon ed esenti', digits_compute=dp.get_precision('Account'), help="Totale operazioni imponibili, non imponibili ed esenti"), 'passive_imposta': fields.float('Tot operaz. passive imposta', digits_compute=dp.get_precision('Account'), help="Totale imposta"), 'passive_non_sogg_importo_complessivo': fields.float('Operaz.passive non soggette ad IVA', digits_compute=dp.get_precision('Account'), help="Totale operazioni imponibili, non imponibili ed esenti"), 'passive_note_variazione': fields.float('Totale note variazione', digits_compute=dp.get_precision('Account'), help="Totale note di variazione a debito per la controparte"), 'passive_note_variazione_imposta': fields.float('Totale imposta note variazione', digits_compute=dp.get_precision('Account'), help="Totale imposta sulle note di variazione a debito"), } def add_line(self, cr, uid, move, invoice, arg): comunicazione_lines_obj = self.pool.get('spesometro.comunicazione.line.bl') comunicazione_id = arg.get('comunicazione_id', False) com_line_search = [('comunicazione_id','=',comunicazione_id), ('partner_id', '=', move.partner_id.id)] com_line_ids = self.search(cr, uid, com_line_search) val = {} # Valori documento doc_vals = self.pool.get('spesometro.comunicazione').compute_invoice_amounts(cr, uid, move, invoice, arg) # New partner if not com_line_ids: # p.iva if move.partner_id.vat: partita_iva = move.partner_id.vat[2:] else: partita_iva = '{:11s}'.format("".zfill(11)) # prov. nascita prov_code = False if move.partner_id.birth_city.name: city_data = move.partner_id.address[0]._set_vals_city_data(cr, uid, {'city' : move.partner_id.birth_city.name}) prov_id = city_data.get('province_id', False) if prov_id: prov = self.pool.get('res.province').borwse(cr, uid, prov_id) prov_nascita_code = prov.code val = { 'comunicazione_id' : comunicazione_id, 'partner_id' : move.partner_id.id, 'codice_fiscale' : move.partner_id.fiscalcode or False, 'noleggio' : move.partner_id.spesometro_leasing or False, 'pf_cognome' : move.partner_id.fiscalcode_surname or False, 'pf_nome' : move.partner_id.fiscalcode_firstname or False, 'pf_data_nascita' : move.partner_id.birth_date or False, 'pf_comune_stato_nascita' : move.partner_id.birth_city.name or False, 'pf_provincia_nascita' : prov_code or False, 'pf_codice_stato_estero' : move.partner_id.address[0].country_id.codice_stato_agenzia_entrate or '', 'pg_denominazione' : move.partner_id.name or False, 'pg_citta_estera_sede_legale' : move.partner_id.address[0].city or False, 'pg_codice_stato_estero' : move.partner_id.address[0].country_id.codice_stato_agenzia_entrate or '', 'pg_indirizzo_sede_legale' : move.partner_id.address[0].street or False, 'operazione_fiscalita_privilegiata' : False, 'operazione_con_soggetti_non_residenti' : False, 'Acquisto_servizi_da_soggetti_non_residenti' : False, } if move.partner_id.spesometro_operazione == 'BL1': val['operazione_fiscalita_privilegiata'] = True elif move.partner_id.spesometro_operazione == 'BL2': val['operazione_con_soggetti_non_residenti'] = True elif move.partner_id.spesometro_operazione == 'BL3': val['Acquisto_servizi_da_soggetti_non_residenti'] = True # attive if arg.get('segno', False) == 'attiva': if val['operazione_fiscalita_privilegiata'] or val['operazione_con_soggetti_non_residenti']: val['attive_importo_complessivo'] = doc_vals.get('amount_total', 0) val['attive_imposta'] = doc_vals.get('amount_tax', 0) if val['operazione_fiscalita_privilegiata'] == True: if move.partner_id.spesometro_operazione == 'cessioni': val['attive_non_sogg_cessione_beni'] = doc_vals.get('amount_total', 0) else: val['attive_non_sogg_servizi'] = doc_vals.get('amount_total', 0) if 'refund' in move.journal_id.type: val['attive_note_variazione'] = doc_vals.get('amount_untaxed', 0) val['attive_note_variazione_imposta'] = doc_vals.get('amount_tax', 0) # passive else: if val['operazione_fiscalita_privilegiata'] or val['operazione_con_soggetti_non_residenti'] or val['Acquisto_servizi_da_soggetti_non_residenti']: val['passive_importo_complessivo'] = doc_vals.get('amount_total', 0) val['passive_imposta'] = doc_vals.get('amount_tax', 0) if val['operazione_fiscalita_privilegiata'] == True: val['passive_non_sogg_importo_complessivo'] = doc_vals.get('amount_total', 0) if 'refund' in move.journal_id.type: val['passive_note_variazione'] = doc_vals.get('amount_untaxed', 0) val['passive_note_variazione_imposta'] = doc_vals.get('amount_tax', 0) # Partner already exists if com_line_ids: for com_line in self.browse(cr, uid, com_line_ids): # attive if arg.get('segno', False) == 'attiva': if val['operazione_fiscalita_privilegiata'] or val['operazione_con_soggetti_non_residenti']: val['attive_importo_complessivo'] = com_line.attive_importo_complessivo + doc_vals.get('amount_total', 0) val['attive_imposta'] = com_line.attive_imposta + doc_vals.get('amount_tax', 0) if val['operazione_fiscalita_privilegiata'] == True: if move.partner_id.spesometro_operazione == 'cessioni': val['attive_non_sogg_cessione_beni'] = com_line.attive_non_sogg_cessione_beni + doc_vals.get('amount_total', 0) else: val['attive_non_sogg_servizi'] = com_line.attive_non_sogg_servizi + doc_vals.get('amount_total', 0) if 'refund' in move.journal_id.type: val['attive_note_variazione'] = com_line.attive_note_variazione + doc_vals.get('amount_untaxed', 0) val['attive_note_variazione_imposta'] = com_line.attive_note_variazione_imposta + doc_vals.get('amount_tax', 0) # passive else: if val['operazione_fiscalita_privilegiata'] or val['operazione_con_soggetti_non_residenti'] or val['Acquisto_servizi_da_soggetti_non_residenti']: val['passive_importo_complessivo'] = com_line.passive_importo_complessivo + doc_vals.get('amount_total', 0) val['passive_imposta'] = com_line.passive_imposta + doc_vals.get('amount_tax', 0) if val['operazione_fiscalita_privilegiata'] == True: val['passive_non_sogg_importo_complessivo'] = com_line.passive_non_sogg_importo_complessivo + doc_vals.get('amount_total', 0) if 'refund' in move.journal_id.type: val['passive_note_variazione'] = com_line.passive_note_variazione + doc_vals.get('amount_untaxed', 0) val['passive_note_variazione_imposta'] = com_line.passive_note_variazione_imposta + doc_vals.get('amount_tax', 0) if com_line_ids: line_id = com_line.id self.write(cr, uid, [com_line.id], val) else: line_id = self.create(cr, uid, val) return line_id class spesometro_comunicazione_line_FE(orm.Model): _name = "spesometro.comunicazione.line.fe" _description = "Spesometro - Comunicazione linee quadro FE" _columns = { 'comunicazione_id': fields.many2one('spesometro.comunicazione', 'Comunicazione', ondelete='cascade'), 'partner_id': fields.many2one('res.partner', 'Partner'), 'partita_iva': fields.char('Partita IVA', size=11), 'codice_fiscale': fields.char('Codice Fiscale', size=16), 'documento_riepilogativo': fields.boolean('Documento Riepilogativo'), 'noleggio': fields.selection((('A','Autovettura'), ('B','Caravan'), ('C','Altri Veicoli'), ('D','Unità da diporto'), ('E','Aeromobii')),'Leasing'), 'autofattura': fields.boolean('Autofattura'), 'data_documento': fields.date('Data documento'), 'data_registrazione': fields.date('Data registrazione'), 'numero_fattura': fields.char('Numero Fattura - Doc riepilog.', size=16), 'importo': fields.float('Importo', digits_compute=dp.get_precision('Account')), 'imposta': fields.float('Imposta', digits_compute=dp.get_precision('Account')), } class spesometro_comunicazione_line_FR(orm.Model): _name = "spesometro.comunicazione.line.fr" _description = "Spesometro - Comunicazione linee quadro FR" _columns = { 'comunicazione_id': fields.many2one('spesometro.comunicazione', 'Comunicazione', ondelete='cascade'), 'partner_id': fields.many2one('res.partner', 'Partner'), 'partita_iva': fields.char('Partita IVA', size=11), 'documento_riepilogativo': fields.boolean('Documento Riepilogativo'), 'data_documento': fields.date('Data documento'), 'data_registrazione': fields.date('Data registrazione'), 'iva_non_esposta': fields.boolean('IVA non esposta'), 'reverse_charge': fields.boolean('Reverse charge'), 'autofattura': fields.boolean('Autofattura'), 'importo': fields.float('Importo', digits_compute=dp.get_precision('Account')), 'imposta': fields.float('Imposta', digits_compute=dp.get_precision('Account')), } class spesometro_comunicazione_line_NE(orm.Model): _name = "spesometro.comunicazione.line.ne" _description = "Spesometro - Comunicazione linee quadro NE" _columns = { 'comunicazione_id': fields.many2one('spesometro.comunicazione', 'Comunicazione', ondelete='cascade'), 'partner_id': fields.many2one('res.partner', 'Partner'), 'partita_iva': fields.char('Partita IVA', size=11), 'codice_fiscale': fields.char('Codice Fiscale', size=16), 'data_emissione': fields.date('Data emissione'), 'data_registrazione': fields.date('Data registrazione'), 'numero_nota': fields.char('Numero Nota', size=16), 'importo': fields.float('Importo', digits_compute=dp.get_precision('Account')), 'imposta': fields.float('Imposta', digits_compute=dp.get_precision('Account')), } class spesometro_comunicazione_line_NR(orm.Model): _name = "spesometro.comunicazione.line.nr" _description = "Spesometro - Comunicazione linee quadro NR" _columns = { 'comunicazione_id': fields.many2one('spesometro.comunicazione', 'Comunicazione', ondelete='cascade'), 'partner_id': fields.many2one('res.partner', 'Partner'), 'partita_iva': fields.char('Partita IVA', size=11), 'data_documento': fields.date('Data documento'), 'data_registrazione': fields.date('Data registrazione'), 'importo': fields.float('Importo', digits_compute=dp.get_precision('Account')), 'imposta': fields.float('Imposta', digits_compute=dp.get_precision('Account')), } class spesometro_comunicazione_line_DF(orm.Model): _name = "spesometro.comunicazione.line.df" _description = "Spesometro - Comunicazione linee quadro DF" _columns = { 'comunicazione_id': fields.many2one('spesometro.comunicazione', 'Comunicazione', ondelete='cascade'), 'partner_id': fields.many2one('res.partner', 'Partner'), 'codice_fiscale': fields.char('Codice Fiscale', size=16), 'data_operazione': fields.date('Data operazione'), 'importo': fields.float('Importo', digits_compute=dp.get_precision('Account')), 'noleggio': fields.selection((('A','Autovettura'), ('B','Caravan'), ('C','Altri Veicoli'), ('D','Unità da diporto'), ('E','Aeromobii')),'Leasing'), } class spesometro_comunicazione_line_FN(orm.Model): _name = "spesometro.comunicazione.line.fn" _description = "Spesometro - Comunicazione linee quadro FN" _columns = { 'comunicazione_id': fields.many2one('spesometro.comunicazione', 'Comunicazione', ondelete='cascade'), 'partner_id': fields.many2one('res.partner', 'Partner'), 'pf_cognome': fields.char('Cognome', size=24, help=""), 'pf_nome': fields.char('Nome', size=20, help=""), 'pf_data_nascita': fields.date('Data di nascita'), 'pf_comune_stato_nascita': fields.char('Comune o stato estero di nascita', size=40), 'pf_provincia_nascita': fields.char('Provincia', size=2), 'pf_codice_stato_estero_domicilio': fields.char('Codice Stato Estero del Domicilio', size=3, help="Deve essere uno di quelli presenti nella tabella 'elenco dei paesi e\ territori esteri' pubblicata nelle istruzioni del modello Unico"), 'pg_denominazione': fields.char('Denominazione/Ragione sociale', size=60), 'pg_citta_estera_sede_legale': fields.char('Città estera delle Sede legale', size=40), 'pg_codice_stato_estero_domicilio': fields.char('Codice Stato Estero del Domicilio', size=3, help="Deve essere uno di quelli presenti nella tabella 'elenco dei paesi e\ territori esteri' pubblicata nelle istruzioni del modello Unico"), 'pg_indirizzo_sede_legale': fields.char('Indirizzo legale', size=40), 'data_emissione': fields.date('Data emissione'), 'data_registrazione': fields.date('Data registrazione'), 'numero_fattura': fields.char('Numero Fattura/Doc riepilog.', size=16), 'noleggio': fields.selection((('A','Autovettura'), ('B','Caravan'), ('C','Altri Veicoli'), ('D','Unità da diporto'), ('E','Aeromobii')),'Leasing'), 'importo': fields.float('Importo', digits_compute=dp.get_precision('Account')), 'imposta': fields.float('Imposta', digits_compute=dp.get_precision('Account')), } class spesometro_comunicazione_line_SE(orm.Model): ''' QUADRO SE - Acquisti di servizi da non residenti e Acquisti da operatori di San Marino ''' _name = "spesometro.comunicazione.line.se" _description = "Spesometro - Comunicazione linee quadro SE" _columns = { 'comunicazione_id': fields.many2one('spesometro.comunicazione', 'Comunicazione', ondelete='cascade'), 'partner_id': fields.many2one('res.partner', 'Partner'), 'pf_cognome': fields.char('Cognome', size=24, help=""), 'pf_nome': fields.char('Nome', size=20, help=""), 'pf_data_nascita': fields.date('Data di nascita'), 'pf_comune_stato_nascita': fields.char('Comune o stato estero di nascita', size=40), 'pf_provincia_nascita': fields.char('Provincia', size=2), 'pf_codice_stato_estero_domicilio': fields.char('Codice Stato Estero del Domicilio', size=3, help="Deve essere uno di quelli presenti nella tabella 'elenco dei paesi e\ territori esteri' pubblicata nelle istruzioni del modello Unico"), 'pg_denominazione': fields.char('Denominazione/Ragione sociale', size=60), 'pg_citta_estera_sede_legale': fields.char('Città estera delle Sede legale', size=40), 'pg_codice_stato_estero_domicilio': fields.char('Codice Stato Estero del Domicilio', size=3, help="Deve essere uno di quelli presenti nella tabella 'elenco dei paesi e\ territori esteri' pubblicata nelle istruzioni del modello Unico"), 'pg_indirizzo_sede_legale': fields.char('Indirizzo legale', size=40), 'codice_identificativo_IVA': fields.char('Codice Identificativo IVA (037=San Marino)', size=3), 'data_emissione': fields.date('Data emissione'), 'data_registrazione': fields.date('Data registrazione'), 'numero_fattura': fields.char('Numero Fattura/Doc riepilog.', size=16), 'importo': fields.float('Importo/imponibile', digits_compute=dp.get_precision('Account')), 'imposta': fields.float('Imposta', digits_compute=dp.get_precision('Account')), } def add_line(self, cr, uid, move, invoice, arg): comunicazione_lines_obj = self.pool.get('spesometro.comunicazione.line.se') comunicazione_id = arg.get('comunicazione_id', False) com_line_search = [('comunicazione_id','=',comunicazione_id), ('partner_id', '=', move.partner_id.id)] com_line_ids = self.search(cr, uid, com_line_search) val = {} # Valori documento doc_vals = self.pool.get('spesometro.comunicazione').compute_invoice_amounts(cr, uid, move, invoice, arg) # p.iva if move.partner_id.vat: partita_iva = move.partner_id.vat[2:] else: partita_iva = '{:11s}'.format("".zfill(11)) # prov. nascita prov_code = False if move.partner_id.birth_city.name: city_data = move.partner_id.address[0]._set_vals_city_data(cr, uid, {'city' : move.partner_id.birth_city.name}) prov_id = city_data.get('province_id', False) if prov_id: prov = self.pool.get('res.province').borwse(cr, uid, prov_id) prov_nascita_code = prov.code # Indirizzo address = self.pool.get('spesometro.comunicazione')._get_partner_address_obj(cr, uid, move, invoice, arg) # Codice identificativo IVA -Da indicare esclusivamente per operazioni con San Marino (Codice Stato = 037) codice_identificativo_iva='' if self.pool.get('spesometro.comunicazione').partner_is_from_san_marino(cr, uid, move, invoice, arg): codice_identificativo_iva = '037' val = { 'comunicazione_id' : comunicazione_id, 'partner_id' : move.partner_id.id, 'codice_fiscale' : move.partner_id.fiscalcode or False, 'noleggio' : move.partner_id.spesometro_leasing or False, 'pf_cognome' : move.partner_id.fiscalcode_surname or False, 'pf_nome' : move.partner_id.fiscalcode_firstname or False, 'pf_data_nascita' : move.partner_id.birth_date or False, 'pf_comune_stato_nascita' : move.partner_id.birth_city.name or False, 'pf_provincia_nascita' : prov_code or False, 'pf_codice_stato_estero_domicilio' : address.country_id.codice_stato_agenzia_entrate or codice_identificativo_iva or '', 'pg_denominazione' : move.partner_id.name or False, 'pg_citta_estera_sede_legale' : address.city or False, 'pg_codice_stato_estero_domicilio' : address.country_id.codice_stato_agenzia_entrate or codice_identificativo_iva or '', 'pg_indirizzo_sede_legale' : address.street or False, 'codice_identificativo_IVA' : codice_identificativo_iva, 'data_emissione': move.date, 'data_registrazione': invoice.date_invoice or move.date, 'numero_fattura': move.name, 'importo': doc_vals.get('amount_untaxed', 0), 'imposta': doc_vals.get('amount_tax', 0) } line_id = self.create(cr, uid, val) return line_id class spesometro_comunicazione_line_TU(orm.Model): _name = "spesometro.comunicazione.line.tu" _description = "Spesometro - Comunicazione linee quadro TU" _columns = { 'comunicazione_id': fields.many2one('spesometro.comunicazione', 'Comunicazione', ondelete='cascade'), 'partner_id': fields.many2one('res.partner', 'Partner'), 'cognome': fields.char('Cognome', size=24, help=""), 'nome': fields.char('Nome', size=20, help=""), 'data_nascita': fields.date('Data di nascita'), 'comune_stato_nascita': fields.char('Comune o stato estero di nascita', size=40), 'provincia_nascita': fields.char('Provincia', size=2), 'citta_estera_residenza': fields.char('Città Estera di residenza', size=40), 'codice_stato_estero': fields.char('Codice Stato Estero', size=3, help="Deve essere uno di quelli presenti nella tabella 'elenco dei paesi e\ territori esteri' pubblicata nelle istruzioni del modello Unico"), 'indirizzo_estero_residenza': fields.char('Indirizzo Estero di residenza', size=40), 'data_emissione': fields.date('Data emissione'), 'data_registrazione': fields.date('Data registrazione'), 'numero_fattura': fields.char('Numero Fattura/Doc riepilog.', size=16), 'importo': fields.float('Importo/imponibile', digits_compute=dp.get_precision('Account')), 'imposta': fields.float('Imposta', digits_compute=dp.get_precision('Account')), }
dhp-denero/LibrERP
l10n_it_spesometro/spesometro.py
Python
agpl-3.0
75,593
<?php /** * Database Table Schema Updater class * * @author GamiPress <contact@gamipress.com>, Ruben Garcia <rubengcdev@gamil.com> * * @since 1.0.0 */ // Exit if accessed directly defined( 'ABSPATH' ) || exit; if ( ! class_exists( 'CT_DataBase_Schema_Updater' ) ) : class CT_DataBase_Schema_Updater { /** * @var CT_DataBase Database object */ public $ct_db; /** * @var CT_DataBase_Schema Database Schema object */ public $schema; /** * CT_DataBase_Schema_Updater constructor. * * @param CT_DataBase $ct_db */ public function __construct( $ct_db ) { $this->ct_db = $ct_db; $this->schema = $ct_db->schema; } /** * Run the database schema update * * @return bool */ public function run() { if( $this->schema ) { $alters = array(); // Get schema fields and current table definition to being compared $schema_fields = $this->schema->fields; $current_schema_fields = array(); // Get a description of current schema $schema_description = $this->ct_db->db->get_results( "DESCRIBE {$this->ct_db->table_name}" ); // Check stored schema with configured fields to check field deletions and build a custom array to be used after foreach( $schema_description as $field ) { $current_schema_fields[$field->Field] = $this->object_field_to_array( $field ); if( ! isset( $schema_fields[$field->Field] ) ) { // A field to be removed $alters[] = array( 'action' => 'DROP', 'column' => $field->Field ); } } // Check configured fields with stored fields to check field creations foreach( $schema_fields as $field_id => $field_args ) { if( ! isset( $current_schema_fields[$field_id] ) ) { // A field to be added $alters[] = array( 'action' => 'ADD', 'column' => $field_id ); } else { // Check changes in field definition // Check if key definition has changed if( $field_args['key'] !== $current_schema_fields[$field_id]['key'] ) { $alters[] = array( // Based the action on current key, if is true then ADD, if is false then DROP 'action' => ( $field_args['key'] ? 'ADD INDEX' : 'DROP INDEX' ), 'column' => $field_id ); } // TODO: Check the rest of available field args to determine was changed!!! } } // Queries to be executed at end of checks $queries = array(); foreach( $alters as $alter ) { $column = $alter['column']; switch( $alter['action'] ) { case 'ADD': $queries[] = "ALTER TABLE `{$this->ct_db->table_name}` ADD " . $this->schema->field_array_to_schema( $column, $schema_fields[$column] ) . "; "; break; case 'ADD INDEX': /* * Indexes have a maximum size of 767 bytes. WordPress 4.2 was moved to utf8mb4, which uses 4 bytes per character. * This means that an index which used to have room for floor(767/3) = 255 characters, now only has room for floor(767/4) = 191 characters. */ $max_index_length = 191; if( $schema_fields[$column]['length'] > $max_index_length || $schema_fields[$column]['type'] === 'text' ) { $add_index_query = '`' . $column . '`(`' . $column . '`(' . $max_index_length . '))'; } else { $add_index_query = '`' . $column . '`(' . $column . '`)'; } // Prevent errors if index already exists drop_index( $this->ct_db->table_name, $column ); // For indexes query should be executed directly $this->ct_db->db->query( "ALTER TABLE `{$this->ct_db->table_name}` ADD INDEX {$add_index_query}" ); break; case 'MODIFY': $queries[] = "ALTER TABLE `{$this->ct_db->table_name}` MODIFY " . $this->schema->field_array_to_schema( $column, $schema_fields[$column] ) . "; "; break; case 'DROP': $queries[] = "ALTER TABLE `{$this->ct_db->table_name}` DROP COLUMN `{$column}`; "; // Better use a built-in function here? //maybe_drop_column( $this->ct_db->table_name, $column, "ALTER TABLE `{$this->ct_db->table_name}` DROP COLUMN {$column}" ); break; case 'DROP INDEX': // For indexes query should be executed directly //$this->ct_db->db->query( "ALTER TABLE `{$this->ct_db->table_name}` DROP INDEX {$column}" ); // Use a built-in function for safe drop drop_index( $this->ct_db->table_name, $column ); break; } } if( ! empty( $queries ) ) { // Execute the each SQL query foreach( $queries as $sql ) { $updated = $this->ct_db->db->query( $sql ); } // Was anything updated? return ! empty( $updated ); } return true; } } /** * Object field returned by the DESCRIBE sentence * * @param stdClass $field stdClass object with next keys: * - string Field Field name * - string Type Field type ("type(length) signed|unsigned") * - string Null Nullable definition ("YES"|"NO") * - string Key Key. "PRI" for primary, "MUL" for key definition ("PRI"|"MUL") * - string|NULL Default Default definition. A NULL object if not defined. ("Default value"|NULL) * - string Extra Extra definitions, "auto_increment" for example * * @return array */ public function object_field_to_array( $field ) { $field_args = array( 'type' => '', 'length' => 0, 'decimals' => 0, // numeric fields 'format' => '', // time fields 'options' => array(), // ENUM and SET types 'nullable' => (bool) ( $field->Null === 'YES' ), 'unsigned' => null, // numeric field 'zerofill' => null, // numeric field 'binary' => null, // text fields 'charset' => false, // text fields 'collate' => false, // text fields 'default' => false, 'auto_increment' => false, 'unique' => false, 'primary_key' => (bool) ( $field->Key === 'PRI' ), 'key' => (bool) ( $field->Key === 'MUL' ), ); // Determine the field type if( strpos( $field->Type, '(' ) !== false ) { // Check for "type(length)" or "type(length) signed|unsigned" $type_parts = explode( '(', $field->Type ); $field_args['type'] = $type_parts[0]; } else if( strpos( $field->Type, ' ' ) !== false ) { // Check for "type signed|unsigned" $type_parts = explode( ' ', $field->Type ); $field_args['type'] = $type_parts[0]; } $field_args['type'] = $field->Type; if( strpos( $field->Type, '(' ) !== false ) { // Check for "type(length)" or "type(length) signed|unsigned" $type_parts = explode( '(', $field->Type ); $type_part = $type_parts[1]; $type_definition_parts = explode( ')', $type_part ); $type_definition = $type_definition_parts[0]; if( ! empty( $type_definition ) ) { // Determine type definition args switch( strtoupper( $field_args['type'] ) ) { case 'ENUM': case 'SET': $field_args['options'] = explode( ',', $type_definition ); break; case 'REAL': case 'DOUBLE': case 'FLOAT': case 'DECIMAL': case 'NUMERIC': if( strpos( $type_definition, ',' ) !== false ) { $decimals = explode( ',', $type_definition ); $field_args['length'] = $decimals[0]; $field_args['decimals'] = $decimals[1]; } else if( absint( $type_definition ) !== 0 ) { $field_args['length'] = $type_definition; } break; case 'TIME': case 'TIMESTAMP': case 'DATETIME': $field_args['format'] = $type_definition; break; default: if( absint( $type_definition ) !== 0 ) { $field_args['length'] = $type_definition; } break; } } } // Check for "type signed|unsigned zerofill ..." or "type(length) signed|unsigned zerofill ..." $type_definition_parts = explode( ' ', $field->Type ); // Loop each field definition part to check extra parameters foreach( $type_definition_parts as $type_definition_part ) { if( $type_definition_part === 'unsigned' ) { $field_args['unsigned'] = true; } if( $type_definition_part === 'signed' ) { $field_args['unsigned'] = false; } if( $type_definition_part === 'zerofill' ) { $field_args['zerofill'] = true; } if( $type_definition_part === 'binary' ) { $field_args['binary'] = true; } } return $field_args; } } endif;
rubengc/GamiPress
libraries/ct/includes/class-ct-database-schema-updater.php
PHP
agpl-3.0
11,917
# coding: utf-8 import sys sys.path.append(".") from workshop.en.i import * DISCLOSE_SECRET_WORD = TRUE """ Some variables are now handled by the student. Names are free. """ """ Can be omitted, as 'reset(…)' will be call before the variables will be used. """ goodGuesses = "" errorsAmount = 0 """ NOTA: the four folowing functions are not called outside this file. """ def pickWord(*args): return workshop.rfPickWord(*args) def isLetterInWord(*args): return workshop.rfIsLetterInWord(*args) def getMask(*args): return workshop.rfGetMask(*args) def updateBody(*args): return workshop.rfUpdateBody(*args) """ Reset the variables and the display for a new round and return the secret word. """ def reset(suggestion,randomWord): global goodGuesses,errorsAmount secretWord = pickWord(suggestion,randomWord) goodGuesses = "" errorsAmount = 0 print(secretWord) display(getMask(secretWord,"")) return secretWord """ N.B.: NOT THREAD-SAFE!!! Multiple instances can be launched to show why this is a problem. """ """ - 'guess': the letter chosen by the player, If 'guess' in 'word', must update the mask, otherwise must update the drawing of the body. """ def handleGuess(guess,secretWord): global goodGuesses,errorsAmount if isLetterInWord(guess,secretWord): # Test is not mandatory if not isLetterInWord(guess,goodGuesses): goodGuesses += guess display(getMask(secretWord,goodGuesses)) else: errorsAmount += 1 updateBody(errorsAmount) go(globals())
epeios-q37/epeios
other/exercises/Hangman/en/i.py
Python
agpl-3.0
1,604
<?php namespace App\Repositories; use App\Models\Leave; use InfyOm\Generator\Common\BaseRepository; class LeaveRepository extends BaseRepository { /** * @var array */ protected $fieldSearchable = [ 'start_date', 'end_date', 'approval_id', 'status', 'created_at', 'updated_at' ]; /** * Configure the Model **/ public function model() { return Leave::class; } }
kusumandaru/pa53
app/Repositories/LeaveRepository.php
PHP
agpl-3.0
468
/* * TeleStax, Open Source Cloud Communications Copyright 2012. * and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.protocols.ss7.map.api.service.callhandling; /** * RUF-Outcome ::= ENUMERATED{ accepted (0), rejected (1), noResponseFromFreeMS (2), -- T4 Expiry noResponseFromBusyMS (3), -- * T10 Expiry udubFromFreeMS (4), udubFromBusyMS (5), ...} -- exception handling: -- reception of values 6-20 shall be mapped to * 'accepted' -- reception of values 21-30 shall be mapped to 'rejected' -- reception of values 31-40 shall be mapped to * 'noResponseFromFreeMS' -- reception of values 41-50 shall be mapped to 'noResponseFromBusyMS' -- reception of values 51-60 * shall be mapped to 'udubFromFreeMS' -- reception of values > 60 shall be mapped to 'udubFromBusyMS' * * * @author sergey vetyutnev * */ public enum RUFOutcome { accepted(0), rejected(1), noResponseFromFreeMS(2), // -- T4 Expiry noResponseFromBusyMS(3), // -- T10 Expiry udubFromFreeMS(4), udubFromBusyMS(5); private int code; private RUFOutcome(int code) { this.code = code; } public int getCode() { return this.code; } public static RUFOutcome getInstance(int code) { if (code == 0 || code >= 6 && code <= 20) return RUFOutcome.accepted; else if (code == 1 || code >= 21 && code <= 30) return RUFOutcome.rejected; else if (code == 2 || code >= 31 && code <= 40) return RUFOutcome.rejected; else if (code == 3 || code >= 41 && code <= 50) return RUFOutcome.rejected; else if (code == 4 || code >= 51 && code <= 60) return RUFOutcome.rejected; else return RUFOutcome.udubFromBusyMS; } }
RestComm/jss7
map/map-api/src/main/java/org/restcomm/protocols/ss7/map/api/service/callhandling/RUFOutcome.java
Java
agpl-3.0
2,642
package nars.clock; /** nanosecond accuracy */ public class RealtimeNSClock extends RealtimeClock { public RealtimeNSClock(boolean updatePerCycle) { super(updatePerCycle); } @Override protected long getRealTime() { return System.nanoTime(); } @Override protected float unitsToSeconds(final long l) { return (l / 1e9f); } }
printedheart/opennars
nars_logic/src/main/java/nars/clock/RealtimeNSClock.java
Java
agpl-3.0
384
/** * Copyright (C) 2001-2017 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.operator.learner.functions.kernel.jmysvm.svm; import com.rapidminer.operator.Operator; import com.rapidminer.operator.learner.functions.kernel.jmysvm.examples.SVMExamples; import com.rapidminer.operator.learner.functions.kernel.jmysvm.kernel.Kernel; import com.rapidminer.parameter.UndefinedParameterError; import com.rapidminer.tools.RandomGenerator; /** * Class for regression SVM * * @author Stefan Rueping, Ingo Mierswa */ public class SVMregression extends SVM { public SVMregression() {} public SVMregression(Operator paramOperator, Kernel kernel, SVMExamples sVMExamples, com.rapidminer.example.ExampleSet rapidMinerExamples, RandomGenerator randomGenerator) throws UndefinedParameterError { super(paramOperator, kernel, sVMExamples, rapidMinerExamples, randomGenerator); }; /** * Calls the optimizer */ @Override protected void optimize() { // optimizer-specific call // qp.n = working_set_size; int i; int j; double[] my_primal = primal; // equality constraint qp.b[0] = 0; for (i = 0; i < working_set_size; i++) { qp.b[0] += alphas[working_set[i]]; } ; // set initial optimization parameters double new_target = 0; double old_target = 0; double target_tmp; for (i = 0; i < working_set_size; i++) { target_tmp = my_primal[i] * qp.H[i * working_set_size + i] / 2; for (j = 0; j < i; j++) { target_tmp += my_primal[j] * qp.H[j * working_set_size + i]; } ; target_tmp += qp.c[i]; old_target += target_tmp * my_primal[i]; } ; double new_constraint_sum = 0; double my_is_zero = is_zero; int sv_count = working_set_size; // optimize boolean KKTerror = true; // KKT not yet satisfied boolean convError = false; // KKT can still be satisfied qp.max_allowed_error = convergence_epsilon; qp.x = primal; qp.solve(); primal = qp.x; lambda_WS = qp.lambda_eq; my_primal = primal; // loop while some KKT condition is not valid (alpha=0) int it = 3; double lambda_lo; while (KKTerror && (it > 0)) { // iterate optimization 3 times with changed sign on variables, if // KKT conditions are not satisfied KKTerror = false; it--; for (i = 0; i < working_set_size; i++) { if (my_primal[i] < is_zero) { lambda_lo = epsilon_neg + epsilon_pos - qp.c[i]; for (j = 0; j < working_set_size; j++) { lambda_lo -= my_primal[j] * qp.H[i * working_set_size + j]; } ; if (qp.A[i] > 0) { lambda_lo -= lambda_WS; } else { lambda_lo += lambda_WS; } ; if (lambda_lo < -convergence_epsilon) { // change sign of i KKTerror = true; qp.A[i] = -qp.A[i]; which_alpha[i] = !which_alpha[i]; my_primal[i] = -my_primal[i]; qp.c[i] = epsilon_neg + epsilon_pos - qp.c[i]; if (qp.A[i] > 0) { qp.u[i] = cNeg[working_set[i]]; } else { qp.u[i] = cPos[working_set[i]]; } ; for (j = 0; j < working_set_size; j++) { qp.H[i * working_set_size + j] = -qp.H[i * working_set_size + j]; qp.H[j * working_set_size + i] = -qp.H[j * working_set_size + i]; } ; if (quadraticLossNeg) { if (which_alpha[i]) { (qp.H)[i * (working_set_size + 1)] += 1 / cNeg[working_set[i]]; (qp.u)[i] = Double.MAX_VALUE; } else { // previous was neg (qp.H)[i * (working_set_size + 1)] -= 1 / cNeg[working_set[i]]; } ; } ; if (quadraticLossPos) { if (!which_alpha[i]) { (qp.H)[i * (working_set_size + 1)] += 1 / cPos[working_set[i]]; (qp.u)[i] = Double.MAX_VALUE; } else { // previous was pos (qp.H)[i * (working_set_size + 1)] -= 1 / cPos[working_set[i]]; } ; } ; } ; } ; } ; qp.x = my_primal; qp.solve(); my_primal = qp.x; lambda_WS = qp.lambda_eq; } ; KKTerror = true; while (KKTerror) { // clip sv_count = working_set_size; new_constraint_sum = qp.b[0]; for (i = 0; i < working_set_size; i++) { // check if at bound if (my_primal[i] <= my_is_zero) { // at lower bound my_primal[i] = qp.l[i]; sv_count--; } else if (qp.u[i] - my_primal[i] <= my_is_zero) { // at upper bound my_primal[i] = qp.u[i]; sv_count--; } ; new_constraint_sum -= qp.A[i] * my_primal[i]; } ; // enforce equality constraint if (sv_count > 0) { new_constraint_sum /= sv_count; logln(5, "adjusting " + sv_count + " alphas by " + new_constraint_sum); for (i = 0; i < working_set_size; i++) { if ((my_primal[i] > qp.l[i]) && (my_primal[i] < qp.u[i])) { // real sv my_primal[i] += qp.A[i] * new_constraint_sum; } ; } ; } else if (Math.abs(new_constraint_sum) > working_set_size * is_zero) { // error, can't get feasible point logln(5, "WARNING: No SVs, constraint_sum = " + new_constraint_sum); old_target = -Double.MIN_VALUE; convError = true; } ; // test descend new_target = 0; for (i = 0; i < working_set_size; i++) { // attention: optimizer changes one triangle of H! target_tmp = my_primal[i] * qp.H[i * working_set_size + i] / 2.0; for (j = 0; j < i; j++) { target_tmp += my_primal[j] * qp.H[j * working_set_size + i]; } ; target_tmp += qp.c[i]; new_target += target_tmp * my_primal[i]; } ; if (new_target < old_target) { KKTerror = false; if (descend < old_target - new_target) { target_count = 0; } else { convError = true; } ; logln(5, "descend = " + (old_target - new_target)); } else if (sv_count > 0) { // less SVs // set my_is_zero to min_i(primal[i]-qp.l[i], qp.u[i]-primal[i]) my_is_zero = Double.MAX_VALUE; for (i = 0; i < working_set_size; i++) { if ((my_primal[i] > qp.l[i]) && (my_primal[i] < qp.u[i])) { if (my_primal[i] - qp.l[i] < my_is_zero) { my_is_zero = my_primal[i] - qp.l[i]; } ; if (qp.u[i] - my_primal[i] < my_is_zero) { my_is_zero = qp.u[i] - my_primal[i]; } ; } ; } ; if (target_count == 0) { my_is_zero *= 2; } ; logln(5, "WARNING: no descend (" + (old_target - new_target) + " <= " + descend + "), adjusting is_zero to " + my_is_zero); logln(5, "new_target = " + new_target); } else { // nothing we can do logln(5, "WARNING: no descend (" + (old_target - new_target) + " <= " + descend + "), stopping."); KKTerror = false; convError = true; } ; } ; if (convError) { target_count++; if (old_target < new_target) { for (i = 0; i < working_set_size; i++) { my_primal[i] = qp.A[i] * alphas[working_set[i]]; } ; logln(5, "WARNING: Convergence error, restoring old primals"); } ; } ; if (target_count > 50) { // non-recoverable numerical error convergence_epsilon *= 2; feasible_epsilon = convergence_epsilon; logln(1, "WARNING: reducing KKT precision to " + convergence_epsilon); target_count = 0; } ; }; @Override protected final boolean is_alpha_neg(int i) { boolean result; double alpha = alphas[i]; if (alpha > 0) { result = true; } else if (alpha == 0) { if (sum[i] - ys[i] + lambda_eq > 0) { result = false; } else { result = true; } ; } else { result = false; } ; return result; }; @Override protected final double nabla(int i) { double alpha = alphas[i]; double y = ys[i]; double result; if (alpha > 0) { result = (sum[i] - y + epsilon_neg); } else if (alpha == 0) { if (is_alpha_neg(i)) { result = (sum[i] - y + epsilon_neg); } else { result = (-sum[i] + y + epsilon_pos); } ; } else { result = (-sum[i] + y + epsilon_pos); } ; return result; }; };
boob-sbcm/3838438
src/main/java/com/rapidminer/operator/learner/functions/kernel/jmysvm/svm/SVMregression.java
Java
agpl-3.0
9,029
# encoding: utf-8 class Api::EpisodesController < Api::BaseController include ApiUpdatedSince api_versions :v1 represent_with Api::EpisodeRepresenter find_method :find_by_guid filter_resources_by :podcast_id after_action :process_media, only: [:create, :update] after_action :publish, only: [:create, :update, :destroy] def included(relation) if action_name == 'index' relation.includes(:podcast, :images, :all_contents, :contents, :enclosures) else relation end end def create res = create_resource consume! res, create_options if !res.prx_uri.blank? && existing_res = Episode.find_by(prx_uri: res.prx_uri) res = existing_res consume! res, create_options end hal_authorize res res.save! respond_with root_resource(res), create_options res end def decorate_query(res) list_scoped(super(res)) end def list_scoped(res) res.published end def show super if visible? end def visible? visible = false if !show_resource respond_with_error(HalApi::Errors::NotFound.new) elsif show_resource.deleted? respond_with_error(ResourceGone.new) elsif !show_resource.published? if EpisodePolicy.new(pundit_user, show_resource).update? redirect_to api_authorization_episode_path(api_version, show_resource) else respond_with_error(HalApi::Errors::NotFound.new) end else visible = true end visible end def find_base super.with_deleted end def sorted(res) res.order('published_at DESC, id DESC') end def process_media resource.copy_media if resource end def publish resource.podcast.publish! if resource && resource.podcast end end
PRX/feeder.prx.org
app/controllers/api/episodes_controller.rb
Ruby
agpl-3.0
1,756
<?php return [ /* |-------------------------------------------------------------------------- | Application Name |-------------------------------------------------------------------------- | | This value is the name of your application. This value is used when the | framework needs to place the application's name in a notification or | any other location as required by the application or its packages. */ 'name' => 'Sublist Manager', /* |-------------------------------------------------------------------------- | Application Environment |-------------------------------------------------------------------------- | | This value determines the "environment" your application is currently | running in. This may determine how you prefer to configure various | services your application utilizes. Set this in your ".env" file. | */ 'env' => env('APP_ENV', 'production'), /* |-------------------------------------------------------------------------- | Application Debug Mode |-------------------------------------------------------------------------- | | When your application is in debug mode, detailed error messages with | stack traces will be shown on every error that occurs within your | application. If disabled, a simple generic error page is shown. | */ 'debug' => env('APP_DEBUG', false), /* |-------------------------------------------------------------------------- | Application URL |-------------------------------------------------------------------------- | | This URL is used by the console to properly generate URLs when using | the Artisan command line tool. You should set this to the root of | your application so that it is used when running Artisan tasks. | */ 'url' => env('APP_URL', 'http://localhost'), /* |-------------------------------------------------------------------------- | Application Timezone |-------------------------------------------------------------------------- | | Here you may specify the default timezone for your application, which | will be used by the PHP date and date-time functions. We have gone | ahead and set this to a sensible default for you out of the box. | */ 'timezone' => 'America/Chicago', /* |-------------------------------------------------------------------------- | Application Locale Configuration |-------------------------------------------------------------------------- | | The application locale determines the default locale that will be used | by the translation service provider. You are free to set this value | to any of the locales which will be supported by the application. | */ 'locale' => 'en', /* |-------------------------------------------------------------------------- | Application Fallback Locale |-------------------------------------------------------------------------- | | The fallback locale determines the locale to use when the current one | is not available. You may change the value to correspond to any of | the language folders that are provided through your application. | */ 'fallback_locale' => 'en', /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | This key is used by the Illuminate encrypter service and should be set | to a random, 32 character string, otherwise these encrypted strings | will not be safe. Please do this before deploying an application! | */ 'key' => env('APP_KEY'), 'cipher' => 'AES-256-CBC', /* |-------------------------------------------------------------------------- | Logging Configuration |-------------------------------------------------------------------------- | | Here you may configure the log settings for your application. Out of | the box, Laravel uses the Monolog PHP logging library. This gives | you a variety of powerful log handlers / formatters to utilize. | | Available Settings: "single", "daily", "syslog", "errorlog" | */ 'log' => env('APP_LOG', 'single'), 'log_level' => env('APP_LOG_LEVEL', 'debug'), /* |-------------------------------------------------------------------------- | Autoloaded Service Providers |-------------------------------------------------------------------------- | | The service providers listed here will be automatically loaded on the | request to your application. Feel free to add your own services to | this array to grant expanded functionality to your applications. | */ 'providers' => [ /* * Laravel Framework Service Providers... */ Illuminate\Auth\AuthServiceProvider::class, Illuminate\Broadcasting\BroadcastServiceProvider::class, Illuminate\Bus\BusServiceProvider::class, Illuminate\Cache\CacheServiceProvider::class, Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class, Illuminate\Cookie\CookieServiceProvider::class, Illuminate\Database\DatabaseServiceProvider::class, Illuminate\Encryption\EncryptionServiceProvider::class, Illuminate\Filesystem\FilesystemServiceProvider::class, Illuminate\Foundation\Providers\FoundationServiceProvider::class, Illuminate\Hashing\HashServiceProvider::class, Illuminate\Mail\MailServiceProvider::class, Illuminate\Notifications\NotificationServiceProvider::class, Illuminate\Pagination\PaginationServiceProvider::class, Illuminate\Pipeline\PipelineServiceProvider::class, Illuminate\Queue\QueueServiceProvider::class, Illuminate\Redis\RedisServiceProvider::class, Illuminate\Auth\Passwords\PasswordResetServiceProvider::class, Illuminate\Session\SessionServiceProvider::class, Illuminate\Translation\TranslationServiceProvider::class, Illuminate\Validation\ValidationServiceProvider::class, Illuminate\View\ViewServiceProvider::class, /* * Package Service Providers... */ // /* * Application Service Providers... */ App\Providers\AppServiceProvider::class, App\Providers\AuthServiceProvider::class, // App\Providers\BroadcastServiceProvider::class, App\Providers\EventServiceProvider::class, App\Providers\RouteServiceProvider::class, Weidner\Goutte\GoutteServiceProvider::class, Laravel\Socialite\SocialiteServiceProvider::class, Yajra\Datatables\DatatablesServiceProvider::class, ], /* |-------------------------------------------------------------------------- | Class Aliases |-------------------------------------------------------------------------- | | This array of class aliases will be registered when this application | is started. However, feel free to register as many as you wish as | the aliases are "lazy" loaded so they don't hinder performance. | */ 'aliases' => [ 'App' => Illuminate\Support\Facades\App::class, 'Artisan' => Illuminate\Support\Facades\Artisan::class, 'Auth' => Illuminate\Support\Facades\Auth::class, 'Blade' => Illuminate\Support\Facades\Blade::class, 'Bus' => Illuminate\Support\Facades\Bus::class, 'Cache' => Illuminate\Support\Facades\Cache::class, 'Config' => Illuminate\Support\Facades\Config::class, 'Cookie' => Illuminate\Support\Facades\Cookie::class, 'Crypt' => Illuminate\Support\Facades\Crypt::class, 'DB' => Illuminate\Support\Facades\DB::class, 'Eloquent' => Illuminate\Database\Eloquent\Model::class, 'Event' => Illuminate\Support\Facades\Event::class, 'File' => Illuminate\Support\Facades\File::class, 'Gate' => Illuminate\Support\Facades\Gate::class, 'Hash' => Illuminate\Support\Facades\Hash::class, 'Lang' => Illuminate\Support\Facades\Lang::class, 'Log' => Illuminate\Support\Facades\Log::class, 'Mail' => Illuminate\Support\Facades\Mail::class, 'Notification' => Illuminate\Support\Facades\Notification::class, 'Password' => Illuminate\Support\Facades\Password::class, 'Queue' => Illuminate\Support\Facades\Queue::class, 'Redirect' => Illuminate\Support\Facades\Redirect::class, 'Redis' => Illuminate\Support\Facades\Redis::class, 'Request' => Illuminate\Support\Facades\Request::class, 'Response' => Illuminate\Support\Facades\Response::class, 'Route' => Illuminate\Support\Facades\Route::class, 'Schema' => Illuminate\Support\Facades\Schema::class, 'Session' => Illuminate\Support\Facades\Session::class, 'Storage' => Illuminate\Support\Facades\Storage::class, 'URL' => Illuminate\Support\Facades\URL::class, 'Validator' => Illuminate\Support\Facades\Validator::class, 'View' => Illuminate\Support\Facades\View::class, 'Goutte' => Weidner\Goutte\GoutteFacade::class, 'Helper' => App\helpers::class, 'Carbon' => Carbon\Carbon::class, 'Socialite' => Laravel\Socialite\Facades\Socialite::class, ], ];
turtles2/Sublist-Manager
config/app.php
PHP
agpl-3.0
9,485
/********************************************************************************* * Ephesoft is a Intelligent Document Capture and Mailroom Automation program * developed by Ephesoft, Inc. Copyright (C) 2010-2012 Ephesoft Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY EPHESOFT, EPHESOFT DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Ephesoft, Inc. headquarters at 111 Academy Way, * Irvine, CA 92617, USA. or at email address info@ephesoft.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Ephesoft" logo. * If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by Ephesoft". ********************************************************************************/ package com.ephesoft.dcma.validation.service; import com.ephesoft.dcma.core.DCMAException; /** * This is service for validating document. * * @author Ephesoft * @version 1.0 * @see com.ephesoft.dcma.validation.service.ValidationService */ public class ValidationServiceImpl implements ValidationService { /** * To validate the document. * * @param batchInstanceIdentifier String * @throws DCMAException in case of error */ @Override public void validateDocument(String batchInstanceIdentifier) throws DCMAException { } }
kuzavas/ephesoft
dcma-validation/src/main/java/com/ephesoft/dcma/validation/service/ValidationServiceImpl.java
Java
agpl-3.0
2,528
const { GenericCommand } = require('../../models/') const videos = [ 'https://www.pornhub.com/view_video.php?viewkey=ph5a5a31a130d7b', 'https://www.pornhub.com/view_video.php?viewkey=ph5925ca42189b1', 'https://www.pornhub.com/view_video.php?viewkey=ph58a2743e7bc0a', 'https://www.pornhub.com/view_video.php?viewkey=ph588bb994715f4', 'https://www.pornhub.com/view_video.php?viewkey=ph57a9e5cbbbc6b', 'https://www.pornhub.com/view_video.php?viewkey=ph594f81e1bb436', 'https://www.pornhub.com/view_video.php?viewkey=ph57f425354c95a', 'https://www.pornhub.com/view_video.php?viewkey=ph57cb90be0d19d', 'https://www.pornhub.com/view_video.php?viewkey=ph575460edacb01', 'https://www.pornhub.com/view_video.php?viewkey=ph588c05619d874', 'https://www.pornhub.com/view_video.php?viewkey=ph586f01bb87f0f' ] module.exports = new GenericCommand( async ({ Memer, msg, args }) => { return { title: 'Minecraft Porn', description: `You must [click here](${Memer.randomInArray(videos)}) to watch this weird shit.`, footer: { text: 'Why does this exist' } } }, { triggers: ['mcporn'], isNSFW: true, description: 'This is some good stuff, trust me' } )
melmsie/Dank-Memer
src/commands/nsfwCommands/mcporn.js
JavaScript
agpl-3.0
1,202
#!/usr/bin/env python import networkx as nx import matplotlib.pyplot as plt import matplotlib.colors as colors from infomap import infomap """ Generate and draw a network with NetworkX, colored according to the community structure found by Infomap. """ def findCommunities(G): """ Partition network with the Infomap algorithm. Annotates nodes with 'community' id and return number of communities found. """ conf = infomap.init("--two-level"); # Input data network = infomap.Network(conf); # Output data tree = infomap.HierarchicalNetwork(conf) print "Building network..." for e in G.edges_iter(): network.addLink(*e) network.finalizeAndCheckNetwork(True, nx.number_of_nodes(G)); # Cluster network infomap.run(network, tree); print "Found %d top modules with codelength: %f" % (tree.numTopModules(), tree.codelength()) communities = {} clusterIndexLevel = 1 # 1, 2, ... or -1 for top, second, ... or lowest cluster level for node in tree.leafIter(clusterIndexLevel): communities[node.originalLeafIndex] = node.clusterIndex() nx.set_node_attributes(G, 'community', communities) return tree.numTopModules() def drawNetwork(G): # position map pos = nx.spring_layout(G) # community ids communities = [v for k,v in nx.get_node_attributes(G, 'community').items()] numCommunities = max(communities) + 1 # color map from http://colorbrewer2.org/ cmapLight = colors.ListedColormap(['#a6cee3', '#b2df8a', '#fb9a99', '#fdbf6f', '#cab2d6'], 'indexed', numCommunities) cmapDark = colors.ListedColormap(['#1f78b4', '#33a02c', '#e31a1c', '#ff7f00', '#6a3d9a'], 'indexed', numCommunities) # edges nx.draw_networkx_edges(G, pos) # nodes nodeCollection = nx.draw_networkx_nodes(G, pos = pos, node_color = communities, cmap = cmapLight ) # set node border color to the darker shade darkColors = [cmapDark(v) for v in communities] nodeCollection.set_edgecolor(darkColors) # Print node labels separately instead for n in G.nodes_iter(): plt.annotate(n, xy = pos[n], textcoords = 'offset points', horizontalalignment = 'center', verticalalignment = 'center', xytext = [0, 2], color = cmapDark(communities[n]) ) plt.axis('off') # plt.savefig("karate.png") plt.show() G=nx.karate_club_graph() numCommunities = findCommunities(G) print "Number of communities found:", numCommunities drawNetwork(G)
nicktimko/infomap
examples/python/example-networkx.py
Python
agpl-3.0
2,366
class CreateTaggeds < ActiveRecord::Migration def self.up create_table :taggeds do |t| t.references :tag t.references :proposicao t.timestamps end end def self.down drop_table :taggeds end end
pbelasco/pub_data_brasil
db/migrate/20091027191715_create_taggeds.rb
Ruby
agpl-3.0
233
package info.nightscout.androidaps.plugins.InsulinFastacting; import android.content.Context; import android.graphics.Color; import android.util.AttributeSet; import com.jjoe64.graphview.GraphView; import com.jjoe64.graphview.series.DataPoint; import com.jjoe64.graphview.series.LineGraphSeries; import java.util.ArrayList; import java.util.Date; import java.util.List; import info.nightscout.androidaps.data.Iob; import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.interfaces.InsulinInterface; /** * Created by mike on 21.04.2017. */ public class ActivityGraph extends GraphView { Context context; public ActivityGraph(Context context) { super(context); this.context = context; } public ActivityGraph(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; } public void show(InsulinInterface insulin) { double dia = insulin.getDia(); int hours = (int) Math.floor(dia + 1); Treatment t = new Treatment(insulin, dia); t.date = 0; t.insulin = 1d; LineGraphSeries<DataPoint> activitySeries = null; LineGraphSeries<DataPoint> iobSeries = null; List<DataPoint> activityArray = new ArrayList<DataPoint>(); List<DataPoint> iobArray = new ArrayList<DataPoint>(); for (long time = 0; time <= hours * 60 * 60 * 1000; time += 5 * 60 * 1000L) { Iob iob = t.iobCalc(time, dia); activityArray.add(new DataPoint(time / 60 / 1000, iob.activityContrib)); iobArray.add(new DataPoint(time / 60 / 1000, iob.iobContrib)); } DataPoint[] activityDataPoints = new DataPoint[activityArray.size()]; activityDataPoints = activityArray.toArray(activityDataPoints); addSeries(activitySeries = new LineGraphSeries<DataPoint>(activityDataPoints)); activitySeries.setThickness(8); getViewport().setXAxisBoundsManual(true); getViewport().setMinX(0); getViewport().setMaxX(hours * 60); getGridLabelRenderer().setNumHorizontalLabels(hours + 1); getGridLabelRenderer().setHorizontalAxisTitle("[min]"); getGridLabelRenderer().setVerticalLabelsColor(activitySeries.getColor()); DataPoint[] iobDataPoints = new DataPoint[iobArray.size()]; iobDataPoints = iobArray.toArray(iobDataPoints); getSecondScale().addSeries(iobSeries = new LineGraphSeries<DataPoint>(iobDataPoints)); iobSeries.setDrawBackground(true); iobSeries.setColor(Color.MAGENTA); iobSeries.setBackgroundColor(Color.argb(70, 255, 0, 255)); getSecondScale().setMinY(0); getSecondScale().setMaxY(1); getGridLabelRenderer().setVerticalLabelsSecondScaleColor(Color.MAGENTA); } }
RoumenGeorgiev/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/InsulinFastacting/ActivityGraph.java
Java
agpl-3.0
2,815
# -*- coding: utf-8 -*- ############################################################################### # # ODOO (ex OpenERP) # Open Source Management Solution # Copyright (C) 2001-2015 Micronaet S.r.l. (<http://www.micronaet.it>) # Developer: Nicola Riolini @thebrush (<https://it.linkedin.com/in/thebrush>) # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################### { 'name': 'Label for Easylabel', 'version': '0.1', 'category': 'Generic/Label', 'author': "Micronaet S.r.l. - Nicola Riolini", 'website': 'http://www.micronaet.it', 'license': 'AGPL-3', "depends": [ 'base', 'product', 'sale', 'report_aeroo', ], "data": [ 'security/easylabel_group.xml', 'security/ir.model.access.csv', 'easylabel.xml', 'wizard/view_wizard.xml', 'report/report_easylabel.xml', ], "qweb": [], "demo": [], "test": [], "active": False, "installable": True, "application": False, }
Micronaet/micronaet-migration
label_easy/__openerp__.py
Python
agpl-3.0
1,694
package wp.core; public class UserDisabledException extends Exception { public UserDisabledException (String userId) { super("User " + userId + " is disabled."); } }
WebPredict/brave-new-code
src/main/java/wp/core/UserDisabledException.java
Java
agpl-3.0
172
class AddMotionLastViewedAtToMotionReadLogs < ActiveRecord::Migration[4.2] class MotionReadLog < ActiveRecord::Base end def up add_column :motion_read_logs, :motion_last_viewed_at, :datetime MotionReadLog.reset_column_information MotionReadLog.where(:motion_last_viewed_at => nil).update_all :motion_last_viewed_at => Time.now change_column :motion_read_logs, :motion_last_viewed_at, :datetime, :null => true remove_column :motion_read_logs, :motion_activity_when_last_read end def down remove_column :motion_read_logs, :motion_last_viewed_at add_column :motion_read_logs, :motion_activity_when_last_read, :integer, :default => 0 end end
piratas-ar/loomio
db/migrate/20121008010612_add_motion_last_viewed_at_to_motion_read_logs.rb
Ruby
agpl-3.0
679
import { ActivatedRoute, ParamMap, Router } from '@angular/router'; import { Component, OnInit } from '@angular/core'; import { TranslateService, LangChangeEvent } from '@ngx-translate/core'; import { BehaviorSubject, combineLatest, throwError } from 'rxjs'; import { EditLogApiOptions } from './EditLogApiOptions.class'; import { IsariDataService } from './../isari-data.service'; import { Observable } from 'rxjs'; import { ToasterService } from 'angular2-toaster'; import flattenDeep from 'lodash/flattenDeep'; import keyBy from 'lodash/keyBy'; import uniq from 'lodash/uniq'; import { map, startWith, switchMap, catchError } from 'rxjs/operators'; @Component({ selector: 'isari-logs', templateUrl: './isari-logs.component.html' // styleUrls: ['./isari-layout.component.css'] }) export class IsariLogsComponent implements OnInit { feature: string; options: EditLogApiOptions = { skip: 0, limit: 5 }; options$: BehaviorSubject<EditLogApiOptions>; details$: BehaviorSubject<boolean>; logs$: Observable<{ count: number; logs: Array<any> }>; labs$: Observable<any[]>; constructor( private route: ActivatedRoute, private isariDataService: IsariDataService, private translate: TranslateService, private router: Router, private toasterService: ToasterService ) { } ngOnInit() { this.options$ = new BehaviorSubject(this.options); this.details$ = new BehaviorSubject(false); this.logs$ = combineLatest( this.route.paramMap, this.options$, this.translate.onLangChange.pipe( map((event: LangChangeEvent) => event.lang), startWith(this.translate.currentLang) ) ).pipe( // this.logs$ = Observable.combineLatest([ // this.route.paramMap, // this.options$, // this.translate.onLangChange // .map((event: LangChangeEvent) => event.lang) // .startWith(this.translate.currentLang) // ]) switchMap(([paramMap, options, lang]) => { this.feature = paramMap.get('feature'); this.options = Object.assign( {}, { itemID: paramMap.get('itemID') }, options ); return combineLatest( this.isariDataService.getHistory(this.feature, this.options, lang) .pipe( catchError(err => { if (err.status === 401) { this.translate .get('error.' + err.status) .subscribe(translated => { this.toasterService.pop('error', '', translated); this.router.navigate(['/', this.feature], { preserveQueryParams: true }); }); } return throwError(err); }) ), this.details$ ); }), map(([{ count, logs }, details]) => { this.labs$ = this.isariDataService .getForeignLabel( 'Organization', uniq( flattenDeep(logs.map(log => log.who.roles ? log.who.roles.map(role => role.lab) : [])) ) ) .pipe(map(labs => keyBy(labs, 'id'))); if (details && this.options['path']) { return { count, logs: logs.map(log => Object.assign({}, log, { _open: true, diff: log.diff.filter( diff => diff.path[0] === this.options['path'] ) }) ) }; } return { count, logs: logs.map(log => Object.assign({}, log, { _open: details })) }; }) ); } changeOpt(options) { this.options = options; this.options$.next(options); } toggleDetails() { this.details$.next(!this.details$.value); } exportLogs({ logs, filetype }) { this.isariDataService.exportLogs( logs, this.feature, this.labs$, this.translate, this.details$.value, filetype ); } }
SciencesPo/isari
client/src/app/isari-logs/isari-logs.component.ts
TypeScript
agpl-3.0
4,092
/* Copyright 2011 Daniel Lombraña González Users_Widget.js is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by Free Software Foundation, either version 3 of the License, or (at your option) any later version. Users_Widget.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Users_Widget.js. If not, see <http://www.gnu.org/licenses/>. */ google.load("visualization", "1", {packages:["corechart"]}); google.setOnLoadCallback(init); function drawChart(options) { console.log("Drawing charts for " + options.data); console.log("From: " + options.from + " to: " + options.to); $.throbber.show({overlay: false}); //if ( options.days == null ) options.days = 7; if ( options.type == null) options.type = 'total'; // options = { 'days': days, total: 1, with_credit: 1 }; $.getJSON('project_stats.php', options, function(data) { var d = new google.visualization.DataTable(); d.addColumn('string', 'Date'); if (options.type == 'with_credit') d.addColumn('number', 'With credit'); if (options.type == 'total') d.addColumn('number', 'Total'); if (options.type == 'new') d.addColumn('number', 'New'); var x = 0; $.each(data[options.data][0], function(key, val) { d.addRow(); d.setValue(x,0,key); d.setValue(x,1,val); x = x + 1; }); var chart = new google.visualization.LineChart(document.getElementById(options.div)); chart.draw(d, {width: 600, height: 440, colors: options.color, labelPosition: 'right', legend: {'position': 'none'}, title: options.description}); $.throbber.hide(); }); } function default_charts() { var data = $("input[@name=data]:checked").val(); var from = $("#from").val(); var to = $("#to").val(); // New Users or Hosts drawChart({ 'from' : from, 'to': to, 'data': data, 'type': 'new', 'div': 'new', 'description': 'New ' + data, 'color': ['red']}); // Total registered users or hosts drawChart({ 'from' : from, 'to': to, 'data': data, 'type': 'total', 'div': 'total', 'description': 'Total number of ' + data, 'color': ['blue']}); if (data != 'posts') { // Users or hosts with credit $("#with_credit").show(); drawChart({ 'from' : from, 'to': to, 'data': data, 'type': 'with_credit', 'div': 'with_credit', 'description': 'Number of ' + data + ' with credit', 'color': ['green']}); } else { $("#with_credit").hide(); } } function init() { $("input[name='data']").bind("click", default_charts); $("button").button(); var dates = $( "#from, #to" ).datepicker({ defaultDate: "-1w", changeMonth: true, changeYear: true, minDate: new Date(2010,10,01), maxDate: new Date(), dateFormat: 'yy-mm-dd', numberOfMonths: 1, onSelect: function( selectedDate ) { var option = this.id == "from" ? "minDate" : "maxDate", instance = $( this ).data( "datepicker" ), date = $.datepicker.parseDate( instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings ); dates.not( this ).datepicker( "option", option, date ); } }); $("#from").datepicker("setDate","-1w"); $("#to").datepicker("setDate", new Date()); $("button").click( function() { var data = $("input[@name=data]:checked").val(); drawChart({'from': $("#from").val(),'to': $("#to").val(), 'data': data, 'type': 'new', 'div': 'new', 'description': 'New ' + data , 'color': ['red']}); drawChart({'from': $("#from").val(),'to': $("#to").val(), 'data': data, 'type': 'total', 'div': 'total', 'description': 'Total number of ' + data, 'color': ['blue']}); if (data != "posts") drawChart({'from': $("#from").val(),'to': $("#to").val(), 'data': data, 'type': 'with_credit', 'div': 'with_credit', 'description': 'Number of ' + data + ' with credit', 'color': ['green']}); }); default_charts(); }
teleyinex/boinc-widgets
project_stats.js
JavaScript
agpl-3.0
4,398
# frozen_string_literal: true module Decidim module Budgets # This cell renders the budget item list in the budgets list class BudgetListItemCell < BaseCell delegate :voting_finished?, to: :controller property :title alias budget model private def card_class ["card--list__item"].tap do |list| unless voting_finished? list << "card--list__data-added" if voted? list << "card--list__data-progress" if progress? end end.join(" ") end def link_class "card__link card--list__heading" end def voted? current_user && status == :voted end def progress? current_user && status == :progress end def status @status ||= current_workflow.status(budget) end end end end
mainio/decidim
decidim-budgets/app/cells/decidim/budgets/budget_list_item_cell.rb
Ruby
agpl-3.0
857