repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
crowdAI/crowdai | app/models/views/challenge_organizer_participants.rb | 165 | class ChallengeOrganizerParticipant < MaterializedView
self.primary_key = :id
after_initialize :readonly!
belongs_to :challenge
belongs_to :participant
end
| agpl-3.0 |
michaelletzgus/nextcloud-server | apps/dav/appinfo/v1/caldav.php | 3452 | <?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@owncloud.com>
* @author Georg Ehrke <oc.list@georgehrke.com>
* @author Joas Schilling <coding@schilljs.com>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code 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.
*
* 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, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
// Backends
use OCA\DAV\CalDAV\CalDavBackend;
use OCA\DAV\Connector\LegacyDAVACL;
use OCA\DAV\CalDAV\CalendarRoot;
use OCA\DAV\Connector\Sabre\Auth;
use OCA\DAV\Connector\Sabre\ExceptionLoggerPlugin;
use OCA\DAV\Connector\Sabre\MaintenancePlugin;
use OCA\DAV\Connector\Sabre\Principal;
$authBackend = new Auth(
\OC::$server->getSession(),
\OC::$server->getUserSession(),
\OC::$server->getRequest(),
\OC::$server->getTwoFactorAuthManager(),
\OC::$server->getBruteForceThrottler(),
'principals/'
);
$principalBackend = new Principal(
\OC::$server->getUserManager(),
\OC::$server->getGroupManager(),
\OC::$server->getShareManager(),
\OC::$server->getUserSession(),
'principals/'
);
$db = \OC::$server->getDatabaseConnection();
$userManager = \OC::$server->getUserManager();
$random = \OC::$server->getSecureRandom();
$logger = \OC::$server->getLogger();
$dispatcher = \OC::$server->getEventDispatcher();
$calDavBackend = new CalDavBackend($db, $principalBackend, $userManager, \OC::$server->getGroupManager(), $random, $logger, $dispatcher, true);
$debugging = \OC::$server->getConfig()->getSystemValue('debug', false);
$sendInvitations = \OC::$server->getConfig()->getAppValue('dav', 'sendInvitations', 'yes') === 'yes';
// Root nodes
$principalCollection = new \Sabre\CalDAV\Principal\Collection($principalBackend);
$principalCollection->disableListing = !$debugging; // Disable listing
$addressBookRoot = new CalendarRoot($principalBackend, $calDavBackend);
$addressBookRoot->disableListing = !$debugging; // Disable listing
$nodes = array(
$principalCollection,
$addressBookRoot,
);
// Fire up server
$server = new \Sabre\DAV\Server($nodes);
$server::$exposeVersion = false;
$server->httpRequest->setUrl(\OC::$server->getRequest()->getRequestUri());
$server->setBaseUri($baseuri);
// Add plugins
$server->addPlugin(new MaintenancePlugin());
$server->addPlugin(new \Sabre\DAV\Auth\Plugin($authBackend, 'ownCloud'));
$server->addPlugin(new \Sabre\CalDAV\Plugin());
$server->addPlugin(new LegacyDAVACL());
if ($debugging) {
$server->addPlugin(new Sabre\DAV\Browser\Plugin());
}
$server->addPlugin(new \Sabre\DAV\Sync\Plugin());
$server->addPlugin(new \Sabre\CalDAV\ICSExportPlugin());
$server->addPlugin(new \OCA\DAV\CalDAV\Schedule\Plugin());
if ($sendInvitations) {
$server->addPlugin(\OC::$server->query(\OCA\DAV\CalDAV\Schedule\IMipPlugin::class));
}
$server->addPlugin(new ExceptionLoggerPlugin('caldav', \OC::$server->getLogger()));
// And off we go!
$server->exec();
| agpl-3.0 |
be-lb/sdi-clients | sdi/print/template.ts | 1571 |
import { fromPredicate, Option } from 'fp-ts/lib/Option';
import { Rect, Box, TextAlign } from './context';
type ResAnnotation = { resolution: number };
export interface TemplateSpec {
rect: Rect;
fontSize: number;
strokeWidth: number;
textAlign: TextAlign;
color: string;
}
export interface PartialSpec {
rect: Rect;
fontSize?: number;
strokeWidth?: number;
textAlign?: TextAlign;
color?: string;
}
export type Spec = TemplateSpec & ResAnnotation;
export const makeSpec =
(s: PartialSpec): TemplateSpec => ({
fontSize: 10,
strokeWidth: 1,
textAlign: 'left',
color: 'black',
...s,
});
export type SpecName = string;
export interface Template {
[s: string]: TemplateSpec;
}
// export type Template = PartialTemplate & ResAnnotation;
export const withSpec =
(template: Template, resolution: number, specName: SpecName): Option<Spec> =>
fromPredicate<Template>(t => specName in t)(template)
.map((t) => {
const tspec = t[specName];
const spec = {
...tspec,
resolution,
};
return spec;
});
export interface ApplyFn<T = Box> {
(specName: SpecName, fn: SpecFn<T>): Option<T>;
}
export interface SpecFn<T = Box> {
(s: Spec): T;
}
export const applySpec =
(template: Template, resolution: number) =>
<T = Box>(specName: SpecName, fn: SpecFn<T>) =>
withSpec(template, resolution, specName).map(fn);
| agpl-3.0 |
ging/isabel | components/gateway/GWSIP/mjsip_1.6/src/local/server/AuthenticationService.java | 2605 | /*
* Copyright (C) 2005 Luca Veltri - University of Parma - Italy
*
* This source code is free software; you can redistribute it and/or modify
* it under the terms of the Affero 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 source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Affero GNU General Public License for more details.
*
* You should have received a copy of the Affero GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author(s):
* Luca Veltri (luca.veltri@unipr.it)
*/
package local.server;
import java.util.Enumeration;
//import org.zoolu.sip.provider.SipStack;
//import org.zoolu.tools.Parser;
//import org.zoolu.tools.Base64;
//import java.util.Hashtable;
//import java.io.*;
/** AuthenticationService is the interface used by a SIP server to access to
* an AAA repository.
*/
public interface AuthenticationService extends Repository
{
/** Adds a new user at the database.
* @param user the user name
* @param key the user key
* @return this object */
public AuthenticationService addUser(String user, byte[] key);
/** Adds a new user at the database.
* @param user the user name
* @param key the user key
* @param seqn the current user SQN value
* @return this object */
//public AuthenticationService addUser(String user, byte[] key, int seqn);
/** Sets the user key.
* @param user the user name
* @param key the user key
* @return this object */
public AuthenticationService setUserKey(String user, byte[] key);
/** Gets the user key.
* @param user the user name
* @return the user key */
public byte[] getUserKey(String user);
/** Sets the user sequence number.
* @param user the user name
* @param rand the user sequence number
* @return this object */
//public AuthenticationService setUserSeqn(String user, int seqn);
/** Gets the user sequence number.
* @param user the user name
* @return the user sequence number */
//public int getUserSeqn(String user);
/** Increments the user sequence number.
* @param user the user name
* @return the new user sequence number */
//public int incUserSeqn(String user);
}
| agpl-3.0 |
ANAXRIDER/OpenAI | OpenAI/OpenAI/Cards/Sim_BRMA06_2H_TB.cs | 557 | using System;
using System.Collections.Generic;
using System.Text;
namespace OpenAI
{
class Sim_BRMA06_2H_TB : SimTemplate //* The Majordomo
{
// Hero Power: Summon a 3/3 Flamewaker Acolyte.
CardDB.Card kid = CardDB.Instance.getCardDataFromID(CardDB.cardIDEnum.BRMA06_4H);//3/3Flamewaker Acolyte
public override void OnCardPlay(Playfield p, bool ownplay, Minion target, int choice)
{
int place = (ownplay) ? p.ownMinions.Count : p.enemyMinions.Count;
p.callKid(kid, place, ownplay, false);
}
}
} | agpl-3.0 |
B3Partners/geo-ov | src/main/java/nl/b3p/kar/stripes/XmlTestActionBean.java | 3545 | package nl.b3p.kar.stripes;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Arrays;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontValidate;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.action.StrictBinding;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.validation.Validate;
import nl.b3p.kar.hibernate.RoadsideEquipment;
import nl.b3p.kar.jaxb.KarNamespacePrefixMapper;
import nl.b3p.kar.jaxb.TmiPush;
import nl.b3p.kar.jaxb.TmiResponse;
/**
*
* @author Matthijs Laan
*/
@UrlBinding("/action/xml")
@StrictBinding
public class XmlTestActionBean implements ActionBean {
private ActionBeanContext context;
@Validate(required=true)
private RoadsideEquipment rseq;
public ActionBeanContext getContext() {
return context;
}
public void setContext(ActionBeanContext context) {
this.context = context;
}
public RoadsideEquipment getRseq() {
return rseq;
}
public void setRseq(RoadsideEquipment rseq) {
this.rseq = rseq;
}
@DefaultHandler
public Resolution test() throws JAXBException {
JAXBContext ctx = JAXBContext.newInstance(TmiPush.class);
Marshaller m = ctx.createMarshaller();
m.setProperty("com.sun.xml.bind.namespacePrefixMapper", new KarNamespacePrefixMapper());
m.setProperty("jaxb.formatted.output", Boolean.TRUE);
TmiPush push = new TmiPush("B3P", Arrays.asList(new RoadsideEquipment[] { rseq }));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
m.marshal(push, bos);
return new StreamingResolution("text/xml", new ByteArrayInputStream(bos.toByteArray()));
}
@DontValidate
public Resolution testResponse() throws JAXBException {
JAXBContext ctx = JAXBContext.newInstance(TmiResponse.class);
Unmarshaller u = ctx.createUnmarshaller();
TmiResponse response = (TmiResponse)u.unmarshal(new File("kv9-RSP.xml"));
Marshaller m = ctx.createMarshaller();
m.setProperty("jaxb.formatted.output", Boolean.TRUE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
m.marshal(response, bos);
return new StreamingResolution("text/xml", new ByteArrayInputStream(bos.toByteArray()));
}
@DontValidate
public Resolution testLoad() throws JAXBException {
JAXBContext ctx = JAXBContext.newInstance(TmiPush.class);
Unmarshaller u = ctx.createUnmarshaller();
TmiPush push = (TmiPush)u.unmarshal(new File("/home/matthijsln/Downloads/geo-ov_kv9_B3P_235.xml"));
Marshaller m = ctx.createMarshaller();
m.setProperty("jaxb.formatted.output", Boolean.TRUE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
m.marshal(push, bos);
return new StreamingResolution("text/xml", new ByteArrayInputStream(bos.toByteArray()));
}
}
| agpl-3.0 |
Sparfel/iTop-s-Portal | library/Zend/Tag/Cloud/Decorator/HtmlTag.php | 8040 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Tag
* @subpackage Cloud
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Tag_Cloud_Decorator_Tag
*/
//$1 'Zend/Tag/Cloud/Decorator/Tag.php';
/**
* Simple HTML decorator for tags
*
* @category Zend
* @package Zend_Tag
* @uses Zend_Tag_Cloud_Decorator_Tag
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Tag_Cloud_Decorator_HtmlTag extends Zend_Tag_Cloud_Decorator_Tag
{
/**
* List of tags which get assigned to the inner element instead of
* font-sizes.
*
* @var array
*/
protected $_classList = null;
/**
* @var string Encoding to utilize
*/
protected $_encoding = 'UTF-8';
/**
* Unit for the fontsize
*
* @var string
*/
protected $_fontSizeUnit = 'px';
/**
* Allowed fontsize units
*
* @var array
*/
protected $_alloweFontSizeUnits = array('em', 'ex', 'px', 'in', 'cm', 'mm', 'pt', 'pc', '%');
/**
* List of HTML tags
*
* @var array
*/
protected $_htmlTags = array(
'li'
);
/**
* Maximum fontsize
*
* @var integer
*/
protected $_maxFontSize = 20;
/**
* Minimum fontsize
*
* @var integer
*/
protected $_minFontSize = 10;
/**
* Set a list of classes to use instead of fontsizes
*
* @param array $classList
* @throws Zend_Tag_Cloud_Decorator_Exception When the classlist is empty
* @throws Zend_Tag_Cloud_Decorator_Exception When the classlist contains an invalid classname
* @return Zend_Tag_Cloud_Decorator_HtmlTag
*/
public function setClassList(array $classList = null)
{
if (is_array($classList)) {
if (count($classList) === 0) {
//$1 'Zend/Tag/Cloud/Decorator/Exception.php';
throw new Zend_Tag_Cloud_Decorator_Exception('Classlist is empty');
}
foreach ($classList as $class) {
if (!is_string($class)) {
//$1 'Zend/Tag/Cloud/Decorator/Exception.php';
throw new Zend_Tag_Cloud_Decorator_Exception('Classlist contains an invalid classname');
}
}
}
$this->_classList = $classList;
return $this;
}
/**
* Get class list
*
* @return array
*/
public function getClassList()
{
return $this->_classList;
}
/**
* Get encoding
*
* @return string
*/
public function getEncoding()
{
return $this->_encoding;
}
/**
* Set encoding
*
* @param string $value
* @return Zend_Tag_Cloud_Decorator_HtmlTag
*/
public function setEncoding($value)
{
$this->_encoding = (string) $value;
return $this;
}
/**
* Set the font size unit
*
* Possible values are: em, ex, px, in, cm, mm, pt, pc and %
*
* @param string $fontSizeUnit
* @throws Zend_Tag_Cloud_Decorator_Exception When an invalid fontsize unit is specified
* @return Zend_Tag_Cloud_Decorator_HtmlTag
*/
public function setFontSizeUnit($fontSizeUnit)
{
if (!in_array($fontSizeUnit, $this->_alloweFontSizeUnits)) {
//$1 'Zend/Tag/Cloud/Decorator/Exception.php';
throw new Zend_Tag_Cloud_Decorator_Exception('Invalid fontsize unit specified');
}
$this->_fontSizeUnit = (string) $fontSizeUnit;
$this->setClassList(null);
return $this;
}
/**
* Retrieve font size unit
*
* @return string
*/
public function getFontSizeUnit()
{
return $this->_fontSizeUnit;
}
/**
* Set the HTML tags surrounding the <a> element
*
* @param array $htmlTags
* @return Zend_Tag_Cloud_Decorator_HtmlTag
*/
public function setHtmlTags(array $htmlTags)
{
$this->_htmlTags = $htmlTags;
return $this;
}
/**
* Get HTML tags map
*
* @return array
*/
public function getHtmlTags()
{
return $this->_htmlTags;
}
/**
* Set maximum font size
*
* @param integer $maxFontSize
* @throws Zend_Tag_Cloud_Decorator_Exception When fontsize is not numeric
* @return Zend_Tag_Cloud_Decorator_HtmlTag
*/
public function setMaxFontSize($maxFontSize)
{
if (!is_numeric($maxFontSize)) {
//$1 'Zend/Tag/Cloud/Decorator/Exception.php';
throw new Zend_Tag_Cloud_Decorator_Exception('Fontsize must be numeric');
}
$this->_maxFontSize = (int) $maxFontSize;
$this->setClassList(null);
return $this;
}
/**
* Retrieve maximum font size
*
* @return int
*/
public function getMaxFontSize()
{
return $this->_maxFontSize;
}
/**
* Set minimum font size
*
* @param int $minFontSize
* @throws Zend_Tag_Cloud_Decorator_Exception When fontsize is not numeric
* @return Zend_Tag_Cloud_Decorator_HtmlTag
*/
public function setMinFontSize($minFontSize)
{
if (!is_numeric($minFontSize)) {
//$1 'Zend/Tag/Cloud/Decorator/Exception.php';
throw new Zend_Tag_Cloud_Decorator_Exception('Fontsize must be numeric');
}
$this->_minFontSize = (int) $minFontSize;
$this->setClassList(null);
return $this;
}
/**
* Retrieve minimum font size
*
* @return int
*/
public function getMinFontSize()
{
return $this->_minFontSize;
}
/**
* Defined by Zend_Tag_Cloud_Decorator_Tag
*
* @param Zend_Tag_ItemList $tags
* @return array
*/
public function render(Zend_Tag_ItemList $tags)
{
if (null === ($weightValues = $this->getClassList())) {
$weightValues = range($this->getMinFontSize(), $this->getMaxFontSize());
}
$tags->spreadWeightValues($weightValues);
$result = array();
$enc = $this->getEncoding();
foreach ($tags as $tag) {
if (null === ($classList = $this->getClassList())) {
$attribute = sprintf('style="font-size: %d%s;"', $tag->getParam('weightValue'), $this->getFontSizeUnit());
} else {
$attribute = sprintf('class="%s"', htmlspecialchars($tag->getParam('weightValue'), ENT_COMPAT, $enc));
}
$tagHtml = sprintf('<a href="%s" %s>%s</a>', htmlSpecialChars($tag->getParam('url'), ENT_COMPAT, $enc), $attribute, $tag->getTitle());
foreach ($this->getHtmlTags() as $key => $data) {
if (is_array($data)) {
$htmlTag = $key;
$attributes = '';
foreach ($data as $param => $value) {
$attributes .= ' ' . $param . '="' . htmlspecialchars($value, ENT_COMPAT, $enc) . '"';
}
} else {
$htmlTag = $data;
$attributes = '';
}
$tagHtml = sprintf('<%1$s%3$s>%2$s</%1$s>', $htmlTag, $tagHtml, $attributes);
}
$result[] = $tagHtml;
}
return $result;
}
}
| agpl-3.0 |
rotdrop/tasks | l10n/hu_HU.js | 2821 | OC.L10N.register(
"tasks",
{
"Tasks" : "Feladatok",
"Important" : "Fontos",
"Today" : "Ma",
"Week" : "Hét",
"All" : "Mind",
"Current" : "Jelenlegi",
"Completed" : "Befejezve",
"Due yesterday" : "Tegnapi teendök",
"Due today" : "Mai teendök",
"Due tomorrow" : "Holnapi teendök",
"Due on" : "Esedékes",
"Started yesterday" : "Megkezdve tegnap",
"Starts today" : "Kezdés ma",
"Starts tomorrow" : "Kezdés holnap",
"Started on" : "Megkezdve",
"Starts on" : "Kezdödik",
"[Remind me yesterday at ]HH:mm" : "[Emlékeztess holnap ]HH:mm",
"[Remind me today at ]HH:mm" : "[Emlékeztess ma ]HH:mm",
"[Remind me tomorrow at ]HH:mm" : "[Emlékeztess holnap ]HH:mm",
"[Remind me on ]MMM DD, YYYY,[ at ]HH:mm" : "[Emlékeztess ]MMM DD, YYYY,HH:mm[ kor ]",
"Yesterday" : "Tegnap",
"Tomorrow" : "Holnap",
"in %s" : "itt: %s",
"%s ago" : "%s ezelött",
"seconds" : "másodpercek",
"a minute" : "perc",
"%d minutes" : "%d perc",
"an hour" : "óra",
"%d hours" : "%d órák",
"a day" : "Nap",
"%d days" : "%d napok",
"a month" : "Hónap",
"%d months" : "%d hónapok",
"a year" : "Év",
"%d years" : "%d évek",
"Hours" : "Órák",
"Minutes" : "Percek",
"week" : "hét",
"weeks" : "hetek",
"day" : "nap",
"days" : "nap",
"hour" : "óra",
"hours" : "órák",
"minute" : "perc",
"minutes" : "percek",
"second" : "másodperc",
"before beginning" : "kezdés elött",
"after beginning" : "kezdés után",
"before end" : "Befejezés elött",
"after end" : "Befejezés után",
"Comment" : "Komment",
"Add a comment" : "Komment hozzáadása",
"This will delete the Calendar \"%s\" and all of its entries." : "Ez törölni fogja a Naptárat \"%s\" és az összes bejegyzést.",
"The name \"%s\" is already used." : "Ez a név \"%s\" már foglalt.",
"An empty name is not allowed." : "Az üres név nem engedélyezett.",
"Hidden" : "Rejtett",
"Visible" : "Látható",
"Automatic" : "Autómatikus",
"Sunday" : "vasárnap",
"Monday" : "hétfő",
"Tuesday" : "kedd",
"Wednesday" : "szerda",
"Thursday" : "csütörtök",
"Friday" : "péntek",
"Saturday" : "szombat",
"_%n Completed Task_::_%n Completed Tasks_" : ["%n befejezett feladat","%n befejezett feladat"],
"Set due date" : "Lejárati dátum beállítása",
"%s %% completed" : "%s %% befejezve",
"Remind me" : "Emlékeztess",
"at the end" : "a végénél",
"at the beginning" : "az elején",
"Set start date" : "Kezdő dátum beállítása",
"Add List..." : "Lista hozzáadása",
"New List" : "Új lista",
"Start of week" : "A hét első napja"
},
"nplurals=2; plural=(n != 1);");
| agpl-3.0 |
misgeatgit/atomspace | opencog/attentionbank/ImportanceIndex.cc | 7370 | /*
* opencog/attentionbank/ImportanceIndex.cc
*
* Copyright (C) 2008-2011 OpenCog Foundation
* Copyright (C) 2017 Linas Vepstas <linasvepstas@gmail.com>
* 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 v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifdef __APPLE__
#include <cmath>
#endif
#include <algorithm>
#include <boost/range/adaptor/reversed.hpp>
#include <opencog/util/functional.h>
#include <opencog/util/Config.h>
#include <opencog/attentionbank/AVUtils.h>
#include <opencog/attentionbank/ImportanceIndex.h>
using namespace opencog;
/**
* This formula is used to calculate the GROUP_NUM given the GROUP_SIZE
* 32768 = (sum 2^b , b = 0 to (GROUP_NUM-1)) * GROUP_SIZE + GROUP_SIZE
* for a GROUP_SIZE of 8 we get:
* 32768 = (sum 2^b , b = 0 to 11) * 8 + 8
* This means we have 12 groups with 8 bins each
* The range of each groups bins is double the previous (2^b) and starts at 1
* We have to add 8 since [2^c - 1 = sum 2^b , b = 0 to (c-1)] and we have 8
* such groups
*/
#define GROUP_SIZE 8
#define GROUP_NUM 12
#define IMPORTANCE_INDEX_SIZE (GROUP_NUM*GROUP_SIZE)+GROUP_NUM //104
// ==============================================================
ImportanceIndex::ImportanceIndex()
: _index(IMPORTANCE_INDEX_SIZE+1)
{
}
size_t ImportanceIndex::importanceBin(AttentionValue::sti_t impo)
{
short importance = (short) impo;
if (importance < 0)
return 0;
if (importance < 2*GROUP_SIZE)
return importance;
short imp = std::ceil((importance - GROUP_SIZE) / GROUP_SIZE);
int sum = 0;
int i;
for (i = 0; i <= GROUP_NUM; i++)
{
if (sum >= imp)
break;
sum = sum + std::pow(2,i);
}
int ad = GROUP_SIZE - std::ceil(importance / std::pow(2, (i-1)));
size_t bin = ((i * GROUP_SIZE) - ad);
#if 0
if (bin > 104)
std::cout << "ibin: "<< bin << "\n";
#endif
assert(bin <= IMPORTANCE_INDEX_SIZE);
return bin;
}
void ImportanceIndex::updateImportance(const Handle& h,
const AttentionValuePtr& oldav,
const AttentionValuePtr& newav)
{
int oldbin = importanceBin(oldav->getSTI());
int newbin = importanceBin(newav->getSTI());
if (oldbin == newbin) return;
_index.remove(oldbin, h);
_index.insert(newbin, h);
}
// ==============================================================
void ImportanceIndex::removeAtom(const Handle& h)
{
AttentionValuePtr oldav = get_av(h);
set_av(h, nullptr);
int bin = ImportanceIndex::importanceBin(oldav->getSTI());
std::lock_guard<std::mutex> lock(_mtx);
_index.remove(bin, h);
}
// ==============================================================
void ImportanceIndex::update(void)
{
// Update MinMax STI values
AttentionValue::sti_t minSTISeen = 0;
UnorderedHandleSet minbin = getMinBinContents();
auto minit = std::min_element(minbin.begin(), minbin.end(),
[&](const Handle& h1, const Handle& h2) {
return get_sti(h1) < get_sti(h2);
});
if (minit != minbin.end()) minSTISeen = get_sti(*minit);
AttentionValue::sti_t maxSTISeen = 0;
UnorderedHandleSet maxbin = getMaxBinContents();
auto maxit = std::max_element(maxbin.begin(), maxbin.end(),
[&](const Handle& h1, const Handle& h2) {
return get_sti(h1) < get_sti(h2);
});
if (maxit != maxbin.end()) maxSTISeen = get_sti(*maxit);
if (minSTISeen > maxSTISeen)
minSTISeen = maxSTISeen;
std::lock_guard<std::mutex> lock(_mtx);
_minSTI = minSTISeen;
_maxSTI = maxSTISeen;
}
// ==============================================================
AttentionValue::sti_t ImportanceIndex::getMaxSTI(bool average) const
{
std::lock_guard<std::mutex> lock(_mtx);
if (average) {
return (AttentionValue::sti_t) _maxSTI.recent;
} else {
return _maxSTI.val;
}
}
AttentionValue::sti_t ImportanceIndex::getMinSTI(bool average) const
{
std::lock_guard<std::mutex> lock(_mtx);
if (average) {
return (AttentionValue::sti_t) _minSTI.recent;
} else {
return _minSTI.val;
}
}
// ==============================================================
UnorderedHandleSet ImportanceIndex::getHandleSet(
AttentionValue::sti_t lowerBound,
AttentionValue::sti_t upperBound) const
{
UnorderedHandleSet ret;
if (lowerBound < 0 || upperBound < 0)
return ret;
// The indexes for the lower bound and upper bound lists is returned.
unsigned int lowerBin = importanceBin(lowerBound);
unsigned int upperBin = importanceBin(upperBound);
// Build a list of atoms whose importance is equal to the lower bound.
// For the lower bound and upper bound index, the list is filtered,
// because there may be atoms that have the same importanceIndex
// and whose importance is lower than lowerBound or bigger than
// upperBound.
std::function<bool(const Handle&)> pred =
[&](const Handle& atom)->bool {
AttentionValue::sti_t sti = get_sti(atom);
return (lowerBound <= sti and sti <= upperBound);
};
std::lock_guard<std::mutex> lock(_mtx);
_index.getContentIf(lowerBin, inserter(ret), pred);
// If both lower and upper bounds are in the same bin,
// Then we are done.
if (lowerBin == upperBin) return ret;
// For every index within lowerBound and upperBound,
// add to the list.
while (++lowerBin < upperBin)
_index.getContent(lowerBin, inserter(ret));
// The two lists are concatenated.
_index.getContentIf(upperBin, inserter(ret), pred);
return ret;
}
Handle ImportanceIndex::getRandomAtom(void) const
{
return _index.getRandomAtom();
}
UnorderedHandleSet ImportanceIndex::getMaxBinContents()
{
UnorderedHandleSet ret;
std::lock_guard<std::mutex> lock(_mtx);
for (int i = IMPORTANCE_INDEX_SIZE ; i >= 0 ; i--)
{
if (0 < _index.size(i))
{
_index.getContent(i, inserter(ret));
return ret;
}
}
return ret;
}
UnorderedHandleSet ImportanceIndex::getMinBinContents()
{
UnorderedHandleSet ret;
std::lock_guard<std::mutex> lock(_mtx);
for (int i = 0; i < IMPORTANCE_INDEX_SIZE; i++)
{
if (0 < _index.size(i))
{
_index.getContent(i, inserter(ret));
return ret;
}
}
return ret;
}
size_t ImportanceIndex::bin_size() const
{
std::lock_guard<std::mutex> lock(_mtx);
return _index.size();
}
size_t ImportanceIndex::size(int i) const
{
std::lock_guard<std::mutex> lock(_mtx);
return _index.size(i);
}
| agpl-3.0 |
harrowio/harrow | frontend/test/spec/resources/project_resource_test.js | 5437 | /*eslint-disable new-cap*/
describe('Resources: projectResource', function () {
var api, model, data, $httpBackend
beforeEach(angular.mock.inject(function (projectResource, _$httpBackend_) {
$httpBackend = _$httpBackend_
data = jasmine.getJSONFixture('GET_api_project.json')
api = projectResource
model = new api.model(data)
}))
describe('.model() - linked resources', function () {
it('defines "notifiers()"', function () {
$httpBackend.expect('GET', /\/api\/projects\/[0-9a-f-]+\/slack-notifiers/).respond(200, jasmine.getJSONFixture('empty_collection.json'))
$httpBackend.expect('GET', /\/api\/projects\/[0-9a-f-]+\/job-notifiers/).respond(200, jasmine.getJSONFixture('empty_collection.json'))
expect(model.notifiers).toBeDefined('has notifiers')
model.notifiers().then(function (response) {
expect(response.slackNotifiers).toBeDefined()
expect(response.taskNotifiers).toBeDefined()
})
$httpBackend.flush()
})
it('defines "triggers()"', function () {
$httpBackend.expect('GET', /\/api\/projects\/[0-9a-f-]+\/git-triggers/).respond(200, jasmine.getJSONFixture('empty_collection.json'))
$httpBackend.expect('GET', /\/api\/projects\/[0-9a-f-]+\/schedules/).respond(200, jasmine.getJSONFixture('empty_collection.json'))
$httpBackend.expect('GET', /\/api\/projects\/[0-9a-f-]+\/webhooks/).respond(200, jasmine.getJSONFixture('empty_collection.json'))
$httpBackend.expect('GET', /\/api\/projects\/[0-9a-f-]+\/job-notifiers/).respond(200, jasmine.getJSONFixture('empty_collection.json'))
expect(model.triggers).toBeDefined('has triggers')
model.triggers().then(function (response) {
expect(response.gitTriggers).toBeDefined()
expect(response.webhooks).toBeDefined()
expect(response.schedules).toBeDefined()
expect()
})
$httpBackend.flush()
})
it('defines "slackNotifiers()"', function () {
$httpBackend.expect('GET', /\/api\/projects\/[0-9a-f-]+\/slack-notifiers/).respond(200, jasmine.getJSONFixture('empty_collection.json'))
expect(model.slackNotifiers).toBeDefined('has slackNotifiers')
model.slackNotifiers()
$httpBackend.flush()
})
it('defines "environments()"', function () {
$httpBackend.expect('GET', /\/api\/projects\/[0-9a-f-]+\/environments/).respond(200, jasmine.getJSONFixture('empty_collection.json'))
expect(model.environments).toBeDefined('has environments')
model.environments()
$httpBackend.flush()
})
it('defines "tasks()"', function () {
$httpBackend.expect('GET', /\/api\/projects\/[0-9a-f-]+\/jobs/).respond(200, jasmine.getJSONFixture('empty_collection.json'))
expect(model.environments).toBeDefined('has tasks')
model.tasks()
$httpBackend.flush()
})
it('defines "tasks()"', function () {
$httpBackend.expect('GET', /\/api\/projects\/[0-9a-f-]+\/jobs/).respond(200, jasmine.getJSONFixture('empty_collection.json'))
expect(model.tasks).toBeDefined('has tasks')
model.tasks()
$httpBackend.flush()
})
it('defines "repositories()"', function () {
$httpBackend.expect('GET', /\/api\/projects\/[0-9a-f-]+\/repositories/).respond(200, jasmine.getJSONFixture('empty_collection.json'))
expect(model.repositories).toBeDefined('has repositories')
model.repositories()
$httpBackend.flush()
})
it('defines "organization()"', function () {
$httpBackend.expect('GET', /\/api\/organizations\/[0-9a-f-]+/).respond(200, {})
expect(model.environments).toBeDefined('has organization')
model.organization()
$httpBackend.flush()
})
it('defines "scripts()"', function () {
$httpBackend.expect('GET', /\/api\/projects\/[0-9a-f-]+\/tasks/).respond(200, {
subject: {
body: ''
}
})
expect(model.scripts).toBeDefined('has scripts')
model.scripts()
$httpBackend.flush()
})
it('defines "gitTriggers()"', function () {
$httpBackend.expect('GET', /\/api\/projects\/[0-9a-f-]+\/git-triggers/).respond(200, {})
expect(model.gitTriggers).toBeDefined('has gitTriggers')
model.gitTriggers()
$httpBackend.flush()
})
it('defines "webhooks()"', function () {
$httpBackend.expect('GET', /\/api\/projects\/[0-9a-f-]+\/webhooks/).respond(200, jasmine.getJSONFixture('empty_collection.json'))
expect(model.webhooks).toBeDefined('has webhooks')
model.webhooks()
$httpBackend.flush()
})
it('defines "members()"', function () {
$httpBackend.expect('GET', /\/api\/projects\/[0-9a-f-]+\/members/).respond(200, jasmine.getJSONFixture('empty_collection.json'))
expect(model.members).toBeDefined('has members')
model.members()
$httpBackend.flush()
})
it('defines "operations()"', function () {
$httpBackend.expect('GET', /\/api\/projects\/[0-9a-f-]+\/operations/).respond(200, {
subject: {}
})
expect(model.operations).toBeDefined('has operations')
model.operations()
$httpBackend.flush()
})
it('defines "leave()"', function () {
$httpBackend.expect('DELETE', /\/api\/projects\/[0-9a-f-]+\/members/).respond(200, jasmine.getJSONFixture('empty_collection.json'))
expect(model.leave).toBeDefined('has leave')
model.leave()
$httpBackend.flush()
})
})
})
| agpl-3.0 |
trendzetter/VegetableGardenPlanner | modules/tasks/client/controllers/admin/task.client.controller.js | 1282 | (function () {
'use strict';
angular
.module('tasks.admin')
.controller('TasksAdminController', TasksAdminController);
TasksAdminController.$inject = ['$scope', '$state', '$window', 'taskResolve', 'Authentication'];
function TasksAdminController($scope, $state, $window, task, Authentication) {
var vm = this;
vm.task = task;
vm.authentication = Authentication;
vm.error = null;
vm.form = {};
vm.remove = remove;
vm.save = save;
// Remove existing Task
function remove() {
if ($window.confirm('Are you sure you want to delete?')) {
vm.task.$remove(function() {
$state.go('admin.tasks.list');
});
}
}
// Save Task
function save(isValid) {
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'vm.form.taskForm');
return false;
}
// Create a new task, or update the current instance
vm.task.createOrUpdate()
.then(successCallback)
.catch(errorCallback);
function successCallback(res) {
$state.go('admin.tasks.list'); // should we send the User to the list or the updated Task's view?
}
function errorCallback(res) {
vm.error = res.data.message;
}
}
}
}());
| agpl-3.0 |
automenta/java_dann | src/syncleus/dann/learn/pattern/algorithms/sequentialpatterns/goKrimp/Event.java | 1777 |
package syncleus.dann.learn.pattern.algorithms.sequentialpatterns.goKrimp;
/**
* This is an implementation of an "event" for the GoKrimp and SedKrimp algorithms
* <br/><br/>
* For more information please refer to the paper Mining Compressing Sequential Patterns in the Journal Statistical Analysis and Data Mining
* <br/><br/>
*
* Copyright (c) 2014 Hoang Thanh Lam (TU Eindhoven and IBM Research)
* Toon Calders (Université Libre de Bruxelles), Fabian Moerchen (Amazon.com inc)
* and Dmitriy Fradkin (Siemens Corporate Research)
* <br/><br/>
*
* This file is part of the SPMF DATA MINING SOFTWARE
* (http://www.philippe-fournier-viger.com/spmf).
* <br/><br/>
*
* SPMF 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.
* <br/><br/>
*
* SPMF 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.
* <br/><br/>
*
* You should have received a copy of the GNU General Public License along with
* SPMF. If not, see <http://www.gnu.org/licenses/>.
*
* @see AlgoGoKrimp
* @see DataReader
* @see Event
* @see MyPattern
* @see SignTest
* @author Hoang Thanh Lam (TU Eindhoven and IBM Research)
*/
class Event implements Comparable<Event> {
int id; // id of the event
int ts; // timestamp
int gap; //gap to previous timestamp
@Override
/**
* compare two events by timestamp
*/
public int compareTo(Event o) {
return this.ts - o.ts ;
}
}
| agpl-3.0 |
ChangezKhan/SuiteCRM | tests/unit/phpunit/modules/AOR_Fields/AOR_FieldTest.php | 1966 | <?php
use SuiteCRM\Test\SuitePHPUnitFrameworkTestCase;
class AOR_FieldTest extends SuitePHPUnitFrameworkTestCase
{
public function testAOR_Field()
{
// Execute the constructor and check for the Object type and attributes
$aor_Field = new AOR_Field();
$this->assertInstanceOf('AOR_Field', $aor_Field);
$this->assertInstanceOf('Basic', $aor_Field);
$this->assertInstanceOf('SugarBean', $aor_Field);
$this->assertAttributeEquals('AOR_Fields', 'module_dir', $aor_Field);
$this->assertAttributeEquals('AOR_Field', 'object_name', $aor_Field);
$this->assertAttributeEquals('aor_fields', 'table_name', $aor_Field);
$this->assertAttributeEquals(true, 'new_schema', $aor_Field);
$this->assertAttributeEquals(true, 'disable_row_level_security', $aor_Field);
$this->assertAttributeEquals(true, 'importable', $aor_Field);
$this->assertAttributeEquals(false, 'tracker_visibility', $aor_Field);
}
public function testsave_lines()
{
$aor_Field = new AOR_Field();
//preset the required data
$post_data = array();
$post_data['field'][] = 'test field';
$post_data['name'][] = 'test';
$post_data['module_path'][] = 'test path';
$post_data['display'][] = '1';
$post_data['link'][] = '1';
$post_data['label'][] = 'test label';
$post_data['field_function'][] = 'test function';
$post_data['total'][] = 'total';
$post_data['group_by'][] = '1';
$post_data['group_order'][] = 'desc';
$post_data['group_display'][] = '1';
// Execute the method and test that it works and doesn't throw an exception.
try {
$aor_Field->save_lines($post_data, new AOR_Report());
$this->assertTrue(true);
} catch (Exception $e) {
$this->fail($e->getMessage() . "\nTrace:\n" . $e->getTraceAsString());
}
}
}
| agpl-3.0 |
coast-team/netflux | docs/jsFromTs/src/service/channelBuilder/ConnectionError.js | 696 | export var ConnectionError;
(function (ConnectionError) {
ConnectionError["RESPONSE_TIMEOUT"] = "Response timeout: remote peer is not responding";
ConnectionError["CONNECTION_TIMEOUT"] = "Connection timeout: unable to establish a channel within a specified time";
ConnectionError["DENIED"] = "Connection denied: remote peer refused the connection request";
ConnectionError["CLEAN"] = "Clean: all connections in progress must be stopped";
ConnectionError["IN_PROGRESS"] = "Connection setup is already in progress";
ConnectionError["NEGOTIATION_ERROR"] = "All connection possibilities have been tried and none of them worked";
})(ConnectionError || (ConnectionError = {}));
| agpl-3.0 |
empirical-org/Empirical-Core | services/QuillLMS/spec/workers/refresh_question_cache_worker_spec.rb | 699 | # frozen_string_literal: true
require 'rails_helper'
describe RefreshQuestionCacheWorker, type: :worker do
let(:worker) { described_class.new }
describe "#perform" do
it "should call force refresh methods" do
expect(Question).to receive(:all_questions_json_cached).with('type', refresh: true)
expect(Question).to receive(:question_json_cached).with('123', refresh: true)
worker.perform('type', '123')
end
it "should call force refresh methods for type only" do
expect(Question).to receive(:all_questions_json_cached).with('type', refresh: true)
expect(Question).to_not receive(:question_json_cached)
worker.perform('type')
end
end
end
| agpl-3.0 |
jchoyt/invasion | src/invasion/servlets/Recharge.java | 6178 | /*
* Copyright 2010 Jeffrey Hoyt. All rights reserved.
*/
package invasion.servlets;
import invasion.ui.Poll;
import invasion.util.*;
import invasion.dataobjects.*;
import java.io.*;
import java.util.*;
import java.util.logging.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.sql.*;
import org.json.*;
/**
* Servlet to recharge Energy Packs and weapons/shields
*
* @author jchoyt
*/
@WebServlet(urlPatterns = { "/map/recharge" } )
public class Recharge extends HttpServlet
{
public final static String KEY = Recharge.class.getName();
public final static Logger log = Logger.getLogger( KEY );
/**
* Constructor for the PqmServlet object
*
* @since
*/
public Recharge()
{
super();
}
/**
* Racharges an Energy Pack
*
*/
@Override
public void doGet( HttpServletRequest request, HttpServletResponse response )
throws IOException, ServletException
{
PrintWriter out = response.getWriter();
String itemid = WebUtils.getRequiredParameter(request, "itemid");
Whatzit wazzit =(Whatzit) request.getSession().getAttribute(Whatzit.KEY);
Alt alt = wazzit.getAlt();
InvasionConnection conn = null;
JSONArray alerts = null;
try
{
conn = new InvasionConnection();
Item i = Item.load( conn, Integer.parseInt(itemid) );
ItemType it = i.getItemtype();
log.finer( "Trying to recharge type " + it.getTypeid() + " which is a " + it.getName() );
if( it.getTypeid() == 49 )
{
//recharge empty energy pack
if( Location.canRecharge( alt ) == 'f' )
{
alerts = new JSONArray();
alerts.put( Poll.createErrorAlert("You cannnot recharge an empty energy pack in this location.") );
return;
}
else if( i.getLocid() != alt.getId() )
{
alerts = new JSONArray();
alerts.put( Poll.createErrorAlert("You do not own that.") );
return;
}
String query = "update item set typeid=? where itemid=?"; //change it to a full energy pack
int count = conn.psExecuteUpdate( query, "Error changing the empty energy pack in the database", 28, i.getItemid() );
new Message( conn, alt.getId(), Message.NORMAL, "You recharge your energy pack using one of dedicated the ports here." );
alt.decrementAp(conn, 1);
}
else
{
String error = rechargeItem( conn, alt, i );
if( error != null )
{
alerts = new JSONArray();
alerts.put( Poll.createErrorAlert(error) );
return;
}
alt.decrementAp(conn, 1);
}
}
catch(SQLException e)
{
log.throwing( KEY, "a useful message", e);
throw new RuntimeException(e);
}
finally
{
Poll.fullPoll( conn, out, wazzit, alerts );
conn.close();
}
}
/**
* Performs the recharge of a weapon
* @return null if successful, otherwise return an error message suitable for the user to see
*
*/
public synchronized static String rechargeItem( InvasionConnection conn, Alt alt, Item i )
throws SQLException
{
ItemType it = i.getItemtype();
String query = "select count(*) as count, min(itemid) as useme from item where locid=? and typeid=28";
ResultSet rs = null;
try
{
rs = conn.psExecuteQuery(query, "How the hell did I screw up getting a simple count?", alt.getId());
rs.next();
int count = rs.getInt("count");
if( count == 0 )
{
return "You have no full Energy Packs. Find some, or recharge some empties and try again.";
}
//we're OK to go
int packToUse = rs.getInt( "useme" );
DatabaseUtility.close(rs);
if( it.getType().equals("weapon") )
{
int capacity = it.getCapacity();
if( (alt.getHumanSkills() & Skills.getValue(Skill.FIREARMS3)) > 0 )
{
capacity *= 2;
}
//set ammo to capacity
i.setAmmoleft( capacity );
}
else if( it.getType().equals("armor") && it.getDamageType() == 'e' )
{
//it's a shield....+10 ammo
i.setAmmoleft( i.getAmmoleft() + 10 );
if( i.getAmmoleft() > (it.getCapacity() ) )
{
i.setAmmoleft( it.getCapacity() );
}
alt.setEquippedShield( i );
}
else
return "You can't figure out how to attach the energy pack to that.";
i.update( conn );
if( i.getItemid() == alt.getEquippedWeapon().getItemid() )
{
alt.setEquippedWeapon( i );
}
new Message( conn, alt.getId(), Message.NORMAL, "You recharge your " + i.getItemtype().getName().toLowerCase() + " using one of your energy packs. The energy pack is now empty and will have to be recharged." );
//empty the pack
query = "update item set typeid=? where itemid=?"; //change it to a full energy pack
count = conn.psExecuteUpdate(query, "Error changing the empty energy pack in the database", 49, packToUse );
}
catch(SQLException e)
{
throw e;
}
finally
{
DatabaseUtility.close(rs);
}
return null;
}
@Override
public void doPost( HttpServletRequest request, HttpServletResponse response )
throws IOException, ServletException
{
doGet( request, response );
}
}
| agpl-3.0 |
FiviumAustralia/OpenEyes | protected/widgets/js/RRuleField.js | 9062 | (function (exports) {
'use strict';
function RRuleField(element, options) {
this.element = element;
this.options = $.extend(true, {}, RRuleField._defaultOptions, options);
this.init();
}
RRuleField._defaultOptions = {
'daysOfWeek': ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
'changeClass': 'rrulefield-input'
};
var dayCodes = ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'];
var dayMap = [RRule.MO, RRule.TU, RRule.WE, RRule.TH, RRule.FR, RRule.SA, RRule.SU];
RRuleField.prototype.init = function()
{
try {
this._rrule = RRule.fromString(this.element.val());
}
catch (e) {
// simple error handling here. In theory should never arise, but this will at
// least prevent the widget from masking any issues by still rendering the form
console.log(this.element.val() + ' is not a valid for rrule');
return;
}
this.render();
};
/**
* Render the form fields for this widget
*/
RRuleField.prototype.render = function()
{
var self = this;
// mask the original input field
$(self.element).hide();
// create a container in which we can store all our input fields for defining the RRule
self.container = $("<div />").insertAfter(self.element);
self.renderDescription(self.container);
// render the days of the week selection
self.renderDaysOfWeek(self.container);
self.renderWeekSelection(self.container);
self.updateField();
// update the field every time the rrule field form is changed
$(self.container).on('change', '.'+self.options.changeClass, function(e) {self.updateField()});
};
/**
* Check current rule configuration for whether the given day should be selected in the form
*
* @param day
* @returns {boolean}
*/
RRuleField.prototype.isDaySelected = function(day)
{
if (this._rrule.options.byweekday)
return ($.inArray(parseInt(day), this._rrule.options.byweekday) > -1);
if (this._rrule.options.bynweekday) {
for (var i in this._rrule.options.bynweekday) {
if (day == this._rrule.options.bynweekday[i][0]) {
return true;
}
}
}
return false;
};
/**
* Only returns true if not all weeks are selected, and the specific week should be.
*
* @param week
* @returns {boolean}
*/
RRuleField.prototype.isWeekSelected = function(week)
{
if (this._rrule.options.byweekday) {
// if the rrule library has set a byweekday option
// this implies all weeks selected
return false;
}
else if (this._rrule.options.bynweekday) {
for (var i in this._rrule.options.bynweekday) {
if (week == this._rrule.options.bynweekday[i][1])
return true;
}
}
return false;
};
/**
* Display the rrule description as the form is updated.
*
* @param container
*/
RRuleField.prototype.renderDescription = function(container)
{
$(container).append('<div class="rrule-description" style="font-style: italic; font-size:0.7em;"></div><hr style="margin: 5px;"/>');
};
/**
* Create the form component for selecting the days of the week the rule applies to
*
* @TODO: templating?
*/
RRuleField.prototype.renderDaysOfWeek = function(container)
{
var self = this;
var fields = "<h4>Day(s) of the Week:</h4>";
for (var i in dayCodes) {
fields += '<label class="inline"><input type="checkbox" name="dayOfWeek[]" value="' + i + '" class="'+ this.options.changeClass +'"';
if (self.isDaySelected(i)) {
fields += ' checked';
}
fields += '/>' + self.options.daysOfWeek[i] + '</label>';
}
$(container).append(fields);
};
/**
* Create form component for selecting which weeks of the month the rule applies to
*
* @param container
*/
RRuleField.prototype.renderWeekSelection = function(container)
{
var self = this;
var weekSelection = $('<div style="padding-top: 20px;" />');
container.append(weekSelection);
// flag to determine set the everyweek box checked
var everyWeek = true;
// the individual weeks checkboxes span
var weekFields = '<span class="week-number-wrapper">or<br />';
for (var i = 1; i <=5; i++) {
weekFields += '<label class="inline"><input type="checkbox" name="week-number[]" value="' + i + '" class="week-number ' + this.options.changeClass + '" ';
if (self.isWeekSelected(i)) {
everyWeek = false;
weekFields += ' checked';
}
weekFields += '/>Week ' + i + '</label>';
}
weekFields += '</span>';
// defining this afterward so we can apply the checked property correctly.
var everyWeekField = '<h4>Weeks of the Month:</h4><label class="inline"><input type="checkbox" name="every-week" class="every-week '+ this.options.changeClass +'";';
if (everyWeek)
everyWeekField += ' checked';
everyWeekField += '/>Every Week</label>';
// the hint field is there to explain why you can't uncheck the every week box alone.
everyWeekField += '<span style="display:none; font-size: 0.6em;" class="info hint">select a week number to uncheck this</span><br />';
weekSelection.append(everyWeekField + weekFields);
weekSelection.on('change', 'input', function(e) {
var showHint = false;
if ($(e.target).hasClass('every-week')) {
if ($(e.target).prop('checked')) {
weekSelection.find('.week-number:checked').prop('checked', false);
}
else {
if (weekSelection.find('.week-number:checked').length == 0) {
$(e.target).prop('checked', true);
showHint = true;
}
}
}
else {
if (weekSelection.find('.week-number:checked').length == 0) {
weekSelection.find('.every-week').prop('checked', true);
}
else {
weekSelection.find('.every-week').prop('checked', false);
}
}
if (showHint) {
weekSelection.find('.hint').fadeIn();
}
else {
weekSelection.find('.hint').fadeOut();
}
});
};
/**
* This iterates through the form to pull out the selected values, create a new RRule object and use that
* to populate the original form element.
*/
RRuleField.prototype.updateField = function()
{
var self = this;
var weekdays = [];
$(self.container).find('input[name="dayOfWeek\[\]"]').each(function() {
if ($(this).prop('checked'))
weekdays.push(dayMap[parseInt($(this).val())]);
});
var rruleOptions = {};
if (!weekdays.length) {
weekdays = dayMap;
}
if ($(self.container).find('input[name="every-week"]').prop('checked')) {
if (weekdays.length == dayMap.length) {
rruleOptions.freq = RRule.DAILY;
}
else {
rruleOptions.freq = RRule.WEEKLY;
rruleOptions.byweekday = weekdays;
}
}
else {
rruleOptions.freq = RRule.MONTHLY;
rruleOptions.byweekday = [];
for (var i in weekdays) {
$(self.container).find('.week-number:checked').each(function() {
rruleOptions.byweekday.push(weekdays[i].nth(parseInt($(this).val())));
});
}
}
self._rrule = new RRule(rruleOptions);
var description = self._rrule.toText();
description = description[0].toUpperCase() + description.slice(1);
$(self.container).find('.rrule-description').text(description);
$(self.element).val(self._rrule.toString());
};
/**
* Simple attachment function
*
* @param element
* @param options
* @returns {*}
*/
function attach(element, options)
{
if (options === undefined)
options = {};
// TODO: (if this were ever to become useful) a remove and replace method to refresh it
if (!element.data('OpenEyes.UI.Widgets.RRuleField')) {
element.data('OpenEyes.UI.Widgets.RRuleField', new RRuleField(element, options));
}
return element;
}
exports.RRuleField = attach;
}(this.OpenEyes.UI.Widgets)); | agpl-3.0 |
OCA/server-tools | upgrade_analysis/odoo_patch/addons/__init__.py | 66 | from . import mrp
from . import point_of_sale
from . import stock
| agpl-3.0 |
axelor/axelor-business-suite | axelor-production/src/main/java/com/axelor/apps/production/service/configurator/ConfiguratorBomServiceImpl.java | 6785 | /*
* Axelor Business Solutions
*
* Copyright (C) 2020 Axelor (<http://axelor.com>).
*
* 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.
*
* 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.axelor.apps.production.service.configurator;
import com.axelor.apps.base.db.Product;
import com.axelor.apps.base.db.Unit;
import com.axelor.apps.base.db.repo.ProductRepository;
import com.axelor.apps.base.db.repo.UnitRepository;
import com.axelor.apps.production.db.BillOfMaterial;
import com.axelor.apps.production.db.ConfiguratorBOM;
import com.axelor.apps.production.db.ProdProcess;
import com.axelor.apps.production.db.repo.BillOfMaterialRepository;
import com.axelor.apps.production.db.repo.ConfiguratorBOMRepository;
import com.axelor.apps.production.db.repo.ProdProcessRepository;
import com.axelor.apps.production.exceptions.IExceptionMessage;
import com.axelor.apps.sale.service.configurator.ConfiguratorService;
import com.axelor.exception.AxelorException;
import com.axelor.exception.db.repo.TraceBackRepository;
import com.axelor.i18n.I18n;
import com.axelor.inject.Beans;
import com.axelor.rpc.JsonContext;
import com.google.inject.Inject;
import com.google.inject.persist.Transactional;
import java.math.BigDecimal;
public class ConfiguratorBomServiceImpl implements ConfiguratorBomService {
private static final int MAX_LEVEL = 10;
protected ConfiguratorBOMRepository configuratorBOMRepo;
protected ConfiguratorService configuratorService;
protected BillOfMaterialRepository billOfMaterialRepository;
protected ConfiguratorProdProcessService confProdProcessService;
@Inject
ConfiguratorBomServiceImpl(
ConfiguratorBOMRepository configuratorBOMRepo,
ConfiguratorService configuratorService,
BillOfMaterialRepository billOfMaterialRepository,
ConfiguratorProdProcessService confProdProcessService) {
this.configuratorBOMRepo = configuratorBOMRepo;
this.configuratorService = configuratorService;
this.billOfMaterialRepository = billOfMaterialRepository;
this.confProdProcessService = confProdProcessService;
}
@Override
@Transactional(rollbackOn = {Exception.class})
public BillOfMaterial generateBillOfMaterial(
ConfiguratorBOM configuratorBOM, JsonContext attributes, int level, Product generatedProduct)
throws AxelorException {
level++;
if (level > MAX_LEVEL) {
throw new AxelorException(
TraceBackRepository.CATEGORY_CONFIGURATION_ERROR,
I18n.get(IExceptionMessage.CONFIGURATOR_BOM_TOO_MANY_CALLS));
}
String name;
Product product;
BigDecimal qty;
Unit unit;
ProdProcess prodProcess;
if (configuratorBOM.getDefNameAsFormula()) {
name =
(String) configuratorService.computeFormula(configuratorBOM.getNameFormula(), attributes);
} else {
name = configuratorBOM.getName();
}
if (configuratorBOM.getDefProductFromConfigurator()) {
if (generatedProduct == null) {
throw new AxelorException(
TraceBackRepository.CATEGORY_CONFIGURATION_ERROR,
I18n.get(IExceptionMessage.CONFIGURATOR_BOM_IMPORT_GENERATED_PRODUCT_NULL));
}
product = generatedProduct;
} else if (configuratorBOM.getDefProductAsFormula()) {
product =
(Product)
configuratorService.computeFormula(configuratorBOM.getProductFormula(), attributes);
if (product == null) {
throw new AxelorException(
TraceBackRepository.CATEGORY_CONFIGURATION_ERROR,
I18n.get(IExceptionMessage.CONFIGURATOR_BOM_IMPORT_FORMULA_PRODUCT_NULL));
}
product = Beans.get(ProductRepository.class).find(product.getId());
} else {
if (configuratorBOM.getProduct() == null) {
throw new AxelorException(
TraceBackRepository.CATEGORY_CONFIGURATION_ERROR,
I18n.get(IExceptionMessage.CONFIGURATOR_BOM_IMPORT_FILLED_PRODUCT_NULL));
}
product = configuratorBOM.getProduct();
}
if (configuratorBOM.getDefQtyAsFormula()) {
qty =
new BigDecimal(
configuratorService
.computeFormula(configuratorBOM.getQtyFormula(), attributes)
.toString());
} else {
qty = configuratorBOM.getQty();
}
if (configuratorBOM.getDefUnitAsFormula()) {
unit =
(Unit) configuratorService.computeFormula(configuratorBOM.getUnitFormula(), attributes);
if (unit != null) {
unit = Beans.get(UnitRepository.class).find(unit.getId());
}
} else {
unit = configuratorBOM.getUnit();
}
if (configuratorBOM.getDefProdProcessAsFormula()) {
prodProcess =
(ProdProcess)
configuratorService.computeFormula(
configuratorBOM.getProdProcessFormula(), attributes);
if (prodProcess != null) {
prodProcess = Beans.get(ProdProcessRepository.class).find(prodProcess.getId());
}
} else if (configuratorBOM.getDefProdProcessAsConfigurator()) {
prodProcess =
confProdProcessService.generateProdProcessService(
configuratorBOM.getConfiguratorProdProcess(), attributes, product);
} else {
prodProcess = configuratorBOM.getProdProcess();
}
BillOfMaterial billOfMaterial = new BillOfMaterial();
billOfMaterial.setCompany(configuratorBOM.getCompany());
billOfMaterial.setName(name);
billOfMaterial.setProduct(product);
billOfMaterial.setQty(qty);
billOfMaterial.setUnit(unit);
billOfMaterial.setProdProcess(prodProcess);
billOfMaterial.setStatusSelect(configuratorBOM.getStatusSelect());
billOfMaterial.setDefineSubBillOfMaterial(configuratorBOM.getDefineSubBillOfMaterial());
if (configuratorBOM.getConfiguratorBomList() != null) {
for (ConfiguratorBOM confBomChild : configuratorBOM.getConfiguratorBomList()) {
BillOfMaterial childBom =
generateBillOfMaterial(confBomChild, attributes, level, generatedProduct);
billOfMaterial.addBillOfMaterialSetItem(childBom);
}
}
billOfMaterial = billOfMaterialRepository.save(billOfMaterial);
configuratorBOM.setBillOfMaterialId(billOfMaterial.getId());
configuratorBOMRepo.save(configuratorBOM);
return billOfMaterial;
}
}
| agpl-3.0 |
Sparfel/iTop-s-Portal | library/Zend/Auth/Adapter/Digest.php | 6305 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Auth
* @subpackage Adapter
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Auth_Adapter_Interface
*/
//$1 'Zend/Auth/Adapter/Interface.php';
/**
* @category Zend
* @package Zend_Auth
* @subpackage Adapter
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Auth_Adapter_Digest implements Zend_Auth_Adapter_Interface
{
/**
* Filename against which authentication queries are performed
*
* @var string
*/
protected $_filename;
/**
* Digest authentication realm
*
* @var string
*/
protected $_realm;
/**
* Digest authentication user
*
* @var string
*/
protected $_username;
/**
* Password for the user of the realm
*
* @var string
*/
protected $_password;
/**
* Sets adapter options
*
* @param mixed $filename
* @param mixed $realm
* @param mixed $username
* @param mixed $password
* @return void
*/
public function __construct($filename = null, $realm = null, $username = null, $password = null)
{
$options = array('filename', 'realm', 'username', 'password');
foreach ($options as $option) {
if (null !== $$option) {
$methodName = 'set' . ucfirst($option);
$this->$methodName($$option);
}
}
}
/**
* Returns the filename option value or null if it has not yet been set
*
* @return string|null
*/
public function getFilename()
{
return $this->_filename;
}
/**
* Sets the filename option value
*
* @param mixed $filename
* @return Zend_Auth_Adapter_Digest Provides a fluent interface
*/
public function setFilename($filename)
{
$this->_filename = (string) $filename;
return $this;
}
/**
* Returns the realm option value or null if it has not yet been set
*
* @return string|null
*/
public function getRealm()
{
return $this->_realm;
}
/**
* Sets the realm option value
*
* @param mixed $realm
* @return Zend_Auth_Adapter_Digest Provides a fluent interface
*/
public function setRealm($realm)
{
$this->_realm = (string) $realm;
return $this;
}
/**
* Returns the username option value or null if it has not yet been set
*
* @return string|null
*/
public function getUsername()
{
return $this->_username;
}
/**
* Sets the username option value
*
* @param mixed $username
* @return Zend_Auth_Adapter_Digest Provides a fluent interface
*/
public function setUsername($username)
{
$this->_username = (string) $username;
return $this;
}
/**
* Returns the password option value or null if it has not yet been set
*
* @return string|null
*/
public function getPassword()
{
return $this->_password;
}
/**
* Sets the password option value
*
* @param mixed $password
* @return Zend_Auth_Adapter_Digest Provides a fluent interface
*/
public function setPassword($password)
{
$this->_password = (string) $password;
return $this;
}
/**
* Defined by Zend_Auth_Adapter_Interface
*
* @throws Zend_Auth_Adapter_Exception
* @return Zend_Auth_Result
*/
public function authenticate()
{
$optionsRequired = array('filename', 'realm', 'username', 'password');
foreach ($optionsRequired as $optionRequired) {
if (null === $this->{"_$optionRequired"}) {
/**
* @see Zend_Auth_Adapter_Exception
*/
//$1 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception("Option '$optionRequired' must be set before authentication");
}
}
if (false === ($fileHandle = @fopen($this->_filename, 'r'))) {
/**
* @see Zend_Auth_Adapter_Exception
*/
//$1 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception("Cannot open '$this->_filename' for reading");
}
$id = "$this->_username:$this->_realm";
$idLength = strlen($id);
$result = array(
'code' => Zend_Auth_Result::FAILURE,
'identity' => array(
'realm' => $this->_realm,
'username' => $this->_username,
),
'messages' => array()
);
while ($line = trim(fgets($fileHandle))) {
if (substr($line, 0, $idLength) === $id) {
if (substr($line, -32) === md5("$this->_username:$this->_realm:$this->_password")) {
$result['code'] = Zend_Auth_Result::SUCCESS;
} else {
$result['code'] = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID;
$result['messages'][] = 'Password incorrect';
}
return new Zend_Auth_Result($result['code'], $result['identity'], $result['messages']);
}
}
$result['code'] = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND;
$result['messages'][] = "Username '$this->_username' and realm '$this->_realm' combination not found";
return new Zend_Auth_Result($result['code'], $result['identity'], $result['messages']);
}
}
| agpl-3.0 |
ONLYOFFICE/core | ASCOfficeXlsFile2/source/XlsFormat/Logic/Biff_records/MulBlank.cpp | 5140 | /*
* (c) Copyright Ascensio System SIA 2010-2019
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#include "MulBlank.h"
#include <boost/lexical_cast.hpp>
namespace XLS
{
std::wstring getColAddress(int col)
{
static const size_t r = (L'Z' - L'A' + 1);
std::wstring res;
size_t r0 = col / r;
if (r0 > 0)
{
const std::wstring rest = getColAddress(col - r*r0);
const std::wstring res = getColAddress(r0-1) + rest;
return res;
}
else
return std::wstring(1, (wchar_t)(L'A' + col));
}
std::wstring getRowAddress(int row)
{
return boost::lexical_cast<std::wstring>(row+1);
}
std::wstring getColRowRef(int col, int row)
{
//(0,0) = A1
return getColAddress(col) + getRowAddress(row);
}
MulBlank::MulBlank()
{
}
MulBlank::~MulBlank()
{
}
BaseObjectPtr MulBlank::clone()
{
return BaseObjectPtr(new MulBlank(*this));
}
void MulBlank::readFields(CFRecord& record)
{
global_info_ = record.getGlobalWorkbookInfo();
// A little hack to extract colLast before it is used
record.skipNunBytes(record.getDataSize() - sizeof(unsigned short));
record >> colLast;
record.resetPointerToBegin();
//------------------
record >> rw >> colFirst;
int r = rw;
int colL = colLast;
int colF = colFirst;
rgixfe.load(record, colLast - colFirst + 1);
record.skipNunBytes(sizeof(unsigned short));
}
const int MulBlank::GetRow() const
{
return static_cast<unsigned short>(rw);
}
const int MulBlank::GetColumn() const
{
return static_cast<unsigned short>(colFirst);
}
int MulBlank::serialize(std::wostream & stream)
{
CP_XML_WRITER(stream)
{
int row = GetRow();
for (long i = colFirst; i <= colLast; i++)
{
std::wstring ref = getColRowRef(i, row);
CP_XML_NODE(L"c")
{
CP_XML_ATTR(L"r", ref);
if(( (i-colFirst) < rgixfe.rgixfe.size()) && (rgixfe.rgixfe[i-colFirst] > global_info_->cellStyleXfs_count))
{
int st = (int)rgixfe.rgixfe[i-colFirst] - global_info_->cellStyleXfs_count;
CP_XML_ATTR(L"s", rgixfe.rgixfe[i-colFirst] - global_info_->cellStyleXfs_count);
}
else if ((rgixfe.common_ixfe > 0) && (rgixfe.common_ixfe > global_info_->cellStyleXfs_count))
{
int st = (int)rgixfe.common_ixfe - global_info_->cellStyleXfs_count;
CP_XML_ATTR(L"s", rgixfe.common_ixfe - global_info_->cellStyleXfs_count);
}
}
//if(( (i-colFirst) < rgixfe.rgixfe.size()) && (rgixfe.rgixfe[i-colFirst] > global_info_->cellStyleXfs_count))
//{
// CP_XML_NODE(L"c")
// {
// CP_XML_ATTR(L"r", ref);
//
// int st = (int)rgixfe.rgixfe[i-colFirst] - global_info_->cellStyleXfs_count;
// CP_XML_ATTR(L"s", rgixfe.rgixfe[i-colFirst] - global_info_->cellStyleXfs_count);
// }
//}
}
}
return 0;
}
BiffStructurePtr IXFCellMulBlankSpecial::clone()
{
return BiffStructurePtr(new IXFCellMulBlankSpecial(*this));
}
void IXFCellMulBlankSpecial::load(CFRecord& record, const size_t num_cells)
{
size_t sz = (record.getDataSize() - record.getRdPtr()-2)/2;
unsigned short ixfe;
for(size_t i = 0; i < (std::min)(sz, num_cells); ++i) //Lighting Load Calculation.xls - третий лист
{
record >> ixfe;
rgixfe.push_back(ixfe);
}
if(rgixfe.size() != 0)
{
common_ixfe = rgixfe[0];
size_t j = 0;
for(; j < rgixfe.size(); ++j)
{
if(rgixfe[j] != common_ixfe) break;
}
if(j == rgixfe.size())
{
rgixfe.clear();
}
}
else
{
common_ixfe = 0; // just to avoid warnings
}
}
} // namespace XLS
| agpl-3.0 |
boob-sbcm/3838438 | src/generated/java/com/rapid_i/repository/wsimport/Rename.java | 2764 | /**
* 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.rapid_i.repository.wsimport;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for rename complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="rename">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="location" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="newName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "rename", propOrder = {
"location",
"newName"
})
public class Rename {
protected String location;
protected String newName;
/**
* Gets the value of the location property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLocation() {
return location;
}
/**
* Sets the value of the location property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLocation(String value) {
this.location = value;
}
/**
* Gets the value of the newName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNewName() {
return newName;
}
/**
* Sets the value of the newName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNewName(String value) {
this.newName = value;
}
}
| agpl-3.0 |
becueb/MconfWeb | spec/features/events/user_registers_in_an_event_spec.rb | 4368 | # This file is part of Mconf-Web, a web application that provides access
# to the Mconf webconferencing system. Copyright (C) 2010-2015 Mconf.
#
# This file is licensed under the Affero General Public License version
# 3 or later. See the LICENSE file.
require 'spec_helper'
require 'support/feature_helpers'
feature "User registers in an event" do
before(:all) { Site.current.update_attributes(events_enabled: true) }
subject { page }
context 'as a logged in user clicking in the link to register' do
let(:event) { FactoryGirl.create(:event, owner: FactoryGirl.create(:user)) }
let(:user) { FactoryGirl.create(:user) }
before {
login_as(user, :scope => :user)
visit event_path(event)
click_button t("events.registration.button")
}
it { has_success_message t('flash.participants.create.notice') }
it { current_path.should eq(event_path(event)) }
it { should have_content t("events.registration.already_registered") }
it { should have_content t("events.registration.unregister") }
it { should_not have_content t("events.registration.button") }
# updates the number of participants in the event
# adds the user as a participant in the event
context 'cancel registration after being registered' do
before {
click_link t("events.registration.unregister")
}
it { current_path.should eq(event_path(event)) }
it { has_success_message t('flash.participants.destroy.notice') }
it { should_not have_content t("events.registration.unregister") }
end
end
context "as a visitor clicking in the link to register" do
let(:event) { FactoryGirl.create(:event, owner: FactoryGirl.create(:user)) }
let(:user) { FactoryGirl.create(:user) }
before {
visit event_path(event)
click_link t("events.registration.button")
}
it { current_path.should eq(new_event_participant_path(event)) }
it { should have_content t("participants.split_form.annonymous_title") }
it { should have_content t("participants.split_form.member_title") }
context "register as annonymous" do
let(:email) { 'cosmo@oot.ze' }
before {
fill_in "participant[email]", with: email
click_button t('participants.form.submit')
}
it { has_success_message t('flash.participants.create.waiting_confirmation') }
it { current_path.should eq(event_path(event)) }
it { should have_content t("events.registration.button") }
end
context "register as annonymous and confirms registration via email" do
skip
end
context "register as annonymous and cancels registration via email" do
skip
end
context "login then register as member" do
before {
user.update_attributes password: '123456', password_confirmation: '123456'
fill_in "user[login]", with: user.permalink
fill_in "user[password]", with: '123456'
click_button t("sessions.login_form.login")
}
it { current_path.should eq(new_event_participant_path(event)) }
it { should have_content(user.email) }
it { should have_content t("participants.form.submit") }
context "finish registering" do
before { click_button t("participants.form.submit") }
it { has_success_message t('flash.participants.create.notice') }
it { current_path.should eq(event_path(event)) }
it { should have_content t("events.registration.already_registered") }
it { should have_content t("events.registration.unregister") }
it { should_not have_content t("events.registration.button") }
end
end
end
scenario "for an event that already ended" do
skip
# shows a message saying that the event ended
# doesn't show the register link
end
scenario "as a logged in user in an event of a private space the user is not a member of" do
skip
# shows a link for the user to join the space
# doesn't show a link to register in the event
end
scenario "as a logged in user in an event of a private space the user is a member of" do
skip
# shows a link to register in the event
end
scenario "as a visitor in an event of a private space" do
skip
# shows a message saying that the user needs to sign in before registration
# doesn't show a link to register in the event
end
end
| agpl-3.0 |
Tatwi/legend-of-hondo | MMOCoreORB/bin/scripts/mobile/lair/npc_theater/global_rebel_specforce_camp2_rebel_small_theater.lua | 1344 | global_rebel_specforce_camp2_rebel_small_theater = Lair:new {
mobiles = {
{"specforce_infiltrator",3},
{"senior_specforce_infiltrator",1}
},
spawnLimit = 9,
buildingsVeryEasy = {"object/building/poi/anywhere_rebel_camp_small_1.iff","object/building/poi/anywhere_rebel_camp_small_2.iff","object/building/poi/anywhere_rebel_camp_small_3.iff"},
buildingsEasy = {"object/building/poi/anywhere_rebel_camp_small_1.iff","object/building/poi/anywhere_rebel_camp_small_2.iff","object/building/poi/anywhere_rebel_camp_small_3.iff"},
buildingsMedium = {"object/building/poi/anywhere_rebel_camp_small_1.iff","object/building/poi/anywhere_rebel_camp_small_2.iff","object/building/poi/anywhere_rebel_camp_small_3.iff"},
buildingsHard = {"object/building/poi/anywhere_rebel_camp_small_1.iff","object/building/poi/anywhere_rebel_camp_small_2.iff","object/building/poi/anywhere_rebel_camp_small_3.iff"},
buildingsVeryHard = {"object/building/poi/anywhere_rebel_camp_small_1.iff","object/building/poi/anywhere_rebel_camp_small_2.iff","object/building/poi/anywhere_rebel_camp_small_3.iff"},
missionBuilding = "object/tangible/lair/base/objective_banner_rebel.iff",
mobType = "npc",
buildingType = "theater",
faction = "rebel"
}
addLairTemplate("global_rebel_specforce_camp2_rebel_small_theater", global_rebel_specforce_camp2_rebel_small_theater)
| agpl-3.0 |
BrickbitSolutions/lpm-core | src/main/java/be/brickbit/lpm/core/command/user/UpdateAccountDetailsCommand.java | 686 | package be.brickbit.lpm.core.command.user;
import java.util.List;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class UpdateAccountDetailsCommand {
@NotBlank(message = "Username may not be empty")
private String username;
@Email
@NotBlank(message = "Email may not be empty")
private String email;
@NotEmpty(message = "User must have at least 1 authority")
private List<String> authorities;
}
| agpl-3.0 |
migue/voltdb | src/ee/common/SQLException.cpp | 3083 | /* This file is part of VoltDB.
* Copyright (C) 2008-2017 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/>.
*/
#include "common/SQLException.h"
#include "common/SerializableEEException.h"
#include "common/serializeio.h"
#include <iostream>
#include <cassert>
using namespace voltdb;
// Please keep these ordered alphabetically.
// Names and codes are standardized.
const char* SQLException::data_exception_division_by_zero = "22012";
const char* SQLException::data_exception_invalid_character_value_for_cast = "22018";
const char* SQLException::data_exception_invalid_parameter = "22023";
const char* SQLException::data_exception_most_specific_type_mismatch = "2200G";
const char* SQLException::data_exception_numeric_value_out_of_range = "22003";
const char* SQLException::data_exception_string_data_length_mismatch = "22026";
const char* SQLException::dynamic_sql_error = "07000";
const char* SQLException::integrity_constraint_violation = "23000";
// This is non-standard -- keep it unique.
const char* SQLException::nonspecific_error_code_for_error_forced_by_user = "99999";
const char* SQLException::specific_error_specified_by_user = "Specific error code specified by user invocation of SQL_ERROR";
// These are ordered by error code. Names and codes are volt
// specific - must find merge conflicts on duplicate codes.
const char* SQLException::volt_output_buffer_overflow = "V0001";
const char* SQLException::volt_temp_table_memory_overflow = "V0002";
const char* SQLException::volt_decimal_serialization_error = "V0003";
SQLException::SQLException(std::string sqlState, std::string message) :
SerializableEEException(VOLT_EE_EXCEPTION_TYPE_SQL, message),
m_sqlState(sqlState), m_internalFlags(0)
{
assert(m_sqlState.length() == 5);
}
SQLException::SQLException(std::string sqlState, std::string message, VoltEEExceptionType type) :
SerializableEEException(type, message),
m_sqlState(sqlState), m_internalFlags(0)
{
assert(m_sqlState.length() == 5);
}
SQLException::SQLException(std::string sqlState, std::string message, int internalFlags) :
SerializableEEException(VOLT_EE_EXCEPTION_TYPE_SQL, message),
m_sqlState(sqlState), m_internalFlags(internalFlags)
{
assert(m_sqlState.length() == 5);
}
void SQLException::p_serialize(ReferenceSerializeOutput *output) const {
const char* sqlState = m_sqlState.c_str();
for (int ii = 0; ii < 5; ii++) {
output->writeByte(sqlState[ii]);
}
}
| agpl-3.0 |
FiviumAustralia/OpenEyes | features/bootstrap/ExaminationContext.php | 60674 | <?php
use Behat\Behat\Context\ClosuredContextInterface, Behat\Behat\Context\TranslatedContextInterface, Behat\Behat\Context\BehatContext, Behat\Behat\Exception\PendingException;
use Behat\Gherkin\Node\PyStringNode, Behat\Gherkin\Node\TableNode;
use Behat\MinkExtension\Context\MinkContext;
use Behat\Mink\Driver\Selenium2Driver;
use \SensioLabs\Behat\PageObjectExtension\Context\PageObjectContext;
use WebDriver\WebDriver;
class ExaminationContext extends PageObjectContext
{
public function __construct(array $parameters)
{
}
/**
* @Then /^I select a History of Blurred Vision, Mild Severity, Onset (\d+) Week, Left Eye, (\d+) Week$/
*/
public function iSelectAHistoryOfBlurredVision()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->history();
}
/**
* @Then /^I Add a Comorbiditiy of "([^"]*)"$/
*/
public function iAddAComorbiditiyOf($com)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->addComorbiditiy($com);
}
/**
* @Then /^I choose to expand the "([^"]*)" section$/
*/
public function iChooseToExpandTheSection($section)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->openExaminationSectionList($section);
/*if($section=='visualFunction') {
$examination->openVisualFunction();
}
elseif($section=='visualAcuity') {
$examination->openVisualAcuity();
}
elseif($section=='nearVisualAcuity') {
$examination->openNearVisualAcuity();
}
elseif($section=='anteriorSegment') {
$examination->openAnteriorSegment();
}
elseif($section=='refraction'){
$examination->openRefraction();
}
elseif($section=='intraocularPressure'){
$examination->expandIntraocularPressure();
}
elseif($section=='dilation'){
$examination->openDilation();
}
elseif($section=='visualFields'){
$examination->expandVisualFields();
}
elseif($section=='gonioscopy'){
$examination->expandGonioscopy();
}
elseif($section=='adnexalComorbidity'){
$examination->expandAdnexalComorbidity();
}
elseif($section=='conclusion'){
$examination->expandConclusion();
}
elseif($section=='pupillaryAbnormalities'){
$examination->expandPupillaryAbnormalities();
}
elseif($section=='DRGrading'){
$examination->expandDRGrading();
}
elseif($section=='opticDisc'){
$examination->expandOpticDisc();
}
elseif($section=='posteriorPole'){
$examination->expandPosteriorPole();
}
elseif($section=='diagnoses'){
$examination->expandDiagnoses();
}
elseif($section=='investigation'){
$examination->expandInvestigation();
}
elseif($section=='clinicalManagement'){
$examination->expandClinicalManagement();
}
elseif($section=='cataractSurgicalManagement'){
$examination->expandCataractSurgicalManagement();
}
elseif($section=='laserManagement'){
$examination->expandLaserManagement();
}
elseif($section=='injectionManagement'){
$examination->expandInjectionManagement();
}
elseif($section=='risks'){
$examination->expandRisks();
}
elseif($section=='clinicalOutcome'){
$examination->expandClinicalOutcome();
}
elseif($section=='overallManagement'){
$examination->expandOverallManagement();
}
elseif($section=='currentManagement'){
$examination->expandCurrentManagement();
}
elseif($section=='colourVision'){
$examination->openColourVision();
}
elseif($section=='comorbidities'){
$examination->openComorbidities();
}
elseif($section=='conclusion') {
$examination->expandConclusion();
}
elseif($section=='opticDisc') {
$examination->expandOpticDisc();
}*/
}
/**
* @Then /^I select a Segment of Tube patch and Material drop down of "([^"]*)"$/
*/
public function iSelectASegmentAndMaterial($material)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->selectASegmentAndMaterial($material);
}
/**
* @Given /^I choose a left eye diagnosis$/
*/
public function iChooseALeftEyeDiagnosis()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->diagnosesLeftEye();
}
/**
* @Given /^I add Anterior Segment Description of "([^"]*)"$/
*/
public function iAddAnteriorSegmentDescriptionOf($description)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->anteriorSegmentDescription($description);
}
/**
* @Given /^I select a Visual Acuity of "([^"]*)"$/
*/
public function iSelectAVisualAcuityOf($unit)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->selectVisualAcuity($unit);
}
/**
* @Given /^I select a Near Visual Acuity of "([^"]*)"$/
*/
public function iSelectANearVisualAcuityOf($unit)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->selectNearVisualAcuity($unit);
}
/**
* @Then /^I choose a left Visual Acuity Snellen Metre "([^"]*)" and a reading method of "([^"]*)"$/
*/
public function SnellenMetreAndAReading($metre, $method)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->selectLeftVA($metre, $method);
}
/**
* @Then /^I choose a right Visual Acuity Snellen Metre "([^"]*)" and a reading method of "([^"]*)"$/
*/
public function RightVisualAcuitySnellenMetre($metre, $method)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->selectRightVA($metre, $method);
}
/**
* @Then /^I choose a left Visual Acuity ETDRS Letters Snellen Metre "([^"]*)" and a reading method of "([^"]*)"$/
*/
public function iChooseALeftVisualAcuityEtdrsLettersSnellenMetreAndAReadingMethodOf($metre, $method)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->selectLeftVA($metre, $method);
}
/**
* @Then /^I choose a right Visual Acuity ETDRS Letters Snellen Metre "([^"]*)" and a reading method of "([^"]*)"$/
*/
public function iChooseARightVisualAcuityEtdrsLettersSnellenMetreAndAReadingMethodOf($metre, $method)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->selectRightVA($metre, $method);
}
/**
* @Then /^I choose a left Near Visual Acuity ETDRS Letters Snellen Metre "([^"]*)" and a reading method of "([^"]*)"$/
*/
public function iChooseALeftNearVisualAcuityEtdrsLettersSnellenMetreAndAReadingMethodOf($metre, $method)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->selectLeftNVA($metre, $method);
}
/**
* @Then /^I choose a right Near Visual Acuity ETDRS Letters Snellen Metre "([^"]*)" and a reading method of "([^"]*)"$/
*/
public function iChooseARightNearVisualAcuityEtdrsLettersSnellenMetreAndAReadingMethodOf($metre, $method)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->selectRightNVA($metre, $method);
}
/**
* @Then /^I choose a left Intraocular Pressure of "([^"]*)" and Instrument "([^"]*)"$/
*/
public function iChooseALeftIntraocularPressureOfAndInstrument($pressure, $instrument)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftIntracocular($pressure, $instrument);
}
/**
* @Then /^I choose a right Intraocular Pressure of "([^"]*)" and Instrument "([^"]*)"$/
*/
public function iChooseARightIntraocularPressureOfAndInstrument($pressure, $instrument)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightIntracocular($pressure, $instrument);
}
/**
* @Then /^I choose left Dilation of "([^"]*)" and drops of "([^"]*)"$/
*/
public function iChooseLeftDilationOfAndDropsOf($dilation, $drops)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->dilationLeft($dilation, $drops);
$examination->dilationLeft($dilation, $drops);
}
/**
* @Then /^I choose right Dilation of "([^"]*)" and drops of "([^"]*)"$/
*/
public function iChooseRightDilationOfAndDropsOf($dilation, $drops)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->dilationRight($dilation, $drops);
}
/**
* @Given /^I enter a left Dilation time of "([^"]*)"$/
*/
public function iEnterALeftDilationTimeOf($time)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->dilationLeftTime($time);
}
/**
* @Given /^I enter a right Dilation time of "([^"]*)"$/
*/
public function iEnterARightDilationTimeOf($time)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->dilationRightTime($time);
}
/**
* @Then /^I Confirm that the Dilation Invalid time error message is displayed$/
*/
public function iConfirmThatTheDilationInvalidTimeErrorMessageIsDisplayed()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->dilationTimeErrorValidation();
$homepage = $this->getPage('HomePage');
$homepage->open();
sleep(5);
$homepage->acceptAlert();
}
/**
* @Then /^I choose to remove left Dilation treatment$/
*/
public function iChooseToRemoveLeftDilation()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->removeLeftDilation();
}
/**
* @Then /^I enter left Refraction details of Sphere "([^"]*)" integer "([^"]*)" fraction "([^"]*)"$/
*/
public function LeftRefractionDetails($sphere, $integer, $fraction)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftRefractionDetails($sphere, $integer, $fraction);
}
/**
* @Given /^I enter left cylinder details of of Cylinder "([^"]*)" integer "([^"]*)" fraction "([^"]*)"$/
*/
public function iEnterLeftCylinderDetails($cylinder, $integer, $fraction)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftCyclinderDetails($cylinder, $integer, $fraction);
}
/**
* @Then /^I enter left Axis degrees of "([^"]*)"$/
*/
public function iEnterLeftAxisDegreesOf($axis)
{
// HACK! I have entered the value twice in the code to stop the Axis from spinning
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftAxis($axis);
}
/**
* @Given /^I enter a left type of "([^"]*)"$/
*/
public function iEnterALeftTypeOf($type)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftType($type);
}
/**
* @Then /^I select a Right Intended Treatment of "([^"]*)"$/
*/
public function iSelectARightIntendedTreatmentOf($treatment)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightIntendedTreatment($treatment);
}
/**
* @Then /^I select a Left Intended Treatment of "([^"]*)"$/
*/
public function iSelectALeftIntendedTreatmentOf($treatment)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftIntendedTreatment($treatment);
}
/**
* @Then /^I enter right Refraction details of Sphere "([^"]*)" integer "([^"]*)" fraction "([^"]*)"$/
*/
public function iEnterRightRefractionDetailsOfSphereIntegerFraction($sphere, $integer, $fraction)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->RightRefractionDetails($sphere, $integer, $fraction);
}
/**
* @Given /^I enter right cylinder details of of Cylinder "([^"]*)" integer "([^"]*)" fraction "([^"]*)"$/
*/
public function iEnterRightCylinderDetailsOfOfCylinderIntegerFraction($cylinder, $integer, $fraction)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->RightCyclinderDetails($cylinder, $integer, $fraction);
}
/**
* @Then /^I enter right Axis degrees of "([^"]*)"$/
*/
public function iEnterRightAxisDegreesOf($axis)
{
// We need a Clear Field function here
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->RightAxis($axis);
// We need to Press the tab key here
}
/**
* @Given /^I enter a right type of "([^"]*)"$/
*/
public function iEnterARightTypeOf($type)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->RightType($type);
}
/**
* @Given /^I add a left Adnexal Comorbidity of "([^"]*)"$/
*/
public function iAddALeftAdnexalComorbidityOf($left)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftAdnexal($left);
}
/**
* @Given /^I add a right Adnexal Comorbidity of "([^"]*)"$/
*/
public function iAddARightAdnexalComorbidityOf($right)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightAdnexal($right);
}
/**
* @Given /^I add a left Abnormality of "([^"]*)"$/
*/
public function iAddALeftAbnormalityOf($left)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftPupillaryAbnormality($left);
}
/**
* @Given /^I add a right Abnormality of "([^"]*)"$/
*/
public function iAddARightAbnormalityOf($right)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightPupillaryAbnormality($right);
}
/**
* @Given /^I select Diagnosis of Cataract$/
*/
public function iSelectDiagnosisOfCataract()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->diagnosesOfCataract();
}
/**
* @Given /^I choose a right eye diagnosis$/
*/
public function iChooseARightEyeDiagnosis()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->diagnosesRightEye();
}
/**
* @Given /^I choose both eyes diagnosis$/
*/
public function iChooseBothEyesDiagnosis()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->diagnosesBothEyes();
}
/**
* @Given /^I choose a principal diagnosis$/
*/
public function principalDiagnosis()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->principalDiagnosis();
}
/**
* @Given /^I add an Investigation of "([^"]*)"$/
*/
public function iAddAnInvestigationOf($investigation)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->addInvestigation($investigation);
}
/**
* @Given /^I add Cataract Management Comments of "([^"]*)"$/
*/
public function iAddCataractManagementCommentsOf($comments)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->cataractManagementComments($comments);
}
/**
* @Then /^I select First Eye$/
*/
public function iSelectFirstEye()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->selectFirstEye();
}
/**
* @Then /^I select Second Eye$/
*/
public function iSelectSecondEye()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->selectSecondEye();
}
/**
* @Given /^I choose City Road$/
*/
public function iChooseCityRoad()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->cityRoad();
}
/**
* @Given /^I choose At Satellite$/
*/
public function iChooseAtSatellite()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->satellite();
}
/**
* @Given /^I choose Straightforward case$/
*/
public function iChooseStraightforwardCase()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->straightforward();
}
/**
* @Then /^I select a post operative refractive target in dioptres of "([^"]*)"$/
*/
public function iSelectAPostOperativeRefractiveTargetInDioptresOf($target)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->postOpRefractiveTarget($target);
}
/**
* @Given /^the post operative target has been discussed with patient Yes$/
*/
public function thePostOperativeTargetHasBeenDiscussedWithPatientYes()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->discussedWithPatientYes();
}
/**
* @Given /^the post operative target has been discussed with patient No$/
*/
public function thePostOperativeTargetHasBeenDiscussedWithPatientNo()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->discussedWithPatientNo();
}
/**
* @Then /^I select a suitable for surgeon of "([^"]*)"$/
*/
public function iSelectASuitableForSurgeonOf($surgeon)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->suitableForSurgeon($surgeon);
// sleep(5);
}
/**
* @Given /^I tick the Supervised checkbox$/
*/
public function iTickTheSupervisedCheckbox()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->supervisedCheckbox();
}
/**
* @Then /^I select Previous Refractive Surgery Yes$/
*/
public function iSelectPreviousRefractiveSurgeryYes()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->previousRefractiveSurgeryYes();
}
/**
* @Then /^I select Previous Refractive Surgery No$/
*/
public function iSelectPreviousRefractiveSurgeryNo()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->previousRefractiveSurgeryNo();
}
/**
* @Given /^I select Vitrectomised Eye Yes$/
*/
public function iSelectVitrectomisedEyeYes()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->vitrectomisedEyeYes();
}
/**
* @Given /^I select Vitrectomised Eye No$/
*/
public function iSelectVitrectomisedEyeNo()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->vitrectomisedEyeNo();
}
/**
* @Given /^I choose a right laser choice of "([^"]*)"$/
*/
public function iChooseARightLaserOf($laser)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->RightLaserStatusChoice($laser);
}
/**
* @Given /^I choose a left laser choice of "([^"]*)"$/
*/
public function iChooseALeftLaserOf($laser)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->LeftLaserStatusChoice($laser);
}
/**
* @Given /^I choose a left laser type of "([^"]*)"$/
*/
public function iChooseALeftLaserTypeOf($laser)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftLaser($laser);
}
/**
* @Given /^I choose a right laser type of "([^"]*)"$/
*/
public function iChooseARightLaserTypeOf($laser)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightLaser($laser);
}
/**
* @Given /^I tick the No Treatment checkbox$/
*/
public function iTickTheNoTreatmentCheckbox()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->noTreatment();
}
/**
* @Then /^I select a reason for No Treatment of "([^"]*)"$/
*/
public function iSelectAReasonForNoTreatmentOf($treatment)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->noTreatmentReason($treatment);
}
/**
* @Given /^I select a Right Diagnosis of Choroidal Retinal Neovascularisation$/
*/
public function iSelectADiagnosisOfChoroidalRetinalNeovascularisation()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightChoroidalRetinal();
}
/**
* @Then /^I select Right Secondary to "([^"]*)"$/
*/
public function iSelectSecondaryTo($secondary)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightSecondaryTo($secondary);
}
/**
* @Given /^I select a Left Diagnosis of Choroidal Retinal Neovascularisation$/
*/
public function iSelectALeftDiagnosisOfChoroidalRetinalNeovascularisation()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftChoroidalRetinal();
}
/**
* @Then /^I select Left Secondary to "([^"]*)"$/
*/
public function iSelectLeftSecondaryTo($secondary)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftSecondaryTo($secondary);
}
/**
* @Then /^I choose a Right CRT Increase <(\d+) of Yes$/
*/
public function iChooseACrtIncreaseOfYes($arg1)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
sleep(5);
$examination->rightCRTIncreaseLowerThanHundredYes();
}
/**
* @Then /^I choose a Right CRT Increase <(\d+) of No$/
*/
public function iChooseACrtIncreaseOfNo($arg1)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightCRTIncreaseLowerThanHundredNo();
}
/**
* @Then /^I choose a Right CRT >=(\d+) of Yes$/
*/
public function iChooseACrtOfYes($arg1)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightCRTIncreaseMoreThanHundredYes();
}
/**
* @Then /^I choose a Right CRT >=(\d+) of No$/
*/
public function iChooseACrtOfNo($arg1)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightCRTIncreaseMoreThanHundredNo();
}
/**
* @Then /^I choose a Right Loss of (\d+) letters Yes$/
*/
public function iChooseALossOfLettersYes($arg1)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightLossOfFiveLettersYes();
}
/**
* @Then /^I choose a Right Loss of (\d+) letters No$/
*/
public function iChooseALossOfLettersNo($arg1)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightLossOfFiveLettersNo();
}
/**
* @Then /^I choose a Right Loss of (\d+) letters >(\d+) Yes$/
*/
public function iChooseALossOfLettersYes2($arg1, $arg2)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightLossOfFiveLettersHigherThanFiveYes();
}
/**
* @Then /^I choose a Right Loss of (\d+) letters >(\d+) No$/
*/
public function iChooseALossOfLettersNo2($arg1, $arg2)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightLossOfFiveLettersHigherThanFiveNo();
}
/**
* @Then /^I choose a Left CRT Increase <(\d+) of Yes$/
*/
public function iChooseALeftCrtIncreaseOfYes($arg1)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftCRTIncreaseLowerThanHundredYes();
}
/**
* @Then /^I choose a Left CRT Increase <(\d+) of No$/
*/
public function iChooseALeftCrtIncreaseOfNo($arg1)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftCRTIncreaseLowerThanHundredNo();
}
/**
* @Then /^I choose a Left CRT >=(\d+) of Yes$/
*/
public function iChooseALeftCrtOfYes($arg1)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftCRTIncreaseMoreThanHundredYes();
}
/**
* @Then /^I choose a Left CRT >=(\d+) of No$/
*/
public function iChooseALeftCrtOfNo($arg1)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftCRTIncreaseMoreThanHundredNo();
}
/**
* @Then /^I choose a Left Loss of (\d+) letters Yes$/
*/
public function iChooseALeftLossOfLettersYes($arg1)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftLossOfFiveLettersYes();
}
/**
* @Then /^I choose a Left Loss of (\d+) letters No$/
*/
public function iChooseALeftLossOfLettersNo($arg1)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftLossOfFiveLettersNo();
}
/**
* @Then /^I choose a Left Loss of (\d+) letters >(\d+) Yes$/
*/
public function iChooseALeftLossOfLettersYes2($arg1, $arg2)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftLossOfFiveLettersHigherThanFiveYes();
}
/**
* @Then /^I choose a Left Loss of (\d+) letters >(\d+) No$/
*/
public function iChooseALeftLossOfLettersNo2($arg1, $arg2)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftLossOfFiveLettersHigherThanFiveNo();
}
/**
* @Given /^I select a Right Diagnosis of Macular retinal oedema$/
*/
public function iSelectARightDiagnosisOfMacularRetinalOedema()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightMacularRetinal();
}
/**
* @Then /^I select Right Secondary of Venous retinal branch occlusion$/
*/
public function iSelectRightSecondaryOfVenousRetinalBranchOcclusion()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightSecondaryVenousRetinalBranchOcclusion();
}
/**
* @Given /^I select a Left Diagnosis of Macular retinal oedema$/
*/
public function iSelectALeftDiagnosisOfMacularRetinalOedema()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftMacularRetinal();
}
/**
* @Then /^I select Left Secondary of Diabetic macular oedema$/
*/
public function iSelectLeftSecondaryOfDiabeticMacularOedema()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftSecondaryDiabeticMacularOedema();
}
/**
* @Then /^I choose a Right Failed Laser of Yes$/
*/
public function iChooseARightFailedLaserOfYes()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightFailedLaserYes();
}
/**
* @Then /^I choose a Right Failed Laser of No$/
*/
public function iChooseARightFailedLaserOfNo()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightFailedLaserNo();
}
/**
* @Then /^I choose a Right Unsuitable Laser of Yes$/
*/
public function iChooseARightUnsuitableLaserOfYes()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightUnsuitableForLaserYes();
}
/**
* @Then /^I choose a Right Unsuitable Laser of No$/
*/
public function iChooseARightUnsuitableLaserOfNo()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightUnsuitableForLaserNo();
}
/**
* @Then /^I choose a Right Previous Ozurdex Yes$/
*/
public function iChooseARightPreviousOzurdexYes()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightPreviousOzurdexYes();
}
/**
* @Then /^I choose a Right Previous Ozurdex No$/
*/
public function iChooseARightPreviousOzurdexNo()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightPreviousOzurdexNo();
}
/**
* @Then /^I choose a Left CRT above Four Hundred of Yes$/
*/
public function iChooseALeftCrtAboveFourHundredOfYes()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftCrtIncreaseMoreThanFourHundredYes();
}
/**
* @Then /^I choose a Left CRT above Four Hundred of No$/
*/
public function iChooseALeftCrtAboveFourHundredOfNo()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftCrtIncreaseMoreThanFourHundredNo();
}
/**
* @Then /^I choose a Left Foveal Structure Damage Yes$/
*/
public function iChooseALeftFovealStructureDamageYes()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftFovealDamageYes();
}
/**
* @Then /^I choose a Left Foveal Structure Damage No$/
*/
public function iChooseALeftFovealStructureDamageNo()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftFovealDamageNo();
}
/**
* @Then /^I choose a Left Failed Laser of Yes$/
*/
public function iChooseALeftFailedLaserOfYes()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftFailedLaserYes();
}
/**
* @Then /^I choose a Left Failed Laser of No$/
*/
public function iChooseALeftFailedLaserOfNo()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftFailedLaserNo();
}
/**
* @Then /^I choose a Left Unsuitable Laser of Yes$/
*/
public function iChooseALeftUnsuitableLaserOfYes()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftUnsuitableForLaserYes();
}
/**
* @Then /^I choose a Left Unsuitable Laser of No$/
*/
public function iChooseALeftUnsuitableLaserOfNo()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftUnsuitableForLaserNo();
}
/**
* @Then /^I choose a Left Previous Anti VEGF of Yes$/
*/
public function iChooseALeftPreviousAntiVegfOfYes()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftPreviousAntiVEGFyes();
}
/**
* @Then /^I choose a Left Previous Anti VEGF of No$/
*/
public function iChooseALeftPreviousAntiVegfOfNo()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftPreviousAntiVEGFno();
}
/**
* @Given /^I add comments to the Risk section of "([^"]*)"$/
*/
public function iAddCommentsToTheRiskSectionOf($comments)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->riskComments($comments);
}
/**
* @Given /^I choose a Clinical Outcome Status of Discharge$/
*/
public function iChooseAClinicalOutcomeStatusOfDischarge()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->clinicalOutcomeDischarge();
}
/**
* @Given /^I choose a Clinical Outcome Status of Follow Up$/
*/
public function iChooseAClinicalOutcomeStatusOfFollowUp()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->clinicalOutcomeFollowUp();
}
/**
* @Then /^I choose a Follow Up quantity of "([^"]*)"$/
*/
public function iChooseAFollowUpQuantityOf($quantity)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->clinicalFollowUpQuantity($quantity);
}
/**
* @Given /^I choose a Follow Up period of "([^"]*)"$/
*/
public function iChooseAFollowUpPeriodOf($period)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->clinicalFollowUpPeriod($period);
}
/**
* @Given /^I tick the Patient Suitable for Community Patient Tariff$/
*/
public function iTickThePatientSuitableForCommunityPatientTariff()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->clinicalSuitablePatient();
}
/**
* @Then /^I choose a Role of "([^"]*)"$/
*/
public function iChooseARoleOf($role)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->clinicalRole($role);
}
/**
* @Given /^I choose a Conclusion option of "([^"]*)"$/
*/
public function iChooseAConclusionOptionOf($option)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->conclusionOption($option);
}
/**
* @Then /^I Save the Examination$/
*/
public function iSaveTheExamination()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->saveExaminationOnly();
}
/**
* @Then /^I Save the Examination and confirm it has been created successfully$/
*/
public function iSaveTheExaminationAndConfirm()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->saveExaminationAndConfirm();
}
// VALIDATION TESTS
/**
* @Then /^a check is made that a right Axis degrees of "([^"]*)" was entered$/
*/
public function aCheckIsMadeThatARightAxisDegreesOfWasEntered($axis)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightAxisCheck($axis);
}
/**
* @Then /^a check is made that a left Axis degrees of "([^"]*)" was entered$/
*/
public function aCheckIsMadeThatALeftAxisDegreesOfWasEntered($axis)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftAxisCheck($axis);
}
/**
* @Then /^I select Add All optional elements$/
*/
public function iSelectAddAllOptionalElements()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->addAllElements();
}
/**
* @Then /^I confirm that the Add All Validation error messages have been displayed$/
*/
public function iConfirmThatTheAddAllValidationErrorMessagesHaveBeenDisplayed()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->addAllElementsValidationCheck();
$homepage = $this->getPage('HomePage');
$homepage->open();
sleep(5);
$homepage->acceptAlert();
}
/**
* @Then /^I select Close All elements$/
*/
public function iSelectCloseAllElements()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->removeAllElements();
}
/**
* @Then /^I confirm that the Remove All Validation error message is displayed$/
*/
public function iConfirmThatTheRemoveAllValidationErrorMessageIsDisplayed()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->removeAllValidationCheck();
$homepage = $this->getPage('HomePage');
$homepage->open();
sleep(5);
$homepage->acceptAlert();
}
/**
* @Then /^I Confirm that the History Validation error message is displayed$/
*/
public function iConfirmThatHistoryErrorMessageIsDisplayed()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->historyValidationCheck();
}
/**
* @Then /^I Confirm that the Conclusion Validation error message is displayed$/
*/
public function iConfirmConlusionValidation()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->conclusionValidationCheck();
$homepage = $this->getPage('HomePage');
$homepage->open();
sleep(5);
$homepage->acceptAlert();
}
/**
* @Then /^I Confirm to leave the page$/
*/
public function iConfirmToLeaveThePage()
{
//$examination = $this->getPage ( 'Examination' );
Sleep(5);
$homepage = $this->getPage('Homepage');
$homepage->ConfirmLeavePage();
}
/**
* @Then /^I cancel the Examnination event$/
*/
public function iCancelTheExamninationEvent()
{
$examination = $this->getPage('Examination');
Sleep(5);
$examination->CancelExaminationEvent();
}
/**
* @Then /^I Confirm that the Dilation Validation error message is displayed$/
*/
public function iConfirmDilationValidation()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->dilationValidationCheck();
$homepage = $this->getPage('HomePage');
$homepage->open();
sleep(5);
$homepage->acceptAlert();
}
/**
* @Then /^I remove Refraction right side$/
*/
public function iRemoveRefractionRightSide()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->removeRefractionRightSide();
}
/**
* @Then /^I remove all comorbidities$/
*/
public function removeComorbidties()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->removeAllComorbidities();
}
/**
* @Given /^I choose to add a new left Visual Acuity reading of "([^"]*)" and a reading method of "([^"]*)"$/
*/
public function iChooseToAddANewLeftVisualAcuityReadingOfAndAReadingMethodOf($reading, $method)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->addLeftVA($reading, $method);
}
/**
* @Given /^I choose to add a new Right Visual Acuity reading of "([^"]*)" and a reading method of "([^"]*)"$/
*/
public function iChooseToAddANewRightVisualAcuityReadingOfAndAReadingMethodOf($reading, $method)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->addRightVA($reading, $method);
}
/**
* @Then /^I remove the initial Left Visual Acuity$/
*/
public function iRemoveTheInitialLeftVisualAcuity()
{
$examination = $this->getPage('Examination');
$examination->removeFirstLeftVA();
}
/**
* @Then /^I remove the initial Right Visual Acuity$/
*/
public function iRemoveTheInitialRightVisualAcuity()
{
$examination = $this->getPage('Examination');
$examination->removeFirstRightVA();
}
/**
* @Then /^I remove the newly added Left Visual Acuity$/
*/
public function iRemoveTheNewlyAddedLeftVisualAcuity()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->removeSecondLeftVA();
}
/**
* @Then /^I remove the newly added Right Visual Acuity$/
*/
public function iRemoveTheNewlyAddedRightVisualAcuity()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->removeSecondRightVA();
}
/**
* @Then /^I select a Diabetes type of Mellitus Type one$/
*/
public function iSelectADiabetesTypeOfMellitusTypeone()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->diabetesTypeOne();
}
/**
* @Then /^I select a Diabetes type of Mellitus Type two$/
*/
public function iSelectADiabetesTypeOfMellitusTypetwo()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->diabetesTypeTwo();
}
/**
* @Given /^I select a left Clinical Grading for Retinopathy of "([^"]*)"$/
*/
public function iSelectALeftClinicalGradingForRetinopathyOf($grading)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftClinicalGradingRetino($grading);
}
/**
* @Given /^I select a left NSC Retinopathy of "([^"]*)"$/
*/
public function iSelectALeftNscRetinopathyOf($nsc)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftNSCRetino($nsc);
}
/**
* @Given /^I select a left Retinopathy photocoagulation of Yes$/
*/
public function iSelectALeftRetinopathyPhotocoagulationOfYes()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftRetinoPhotoYes();
}
/**
* @Given /^I select a left Retinopathy photocoagulation of No$/
*/
public function iSelectALeftRetinopathyPhotocoagulationOfNo()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftRetinoPhotoNo();
}
/**
* @Given /^I select a left Clinical Grading for maculopathy of "([^"]*)"$/
*/
public function iSelectALeftClinicalGradingForMaculopathyOf($grading)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftClinicalGradingMaculo($grading);
}
/**
* @Given /^I select a left NSC maculopathy of "([^"]*)"$/
*/
public function iSelectALeftNscMaculopathyOf($nsc)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftNSCMaculo($nsc);
}
/**
* @Given /^I select a left Maculopathy photocoagulation of Yes$/
*/
public function iSelectALeftMaculopathyPhotocoagulationOfYes()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftMaculoPhotoYes();
}
/**
* @Given /^I select a left Maculopathy photocoagulation of No$/
*/
public function iSelectALeftMaculopathyPhotocoagulationOfNo()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftMaculoPhotoNo();
}
/**
* @Given /^I select a right Clinical Grading for Retinopathy of "([^"]*)"$/
*/
public function iSelectARightClinicalGradingForRetinopathyOf($grading)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightClinicalGradingRetino($grading);
}
/**
* @Given /^I select a right NSC Retinopathy of "([^"]*)"$/
*/
public function iSelectARightNscRetinopathyOf($nsc)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightNSCRetino($nsc);
}
/**
* @Given /^I select a right Retinopathy photocoagulation of Yes$/
*/
public function iSelectARightRetinopathyPhotocoagulationOfYes()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightRetinoPhotoYes();
}
/**
* @Given /^I select a right Retinopathy photocoagulation of No$/
*/
public function iSelectARightRetinopathyPhotocoagulationOfNo()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightRetinoPhotoNo();
}
/**
* @Given /^I select a right Clinical Grading for maculopathy of "([^"]*)"$/
*/
public function iSelectARightClinicalGradingForMaculopathyOf($grading)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightClinicalGradingMaculo($grading);
}
/**
* @Given /^I select a right NSC maculopathy of "([^"]*)"$/
*/
public function iSelectARightNscMaculopathyOf($nsc)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightNSCMaculo($nsc);
}
/**
* @Given /^I select a right Maculopathy photocoagulation of Yes$/
*/
public function iSelectARightMaculopathyPhotocoagulationOfYes()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightMaculoPhotoYes();
}
/**
* @Given /^I select a right Maculopathy photocoagulation of No$/
*/
public function iSelectARightMaculopathyPhotocoagulationOfNo()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightMaculoPhotoNo();
}
/**
* @Given /^I select Left Unable to assess checkbox$/
*/
public function iSelectLeftUnableToAssessCheckbox()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftUnableAssess();
}
/**
* @Given /^I select Left Eye Missing checkbox$/
*/
public function iSelectLeftEyeMissingCheckbox()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftEyeMissing();
}
/**
* @Given /^I select Right Unable to assess checkbox$/
*/
public function iSelectRightUnableToAssessCheckbox()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightUnableAssess();
}
/**
* @Given /^I select Right Eye Missing checkbox$/
*/
public function iSelectRightEyeMissingCheckbox()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightEyeMissing();
}
/**
* @Given /^I choose a Clinical Interval of "([^"]*)"$/
*/
public function iChooseAClinicalIntervalOf($interval)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->clinicalInterval($interval);
}
/**
* @Given /^I choose a Photo of "([^"]*)"$/
*/
public function iChooseAPhotoOf($photo)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->photo($photo);
}
/**
* @Given /^I choose a OCT of "([^"]*)"$/
*/
public function iChooseAOctOf($oct)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->OCT($oct);
}
/**
* @Given /^I choose a Visual Fields of "([^"]*)"$/
*/
public function iChooseAVisualFieldsOf($visual)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->visualFields($visual);
}
/**
* @Given /^I choose Overall Management Section Comments of "([^"]*)"$/
*/
public function iChooseOverallManagementSectionCommentsOf($comments)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->overallComments($comments);
}
/**
* @Given /^I choose a Gonio of "([^"]*)"$/
*/
public function iChooseAGonioOf($gonio)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->gonioDropdown($gonio);
}
/**
* @Given /^I choose a Right Target IOP of "([^"]*)"$/
*/
public function iChooseARightTargetIopOf($iop)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightIOP($iop);
}
/**
* @Given /^I choose a Right Gonio of "([^"]*)"$/
*/
public function iChooseARightGonioOf($gonio)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightGonio($gonio);
}
/**
* @Given /^I choose a Left Target IOP of "([^"]*)"$/
*/
public function iChooseALeftTargetIopOf($iop)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftIOP($iop);
}
/**
* @Given /^I choose a Left Gonio of "([^"]*)"$/
*/
public function iChooseALeftGonioOf($gonio)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftGonio($gonio);
}
/**
* @Given /^I choose a Referral of Other Service$/
*/
public function iChooseAReferralOfOtherService()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->referralOther();
}
/**
* @Given /^I choose a Referral of Refraction$/
*/
public function iChooseAReferralOfRefraction()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->referralRefraction();
}
/**
* @Given /^I choose a Referral of LVA$/
*/
public function iChooseAReferralOfLva()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->referralLVA();
}
/**
* @Given /^I choose a Referral of Orthopics$/
*/
public function iChooseAReferralOfOrthopics()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->referralOrthoptics();
}
/**
* @Given /^I choose a Referral of CL clinic$/
*/
public function iChooseAReferralOfClClinic()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->referralCLClinic();
}
/**
* @Then /^I choose Investigations of VF$/
*/
public function iChooseInvestigationsOfVf()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->investigationsVF();
}
/**
* @Then /^I choose Investigations of US$/
*/
public function iChooseInvestigationsOfUs()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->investigationsUS();
}
/**
* @Then /^I choose Investigations of Biometry$/
*/
public function iChooseInvestigationsOfBiometry()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->investigationsBiometry();
}
/**
* @Then /^I choose Investigations of OCT$/
*/
public function iChooseInvestigationsOfOct()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->investigationsOCT();
}
/**
* @Then /^I choose Investigations of HRT$/
*/
public function iChooseInvestigationsOfHrt()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->investigationsHRT();
}
/**
* @Then /^I choose Investigations of Disc Photos$/
*/
public function iChooseInvestigationsOfDiscPhotos()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->investigationsDiscPhotos();
}
/**
* @Then /^I choose Investigations of EDT$/
*/
public function iChooseInvestigationsOfEdt()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->investigationsEDT();
}
/**
* @Given /^I select a Left Glaucoma Status of "([^"]*)"$/
*/
public function iSelectALeftGlaucomaStatusOf($status)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftGlaucomaStatus($status);
}
/**
* @Given /^I select a Left Drop related problem of "([^"]*)"$/
*/
public function iSelectALeftDropRelatedProblemOf($problem)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftDropProblems($problem);
}
/**
* @Given /^I select a Left Drops of "([^"]*)"$/
*/
public function iSelectALeftDropsOf($drops)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftDrops($drops);
}
/**
* @Given /^I select a Left Surgery of "([^"]*)"$/
*/
public function iSelectALeftSurgeryOf($surgery)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftSurgery($surgery);
}
/**
* @Given /^I select a Right Glaucoma Status of "([^"]*)"$/
*/
public function iSelectARightGlaucomaStatusOf($status)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightGlaucomaStatus($status);
}
/**
* @Given /^I select a Right Drop related problem of "([^"]*)"$/
*/
public function iSelectARightDropRelatedProblemOf($problem)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightDropProblems($problem);
}
/**
* @Given /^I select a Right Drops of "([^"]*)"$/
*/
public function iSelectARightDropsOf($drops)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightDrops($drops);
}
/**
* @Given /^I select a Right Surgery of "([^"]*)"$/
*/
public function iSelectARightSurgeryOf($surgery)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightSurgery($surgery);
}
/**
* @Given /^I choose a Right Risks of "([^"]*)"$/
*/
public function iChooseARightRisksOf($risks)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightRisks($risks);
}
/**
* @Then /^I choose Right Injection Management Comments of "([^"]*)"$/
*/
public function iChooseRightInjectionManagementCommentsOf($comments)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightInjectionComments($comments);
}
/**
* @Given /^I choose a Left Risks of "([^"]*)"$/
*/
public function iChooseALeftRisksOf($risks)
{
/**
*
* @var Examination $examination
*/
sleep(5);
$examination = $this->getPage('Examination');
$examination->leftRisks($risks);
}
/**
* @Then /^I choose Left Injection Management Comments of "([^"]*)"$/
*/
public function iChooseLeftInjectionManagementCommentsOf($comments)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftInjectionComments($comments);
}
/**
* @Then /^I select a Left RAPD$/
*/
public function iSelectALeftRapd()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftRAPD();
}
/**
* @Given /^I add Left RAPD comments of "([^"]*)"$/
*/
public function iAddLeftRapdCommentsOf($comments)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftRAPDComments($comments);
}
/**
* @Then /^I select a Right RAPD$/
*/
public function iSelectARightRapd()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightRAPD();
}
/**
* @Given /^I add Right RAPD comments of "([^"]*)"$/
*/
public function iAddRightRapdCommentsOf($comments)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightRAPDComments($comments);
}
/**
* @Given /^I choose a Left Colour Vision of "([^"]*)"$/
*/
public function iChooseALeftColourVisionOf($vision)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftColourVision($vision);
}
/**
* @Given /^I choose A Left Colour Vision Value of "([^"]*)"$/
*/
public function iChooseALeftColourVisionValueOf($value)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->leftColourVisionValue($value);
}
/**
* @Given /^I choose a Right Colour Vision of "([^"]*)"$/
*/
public function iChooseARightColourVisionOf($vision)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightColourVision($vision);
}
/**
* @Given /^I choose A Right Colour Vision Value of "([^"]*)"$/
*/
public function iChooseARightColourVisionValueOf($value)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->rightColourVisionValue($value);
}
/**
* @Then /^I add the changes to left eye$/
*/
public function iAddTheChangesToLeftEye()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->$this->iAddTheChangesToLeftEye();
//throw new PendingException();
}
/**
* @Then /^I click on Right Eye PCR Risk$/
*/
public function iClickOnRightEyePCRRISK()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->clickOnRightEyePCRRISK();
}
/**
* @Then /^I click on Left Eye PCR Risk$/
*/
public function iClickOnLeftEyePCRRISK()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->clickOnLeftEyePCRRISK();
}
/**
* @Then /^I should see reference link on PCR Right Eye block$/
*/
public function iShouldSeeReferenceLinkOnPCRRightEyeBlock()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->referenceLinkOnPCRRightEyeBlock();
}
/**
* @Then /^I should see reference link on PCR Left Eye block$/
*/
public function iShouldSeeReferenceLinkOnPCRLeftEyeBlock()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->referenceLinkOnPCRLeftEyeBlock();
}
/**
* @Then /^I click on reference link on PCR Right Eye block$/
*/
public function iClickOnReferenceLinkOnPCRRightEyeBlock()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->clickOnReferenceLinkOnPCRRightEyeBlock();
}
/**
* @Then /^I click on reference link on PCR Left Eye block$/
*/
public function iClickOnReferenceLinkOnPCRLeftEyeBlock()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->clickOnReferenceLinkOnPCRLeftEyeBlock();
}
/**
* @Then /^I should see the reference Page$/
*/
public function iShouldSeeTheReferencePage()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->onPCRReferencePage();
}
/**
* @Then /^I should have the default PCR values$/
*/
public function iShouldHaveDefaultPcrValues()
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->checkPcrDefaultValues();
}
/**
* @Then /^I set the "([^"]*)" PCR option "([^"]*)" to be "([^"]*)"$/
*/
public function iSetThePcrOptionTo($side, $option, $value)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->setPcrValue($side, $option, $value);
}
/**
* @Then /^I should have a calculated "([^"]*)" PCR value of "([^"]*)"$/
*/
public function iShouldHaveCalculatedPcrValue($side, $value)
{
/**
*
* @var Examination $examination
*/
$examination = $this->getPage('Examination');
$examination->checkPcrCalculatedValue($side, $value);
}
}
| agpl-3.0 |
CloCkWeRX/abn-input | abn.js | 2557 | /*jslint indent: 2 */
$().ready(function () {
var ABNControl = {
permitted_key: function (e) {
var numeric_keys, editing_keys;
numeric_keys = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57];
editing_keys = [8, 13, 46, 37, 38, 40, 9, 0, 35, 36, 39, 32];
if (numeric_keys.indexOf(e.which) > -1) {
return true;
}
if (editing_keys.indexOf(e.which) > -1) {
return true;
}
if (e.ctrlKey) {
return true;
}
return false;
},
format_abn: function (value) {
value = value.split(" ").join("");
return [
value.slice(0, 2),
value.slice(2, 5),
value.slice(5, 8),
value.slice(8, 11)
].join(" ").trim();
},
validate_abn: function (value) {
var total, weightings, new_value, i;
//http://www.ato.gov.au/Business/Australian-business-number/In-detail/Introduction/Format-of-the-ABN/
weightings = [10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19];
new_value = value.split(" ").join("");
if (new_value.length !== 11) {
return false;
}
// Subtract 1 from the first (left) digit to give a new eleven digit number
new_value = String(parseInt(new_value, 10) - 10000000000);
// Multiply each of the digits in this new number by its weighting factor
total = 0;
for (i = 0; i < new_value.length; i++) {
// Sum the resulting 11 products
total += parseInt(new_value.charAt(i), 10) * weightings[i];
}
// Divide the total by 89, noting the remainder
// If the remainder is zero the number is valid
return total % 89 === 0;
}
};
$.fn.bindABNControls = function () {
this.keydown(function (e) {
if (!ABNControl.permitted_key(e)) {
e.preventDefault();
}
});
// TODO Maintain cursor position?
this.keypress(function (e) {
var value = $(this).val().split(" ").join("");
if (value.length >= 11) {
e.preventDefault();
}
$(this).val(ABNControl.format_abn($(this).val()));
this.setCustomValidity(
ABNControl.validate_abn($(this).val()) ? "" : "Not a valid ABN"
);
});
this.change(function () {
$(this).val(ABNControl.format_abn($(this).val()));
this.setCustomValidity(
ABNControl.validate_abn($(this).val()) ? "" : "Not a valid ABN"
);
});
this.each(function () {
this.setCustomValidity(
ABNControl.validate_abn($(this).val()) ? "" : "Not a valid ABN"
);
});
};
}); | agpl-3.0 |
bitsquare/bitsquare | core/src/main/java/bisq/core/provider/price/PriceRequest.java | 2549 | /*
* This file is part of Bisq.
*
* Bisq 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.
*
* Bisq 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 Bisq. If not, see <http://www.gnu.org/licenses/>.
*/
package bisq.core.provider.price;
import bisq.common.util.Tuple2;
import bisq.common.util.Utilities;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.SettableFuture;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
@Slf4j
public class PriceRequest {
private static final ListeningExecutorService executorService = Utilities.getListeningExecutorService("PriceRequest", 3, 5, 10 * 60);
public PriceRequest() {
}
public SettableFuture<Tuple2<Map<String, Long>, Map<String, MarketPrice>>> requestAllPrices(PriceProvider provider) {
final String baseUrl = provider.getBaseUrl();
final SettableFuture<Tuple2<Map<String, Long>, Map<String, MarketPrice>>> resultFuture = SettableFuture.create();
ListenableFuture<Tuple2<Map<String, Long>, Map<String, MarketPrice>>> future = executorService.submit(() -> {
Thread.currentThread().setName("PriceRequest-" + provider.toString());
return provider.getAll();
});
Futures.addCallback(future, new FutureCallback<Tuple2<Map<String, Long>, Map<String, MarketPrice>>>() {
public void onSuccess(Tuple2<Map<String, Long>, Map<String, MarketPrice>> marketPriceTuple) {
log.trace("Received marketPriceTuple of {}\nfrom provider {}", marketPriceTuple, provider);
resultFuture.set(marketPriceTuple);
}
public void onFailure(@NotNull Throwable throwable) {
resultFuture.setException(new PriceRequestException(throwable, baseUrl));
}
});
return resultFuture;
}
}
| agpl-3.0 |
vincent314/legstar-core2 | legstar-base/src/main/java/com/legstar/base/type/primitive/CobolPackedDecimalType.java | 5729 | package com.legstar.base.type.primitive;
import com.legstar.base.context.CobolContext;
/**
* A Packed Decimal (COMP-3).
*
*/
public class CobolPackedDecimalType<T extends Number> extends
CobolDecimalType < T > {
// COMP-3 might have up to 31 digits (with arith(extend))
public static final int MAX_TOTAL_DIGITS = 31;
/** {@inheritDoc} */
protected boolean isValidInternal(Class < T > javaClass,
CobolContext cobolContext, byte[] hostData, int start) {
int end = start + getBytesLen();
// examine nibbles in each byte in turn
int[] nibbles = new int[2];
// all nibbles, except the last one, must hold valid digits
for (int i = start; i < end - 1; i++) {
setNibbles(nibbles, hostData[i]);
if (!isDigit(nibbles[0]) || !isDigit(nibbles[1])) {
return false;
}
}
// Check last byte
setNibbles(nibbles, hostData[end - 1]);
if (!isDigit(nibbles[0])) {
return false;
}
// Last byte must hold a valid sign (in the right nibble)
if (isSigned()) {
if (nibbles[1] != cobolContext.getPositiveSignNibbleValue()
&& nibbles[1] != cobolContext.getNegativeSignNibbleValue()) {
return false;
}
} else {
if (nibbles[1] != cobolContext.getUnspecifiedSignNibbleValue()) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
protected FromHostPrimitiveResult < T > fromHostInternal(
Class < T > javaClass, CobolContext cobolContext, byte[] hostData,
int start) {
int end = start + getBytesLen();
StringBuffer sb = new StringBuffer();
int[] nibbles = new int[2];
for (int i = start; i < end; i++) {
setNibbles(nibbles, hostData[i]);
char digit0 = getDigit(nibbles[0]);
if (digit0 == '\0') {
return new FromHostPrimitiveResult < T >(
"First nibble is not a digit", hostData, start, i,
getBytesLen());
}
sb.append(digit0);
if (i == end - 1) {
if (isSigned()) {
if (nibbles[1] == cobolContext.getNegativeSignNibbleValue()) {
sb.insert(0, "-");
} else if (nibbles[1] != cobolContext
.getPositiveSignNibbleValue()) {
return new FromHostPrimitiveResult < T >(
"Nibble at sign position does not contain the expected values 0x"
+ Integer.toHexString(cobolContext
.getNegativeSignNibbleValue())
+ " or 0x"
+ Integer.toHexString(cobolContext
.getPositiveSignNibbleValue()),
hostData, start, i, getBytesLen());
}
} else if (nibbles[1] != cobolContext
.getUnspecifiedSignNibbleValue()) {
return new FromHostPrimitiveResult < T >(
"Nibble at sign position does not contain the expected value 0x"
+ Integer.toHexString(cobolContext
.getUnspecifiedSignNibbleValue()),
hostData, start, i, getBytesLen());
}
} else {
char digit1 = getDigit(nibbles[1]);
if (digit1 == '\0') {
return new FromHostPrimitiveResult < T >(
"Second nibble is not a digit", hostData, start, i,
getBytesLen());
}
sb.append(digit1);
}
}
if (getFractionDigits() > 0) {
sb.insert(sb.length() - getFractionDigits(), JAVA_DECIMAL_POINT);
}
try {
T value = valueOf(javaClass, sb.toString());
return new FromHostPrimitiveResult < T >(value);
} catch (NumberFormatException e) {
return new FromHostPrimitiveResult < T >("Host " + getMaxBytesLen()
+ " bytes numeric converts to '" + sb.toString()
+ "' which is not a valid " + javaClass.getName(),
hostData, start, getBytesLen());
}
}
/** {@inheritDoc} */
public int getBytesLen() {
return getBytesLen(getTotalDigits());
}
public static int getBytesLen(int totalDigits) {
return (totalDigits + 2) / 2;
}
// -----------------------------------------------------------------------------
// Builder section
// -----------------------------------------------------------------------------
public static class Builder<T extends Number> extends
CobolDecimalType.Builder < T, Builder < T >> {
public Builder(Class < T > clazz) {
super(clazz, MAX_TOTAL_DIGITS);
}
public CobolPackedDecimalType < T > build() {
return new CobolPackedDecimalType < T >(this);
}
protected Builder < T > self() {
return this;
}
}
// -----------------------------------------------------------------------------
// Constructor
// -----------------------------------------------------------------------------
private CobolPackedDecimalType(Builder < T > builder) {
super(builder);
}
}
| agpl-3.0 |
RussWhitehead/HPCC-Platform | thorlcr/master/thactivitymaster.cpp | 22265 | /*##############################################################################
Copyright (C) 2011 HPCC Systems.
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/>.
############################################################################## */
#include "platform.h"
#include "jprop.hpp"
#include "jstring.hpp"
#include "commonext.hpp"
#include "thgraphmaster.ipp"
#include "thormisc.hpp"
#include "thactivitymaster.ipp"
#include "thexception.hpp"
actmaster_decl CGraphElementBase *createMasterContainer(IPropertyTree &xgmml, CGraphBase &owner, CGraphBase *resultsGraph);
MODULE_INIT(INIT_PRIORITY_STANDARD)
{
registerCreateFunc(createMasterContainer);
return true;
}
#include "action/thaction.ipp"
#include "aggregate/thaggregate.ipp"
#include "apply/thapply.ipp"
#include "catch/thcatch.ipp"
#include "choosesets/thchoosesets.ipp"
#include "countproject/thcountproject.ipp"
#include "csvread/thcsvread.ipp"
#include "diskread/thdiskread.ipp"
#include "diskwrite/thdiskwrite.ipp"
#include "distribution/thdistribution.ipp"
#include "enth/thenth.ipp"
#include "filter/thfilter.ipp"
#include "firstn/thfirstn.ipp"
#include "funnel/thfunnel.ipp"
#include "hashdistrib/thhashdistrib.ipp"
#include "indexread/thindexread.ipp"
#include "indexwrite/thindexwrite.ipp"
#include "iterate/thiterate.ipp"
#include "join/thjoin.ipp"
#include "keydiff/thkeydiff.ipp"
#include "keyedjoin/thkeyedjoin.ipp"
#include "keypatch/thkeypatch.ipp"
#include "limit/thlimit.ipp"
#include "lookupjoin/thlookupjoin.ipp"
#include "msort/thmsort.ipp"
#include "nullaction/thnullaction.ipp"
#include "pipewrite/thpipewrite.ipp"
#include "result/thresult.ipp"
#include "rollup/throllup.ipp"
#include "selectnth/thselectnth.ipp"
#include "spill/thspill.ipp"
#include "topn/thtopn.ipp"
#include "when/thwhen.ipp"
#include "wuidread/thwuidread.ipp"
#include "wuidwrite/thwuidwrite.ipp"
#include "xmlread/thxmlread.ipp"
#include "xmlwrite/thxmlwrite.ipp"
#include "merge/thmerge.ipp"
#include "fetch/thfetch.ipp"
#include "soapcall/thsoapcall.ipp"
#include "loop/thloop.ipp"
class CGenericMasterGraphElement : public CMasterGraphElement
{
public:
CGenericMasterGraphElement(CGraphBase &owner, IPropertyTree &xgmml) : CMasterGraphElement(owner, xgmml)
{
}
virtual void serializeCreateContext(MemoryBuffer &mb)
{
// bit of hack, need to tell slave if wuidread converted to diskread (see master activity)
CMasterGraphElement::serializeCreateContext(mb);
if (kind == TAKworkunitread)
{
if (!activity)
doCreateActivity();
IHThorArg *helper = activity->queryHelper();
IHThorDiskReadArg *diskHelper = QUERYINTERFACE(helper, IHThorDiskReadArg);
mb.append(NULL != diskHelper); // flag to slaves that they should create diskread
if (diskHelper)
mb.append(diskHelper->getFileName());
}
}
virtual CActivityBase *factory(ThorActivityKind kind)
{
CActivityBase *ret = NULL;
switch (kind)
{
case TAKcountdisk:
case TAKfiltergroup:
case TAKlocalresultread:
case TAKchildif:
case TAKdegroup:
case TAKsplit:
case TAKproject:
case TAKprefetchproject:
case TAKprefetchcountproject:
case TAKxmlparse:
case TAKchilditerator:
case TAKrawiterator:
case TAKlinkedrawiterator:
case TAKcatch:
case TAKsample:
case TAKnormalize:
case TAKnormalizechild:
case TAKnormalizelinkedchild:
case TAKgroup:
case TAKtemptable:
case TAKtemprow:
case TAKpull:
case TAKnull:
case TAKpiperead:
case TAKpipethrough:
case TAKparse:
case TAKchildaggregate:
case TAKchildgroupaggregate:
case TAKchildthroughnormalize:
case TAKchildnormalize:
case TAKapply:
case TAKfunnel:
case TAKcombine:
case TAKregroup:
case TAKsorted:
case TAKnwayinput:
case TAKnwayselect:
case TAKnwaymerge:
case TAKnwaymergejoin:
case TAKnwayjoin:
case TAKgraphloopresultread:
case TAKstreamediterator:
ret = new CMasterActivity(this);
break;
case TAKskipcatch:
case TAKcreaterowcatch:
ret = createSkipCatchActivityMaster(this);
break;
case TAKdiskread:
case TAKdisknormalize:
ret = createDiskReadActivityMaster(this);
break;
case TAKdiskaggregate:
ret = createDiskAggregateActivityMaster(this);
break;
case TAKdiskcount:
ret = createDiskCountActivityMaster(this);
break;
case TAKdiskgroupaggregate:
ret = createDiskGroupAggregateActivityMaster(this);
break;
case TAKindexread:
ret = createIndexReadActivityMaster(this);
break;
case TAKindexcount:
ret = createIndexCountActivityMaster(this);
break;
case TAKindexnormalize:
ret = createIndexNormalizeActivityMaster(this);
break;
case TAKindexaggregate:
ret = createIndexAggregateActivityMaster(this);
break;
case TAKindexgroupaggregate:
case TAKindexgroupexists:
case TAKindexgroupcount:
ret = createIndexGroupAggregateActivityMaster(this);
break;
case TAKdiskwrite:
ret = createDiskWriteActivityMaster(this);
break;
case TAKcsvwrite:
ret = createCsvWriteActivityMaster(this);
break;
case TAKspill:
ret = createSpillActivityMaster(this);
break;
case TAKdedup:
case TAKrollup:
case TAKrollupgroup:
ret = createDedupRollupActivityMaster(this);
break;
case TAKfilter:
case TAKfilterproject:
ret = createFilterActivityMaster(this);
break;
case TAKnonempty:
ret = createNonEmptyActivityMaster(this);
break;
case TAKsort:
ret = createSortActivityMaster(this);
break;
case TAKprocess:
case TAKiterate:
ret = createIterateActivityMaster(this);
break;
case TAKthroughaggregate:
ret = createThroughAggregateActivityMaster(this);
break;
case TAKaggregate:
case TAKexistsaggregate:
case TAKcountaggregate:
ret = createAggregateActivityMaster(this);
break;
case TAKhashdistribute:
case TAKpartition:
ret = createHashDistributeActivityMaster(this);
break;
case TAKhashaggregate:
ret = createHashAggregateActivityMaster(this);
break;
case TAKhashjoin:
case TAKhashdenormalize:
case TAKhashdenormalizegroup:
ret= createHashJoinActivityMaster(this);
break;
case TAKkeyeddistribute:
ret = createKeyedDistributeActivityMaster(this);
break;
case TAKhashdistributemerge:
ret = createDistributeMergeActivityMaster(this);
break;
case TAKhashdedup:
ret = createHashDedupMergeActivityMaster(this);
break;
case TAKfirstn:
ret = createFirstNActivityMaster(this);
break;
case TAKjoin:
case TAKselfjoin:
case TAKselfjoinlight:
case TAKdenormalize:
case TAKdenormalizegroup:
ret = createJoinActivityMaster(this);
break;
case TAKlookupjoin:
case TAKalljoin:
case TAKlookupdenormalize:
case TAKlookupdenormalizegroup:
case TAKalldenormalize:
case TAKalldenormalizegroup:
ret = createLookupJoinActivityMaster(this);
break;
case TAKkeyedjoin:
case TAKkeyeddenormalize:
case TAKkeyeddenormalizegroup:
ret = createKeyedJoinActivityMaster(this);
break;
case TAKworkunitwrite:
ret = createWorkUnitWriteActivityMaster(this);
break;
case TAKremoteresult:
ret = createResultActivityMaster(this);
break;
case TAKselectn:
ret = createSelectNthActivityMaster(this);
break;
case TAKenth:
ret = createEnthActivityMaster(this);
break;
case TAKdistribution:
ret = createDistributionActivityMaster(this);
break;
case TAKcountproject:
ret = createCountProjectActivityMaster(this);
break;
case TAKchoosesets:
ret = createChooseSetsActivityMaster(this);
break;
case TAKchoosesetsenth:
case TAKchoosesetslast:
ret = createChooseSetsPlusActivityMaster(this);
break;
case TAKpipewrite:
ret = createPipeWriteActivityMaster(this);
break;
case TAKcsvread:
ret = createCCsvReadActivityMaster(this);
break;
case TAKindexwrite:
ret = createIndexWriteActivityMaster(this);
break;
case TAKfetch:
ret = createFetchActivityMaster(this);
break;
case TAKcsvfetch:
ret = createCsvFetchActivityMaster(this);
break;
case TAKxmlfetch:
ret = createXmlFetchActivityMaster(this);
break;
case TAKworkunitread:
ret = createWorkUnitActivityMaster(this);
break;
case TAKsideeffect:
ret = createNullActionActivityMaster(this);
break;
case TAKsimpleaction:
ret = createActionActivityMaster(this);
break;
case TAKtopn:
ret = createTopNActivityMaster(this);
break;
case TAKxmlread:
ret = createXmlReadActivityMaster(this);
break;
case TAKxmlwrite:
ret = createXmlWriteActivityMaster(this);
break;
case TAKmerge:
ret = createMergeActivityMaster(this);
break;
case TAKsoap_rowdataset:
case TAKsoap_rowaction:
case TAKsoap_datasetdataset:
case TAKsoap_datasetaction:
ret = createSoapCallActivityMaster(this);
break;
case TAKkeydiff:
ret = createKeyDiffActivityMaster(this);
break;
case TAKkeypatch:
ret = createKeyPatchActivityMaster(this);
break;
case TAKlimit:
case TAKskiplimit:
case TAKcreaterowlimit:
ret = createLimitActivityMaster(this);
break;
case TAKlooprow:
case TAKloopcount:
ret = createLoopActivityMaster(this);
break;
case TAKgraphloop:
case TAKparallelgraphloop:
ret = createGraphLoopActivityMaster(this);
break;
case TAKloopdataset:
throw MakeThorException(0, "Thor currently, does not support a dataset loop condition, activity id: %"ACTPF"d", queryId());
case TAKlocalresultspill:
case TAKlocalresultwrite:
ret = createLocalResultActivityMaster(this);
break;
case TAKgraphloopresultwrite:
ret = createGraphLoopResultActivityMaster(this);
break;
case TAKchilddataset:
UNIMPLEMENTED;
case TAKcase: // gen. time.
case TAKif:
throwUnexpected();
case TAKwhen:
ret = createWhenActivityMaster(this);
break;
case TAKifaction:
ret = createIfActionActivityMaster(this);
break;
default:
throw MakeActivityException(this, TE_UnsupportedActivityKind, "Unsupported activity kind: %s", activityKindStr(kind));
}
return ret;
}
};
actmaster_decl CGraphElementBase *createMasterContainer(IPropertyTree &xgmml, CGraphBase &owner, CGraphBase *resultsGraph)
{
return new CGenericMasterGraphElement(owner, xgmml);
}
void updateActivityResult(IConstWorkUnit &workunit, unsigned helperFlags, unsigned sequence, const char *logicalFilename, unsigned __int64 recordCount)
{
Owned<IWorkUnit> wu = &workunit.lock();
Owned<IWUResult> r;
r.setown(wu->updateResultBySequence(sequence));
r->setResultTotalRowCount(recordCount);
r->setResultStatus(ResultStatusCalculated);
if (TDWresult & helperFlags)
r->setResultFilename(logicalFilename);
else
r->setResultLogicalName(logicalFilename);
r.clear();
wu.clear();
}
void CSlavePartMapping::getParts(unsigned i, IArrayOf<IPartDescriptor> &parts)
{
if (local)
i = 0;
if (i>=maps.ordinality()) return;
CSlaveMap &map = maps.item(i);
ForEachItemIn(m, map)
parts.append(*LINK(&map.item(m)));
}
void CSlavePartMapping::serializeNullMap(MemoryBuffer &mb)
{
mb.append((unsigned)0);
}
void CSlavePartMapping::serializeNullOffsetMap(MemoryBuffer &mb)
{
mb.append((unsigned)0);
}
void CSlavePartMapping::serializeMap(unsigned i, MemoryBuffer &mb, IGetSlaveData *extra)
{
if (local)
i = 0;
if (i >= maps.ordinality())
{
mb.append((unsigned)0);
return;
}
CSlaveMap &map = maps.item(i);
unsigned nPos = mb.length();
unsigned n=0;
mb.append(n);
UnsignedArray parts;
ForEachItemIn(m, map)
parts.append(map.item(m).queryPartIndex());
MemoryBuffer extraMb;
if (extra)
{
ForEachItemIn(m2, map)
{
unsigned xtraLen = 0;
unsigned xtraPos = extraMb.length();
extraMb.append(xtraLen);
IPartDescriptor &partDesc = map.item(m2);
if (!extra->getData(m2, partDesc.queryPartIndex(), extraMb))
{
parts.zap(partDesc.queryPartIndex());
extraMb.rewrite(xtraPos);
}
else
{
xtraLen = (extraMb.length()-xtraPos)-sizeof(xtraLen);
extraMb.writeDirect(xtraPos, sizeof(xtraLen), &xtraLen);
}
}
}
n = parts.ordinality();
mb.writeDirect(nPos, sizeof(n), &n);
if (n)
{
fileDesc->serializeParts(mb, parts);
mb.append(extraMb);
}
}
CSlavePartMapping::CSlavePartMapping(const char *_logicalName, IFileDescriptor &_fileDesc, IUserDescriptor *_userDesc, IGroup &localGroup, bool _local, bool index, IHash *hash, IDistributedSuperFile *super)
: fileDesc(&_fileDesc), userDesc(_userDesc), local(_local)
{
unsigned maxWidth = local ? 1 : localGroup.ordinality();
logicalName.set(_logicalName);
fileWidth = fileDesc->numParts();
if (super && fileWidth)
{
bool merge = index;
unsigned _maxWidth = super->querySubFile(0,true).numParts();
if (_maxWidth > 1)
{
if (index)
{
fileWidth -= super->numSubFiles(true); // tlk's
if (merge)
_maxWidth -= 1; // tlk
}
if (merge && _maxWidth < maxWidth)
maxWidth = _maxWidth;
}
}
else if (index && fileWidth>1)
fileWidth -= 1;
unsigned p;
unsigned which = 0;
if (fileWidth<=maxWidth || NULL!=hash)
{
if (fileWidth>maxWidth && 0 != fileWidth % maxWidth)
throw MakeThorException(0, "Unimplemented - attempting to read distributed file (%s), on smaller cluster that is not a factor of original", logicalName.get());
for (p=0; p<fileWidth; p++)
{
Owned<IPartDescriptor> partDesc = fileDesc->getPart(p);
CSlaveMap *map;
if (maps.isItem(which))
map = &maps.item(which);
else
{
map = new CSlaveMap();
maps.append(*map);
}
map->append(*LINK(partDesc));
partToNode.append(which);
which++;
if (which>=maxWidth) which = 0;
}
}
else
{
unsigned tally = 0;
for (p=0; p<fileWidth; p++)
{
Owned<IPartDescriptor> partDesc = fileDesc->getPart(p);
CSlaveMap *map;
if (maps.isItem(which))
map = &maps.item(which);
else
{
map = new CSlaveMap();
maps.append(*map);
}
map->append(*LINK(partDesc));
partToNode.append(which);
tally += maxWidth;
if (tally >= fileWidth)
{
tally -= fileWidth;
which++;
}
}
}
}
#include "../activities/fetch/thfetchcommon.hpp"
void CSlavePartMapping::serializeFileOffsetMap(MemoryBuffer &mb)
{
mb.append(fileWidth);
unsigned pos = mb.length();
mb.append((unsigned)0);
ForEachItemIn(sm, maps)
{
CSlaveMap &map = maps.item(sm);
ForEachItemIn(m, map)
{
IPartDescriptor &partDesc = map.item(m);
IPropertyTree &props = partDesc.queryProperties();
FPosTableEntry entry;
entry.base = props.getPropInt64("@offset"); // should check
entry.top = entry.base+props.getPropInt64("@size"); // was -1?
entry.index = sm;
mb.append(sizeof(FPosTableEntry), &entry);
}
}
unsigned l = mb.length()-pos-sizeof(unsigned);
mb.writeDirect(pos, sizeof(unsigned), &l);
}
CSlavePartMapping *getFileSlaveMaps(const char *logicalName, IFileDescriptor &fileDesc, IUserDescriptor *userDesc, IGroup &localGroup, bool local, bool index, IHash *hash, IDistributedSuperFile *super)
{
return new CSlavePartMapping(logicalName, fileDesc, userDesc, localGroup, local, index, hash, super);
}
WUFileKind getDiskOutputKind(unsigned flags)
{
if (TDXtemporary & flags)
return WUFileTemporary;
else if(TDXjobtemp & flags)
return WUFileJobOwned;
else if(TDWowned & flags)
return WUFileOwned;
else
return WUFileStandard;
}
void checkSuperFileOwnership(IDistributedFile &file)
{
if (file.queryProperties().hasProp("SuperOwner"))
{
StringBuffer owners;
Owned<IPropertyTreeIterator> iter = file.queryProperties().getElements("SuperOwner");
if (iter->first())
{
loop
{
iter->query().getProp(NULL, owners);
if (!iter->next())
break;
owners.append(", ");
}
}
throw MakeStringException(TE_MemberOfSuperFile, "Cannot write %s, as owned by superfile(s): %s", file.queryLogicalName(), owners.str());
}
}
void checkFormatCrc(CActivityBase *activity, IDistributedFile *file, unsigned helperCrc, bool index)
{
IDistributedFile *f = file;
IDistributedSuperFile *super = f->querySuperFile();
Owned<IDistributedFileIterator> iter;
if (super)
{
iter.setown(super->getSubFileIterator(true));
verifyex(iter->first());
f = &iter->query();
}
StringBuffer kindStr(activityKindStr(activity->queryContainer().getKind()));
loop
{
unsigned dfsCrc;
if (f->getFormatCrc(dfsCrc) && helperCrc != dfsCrc)
{
StringBuffer fileStr;
if (super) fileStr.append("Superfile: ").append(file->queryLogicalName()).append(", subfile: ");
else fileStr.append("File: ");
fileStr.append(f->queryLogicalName());
Owned<IThorException> e = MakeActivityException(activity, TE_FormatCrcMismatch, "%s: Layout does not match published layout. %s", kindStr.str(), fileStr.str());
if (index && !f->queryProperties().hasProp("_record_layout")) // Cannot verify if _true_ crc mismatch if soft layout missing anymore
LOG(MCwarning, thorJob, e);
else
{
if (!activity->queryContainer().queryJob().getWorkUnitValueInt("skipFileFormatCrcCheck", 0))
throw LINK(e);
e->setAction(tea_warning);
activity->fireException(e);
}
}
if (!super||!iter->next())
break;
f = &iter->query();
}
}
void loadMasters()
{
}
| agpl-3.0 |
ayssi/Biblimetrics-Data-processing | test.py | 199 | ceci est un test ....
ceci est un test ....
ceci est un test ....
ceci est un test ....
ceci est un test ....
Ligne rajoutée le 07 avril 2020 à 00.09
Ligne 2 rajoutée le 07 avril 2020 à 19.09
| agpl-3.0 |
BillRun/system | library/Billrun/Template/Token/Base.php | 3720 | <?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
class Billrun_Template_Token_Base {
/**
* Base array instances container
*
* @var array
*/
static protected $instance = array();
protected $replacers = array();
protected $replacer_class_prefix = 'Billrun_Template_Token_Replacers_';
protected $replacer_token_pattern = '/(\[{2}[\w\d]+::[\w\d]+\]{2})/';
public function __construct($settings) {
$tokens_categories = $this->getTokensCategories();
$this->initTokensReplacers($tokens_categories);
}
/**
* Loose coupling of objects in the system
*
* @return mixed the bridge class
*/
static public function getInstance() {
$args = func_get_args();
$stamp = md5(serialize($args));
if (isset(self::$instance[$stamp])) {
return self::$instance[$stamp];
}
$called_class = get_called_class();
if ($called_class && Billrun_Factory::config()->getConfigValue('TemplateTokens')) {
$args = array_merge(Billrun_Factory::config()->getConfigValue($called_class)->toArray(), $args);
}
self::$instance[$stamp] = new $called_class($args);
return self::$instance[$stamp];
}
/**
* Return avalible tokens array by category
*
* @return Array
*/
public function getTokens() {
$tokens = array();
foreach ($this->replacers as $category => $replacer) {
$tokens[$category] = $replacer->getAvailableTokens();
}
return $tokens;
}
/**
* Function to replace string tokens
*
* @param String $string the string with tokens
* @param Array $params data for replaccers by categort
* @return String with replaced tokens
*/
public function replaceTokens($string, $params) {
$string_tokens = $this->parseStringTokens($string);
//get all unique tokens
foreach ($string_tokens as $category => $tokens_match) {
$this->replacers[$category]->setData($params[$category]);
foreach ($tokens_match['value'] as $key => $value) {
$string_tokens[$category]['replace'][$key] = $this->replacers[$category]->replaceTokens($value);
}
}
//replace tokens with values
foreach ($string_tokens as $tokens_type) {
foreach ($tokens_type['matche'] as $key => $matche) {
$string = str_replace($matche, $tokens_type['replace'][$key], $string);
}
}
return $string;
}
protected function getTokensCategories() {
$conf = Billrun_Config::getInstance(new Yaf_Config_Ini(APPLICATION_PATH . '/conf/TemplateTokens/conf.ini'));
$tokens_categories = $conf->getConfigValue("templateTokens.enabled", array());
return $tokens_categories;
}
protected function initTokensReplacers($tokens_categories) {
if(!empty($tokens_categories) && is_array($tokens_categories)){
foreach ($tokens_categories as $category) {
if(!isset($this->replacers[$category])){
$replacer_class = $this->replacer_class_prefix . ucfirst($category);
$this->replacers[$category] = new $replacer_class();
}
}
}
}
protected function parseStringTokens($string) {
$tokens = array();
$matches = array();
preg_match_all($this->replacer_token_pattern, $string, $matches);
if (!empty($matches[0]) && is_array($matches[0])) {
foreach ($matches[0] as $matche) {
$trimed_matche = trim($matche, "[]");
$exploded_matche = explode("::", $trimed_matche);
if (empty($tokens[$exploded_matche[0]])) {
$tokens[$exploded_matche[0]] = array();
}
if (!in_array($exploded_matche[1], $tokens[$exploded_matche[0]]['value'])) {
$tokens[$exploded_matche[0]]['value'][] = $exploded_matche[1];
$tokens[$exploded_matche[0]]['matche'][] = $matche;
}
}
}
return $tokens;
}
}
| agpl-3.0 |
eileenmcnaughton/nz.co.fuzion.omnipaymultiprocessor | vendor/moneyphp/money/tests/Parser/DecimalMoneyParserTest.php | 4251 | <?php
namespace Tests\Money\Parser;
use Money\Currencies;
use Money\Currency;
use Money\Exception\ParserException;
use Money\Parser\DecimalMoneyParser;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
final class DecimalMoneyParserTest extends TestCase
{
/**
* @dataProvider formattedMoneyExamples
* @test
*/
public function it_parses_money($decimal, $currency, $subunit, $result)
{
$currencies = $this->prophesize(Currencies::class);
$currencies->subunitFor(Argument::allOf(
Argument::type(Currency::class),
Argument::which('getCode', $currency)
))->willReturn($subunit);
$parser = new DecimalMoneyParser($currencies->reveal());
$this->assertEquals($result, $parser->parse($decimal, new Currency($currency))->getAmount());
}
/**
* @dataProvider invalidMoneyExamples
* @test
*/
public function it_throws_an_exception_upon_invalid_inputs($input)
{
$currencies = $this->prophesize(Currencies::class);
$currencies->subunitFor(Argument::allOf(
Argument::type(Currency::class),
Argument::which('getCode', 'USD')
))->willReturn(2);
$parser = new DecimalMoneyParser($currencies->reveal());
$this->expectException(ParserException::class);
$parser->parse($input, new Currency('USD'))->getAmount();
}
/**
* @group legacy
* @expectedDeprecation Passing a currency as string is deprecated since 3.1 and will be removed in 4.0. Please pass a Money\Currency instance instead.
* @test
*/
public function it_accepts_only_a_currency_object()
{
$currencies = $this->prophesize(Currencies::class);
$currencies->subunitFor(Argument::allOf(
Argument::type(Currency::class),
Argument::which('getCode', 'USD')
))->willReturn(2);
$parser = new DecimalMoneyParser($currencies->reveal());
$parser->parse('1.0', 'USD')->getAmount();
}
public function formattedMoneyExamples()
{
return [
['1000.50', 'USD', 2, 100050],
['1000.00', 'USD', 2, 100000],
['1000.0', 'USD', 2, 100000],
['1000', 'USD', 2, 100000],
['0.01', 'USD', 2, 1],
['0.00', 'USD', 2, 0],
['1', 'USD', 2, 100],
['-1000.50', 'USD', 2, -100050],
['-1000.00', 'USD', 2, -100000],
['-1000.0', 'USD', 2, -100000],
['-1000', 'USD', 2, -100000],
['-0.01', 'USD', 2, -1],
['-1', 'USD', 2, -100],
['1000.501', 'USD', 3, 1000501],
['1000.001', 'USD', 3, 1000001],
['1000.50', 'USD', 3, 1000500],
['1000.00', 'USD', 3, 1000000],
['1000.0', 'USD', 3, 1000000],
['1000', 'USD', 3, 1000000],
['0.001', 'USD', 3, 1],
['0.01', 'USD', 3, 10],
['1', 'USD', 3, 1000],
['-1000.501', 'USD', 3, -1000501],
['-1000.001', 'USD', 3, -1000001],
['-1000.50', 'USD', 3, -1000500],
['-1000.00', 'USD', 3, -1000000],
['-1000.0', 'USD', 3, -1000000],
['-1000', 'USD', 3, -1000000],
['-0.001', 'USD', 3, -1],
['-0.01', 'USD', 3, -10],
['-1', 'USD', 3, -1000],
['1000.50', 'JPY', 0, 1001],
['1000.00', 'JPY', 0, 1000],
['1000.0', 'JPY', 0, 1000],
['1000', 'JPY', 0, 1000],
['0.01', 'JPY', 0, 0],
['1', 'JPY', 0, 1],
['-1000.50', 'JPY', 0, -1001],
['-1000.00', 'JPY', 0, -1000],
['-1000.0', 'JPY', 0, -1000],
['-1000', 'JPY', 0, -1000],
['-0.01', 'JPY', 0, -0],
['-1', 'JPY', 0, -1],
['', 'USD', 2, 0],
['.99', 'USD', 2, 99],
['99.', 'USD', 2, 9900],
['-9.999', 'USD', 2, -1000],
['9.999', 'USD', 2, 1000],
['9.99', 'USD', 2, 999],
['-9.99', 'USD', 2, -999],
];
}
public static function invalidMoneyExamples()
{
return [
['INVALID'],
['.'],
];
}
}
| agpl-3.0 |
scylladb/scylla | sstables/sstable_mutation_reader.hh | 10071 | /*
* Copyright (C) 2015-present ScyllaDB
*/
/*
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
#include "mutation.hh"
#include "sstables.hh"
#include "types.hh"
#include <seastar/core/future-util.hh>
#include <seastar/core/coroutine.hh>
#include "key.hh"
#include "keys.hh"
#include <seastar/core/do_with.hh>
#include "unimplemented.hh"
#include "dht/i_partitioner.hh"
#include <seastar/core/byteorder.hh>
#include "index_reader.hh"
#include "counters.hh"
#include "utils/data_input.hh"
#include "clustering_ranges_walker.hh"
#include "binary_search.hh"
#include "../dht/i_partitioner.hh"
#include "flat_mutation_reader_v2.hh"
#include "sstables/mx/partition_reversing_data_source.hh"
namespace sstables {
namespace kl {
class mp_row_consumer_k_l;
}
namespace mx {
class mp_row_consumer_m;
}
class mp_row_consumer_reader_base {
protected:
shared_sstable _sst;
// Whether index lower bound is in current partition
bool _index_in_current_partition = false;
// True iff the consumer finished generating fragments for a partition and hasn't
// entered the new partition yet.
// Implies that partition_end was emitted for the last partition.
// Will cause the reader to skip to the next partition if !_before_partition.
bool _partition_finished = true;
// When set, the consumer is positioned right before a partition or at end of the data file.
// _index_in_current_partition applies to the partition which is about to be read.
bool _before_partition = true;
std::optional<dht::decorated_key> _current_partition_key;
public:
mp_row_consumer_reader_base(shared_sstable sst)
: _sst(std::move(sst))
{ }
// Called when all fragments relevant to the query range or fast forwarding window
// within the current partition have been pushed.
// If no skipping is required, this method may not be called before transitioning
// to the next partition.
virtual void on_out_of_clustering_range() = 0;
};
class mp_row_consumer_reader_k_l : public mp_row_consumer_reader_base, public flat_mutation_reader::impl {
friend class sstables::kl::mp_row_consumer_k_l;
public:
mp_row_consumer_reader_k_l(schema_ptr s, reader_permit permit, shared_sstable sst)
: mp_row_consumer_reader_base(std::move(sst))
, impl(std::move(s), std::move(permit))
{}
void on_next_partition(dht::decorated_key, tombstone);
};
inline atomic_cell make_atomic_cell(const abstract_type& type,
api::timestamp_type timestamp,
fragmented_temporary_buffer::view value,
gc_clock::duration ttl,
gc_clock::time_point expiration,
atomic_cell::collection_member cm) {
if (ttl != gc_clock::duration::zero()) {
return atomic_cell::make_live(type, timestamp, value, expiration, ttl, cm);
} else {
return atomic_cell::make_live(type, timestamp, value, cm);
}
}
atomic_cell make_counter_cell(api::timestamp_type timestamp, fragmented_temporary_buffer::view value);
position_in_partition_view get_slice_upper_bound(const schema& s, const query::partition_slice& slice, dht::ring_position_view key);
// data_consume_rows() iterates over rows in the data file from
// a particular range, feeding them into the consumer. The iteration is
// done as efficiently as possible - reading only the data file (not the
// summary or index files) and reading data in batches.
//
// The consumer object may request the iteration to stop before reaching
// the end of the requested data range (e.g. stop after each sstable row).
// A context object is returned which allows to resume this consumption:
// This context's read() method requests that consumption begins, and
// returns a future which will be resolved when it ends (because the
// consumer asked to stop, or the data range ended). Only after the
// returned future is resolved, may read() be called again to consume
// more.
// The caller must ensure (e.g., using do_with()) that the context object,
// as well as the sstable, remains alive as long as a read() is in
// progress (i.e., returned a future which hasn't completed yet).
//
// The "toread" range specifies the range we want to read initially.
// However, the object returned by the read, a data_consume_context, also
// provides a fast_forward_to(start,end) method which allows resetting
// the reader to a new range. To allow that, we also have a "last_end"
// byte which should be the last end to which fast_forward_to is
// eventually allowed. If last_end==end, fast_forward_to is not allowed
// at all, if last_end==file_size fast_forward_to is allowed until the
// end of the file, and it can be something in between if we know that we
// are planning to skip parts, but eventually read until last_end.
// When last_end==end, we guarantee that the read will only read the
// desired byte range from disk. However, when last_end > end, we may
// read beyond end in anticipation of a small skip via fast_foward_to.
// The amount of this excessive read is controlled by read ahead
// hueristics which learn from the usefulness of previous read aheads.
template <typename DataConsumeRowsContext>
inline std::unique_ptr<DataConsumeRowsContext> data_consume_rows(const schema& s, shared_sstable sst, typename DataConsumeRowsContext::consumer& consumer, sstable::disk_read_range toread, uint64_t last_end) {
// Although we were only asked to read until toread.end, we'll not limit
// the underlying file input stream to this end, but rather to last_end.
// This potentially enables read-ahead beyond end, until last_end, which
// can be beneficial if the user wants to fast_forward_to() on the
// returned context, and may make small skips.
auto input = sst->data_stream(toread.start, last_end - toread.start, consumer.io_priority(),
consumer.permit(), consumer.trace_state(), sst->_partition_range_history);
return std::make_unique<DataConsumeRowsContext>(s, std::move(sst), consumer, std::move(input), toread.start, toread.end - toread.start);
}
template <typename DataConsumeRowsContext>
struct reversed_context {
std::unique_ptr<DataConsumeRowsContext> the_context;
// Underneath, the context is iterating over the sstable file in reverse order.
// This points to the current position of the context over the underlying sstable file;
// either the end of partition or the beginning of some row (never in the middle of a row).
// The reference is valid as long as the context is alive.
const uint64_t& current_position_in_sstable;
};
// See `sstables::mx::make_partition_reversing_data_source` for documentation.
template <typename DataConsumeRowsContext>
inline reversed_context<DataConsumeRowsContext> data_consume_reversed_partition(
const schema& s, shared_sstable sst, index_reader& ir,
typename DataConsumeRowsContext::consumer& consumer, sstable::disk_read_range toread) {
auto reversing_data_source = sstables::mx::make_partition_reversing_data_source(
s, sst, ir, toread.start, toread.end - toread.start,
consumer.permit(), consumer.io_priority(), consumer.trace_state());
return reversed_context<DataConsumeRowsContext> {
.the_context = std::make_unique<DataConsumeRowsContext>(
s, std::move(sst), consumer, input_stream<char>(std::move(reversing_data_source.the_source)),
toread.start, toread.end - toread.start),
.current_position_in_sstable = reversing_data_source.current_position_in_sstable
};
}
template <typename DataConsumeRowsContext>
inline std::unique_ptr<DataConsumeRowsContext> data_consume_single_partition(const schema& s, shared_sstable sst, typename DataConsumeRowsContext::consumer& consumer, sstable::disk_read_range toread) {
auto input = sst->data_stream(toread.start, toread.end - toread.start, consumer.io_priority(),
consumer.permit(), consumer.trace_state(), sst->_single_partition_history);
return std::make_unique<DataConsumeRowsContext>(s, std::move(sst), consumer, std::move(input), toread.start, toread.end - toread.start);
}
// Like data_consume_rows() with bounds, but iterates over whole range
template <typename DataConsumeRowsContext>
inline std::unique_ptr<DataConsumeRowsContext> data_consume_rows(const schema& s, shared_sstable sst, typename DataConsumeRowsContext::consumer& consumer) {
auto data_size = sst->data_size();
return data_consume_rows<DataConsumeRowsContext>(s, std::move(sst), consumer, {0, data_size}, data_size);
}
template<typename T>
concept RowConsumer =
requires(T t,
const partition_key& pk,
position_range cr) {
{ t.io_priority() } -> std::convertible_to<const io_priority_class&>;
{ t.is_mutation_end() } -> std::same_as<bool>;
{ t.setup_for_partition(pk) } -> std::same_as<void>;
{ t.push_ready_fragments() } -> std::same_as<void>;
{ t.maybe_skip() } -> std::same_as<std::optional<position_in_partition_view>>;
{ t.fast_forward_to(std::move(cr)) } -> std::same_as<std::optional<position_in_partition_view>>;
};
/*
* Helper method to set or reset the range tombstone start bound according to the
* end open marker of a promoted index block.
*
* Only applies to consumers that have the following methods:
* void reset_range_tombstone_start();
* void set_range_tombstone_start(clustering_key_prefix, bound_kind, tombstone);
*
* For other consumers, it is a no-op.
*/
template <typename Consumer>
void set_range_tombstone_start_from_end_open_marker(Consumer& c, const schema& s, const index_reader& idx) {
if constexpr (Consumer::is_setting_range_tombstone_start_supported) {
auto open_end_marker = idx.end_open_marker();
if (open_end_marker) {
auto[pos, tomb] = *open_end_marker;
c.set_range_tombstone_start(tomb);
}
}
}
}
| agpl-3.0 |
cadr-sa/fengoffice | public/upgrade/console.php | 1325 | <?php
define('ROOT', dirname(__FILE__) . '/../..');
define('PRODUCT_NAME', 'Feng Office');
define('PRODUCT_URL', 'http://www.fengoffice.com');
require_once dirname(__FILE__) . '/include.php';
if(!isset($argv) || !is_array($argv)) {
die('There is no input arguments');
} // if
if (count($argv) == 1) {
if (!file_exists(ROOT."/config/installed_version.php")) {
die('File does not exists: config/installed_version.php');
}
$from_version = include ROOT."/config/installed_version.php";
$to_version = include ROOT."/version.php";
} else { // version number received in parameters
$from_version = array_var($argv, 1);
$to_version = array_var($argv, 2);
if(trim($from_version) == '') {
die('First argument (current version) is required');
} // if
if(trim($to_version) == '') {
die('Second argument (to version) is required');
} // if
}
// Construct the upgrader and load the scripts
$upgrader = new ScriptUpgrader(new Output_Console(), 'Upgrade Feng Office', 'Upgrade your Feng Office installation');
$upgrader->upgrade($from_version, $to_version);
echo date("Y-m-d H:i:s") . " - Updating plugins...\n";
if (substr(php_uname(), 0, 5) == "Linux") {
$command = "php ".ROOT."/public/install/plugin-console.php update_all";
exec("$command");
}
echo date("Y-m-d H:i:s") . " - Finished plugins update.\n";
?> | agpl-3.0 |
inad9300/Soil | examples/counter_rollup/rollup.config.js | 341 | import resolve from 'rollup-plugin-node-resolve'
import typescript from 'rollup-plugin-typescript'
export default {
input: './src/main.ts',
output: {
file: 'build/main.js',
format: 'iife'
},
treeshake: {
pureExternalModules: true
},
plugins: [
resolve(),
typescript()
]
}
| agpl-3.0 |
elki-project/elki | elki-core-distance/src/main/java/elki/distance/minkowski/MaximumDistance.java | 5561 | /*
* This file is part of ELKI:
* Environment for Developing KDD-Applications Supported by Index-Structures
*
* Copyright (C) 2019
* ELKI Development Team
*
* 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 elki.distance.minkowski;
import elki.data.NumberVector;
import elki.data.spatial.SpatialComparable;
import elki.utilities.Alias;
import elki.utilities.optionhandling.Parameterizer;
/**
* Maximum distance for {@link NumberVector}s.
* <p>
* The maximum distance is defined as:
* \[ \text{Maximum}(\vec{x},\vec{y}) := \max_i |x_i-y_i| \]
* and can be seen as limiting case of the {@link LPNormDistance}
* for \( p \rightarrow \infty \).
*
* @author Erich Schubert
* @since 0.3
*/
@Alias({ "maximum", "max", "chebyshev" })
public class MaximumDistance extends LPNormDistance {
/**
* Static instance.
*/
public static final MaximumDistance STATIC = new MaximumDistance();
/**
* Constructor - use {@link #STATIC} instead.
*
* @deprecated Use static instance!
*/
@Deprecated
public MaximumDistance() {
super(Double.POSITIVE_INFINITY);
}
private double preDistance(NumberVector v1, NumberVector v2, int start, int end) {
double agg = 0.;
for(int d = start; d < end; d++) {
final double xd = v1.doubleValue(d), yd = v2.doubleValue(d);
final double delta = xd >= yd ? xd - yd : yd - xd;
agg = delta >= agg ? delta : agg;
}
return agg;
}
private double preDistanceVM(NumberVector v, SpatialComparable mbr, int start, int end) {
double agg = 0.;
for(int d = start; d < end; d++) {
final double value = v.doubleValue(d), min = mbr.getMin(d);
double delta = min - value;
delta = delta >= 0 ? delta : value - mbr.getMax(d);
agg = delta >= agg ? delta : agg;
}
return agg;
}
private double preDistanceMBR(SpatialComparable mbr1, SpatialComparable mbr2, int start, int end) {
double agg = 0.;
for(int d = start; d < end; d++) {
double delta = mbr2.getMin(d) - mbr1.getMax(d);
delta = delta >= 0 ? delta : mbr1.getMin(d) - mbr2.getMax(d);
agg = delta >= agg ? delta : agg;
}
return agg;
}
private double preNorm(NumberVector v, int start, int end) {
double agg = 0.;
for(int d = start; d < end; d++) {
final double xd = v.doubleValue(d);
final double delta = xd >= 0. ? xd : -xd;
agg = delta >= agg ? delta : agg;
}
return agg;
}
private double preNormMBR(SpatialComparable mbr, int start, int end) {
double agg = 0.;
for(int d = start; d < end; d++) {
double delta = mbr.getMin(d);
delta = delta >= 0 ? delta : -mbr.getMax(d);
agg = delta >= agg ? delta : agg;
}
return agg;
}
@Override
public double distance(NumberVector v1, NumberVector v2) {
final int dim1 = v1.getDimensionality(), dim2 = v2.getDimensionality();
final int mindim = dim1 < dim2 ? dim1 : dim2;
double agg = preDistance(v1, v2, 0, mindim);
if(dim1 > mindim) {
double b = preNorm(v1, mindim, dim1);
agg = agg >= b ? agg : b;
}
else if(dim2 > mindim) {
double b = preNorm(v2, mindim, dim2);
agg = agg >= b ? agg : b;
}
return agg;
}
@Override
public double norm(NumberVector v) {
return preNorm(v, 0, v.getDimensionality());
}
@Override
public double minDist(SpatialComparable mbr1, SpatialComparable mbr2) {
final int dim1 = mbr1.getDimensionality(), dim2 = mbr2.getDimensionality();
final int mindim = dim1 < dim2 ? dim1 : dim2;
final NumberVector v1 = (mbr1 instanceof NumberVector) ? (NumberVector) mbr1 : null;
final NumberVector v2 = (mbr2 instanceof NumberVector) ? (NumberVector) mbr2 : null;
double agg = (v1 != null) //
? (v2 != null) ? preDistance(v1, v2, 0, mindim) : preDistanceVM(v1, mbr2, 0, mindim) //
: (v2 != null) ? preDistanceVM(v2, mbr1, 0, mindim) : preDistanceMBR(mbr1, mbr2, 0, mindim);
// first object has more dimensions.
if(dim1 > mindim) {
double b = (v1 != null) ? preNorm(v1, mindim, dim1) : preNormMBR(mbr1, mindim, dim1);
agg = agg >= b ? agg : b;
}
// second object has more dimensions.
if(dim2 > mindim) {
double b = (v2 != null) ? preNorm(v2, mindim, dim2) : preNormMBR(mbr2, mindim, dim2);
agg = agg >= b ? agg : b;
}
return agg;
}
@Override
public boolean isMetric() {
return true;
}
@Override
public String toString() {
return "MaximumDistance";
}
@Override
public boolean equals(Object obj) {
return obj == this || (obj != null && this.getClass().equals(obj.getClass()));
}
@Override
public int hashCode() {
return getClass().hashCode();
}
/**
* Parameterization class.
*
* @author Erich Schubert
*/
public static class Par implements Parameterizer {
@Override
public MaximumDistance make() {
return MaximumDistance.STATIC;
}
}
}
| agpl-3.0 |
martinly/Traversal_disk | Traversal_disk.py | 642 | #file:Traversal_disk.py
#encoding=utf-8
import os
def travelTree(currentPath,count):
f=open('out88.txt','a')
if not os.path.exists(currentPath):
return
if os.path.isfile(currentPath):
#fileName=os.path.basename(currentPath)
fileName=os.path.basename(currentPath)
print '\t'*count +'|~~'+ fileName
elif os.path.isdir(currentPath):
print '\t'*count +'|~~'+ currentPath
pathList=os.listdir(currentPath)
for eachPath in pathList:
travelTree(currentPath + '/'+ eachPath,count +1)
f.write(currentPath+'/'+ eachPath+'\n')
f.close()
c=raw_input("Please input the disk you want travel(Not C):")
travelTree(c,1)
| agpl-3.0 |
k10r/shopware | engine/Shopware/Bundle/SearchBundleDBAL/ConditionHandler/DynamicConditionParserTrait.php | 8508 | <?php
/**
* Shopware 5
* Copyright (c) shopware AG
*
* 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 with an additional
* permission and of our proprietary license can be found at and
* 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.
*
* "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, title and interest in
* our trademarks remain entirely with us.
*/
namespace Shopware\Bundle\SearchBundleDBAL\ConditionHandler;
use Doctrine\DBAL\Connection;
use Shopware\Bundle\SearchBundle\Condition\ProductAttributeCondition as Condition;
use Shopware\Bundle\SearchBundleDBAL\QueryBuilder;
trait DynamicConditionParserTrait
{
/**
* Adds base conditions to a query builder object
* NOTE: The method will also verify that the column to be compared actually exists in the table.
*
* @param QueryBuilder $query
* @param string $table table name
* @param string $tableAlias table alias in query
* @param string $field Field to be used in the comparisons
* @param array|string|null $value
* @param string|null $operator
*
* @throws \InvalidArgumentException If field value is empty (code: 1)
* @throws \InvalidArgumentException If an invalid column name has been specified (code: 2)
* @throws \InvalidArgumentException If an unsupported operator has been specified (code: 3)
* @throws \RuntimeException If columns could not be retrieved from the table
*/
public function parse(QueryBuilder $query, $table, $tableAlias, $field = null, $value = null, $operator = null)
{
$field = trim($field);
if (empty($field)) {
$msg = 'Condition class requires a defined attribute field!';
throw new \InvalidArgumentException($msg, 1);
}
/**
* Verify the table effectively has the column/field that is being queried
*/
$columns = $query->getConnection()
->getSchemaManager()
->listTableColumns($table);
if (empty($columns)) {
throw new \RuntimeException("Could not retrieve columns from '$table'");
}
$names = array_map(function (\Doctrine\DBAL\Schema\Column $column) {
return strtolower($column->getName());
}, $columns);
if (!array_key_exists(strtolower($field), $names)) {
throw new \InvalidArgumentException("Invalid column name specified '$field'", 1);
}
$validOperators = [
Condition::OPERATOR_EQ,
Condition::OPERATOR_NEQ,
Condition::OPERATOR_LT,
Condition::OPERATOR_LTE,
Condition::OPERATOR_GT,
Condition::OPERATOR_GTE,
Condition::OPERATOR_NOT_IN,
Condition::OPERATOR_IN,
Condition::OPERATOR_BETWEEN,
Condition::OPERATOR_STARTS_WITH,
Condition::OPERATOR_ENDS_WITH,
Condition::OPERATOR_CONTAINS,
];
// Normalize with strtoupper in case of non-algorithmic comparisons NOT IN, IN, STARTS WITH
$operator = strtoupper(trim($operator));
/*
* When an operator is not specified, by default, return all results that are not null
*/
if (empty($operator)) {
throw new \InvalidArgumentException(
sprintf('Must specify an operator, please use one of: %s', implode(', ', $validOperators)),
3
);
}
//Identify each field placeholder value with table alias and a hash of condition properties
$boundParamName = sprintf(':%s_%s', $tableAlias, md5($field . $operator . json_encode($value)));
$field = sprintf('%s.%s', $tableAlias, $field);
switch (true) {
case $operator === Condition::OPERATOR_EQ:
if ($value === null) {
$query->andWhere($query->expr()->isNull($field));
break;
}
$query->andWhere($query->expr()->eq($field, $boundParamName));
$query->setParameter($boundParamName, $value);
break;
case $operator === Condition::OPERATOR_NEQ:
if ($value === null) {
$query->andWhere($query->expr()->isNotNull($field));
break;
}
$query->andWhere($query->expr()->neq($field, $boundParamName));
$query->setParameter($boundParamName, $value);
break;
case $operator === Condition::OPERATOR_LT:
$query->andWhere($query->expr()->lt($field, $boundParamName));
$query->setParameter($boundParamName, $value);
break;
case $operator === Condition::OPERATOR_LTE:
$query->andWhere($query->expr()->lte($field, $boundParamName));
$query->setParameter($boundParamName, $value);
break;
case $operator === Condition::OPERATOR_GT:
$query->andWhere($query->expr()->gt($field, $boundParamName));
$query->setParameter($boundParamName, $value);
break;
case $operator === Condition::OPERATOR_GTE:
$query->andWhere($query->expr()->gte($field, $boundParamName));
$query->setParameter($boundParamName, $value);
break;
case $operator === Condition::OPERATOR_NOT_IN:
$query->andWhere($query->expr()->notIn($field, $boundParamName));
$query->setParameter(
$boundParamName,
!is_array($value) ? [(string) $value] : $value,
Connection::PARAM_STR_ARRAY
);
break;
case $operator === Condition::OPERATOR_IN:
$query->andWhere($query->expr()->in($field, $boundParamName));
$query->setParameter(
$boundParamName,
!is_array($value) ? [(string) $value] : $value,
Connection::PARAM_STR_ARRAY
);
break;
case $operator === Condition::OPERATOR_BETWEEN:
if (!isset($value['min']) && !isset($value['max'])) {
throw new \InvalidArgumentException('The between operator needs a minimum or a maximum', 3);
}
if (isset($value['min'])) {
$query->andWhere($query->expr()->gte($field, $boundParamName . 'Min'))
->setParameter($boundParamName . 'Min', $value['min']);
}
if (isset($value['max'])) {
$query->andWhere($query->expr()->lte($field, $boundParamName . 'Max'))
->setParameter($boundParamName . 'Max', $value['max']);
}
break;
case $operator === Condition::OPERATOR_STARTS_WITH:
$query->andWhere($query->expr()->like($field, $boundParamName));
$query->setParameter($boundParamName, $value . '%');
break;
case $operator === Condition::OPERATOR_ENDS_WITH:
$query->andWhere($query->expr()->like($field, $boundParamName));
$query->setParameter($boundParamName, '%' . $value);
break;
case $operator === Condition::OPERATOR_CONTAINS:
$query->andWhere($query->expr()->like($field, $boundParamName));
$query->setParameter($boundParamName, '%' . $value . '%');
break;
default:
throw new \InvalidArgumentException(
sprintf('Invalid operator specified, please use one of: %s', implode(', ', $validOperators)),
3
);
break;
}
}
}
| agpl-3.0 |
nikolaykhodov/clipperz-password-manager | frontend/delta/js/Clipperz/Crypto/PRNG.js | 21706 | /*
Copyright 2008-2013 Clipperz Srl
This file is part of Clipperz, the online password manager.
For further information about its features and functionalities please
refer to http://www.clipperz.com.
* Clipperz 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.
* Clipperz 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 Clipperz. If not, see http://www.gnu.org/licenses/.
*/
"use strict";
try { if (typeof(Clipperz.ByteArray) == 'undefined') { throw ""; }} catch (e) {
throw "Clipperz.Crypto.PRNG depends on Clipperz.ByteArray!";
}
try { if (typeof(Clipperz.Crypto.SHA) == 'undefined') { throw ""; }} catch (e) {
throw "Clipperz.Crypto.PRNG depends on Clipperz.Crypto.SHA!";
}
try { if (typeof(Clipperz.Crypto.AES) == 'undefined') { throw ""; }} catch (e) {
throw "Clipperz.Crypto.PRNG depends on Clipperz.Crypto.AES!";
}
if (typeof(Clipperz.Crypto.PRNG) == 'undefined') { Clipperz.Crypto.PRNG = {}; }
//#############################################################################
Clipperz.Crypto.PRNG.EntropyAccumulator = function(args) {
args = args || {};
// MochiKit.Base.bindMethods(this);
this._stack = new Clipperz.ByteArray();
this._maxStackLengthBeforeHashing = args.maxStackLengthBeforeHashing || 256;
return this;
}
Clipperz.Crypto.PRNG.EntropyAccumulator.prototype = MochiKit.Base.update(null, {
'toString': function() {
return "Clipperz.Crypto.PRNG.EntropyAccumulator";
},
//-------------------------------------------------------------------------
'stack': function() {
return this._stack;
},
'setStack': function(aValue) {
this._stack = aValue;
},
'resetStack': function() {
this.stack().reset();
},
'maxStackLengthBeforeHashing': function() {
return this._maxStackLengthBeforeHashing;
},
//-------------------------------------------------------------------------
'addRandomByte': function(aValue) {
this.stack().appendByte(aValue);
if (this.stack().length() > this.maxStackLengthBeforeHashing()) {
this.setStack(Clipperz.Crypto.SHA.sha_d256(this.stack()));
}
},
//-------------------------------------------------------------------------
__syntaxFix__: "syntax fix"
});
//#############################################################################
Clipperz.Crypto.PRNG.RandomnessSource = function(args) {
args = args || {};
MochiKit.Base.bindMethods(this);
this._generator = args.generator || null;
this._sourceId = args.sourceId || null;
this._boostMode = args.boostMode || false;
this._nextPoolIndex = 0;
return this;
}
Clipperz.Crypto.PRNG.RandomnessSource.prototype = MochiKit.Base.update(null, {
'generator': function() {
return this._generator;
},
'setGenerator': function(aValue) {
this._generator = aValue;
},
//-------------------------------------------------------------------------
'boostMode': function() {
return this._boostMode;
},
'setBoostMode': function(aValue) {
this._boostMode = aValue;
},
//-------------------------------------------------------------------------
'sourceId': function() {
return this._sourceId;
},
'setSourceId': function(aValue) {
this._sourceId = aValue;
},
//-------------------------------------------------------------------------
'nextPoolIndex': function() {
return this._nextPoolIndex;
},
'incrementNextPoolIndex': function() {
this._nextPoolIndex = ((this._nextPoolIndex + 1) % this.generator().numberOfEntropyAccumulators());
},
//-------------------------------------------------------------------------
'updateGeneratorWithValue': function(aRandomValue) {
if (this.generator() != null) {
this.generator().addRandomByte(this.sourceId(), this.nextPoolIndex(), aRandomValue);
this.incrementNextPoolIndex();
}
},
//-------------------------------------------------------------------------
__syntaxFix__: "syntax fix"
});
//#############################################################################
Clipperz.Crypto.PRNG.TimeRandomnessSource = function(args) {
args = args || {};
// MochiKit.Base.bindMethods(this);
this._intervalTime = args.intervalTime || 1000;
Clipperz.Crypto.PRNG.RandomnessSource.call(this, args);
this.collectEntropy();
return this;
}
Clipperz.Crypto.PRNG.TimeRandomnessSource.prototype = MochiKit.Base.update(new Clipperz.Crypto.PRNG.RandomnessSource, {
'intervalTime': function() {
return this._intervalTime;
},
//-------------------------------------------------------------------------
'collectEntropy': function() {
var now;
var entropyByte;
var intervalTime;
now = new Date();
entropyByte = (now.getTime() & 0xff);
intervalTime = this.intervalTime();
if (this.boostMode() == true) {
intervalTime = intervalTime / 9;
}
this.updateGeneratorWithValue(entropyByte);
setTimeout(this.collectEntropy, intervalTime);
},
//-------------------------------------------------------------------------
'numberOfRandomBits': function() {
return 5;
},
//-------------------------------------------------------------------------
__syntaxFix__: "syntax fix"
});
//*****************************************************************************
Clipperz.Crypto.PRNG.MouseRandomnessSource = function(args) {
args = args || {};
Clipperz.Crypto.PRNG.RandomnessSource.call(this, args);
this._numberOfBitsToCollectAtEachEvent = 4;
this._randomBitsCollector = 0;
this._numberOfRandomBitsCollected = 0;
MochiKit.Signal.connect(document, 'onmousemove', this, 'collectEntropy');
return this;
}
Clipperz.Crypto.PRNG.MouseRandomnessSource.prototype = MochiKit.Base.update(new Clipperz.Crypto.PRNG.RandomnessSource, {
//-------------------------------------------------------------------------
'numberOfBitsToCollectAtEachEvent': function() {
return this._numberOfBitsToCollectAtEachEvent;
},
//-------------------------------------------------------------------------
'randomBitsCollector': function() {
return this._randomBitsCollector;
},
'setRandomBitsCollector': function(aValue) {
this._randomBitsCollector = aValue;
},
'appendRandomBitsToRandomBitsCollector': function(aValue) {
var collectedBits;
var numberOfRandomBitsCollected;
numberOfRandomBitsCollected = this.numberOfRandomBitsCollected();
collectedBits = this.randomBitsCollector() | (aValue << numberOfRandomBitsCollected);
this.setRandomBitsCollector(collectedBits);
numberOfRandomBitsCollected += this.numberOfBitsToCollectAtEachEvent();
if (numberOfRandomBitsCollected == 8) {
this.updateGeneratorWithValue(collectedBits);
numberOfRandomBitsCollected = 0;
this.setRandomBitsCollector(0);
}
this.setNumberOfRandomBitsCollected(numberOfRandomBitsCollected)
},
//-------------------------------------------------------------------------
'numberOfRandomBitsCollected': function() {
return this._numberOfRandomBitsCollected;
},
'setNumberOfRandomBitsCollected': function(aValue) {
this._numberOfRandomBitsCollected = aValue;
},
//-------------------------------------------------------------------------
'collectEntropy': function(anEvent) {
var mouseLocation;
var randomBit;
var mask;
mask = 0xffffffff >>> (32 - this.numberOfBitsToCollectAtEachEvent());
mouseLocation = anEvent.mouse().client;
randomBit = ((mouseLocation.x ^ mouseLocation.y) & mask);
this.appendRandomBitsToRandomBitsCollector(randomBit)
},
//-------------------------------------------------------------------------
'numberOfRandomBits': function() {
return 1;
},
//-------------------------------------------------------------------------
__syntaxFix__: "syntax fix"
});
//*****************************************************************************
Clipperz.Crypto.PRNG.CryptoRandomRandomnessSource = function(args) {
args = args || {};
this._intervalTime = args.intervalTime || 500;
this._browserCrypto = args.browserCrypto;
Clipperz.Crypto.PRNG.RandomnessSource.call(this, args);
this.collectEntropy();
return this;
}
Clipperz.Crypto.PRNG.CryptoRandomRandomnessSource.prototype = MochiKit.Base.update(new Clipperz.Crypto.PRNG.RandomnessSource, {
'intervalTime': function() {
return this._intervalTime;
},
'browserCrypto': function () {
return this._browserCrypto;
},
//-------------------------------------------------------------------------
'collectEntropy': function() {
var bytesToCollect;
if (this.boostMode() == true) {
bytesToCollect = 256;
} else {
bytesToCollect = 8;
}
var randomValuesArray = new Uint8Array(bytesToCollect);
this.browserCrypto().getRandomValues(randomValuesArray);
for (var i = 0; i < randomValuesArray.length; i++) {
this.updateGeneratorWithValue(randomValuesArray[i]);
}
setTimeout(this.collectEntropy, this.intervalTime());
},
//-------------------------------------------------------------------------
__syntaxFix__: "syntax fix"
});
//#############################################################################
Clipperz.Crypto.PRNG.Fortuna = function(args) {
var i,c;
args = args || {};
this._key = args.seed || null;
if (this._key == null) {
this._counter = 0;
this._key = new Clipperz.ByteArray();
} else {
this._counter = 1;
}
this._aesKey = null;
this._firstPoolReseedLevel = args.firstPoolReseedLevel || 32 || 64;
this._numberOfEntropyAccumulators = args.numberOfEntropyAccumulators || 32;
this._accumulators = [];
c = this.numberOfEntropyAccumulators();
for (i=0; i<c; i++) {
this._accumulators.push(new Clipperz.Crypto.PRNG.EntropyAccumulator());
}
this._randomnessSources = [];
this._reseedCounter = 0;
return this;
}
Clipperz.Crypto.PRNG.Fortuna.prototype = MochiKit.Base.update(null, {
'toString': function() {
return "Clipperz.Crypto.PRNG.Fortuna";
},
//-------------------------------------------------------------------------
'key': function() {
return this._key;
},
'setKey': function(aValue) {
this._key = aValue;
this._aesKey = null;
},
'aesKey': function() {
if (this._aesKey == null) {
this._aesKey = new Clipperz.Crypto.AES.Key({key:this.key()});
}
return this._aesKey;
},
'accumulators': function() {
return this._accumulators;
},
'firstPoolReseedLevel': function() {
return this._firstPoolReseedLevel;
},
//-------------------------------------------------------------------------
'reseedCounter': function() {
return this._reseedCounter;
},
'incrementReseedCounter': function() {
this._reseedCounter = this._reseedCounter +1;
},
//-------------------------------------------------------------------------
'reseed': function() {
var newKeySeed;
var reseedCounter;
var reseedCounterMask;
var i, c;
newKeySeed = this.key();
this.incrementReseedCounter();
reseedCounter = this.reseedCounter();
c = this.numberOfEntropyAccumulators();
reseedCounterMask = 0xffffffff >>> (32 - c);
for (i=0; i<c; i++) {
if ((i == 0) || ((reseedCounter & (reseedCounterMask >>> (c - i))) == 0)) {
newKeySeed.appendBlock(this.accumulators()[i].stack());
this.accumulators()[i].resetStack();
}
}
if (reseedCounter == 1) {
c = this.randomnessSources().length;
for (i=0; i<c; i++) {
this.randomnessSources()[i].setBoostMode(false);
}
}
this.setKey(Clipperz.Crypto.SHA.sha_d256(newKeySeed));
if (reseedCounter == 1) {
Clipperz.log("### PRNG.readyToGenerateRandomBytes");
MochiKit.Signal.signal(this, 'readyToGenerateRandomBytes');
}
MochiKit.Signal.signal(this, 'reseeded');
},
//-------------------------------------------------------------------------
'isReadyToGenerateRandomValues': function() {
return this.reseedCounter() != 0;
},
//-------------------------------------------------------------------------
'entropyLevel': function() {
return this.accumulators()[0].stack().length() + (this.reseedCounter() * this.firstPoolReseedLevel());
},
//-------------------------------------------------------------------------
'counter': function() {
return this._counter;
},
'incrementCounter': function() {
this._counter += 1;
},
'counterBlock': function() {
var result;
result = new Clipperz.ByteArray().appendWords(this.counter(), 0, 0, 0);
return result;
},
//-------------------------------------------------------------------------
'getRandomBlock': function() {
var result;
result = new Clipperz.ByteArray(Clipperz.Crypto.AES.encryptBlock(this.aesKey(), this.counterBlock().arrayValues()));
this.incrementCounter();
return result;
},
//-------------------------------------------------------------------------
'getRandomBytes': function(aSize) {
var result;
if (this.isReadyToGenerateRandomValues()) {
var i,c;
var newKey;
result = new Clipperz.ByteArray();
c = Math.ceil(aSize / (128 / 8));
for (i=0; i<c; i++) {
result.appendBlock(this.getRandomBlock());
}
if (result.length() != aSize) {
result = result.split(0, aSize);
}
newKey = this.getRandomBlock().appendBlock(this.getRandomBlock());
this.setKey(newKey);
} else {
Clipperz.logWarning("Fortuna generator has not enough entropy, yet!");
throw Clipperz.Crypto.PRNG.exception.NotEnoughEntropy;
}
return result;
},
//-------------------------------------------------------------------------
'addRandomByte': function(aSourceId, aPoolId, aRandomValue) {
var selectedAccumulator;
selectedAccumulator = this.accumulators()[aPoolId];
selectedAccumulator.addRandomByte(aRandomValue);
if (aPoolId == 0) {
MochiKit.Signal.signal(this, 'addedRandomByte')
if (selectedAccumulator.stack().length() > this.firstPoolReseedLevel()) {
this.reseed();
}
}
},
//-------------------------------------------------------------------------
'numberOfEntropyAccumulators': function() {
return this._numberOfEntropyAccumulators;
},
//-------------------------------------------------------------------------
'randomnessSources': function() {
return this._randomnessSources;
},
'addRandomnessSource': function(aRandomnessSource) {
aRandomnessSource.setGenerator(this);
aRandomnessSource.setSourceId(this.randomnessSources().length);
this.randomnessSources().push(aRandomnessSource);
if (this.isReadyToGenerateRandomValues() == false) {
aRandomnessSource.setBoostMode(true);
}
},
//-------------------------------------------------------------------------
'deferredEntropyCollection': function(aValue) {
var result;
if (this.isReadyToGenerateRandomValues()) {
result = aValue;
} else {
var deferredResult;
deferredResult = new Clipperz.Async.Deferred("PRNG.deferredEntropyCollection");
deferredResult.addCallback(MochiKit.Base.partial(MochiKit.Async.succeed, aValue));
MochiKit.Signal.connect(this,
'readyToGenerateRandomBytes',
deferredResult,
'callback');
result = deferredResult;
}
return result;
},
//-------------------------------------------------------------------------
'fastEntropyAccumulationForTestingPurpose': function() {
while (! this.isReadyToGenerateRandomValues()) {
this.addRandomByte(Math.floor(Math.random() * 32), Math.floor(Math.random() * 32), Math.floor(Math.random() * 256));
}
},
//-------------------------------------------------------------------------
/*
'dump': function(appendToDoc) {
var tbl;
var i,c;
tbl = document.createElement("table");
tbl.border = 0;
with (tbl.style) {
border = "1px solid lightgrey";
fontFamily = 'Helvetica, Arial, sans-serif';
fontSize = '8pt';
//borderCollapse = "collapse";
}
var hdr = tbl.createTHead();
var hdrtr = hdr.insertRow(0);
// document.createElement("tr");
{
var ntd;
ntd = hdrtr.insertCell(0);
ntd.style.borderBottom = "1px solid lightgrey";
ntd.style.borderRight = "1px solid lightgrey";
ntd.appendChild(document.createTextNode("#"));
ntd = hdrtr.insertCell(1);
ntd.style.borderBottom = "1px solid lightgrey";
ntd.style.borderRight = "1px solid lightgrey";
ntd.appendChild(document.createTextNode("s"));
ntd = hdrtr.insertCell(2);
ntd.colSpan = this.firstPoolReseedLevel();
ntd.style.borderBottom = "1px solid lightgrey";
ntd.style.borderRight = "1px solid lightgrey";
ntd.appendChild(document.createTextNode("base values"));
ntd = hdrtr.insertCell(3);
ntd.colSpan = 20;
ntd.style.borderBottom = "1px solid lightgrey";
ntd.appendChild(document.createTextNode("extra values"));
}
c = this.accumulators().length;
for (i=0; i<c ; i++) {
var currentAccumulator;
var bdytr;
var bdytd;
var ii, cc;
currentAccumulator = this.accumulators()[i]
bdytr = tbl.insertRow(true);
bdytd = bdytr.insertCell(0);
bdytd.style.borderRight = "1px solid lightgrey";
bdytd.style.color = "lightgrey";
bdytd.appendChild(document.createTextNode("" + i));
bdytd = bdytr.insertCell(1);
bdytd.style.borderRight = "1px solid lightgrey";
bdytd.style.color = "gray";
bdytd.appendChild(document.createTextNode("" + currentAccumulator.stack().length()));
cc = Math.max(currentAccumulator.stack().length(), this.firstPoolReseedLevel());
for (ii=0; ii<cc; ii++) {
var cellText;
bdytd = bdytr.insertCell(ii + 2);
if (ii < currentAccumulator.stack().length()) {
cellText = Clipperz.ByteArray.byteToHex(currentAccumulator.stack().byteAtIndex(ii));
} else {
cellText = "_";
}
if (ii == (this.firstPoolReseedLevel() - 1)) {
bdytd.style.borderRight = "1px solid lightgrey";
}
bdytd.appendChild(document.createTextNode(cellText));
}
}
if (appendToDoc) {
var ne = document.createElement("div");
ne.id = "entropyGeneratorStatus";
with (ne.style) {
fontFamily = "Courier New, monospace";
fontSize = "12px";
lineHeight = "16px";
borderTop = "1px solid black";
padding = "10px";
}
if (document.getElementById(ne.id)) {
MochiKit.DOM.swapDOM(ne.id, ne);
} else {
document.body.appendChild(ne);
}
ne.appendChild(tbl);
}
return tbl;
},
*/
//-----------------------------------------------------------------------------
__syntaxFix__: "syntax fix"
});
//#############################################################################
Clipperz.Crypto.PRNG.Random = function(args) {
args = args || {};
// MochiKit.Base.bindMethods(this);
return this;
}
Clipperz.Crypto.PRNG.Random.prototype = MochiKit.Base.update(null, {
'toString': function() {
return "Clipperz.Crypto.PRNG.Random";
},
//-------------------------------------------------------------------------
'getRandomBytes': function(aSize) {
//Clipperz.Profile.start("Clipperz.Crypto.PRNG.Random.getRandomBytes");
var result;
var i,c;
result = new Clipperz.ByteArray()
c = aSize || 1;
for (i=0; i<c; i++) {
result.appendByte((Math.random()*255) & 0xff);
}
//Clipperz.Profile.stop("Clipperz.Crypto.PRNG.Random.getRandomBytes");
return result;
},
//-------------------------------------------------------------------------
__syntaxFix__: "syntax fix"
});
//#############################################################################
var _clipperz_crypt_prng_defaultPRNG = null;
Clipperz.Crypto.PRNG.defaultRandomGenerator = function() {
if (_clipperz_crypt_prng_defaultPRNG == null) {
_clipperz_crypt_prng_defaultPRNG = new Clipperz.Crypto.PRNG.Fortuna();
//.............................................................
//
// TimeRandomnessSource
//
//.............................................................
{
var newRandomnessSource;
newRandomnessSource = new Clipperz.Crypto.PRNG.TimeRandomnessSource({intervalTime:111});
_clipperz_crypt_prng_defaultPRNG.addRandomnessSource(newRandomnessSource);
}
//.............................................................
//
// MouseRandomnessSource
//
//.............................................................
{
var newRandomnessSource;
newRandomnessSource = new Clipperz.Crypto.PRNG.MouseRandomnessSource();
_clipperz_crypt_prng_defaultPRNG.addRandomnessSource(newRandomnessSource);
}
//.............................................................
//
// CryptoRandomRandomnessSource
//
//.............................................................
{
var newRandomnessSource;
var browserCrypto;
if (window.crypto && window.crypto.getRandomValues) {
browserCrypto = window.crypto;
} else if (window.msCrypto && window.msCrypto.getRandomValues) {
browserCrypto = window.msCrypto;
} else {
browserCrypto = null;
}
if (browserCrypto != null) {
newRandomnessSource = new Clipperz.Crypto.PRNG.CryptoRandomRandomnessSource({'browserCrypto':browserCrypto});
_clipperz_crypt_prng_defaultPRNG.addRandomnessSource(newRandomnessSource);
}
}
}
return _clipperz_crypt_prng_defaultPRNG;
};
//#############################################################################
Clipperz.Crypto.PRNG.exception = {
NotEnoughEntropy: new MochiKit.Base.NamedError("Clipperz.Crypto.PRNG.exception.NotEnoughEntropy")
};
MochiKit.DOM.addLoadEvent(Clipperz.Crypto.PRNG.defaultRandomGenerator);
| agpl-3.0 |
akvo/akvo-rsr | akvo/rsr/management/commands/fix_orphaned_periods.py | 5519 | # -*- coding: utf-8 -*-
# Akvo Reporting is covered by the GNU Affero General Public License.
# See more details in the license.txt file located at the root folder of the Akvo RSR module.
# For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.
import sys
from django.core.management.base import BaseCommand
from django.db.models import Count
from ...models import Indicator, IndicatorPeriod
def pprint_period_lineage(period):
indicator = period.indicator
result = indicator.result
project = result.project
print('{} > {} > {} > {}--{}'.format(
project.title, result.title, indicator.title, period.period_start, period.period_end
).encode('utf8'))
print('{} > {} > {} > {}'.format(project.id, result.id, indicator.id, period.id))
print('#' * 20)
def find_orphaned_indicators():
"""Find indicators which are orphaned, whose parents can be deduced."""
# Indicators with no parent, but whose indicators have parents
indicators = Indicator.objects.filter(parent_indicator=None)\
.exclude(result__parent_result=None)
# Indicators with no siblings
indicators = indicators.annotate(siblings=Count('result__indicators')).filter(siblings=1)
# Indicators whose results's parents have a single child
indicators = indicators.annotate(parent_siblings=Count('result__parent_result__indicators'))\
.filter(parent_siblings=1).distinct()
return list(indicators.values_list('id', 'result__parent_result__indicators'))
def find_orphaned_periods():
"""Find periods which are orphaned, whose parents can be deduced."""
# Periods with no parent, but whose indicators have parents
periods = IndicatorPeriod.objects.filter(parent_period=None)\
.exclude(indicator__parent_indicator=None)
# Periods with no siblings
periods = periods.annotate(siblings=Count('indicator__periods')).filter(siblings=1)
# Periods whose indicator's parents have a single child
periods = periods.annotate(parent_siblings=Count('indicator__parent_indicator__periods'))\
.filter(parent_siblings=1).distinct()
return list(periods.values_list('id', 'indicator__parent_indicator__periods'))
class Command(BaseCommand):
args = '<indicator|indicator_period> [<child_id> <parent_id>]'
help = 'Script for fixing orphaned indicators and periods'
def handle(self, *args, **options):
# parse options
verbosity = int(options['verbosity'])
if len(args) == 1 and args[0] == 'indicator':
indicators = find_orphaned_indicators()
periods = []
self.stdout.write('Fixing {} orphaned indicators'.format(len(indicators)))
elif len(args) == 1 and args[0] == 'indicator_period':
indicators = []
periods = find_orphaned_periods()
self.stdout.write('Fixing {} orphaned periods'.format(len(periods)))
elif len(args) == 3 and args[0] == 'indicator':
indicators = [(int(args[1]), int(args[2]))]
periods = []
elif len(args) == 3 and args[0] == 'indicator_period':
indicators = []
periods = [(int(args[1]), int(args[2]))]
else:
print('Usage: {} {}'.format(sys.argv[0], self.args))
sys.exit(1)
for child_id, parent_id in indicators:
child_indicator = Indicator.objects.get(id=child_id)
parent_indicator = Indicator.objects.get(id=parent_id)
assertion_message = '{} cannot be a parent of {}'.format(parent_id, child_id)
assert child_indicator.result.parent_result == parent_indicator.result, assertion_message
child_indicator.parent_indicator = parent_indicator
child_indicator.save()
# Any additional missing data is taken care of by saving the parent.
# parent_indicator.save()
if verbosity > 1:
self.stdout.write('{} indicator made parent of {}'.format(parent_id, child_id))
for child_id, parent_id in periods:
child_period = IndicatorPeriod.objects.get(id=child_id)
parent_period = IndicatorPeriod.objects.get(id=parent_id)
child_result = child_period.indicator.result
parent_result = parent_period.indicator.result
assertion_message = '{} cannot be a parent of {}'.format(parent_id, child_id)
assert child_result.parent_result == parent_result, assertion_message
child_period.parent_period = parent_period
child_period.save()
# Any additional missing data is taken care of by saving the parent.
# parent_period.save()
if parent_period.indicator.periods.count() != child_period.indicator.periods.count():
print('No. of periods mismatch with parent :: ')
pprint_period_lineage(parent_period)
if verbosity > 1:
self.stdout.write('{} period made parent of {}'.format(parent_id, child_id))
if indicators:
fixed_indicators = ', '.join(str(id_) for id_, _ in indicators)
self.stdout.write('Fixed parents for indicator ids: {}'.format(fixed_indicators))
if periods:
fixed_periods = ', '.join(str(id_) for id_, _ in periods)
self.stdout.write('Fixed parents for period ids: {}'.format(fixed_periods))
| agpl-3.0 |
brewingagile/backoffice.brewingagile.org | application/src/main/java/org/brewingagile/backoffice/rest/json/ToJson.java | 1547 | package org.brewingagile.backoffice.rest.json;
import argo.jdom.JsonNode;
import argo.jdom.JsonStringNode;
import fj.F;
import fj.data.Option;
import org.brewingagile.backoffice.types.*;
import java.time.Instant;
import static argo.jdom.JsonNodeFactories.nullNode;
import static argo.jdom.JsonNodeFactories.string;
public class ToJson {
public static <A> JsonNode nullable(Option<A> oa, F<A,JsonNode> f) {
return oa.map(f).orSome(nullNode());
}
public static JsonNode json(TicketName x) { return string(x.ticketName); }
public static JsonNode account(Account x) { return string(x.value); }
public static JsonNode ticketName(TicketName x) { return string(x.ticketName); }
public static JsonNode accountSecret(AccountSecret x) { return string(x.value.toString()); }
public static JsonNode accountSignupSecret(AccountSignupSecret x) { return string(x.value.toString()); }
public static JsonNode json(ParticipantOrganisation x) { return string(x.value); }
public static JsonStringNode participantEmail(ParticipantEmail participantEmail) { return string(participantEmail.value); }
public static JsonStringNode participantName(ParticipantName participantName) { return string(participantName.value); }
public static JsonStringNode registrationId(RegistrationId registrationId) { return string(registrationId.value.toString()); }
public static JsonNode chargeId(ChargeId chargeId) { return string(chargeId.value); }
public static JsonNode instant(Instant stripeChargeTimestamp) { return string(stripeChargeTimestamp.toString()); }
}
| agpl-3.0 |
afshinnj/php-mvc | assets/framework/ckeditor/plugins/table/lang/et.js | 2356 | /*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'table', 'et', {
border: 'Joone suurus',
caption: 'Tabeli tiitel',
cell: {
menu: 'Lahter',
insertBefore: 'Sisesta lahter enne',
insertAfter: 'Sisesta lahter peale',
deleteCell: 'Eemalda lahtrid',
merge: 'Ühenda lahtrid',
mergeRight: 'Ühenda paremale',
mergeDown: 'Ühenda alla',
splitHorizontal: 'Poolita lahter horisontaalselt',
splitVertical: 'Poolita lahter vertikaalselt',
title: 'Lahtri omadused',
cellType: 'Lahtri liik',
rowSpan: 'Ridade vahe',
colSpan: 'Tulpade vahe',
wordWrap: 'Sõnade murdmine',
hAlign: 'Horisontaalne joondus',
vAlign: 'Vertikaalne joondus',
alignBaseline: 'Baasjoon',
bgColor: 'Tausta värv',
borderColor: 'Äärise värv',
data: 'Andmed',
header: 'Päis',
yes: 'Jah',
no: 'Ei',
invalidWidth: 'Lahtri laius peab olema number.',
invalidHeight: 'Lahtri kõrgus peab olema number.',
invalidRowSpan: 'Ridade vahe peab olema täisarv.',
invalidColSpan: 'Tulpade vahe peab olema täisarv.',
chooseColor: 'Vali'
},
cellPad: 'Lahtri täidis',
cellSpace: 'Lahtri vahe',
column: {
menu: 'Veerg',
insertBefore: 'Sisesta veerg enne',
insertAfter: 'Sisesta veerg peale',
deleteColumn: 'Eemalda veerud'
},
columns: 'Veerud',
deleteTable: 'Kustuta tabel',
headers: 'Päised',
headersBoth: 'Mõlemad',
headersColumn: 'Esimene tulp',
headersNone: 'Puudub',
headersRow: 'Esimene rida',
invalidBorder: 'Äärise suurus peab olema number.',
invalidCellPadding: 'Lahtrite polsterdus (padding) peab olema positiivne arv.',
invalidCellSpacing: 'Lahtrite vahe peab olema positiivne arv.',
invalidCols: 'Tulpade arv peab olema nullist suurem.',
invalidHeight: 'Tabeli kõrgus peab olema number.',
invalidRows: 'Ridade arv peab olema nullist suurem.',
invalidWidth: 'Tabeli laius peab olema number.',
menu: 'Tabeli omadused',
row: {
menu: 'Rida',
insertBefore: 'Sisesta rida enne',
insertAfter: 'Sisesta rida peale',
deleteRow: 'Eemalda read'
},
rows: 'Read',
summary: 'Kokkuvõte',
title: 'Tabeli omadused',
toolbar: 'Tabel',
widthPc: 'protsenti',
widthPx: 'pikslit',
widthUnit: 'laiuse ühik'
} );
| agpl-3.0 |
ho-dieu-it/CMS | app/Models/Event.php | 2324 | <?php
/*
* This file is part of Bootstrap CMS.
*
* (c) Graham Campbell <graham@cachethq.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace GrahamCampbell\BootstrapCMS\Models;
use GrahamCampbell\Credentials\Models\AbstractModel;
use GrahamCampbell\Credentials\Models\Relations\BelongsToUserTrait;
use GrahamCampbell\Credentials\Models\Relations\RevisionableTrait;
use Illuminate\Database\Eloquent\SoftDeletes;
use McCool\LaravelAutoPresenter\HasPresenter;
/**
* This is the event model class.
*
* @author Graham Campbell <graham@cachethq.io>
*/
class Event extends AbstractModel implements HasPresenter
{
use BelongsToUserTrait, RevisionableTrait, SoftDeletes;
/**
* The table the events are stored in.
*
* @var string
*/
protected $table = 'events';
/**
* The model name.
*
* @var string
*/
public static $name = 'event';
/**
* The properties on the model that are dates.
*
* @var array
*/
protected $dates = ['date', 'deleted_at'];
/**
* The revisionable columns.
*
* @var array
*/
protected $keepRevisionOf = ['title', 'body', 'date', 'location'];
/**
* The columns to select when displaying an index.
*
* @var array
*/
public static $index = ['id', 'title', 'date'];
/**
* The max events per page when displaying a paginated index.
*
* @var int
*/
public static $paginate = 10;
/**
* The columns to order by when displaying an index.
*
* @var string
*/
public static $order = 'date';
/**
* The direction to order by when displaying an index.
*
* @var string
*/
public static $sort = 'asc';
/**
* The event validation rules.
*
* @var array
*/
public static $rules = [
'title' => 'required',
'location' => 'required',
'date' => 'required',
'body' => 'required',
'user_id' => 'required',
];
/**
* Get the presenter class.
*
* @return string
*/
public function getPresenterClass()
{
return 'GrahamCampbell\BootstrapCMS\Presenters\EventPresenter';
}
}
| agpl-3.0 |
cswcl/lvt | src/index.js | 4362 | 'use strict';
/* globals fetch, FileReader */
const Pbf = require('pbf');
const vectorTile = require('@mapbox/vector-tile');
const L = require('leaflet');
const InteractiveTile = require('./interactive-tile');
const parseStyle = require('./style').parseStyle;
const VectorTileLayer = L.GridLayer.extend({
options: {
subdomains: 'abc' // Like L.TileLayer
},
initialize: function(url, options) {
const noReRender = false;
L.GridLayer.prototype.initialize.call(this, options);
this._url = url;
this._filter = () => true;
this.setStyle(options.style || {}, noReRender);
},
createTile: function(coords, done) {
const tile = new InteractiveTile(coords, this.getTileSize().x); // this assumes square tiles
const vectorTilePromise = this._getVectorTilePromise(coords);
const styleFn = this._styleFn;
// set filter
tile.filter = (feature) => this._filter(feature);
vectorTilePromise.then(function renderTile(vectorTile) {
for (let layerId in vectorTile.layers) {
let layer = vectorTile.layers[layerId];
tile.addVTLayer(layer);
}
tile.draw(styleFn);
L.Util.requestAnimFrame(() => done());
});
const canvas = tile.getContainer();
// save reference to interactiveTile.
canvas._interactiveTile = tile;
return canvas;
},
query: function (latLng) {
const point = this._map.project(latLng);
const tileSize = this.getTileSize().x; // this assumes square tiles
const tileXY = point.divideBy(tileSize).floor();
const xy = point.subtract(tileXY.multiplyBy(tileSize));
const zoom = this._map.getZoom();
const tileKey = this._tileCoordsToKey({x: tileXY.x, y: tileXY.y, z: zoom});
const tile = this._tiles[tileKey];
if (tile) {
const interactiveTile = this._getInteractiveTile(tile);
const vtFeature = interactiveTile.query({x: xy.x, y: xy.y});
if (!vtFeature) {
return null;
}
const feature = vtFeature.toGeoJSON(tileXY.x, tileXY.y, zoom);
// remove feature.id because is internaly. And we don't know what property is used as id
delete feature.id;
return feature;
}
},
setStyle: function(styleDef, reRender = true) {
if (typeof styleDef !== 'object') {
throw new Error('style must be an object');
}
this._styleDef = styleDef;
this._styleFn = parseStyle(styleDef);
if (reRender) {
this.reRender();
}
},
getStyle: function() {
return this._styleDef;
},
getStyleFn: function() {
return this._styleFn;
},
// esta función se nombró reRender en vez de redraw porque redraw ya esta definida en leaflet
// y permite redibujar un tile pero descargando de nuevo la información.
reRender: function() {
const clean = true;
this._eachTile(interactiveTile => interactiveTile.draw(this._styleFn, clean));
},
setFilter: function(fn) {
this._filter = fn || (() => true);
this.reRender();
},
_eachTile: function(fn) {
for (let key in this._tiles) {
const tile = this._tiles[key];
const interactiveTile = this._getInteractiveTile(tile);
fn(interactiveTile);
}
},
_getInteractiveTile: function(leafletTile) {
return leafletTile.el._interactiveTile;
},
_getSubdomain: L.TileLayer.prototype._getSubdomain,
_getVectorTilePromise: function(coords) {
const tileUrl = L.Util.template(this._url, L.extend({
s: this._getSubdomain(coords),
x: coords.x,
y: coords.y,
z: coords.z
// z: this._getZoomForUrl() /// TODO: Maybe replicate TileLayer's maxNativeZoom
}, this.options));
return fetch(tileUrl)
.then(function(response) {
if (!response.ok) {
return {layers:[]};
}
return response.blob().then(function(blob) {
const reader = new FileReader();
return new Promise(function(resolve) {
reader.addEventListener('loadend', function() {
// reader.result contains the contents of blob as a typed array
// blob.type === 'application/x-protobuf'
const pbf = new Pbf( reader.result );
return resolve(new vectorTile.VectorTile(pbf));
});
reader.readAsArrayBuffer(blob);
});
});
});
}
});
module.exports = VectorTileLayer;
| agpl-3.0 |
onlylin/mycollab | mycollab-services/src/main/java/com/esofthead/mycollab/common/domain/AuditLog.java | 11766 | /**
* This file is part of mycollab-services.
*
* mycollab-services 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.
*
* mycollab-services 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 mycollab-services. If not, see <http://www.gnu.org/licenses/>.
*/
/*Domain class of table m_audit_log*/
package com.esofthead.mycollab.common.domain;
import com.esofthead.mycollab.core.arguments.ValuedBean;
import com.esofthead.mycollab.core.db.metadata.Column;
import com.esofthead.mycollab.core.db.metadata.Table;
import java.util.Date;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.hibernate.validator.constraints.Length;
@SuppressWarnings("ucd")
@Table("m_audit_log")
public class AuditLog extends ValuedBean {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column m_audit_log.id
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
@Column("id")
private Integer id;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column m_audit_log.object_class
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
@Length(max=255, message="Field value is too long")
@Column("object_class")
private String objectClass;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column m_audit_log.posteddate
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
@Column("posteddate")
private Date posteddate;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column m_audit_log.posteduser
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
@Length(max=45, message="Field value is too long")
@Column("posteduser")
private String posteduser;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column m_audit_log.sAccountId
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
@Column("sAccountId")
private Integer saccountid;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column m_audit_log.type
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
@Length(max=45, message="Field value is too long")
@Column("type")
private String type;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column m_audit_log.typeid
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
@Column("typeid")
private Integer typeid;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column m_audit_log.module
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
@Length(max=45, message="Field value is too long")
@Column("module")
private String module;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column m_audit_log.activityLogId
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
@Column("activityLogId")
private Integer activitylogid;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column m_audit_log.changeset
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
@Length(max=65535, message="Field value is too long")
@Column("changeset")
private String changeset;
private static final long serialVersionUID = 1;
public final boolean equals(Object obj) {
if (obj == null) { return false;}
if (obj == this) { return true;}
if (obj.getClass() != getClass()) { return false;}
AuditLog item = (AuditLog)obj;
return new EqualsBuilder().append(id, item.id).build();
}
public final int hashCode() {
return new HashCodeBuilder(897, 319).append(id).build();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column m_audit_log.id
*
* @return the value of m_audit_log.id
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column m_audit_log.id
*
* @param id the value for m_audit_log.id
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column m_audit_log.object_class
*
* @return the value of m_audit_log.object_class
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
public String getObjectClass() {
return objectClass;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column m_audit_log.object_class
*
* @param objectClass the value for m_audit_log.object_class
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
public void setObjectClass(String objectClass) {
this.objectClass = objectClass;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column m_audit_log.posteddate
*
* @return the value of m_audit_log.posteddate
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
public Date getPosteddate() {
return posteddate;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column m_audit_log.posteddate
*
* @param posteddate the value for m_audit_log.posteddate
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
public void setPosteddate(Date posteddate) {
this.posteddate = posteddate;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column m_audit_log.posteduser
*
* @return the value of m_audit_log.posteduser
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
public String getPosteduser() {
return posteduser;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column m_audit_log.posteduser
*
* @param posteduser the value for m_audit_log.posteduser
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
public void setPosteduser(String posteduser) {
this.posteduser = posteduser;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column m_audit_log.sAccountId
*
* @return the value of m_audit_log.sAccountId
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
public Integer getSaccountid() {
return saccountid;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column m_audit_log.sAccountId
*
* @param saccountid the value for m_audit_log.sAccountId
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
public void setSaccountid(Integer saccountid) {
this.saccountid = saccountid;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column m_audit_log.type
*
* @return the value of m_audit_log.type
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
public String getType() {
return type;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column m_audit_log.type
*
* @param type the value for m_audit_log.type
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
public void setType(String type) {
this.type = type;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column m_audit_log.typeid
*
* @return the value of m_audit_log.typeid
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
public Integer getTypeid() {
return typeid;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column m_audit_log.typeid
*
* @param typeid the value for m_audit_log.typeid
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
public void setTypeid(Integer typeid) {
this.typeid = typeid;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column m_audit_log.module
*
* @return the value of m_audit_log.module
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
public String getModule() {
return module;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column m_audit_log.module
*
* @param module the value for m_audit_log.module
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
public void setModule(String module) {
this.module = module;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column m_audit_log.activityLogId
*
* @return the value of m_audit_log.activityLogId
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
public Integer getActivitylogid() {
return activitylogid;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column m_audit_log.activityLogId
*
* @param activitylogid the value for m_audit_log.activityLogId
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
public void setActivitylogid(Integer activitylogid) {
this.activitylogid = activitylogid;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column m_audit_log.changeset
*
* @return the value of m_audit_log.changeset
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
public String getChangeset() {
return changeset;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column m_audit_log.changeset
*
* @param changeset the value for m_audit_log.changeset
*
* @mbggenerated Tue Sep 08 09:15:20 ICT 2015
*/
public void setChangeset(String changeset) {
this.changeset = changeset;
}
public enum Field {
id,
objectClass,
posteddate,
posteduser,
saccountid,
type,
typeid,
module,
activitylogid,
changeset;
public boolean equalTo(Object value) {
return name().equals(value);
}
}
} | agpl-3.0 |
ervinb/Airesis | app/assets/javascripts/i18n/bootstrap-datetimepicker.hu.js | 867 | /**
* Hungarian translation for bootstrap-datetimepicker
* darevish <http://github.com/darevish>
*/
;(function($){
$.fn.fdatetimepicker.dates['hu'] = {
days: ["Vasárnap", "Hétfő", "Kedd", "Szerda", "Csütörtök", "Péntek", "Szombat", "Vasárnap"],
daysShort: ["Vas", "Hét", "Ked", "Sze", "Csü", "Pén", "Szo", "Vas"],
daysMin: ["V", "H", "K", "Sze", "Cs", "P", "Szo", "V"],
months: ["Január", "Február", "Március", "Április", "Május", "Június", "Július", "Augusztus", "Szeptember", "Október", "November", "December"],
monthsShort: ["Jan", "Feb", "Már", "Ápr", "Máj", "Jún", "Júl", "Aug", "Sze", "Okt", "Nov", "Dec"],
today: "Ma",
suffix: [],
meridiem: [],
weekStart: 1,
format: "dd/mm/yyyy hh:ii",
formatDate: "dd/mm/yyyy"
};
$.fn.fdatetimepicker.defaults = $.fn.fdatetimepicker.dates['hu'];
}(jQuery));
| agpl-3.0 |
nu7hatch/desantapp | apps/admin/assets/app/views/locations_list_view.js | 3654 | /**
* Internal: A view for the cities list items. It's derived from
* the default listing.
*/
Desant.Admin.CitiesListItemsView = Backbone.View.extend({
el: '#cities tbody',
template: JST['templates/admin/city_items'],
initialize: function() {
this.models = new Desant.Admin.Cities()
this.initListing()
},
})
_.extend(Desant.Admin.CitiesListItemsView.prototype,
Desant.Admin.Mixins.DefaultListing)
/**
* Internal: A view for the countries list items. It's derived from
* the default listing.
*/
Desant.Admin.CountriesListItemsView = Backbone.View.extend({
el: '#countries tbody',
template: JST['templates/admin/country_items'],
initialize: function() {
this.models = new Desant.Admin.Countries()
this.initListing()
},
})
_.extend(Desant.Admin.CountriesListItemsView.prototype,
Desant.Admin.Mixins.DefaultListing)
/**
* Internal: A shared view for the locations list. It can either
* display list of cities or countries, dependent on the 'group'
* option specified. It's an infinitely scrolled listing.
*/
Desant.Admin.LocationsListView = Backbone.View.extend({
el: '#content',
template: JST['templates/admin/listing'],
subnav_template: JST['templates/admin/locations_subnav'],
events: {
'click .tab': 'switchTab',
},
initialize: function() {
this.initScroll()
},
render: function() {
if (this.options.group == 'cities') {
this.renderCities()
} else {
this.renderCountries()
}
return this
},
/**
* Internal: Switches tab to specified one and navigates to related
* action.
*
* to - A String name of the tab to switch (can be 'cities' or 'countries')
*
*/
navigate: function(to) {
app.navigate(to)
this.$('.subnav').html(this.subnav_template())
this.$('.subnav .' + this.options.group + '_tab').addClass('current')
},
/**
* Internal: Renders list of the cities.
*/
renderCities: function() {
this.$el.html(this.template({
id: 'cities',
icon: 'map-marker',
title: "User locations",
columns: ['#', 'City', 'Country', 'Total users'],
}))
this.navigate('/admin/locations/cities')
this.items = new Desant.Admin.CitiesListItemsView().render()
this.map = new Desant.Admin.LocationsMapView({ group: 'cities' }).render()
return this
},
/**
* Internal: Renders list of the countries.
*/
renderCountries: function() {
this.$el.html(this.template({
id: 'countries',
icon: 'map-marker',
title: "User locations",
columns: ['#', 'Country', 'Total users'],
}))
this.navigate('/admin/locations/countries')
this.items = new Desant.Admin.CountriesListItemsView().render()
this.map = new Desant.Admin.LocationsMapView({ group: 'countries' }).render()
return this
},
/**
* Internal: An event fired when user clicks on one of the tabs -
* 'By cities' or 'By countries' and switches listing context to
* appropriate one.
*
* e - An Event passed by the caller.
*
*/
switchTab: function(e) {
e.preventDefault()
group = $(e.target).data('group')
if (this.options.group != group) {
this.options.group = group
this.render()
}
},
})
_.extend(Desant.Admin.LocationsListView.prototype,
Desant.Admin.Mixins.InifiniteScrollListing)
| agpl-3.0 |
yajinni/WoWAnalyzer | src/game/shadowlands/SOULBINDS.ts | 1557 | import { Soulbind } from 'parser/core/Events';
import indexById from 'common/indexById';
const SOULBINDS: {
[key: string]: Soulbind,
[id: number]: Soulbind,
} = {
NIYA: {
name: 'Niya',
id: 1,
covenantID: 3,
garrisonTalentTreeId: 276,
},
DREAMWEAVER: {
name: 'Dreamweaver',
id: 2,
covenantID: 3,
garrisonTalentTreeId: 275,
},
GENERAL_DRAVEN: {
name: 'General Draven',
id: 3,
covenantID: 2,
garrisonTalentTreeId: 304,
},
PLAGUE_DEVISER_MARILETH: {
name: 'Plague Deviser Marileth',
id: 4,
covenantID: 4,
garrisonTalentTreeId: 325,
},
EMENI: {
name: 'Emeni',
id: 5,
covenantID: 4,
garrisonTalentTreeId: 330,
},
KORAYN: {
name: 'Korayn',
id: 6,
covenantID: 3,
garrisonTalentTreeId: 334,
},
PELAGOS: {
name: 'Pelagos',
id: 7,
covenantID: 1,
garrisonTalentTreeId: 357,
},
NADJIA_THE_MISTBLADE: {
name: 'Nadjia the Mistblade',
id: 8,
covenantID: 2,
garrisonTalentTreeId: 368,
},
THEOTAR_THE_MAD_DUKE: {
name: 'Theotar the Mad Duke',
id: 9,
covenantID: 2,
garrisonTalentTreeId: 392,
},
BONESMITH_HEIRMIR: {
name: 'Bonesmith Heirmir',
id: 10,
covenantID: 4,
garrisonTalentTreeId: 349,
},
KLEIA: {
name: 'Kleia',
id: 13,
covenantID: 1,
garrisonTalentTreeId: 360,
},
FORGELITE_PRIME_MIKANIKOS: {
name: 'Forgelite Prime Mikanikos',
id: 18,
covenantID: 1,
garrisonTalentTreeId: 365,
},
};
export default indexById(SOULBINDS);
| agpl-3.0 |
lmaslag/test | engine/Library/Zend/Translate/Adapter/Xliff.php | 8721 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Translate
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @version $Id$
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/** Zend_Locale */
require_once 'Zend/Locale.php';
/** Zend_Translate_Adapter */
require_once 'Zend/Translate/Adapter.php';
/**
* @category Zend
* @package Zend_Translate
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Translate_Adapter_Xliff extends Zend_Translate_Adapter {
// Internal variables
private $_file = false;
private $_useId = true;
private $_cleared = array();
private $_transunit = null;
private $_source = null;
private $_target = null;
private $_langId = null;
private $_scontent = null;
private $_tcontent = null;
private $_stag = false;
private $_ttag = false;
private $_data = array();
/**
* Load translation data (XLIFF file reader)
*
* @param string $locale Locale/Language to add data for, identical with locale identifier,
* see Zend_Locale for more information
* @param string $filename XLIFF file to add, full path must be given for access
* @param array $option OPTIONAL Options to use
* @throws Zend_Translation_Exception
* @return array
*/
protected function _loadTranslationData($filename, $locale, array $options = array())
{
$this->_data = array();
if (!is_readable($filename)) {
require_once 'Zend/Translate/Exception.php';
throw new Zend_Translate_Exception('Translation file \'' . $filename . '\' is not readable.');
}
if (empty($options['useId'])) {
$this->_useId = false;
} else {
$this->_useId = true;
}
$encoding = $this->_findEncoding($filename);
$this->_target = $locale;
$this->_file = xml_parser_create($encoding);
xml_set_object($this->_file, $this);
xml_parser_set_option($this->_file, XML_OPTION_CASE_FOLDING, 0);
xml_set_element_handler($this->_file, "_startElement", "_endElement");
xml_set_character_data_handler($this->_file, "_contentElement");
if (!xml_parse($this->_file, file_get_contents($filename))) {
$ex = sprintf('XML error: %s at line %d of file %s',
xml_error_string(xml_get_error_code($this->_file)),
xml_get_current_line_number($this->_file),
$filename);
xml_parser_free($this->_file);
require_once 'Zend/Translate/Exception.php';
throw new Zend_Translate_Exception($ex);
}
return $this->_data;
}
private function _startElement($file, $name, $attrib)
{
if ($this->_stag === true) {
$this->_scontent .= "<".$name;
foreach($attrib as $key => $value) {
$this->_scontent .= " $key=\"$value\"";
}
$this->_scontent .= ">";
} else if ($this->_ttag === true) {
$this->_tcontent .= "<".$name;
foreach($attrib as $key => $value) {
$this->_tcontent .= " $key=\"$value\"";
}
$this->_tcontent .= ">";
} else {
switch(strtolower($name)) {
case 'file':
$this->_source = $attrib['source-language'];
if (isset($attrib['target-language'])) {
$this->_target = $attrib['target-language'];
}
if (!isset($this->_data[$this->_source])) {
$this->_data[$this->_source] = array();
}
if (!isset($this->_data[$this->_target])) {
$this->_data[$this->_target] = array();
}
break;
case 'trans-unit':
$this->_transunit = true;
$this->_langId = $attrib['id'];
break;
case 'source':
if ($this->_transunit === true) {
$this->_scontent = null;
$this->_stag = true;
$this->_ttag = false;
}
break;
case 'target':
if ($this->_transunit === true) {
$this->_tcontent = null;
$this->_ttag = true;
$this->_stag = false;
}
break;
default:
break;
}
}
}
private function _endElement($file, $name)
{
if (($this->_stag === true) and ($name !== 'source')) {
$this->_scontent .= "</".$name.">";
} else if (($this->_ttag === true) and ($name !== 'target')) {
$this->_tcontent .= "</".$name.">";
} else {
switch (strtolower($name)) {
case 'trans-unit':
$this->_transunit = null;
$this->_langId = null;
$this->_scontent = null;
$this->_tcontent = null;
break;
case 'source':
if ($this->_useId) {
if (!empty($this->_scontent) && !empty($this->_langId) &&
!isset($this->_data[$this->_source][$this->_langId])) {
$this->_data[$this->_source][$this->_langId] = $this->_scontent;
}
} else {
if (!empty($this->_scontent) &&
!isset($this->_data[$this->_source][$this->_scontent])) {
$this->_data[$this->_source][$this->_scontent] = $this->_scontent;
}
}
$this->_stag = false;
break;
case 'target':
if ($this->_useId) {
if (!empty($this->_tcontent) && !empty($this->_langId) &&
!isset($this->_data[$this->_target][$this->_langId])) {
$this->_data[$this->_target][$this->_langId] = $this->_tcontent;
}
} else {
if (!empty($this->_tcontent) && !empty($this->_scontent) &&
!isset($this->_data[$this->_target][$this->_scontent])) {
$this->_data[$this->_target][$this->_scontent] = $this->_tcontent;
}
}
$this->_ttag = false;
break;
default:
break;
}
}
}
private function _contentElement($file, $data)
{
if (($this->_transunit !== null) and ($this->_source !== null) and ($this->_stag === true)) {
$this->_scontent .= $data;
}
if (($this->_transunit !== null) and ($this->_target !== null) and ($this->_ttag === true)) {
$this->_tcontent .= $data;
}
}
private function _findEncoding($filename)
{
$file = file_get_contents($filename, null, null, 0, 100);
if (strpos($file, "encoding") !== false) {
$encoding = substr($file, strpos($file, "encoding") + 9);
$encoding = substr($encoding, 1, strpos($encoding, $encoding[0], 1) - 1);
return $encoding;
}
return 'UTF-8';
}
/**
* Returns the adapter name
*
* @return string
*/
public function toString()
{
return "Xliff";
}
}
| agpl-3.0 |
leslin123/Bootstrap-CMS | app/config/packages/graham-campbell/logviewer/config.php | 1352 | <?php
/**
* This file is part of Laravel LogViewer by Graham Campbell.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
return array(
/*
|--------------------------------------------------------------------------
| Filters
|--------------------------------------------------------------------------
|
| This defines the filters to be put in front of the endpoints provided by
| this package. A common use will be for your own authentication filters.
|
| Default to array().
|
*/
'filters' => array('credentials:admin'),
/*
|--------------------------------------------------------------------------
| Per Page
|--------------------------------------------------------------------------
|
| This defines how many log entries are displayed per page.
|
| Default to 20.
|
*/
'per_page' => 20
);
| agpl-3.0 |
griggsk/Library-a-la-Carte | test/unit/dod_test.rb | 189 | require File.dirname(__FILE__) + '/../test_helper'
class DodTest < Test::Unit::TestCase
fixtures :dods
# Replace this with your real tests.
def test_truth
assert true
end
end
| agpl-3.0 |
avikivity/scylla | test/boost/alternator_base64_test.cc | 2922 | /*
* Copyright (C) 2020 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla 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.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#define BOOST_TEST_MODULE alternator
#include <boost/test/included/unit_test.hpp>
#include "alternator/base64.hh"
static bytes_view to_bytes_view(const std::string& s) {
return bytes_view(reinterpret_cast<const signed char*>(s.c_str()), s.size());
}
static std::map<std::string, std::string> strings {
{"", ""},
{"a", "YQ=="},
{"ab", "YWI="},
{"abc", "YWJj"},
{"abcd", "YWJjZA=="},
{"abcde", "YWJjZGU="},
{"abcdef", "YWJjZGVm"},
{"abcdefg", "YWJjZGVmZw=="},
{"abcdefgh", "YWJjZGVmZ2g="},
};
BOOST_AUTO_TEST_CASE(test_base64_encode_decode) {
for (auto& [str, encoded] : strings) {
BOOST_REQUIRE_EQUAL(base64_encode(to_bytes_view(str)), encoded);
auto decoded = base64_decode(encoded);
BOOST_REQUIRE_EQUAL(to_bytes_view(str), bytes_view(decoded));
}
}
BOOST_AUTO_TEST_CASE(test_base64_decoded_len) {
for (auto& [str, encoded] : strings) {
BOOST_REQUIRE_EQUAL(str.size(), base64_decoded_len(encoded));
}
}
BOOST_AUTO_TEST_CASE(test_base64_begins_with) {
for (auto& [str, encoded] : strings) {
for (size_t i = 0; i < str.size(); ++i) {
std::string prefix(str.c_str(), i);
std::string encoded_prefix = base64_encode(to_bytes_view(prefix));
BOOST_REQUIRE(base64_begins_with(encoded, encoded_prefix));
}
}
std::string str1 = "ABCDEFGHIJKL123456";
std::string str2 = "ABCDEFGHIJKL1234567";
std::string str3 = "ABCDEFGHIJKL12345678";
std::string encoded_str1 = base64_encode(to_bytes_view(str1));
std::string encoded_str2 = base64_encode(to_bytes_view(str2));
std::string encoded_str3 = base64_encode(to_bytes_view(str3));
std::vector<std::string> non_prefixes = {
"B", "AC", "ABD", "ACD", "ABCE", "ABCEG", "ABCDEFGHIJKLM", "ABCDEFGHIJKL123456789"
};
for (auto& non_prefix : non_prefixes) {
std::string encoded_non_prefix = base64_encode(to_bytes_view(non_prefix));
BOOST_REQUIRE(!base64_begins_with(encoded_str1, encoded_non_prefix));
BOOST_REQUIRE(!base64_begins_with(encoded_str2, encoded_non_prefix));
BOOST_REQUIRE(!base64_begins_with(encoded_str3, encoded_non_prefix));
}
}
| agpl-3.0 |
InfinniPlatform/InfinniPlatform | InfinniPlatform.Core/Http/Middlewares/PerformanceLoggingMiddleware.cs | 1950 | using System;
using System.Threading.Tasks;
using InfinniPlatform.Logging;
using Microsoft.AspNetCore.Http;
namespace InfinniPlatform.Http.Middlewares
{
/// <summary>
/// Logs performance information of request execution.
/// </summary>
public class PerformanceLoggingMiddleware
{
private readonly IPerformanceLogger<PerformanceLoggingMiddleware> _perfLogger;
private readonly RequestDelegate _next;
/// <summary>
/// Initializes a new instance of <see cref="PerformanceLoggingMiddleware" />.
/// </summary>
/// <param name="next">The delegate representing the remaining middleware in the request pipeline.</param>
/// <param name="perfLogger">Performance logger.</param>
public PerformanceLoggingMiddleware(RequestDelegate next,
IPerformanceLogger<PerformanceLoggingMiddleware> perfLogger)
{
_next = next;
_perfLogger = perfLogger;
}
/// <summary>
/// Request handling method.
/// </summary>
/// <param name="context">The <see cref="HttpContext" /> for the current request.</param>
public async Task Invoke(HttpContext context)
{
var start = DateTime.Now;
try
{
await _next.Invoke(context).ContinueWith(task => LogPerformance(context, start, task.Exception));
}
catch (Exception exception)
{
await LogPerformance(context, start, exception);
}
}
private Task LogPerformance(HttpContext httpContext, DateTime start, Exception exception)
{
// TODO Use ASP.NET log information?
var method = $"{httpContext.Request.Method}::{httpContext.Request.Path}";
_perfLogger.Log(method, start, exception);
return Task.CompletedTask;
}
}
} | agpl-3.0 |
caleboau2012/edusupport | cache/smarty/templates_c/%%E3^E32^E3280675%%header.tpl.php | 7965 | <?php /* Smarty version 2.6.11, created on 2015-11-23 16:50:19
compiled from include/DetailView/header.tpl */ ?>
<?php require_once(SMARTY_CORE_DIR . 'core.load_plugins.php');
smarty_core_load_plugins(array('plugins' => array(array('function', 'sugar_button', 'include/DetailView/header.tpl', 59, false),array('function', 'counter', 'include/DetailView/header.tpl', 63, false),array('function', 'sugar_action_menu', 'include/DetailView/header.tpl', 99, false),)), $this); ?>
{*
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
* SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd.
* Copyright (C) 2011 - 2014 Salesagility Ltd.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
* reasonably feasible for technical reasons, the Appropriate Legal Notices must
* display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM".
********************************************************************************/
*}
<?php if ($this->_tpl_vars['preForm']): ?>
<?php echo $this->_tpl_vars['preForm']; ?>
<?php endif; ?>
<script language="javascript">
{literal}
SUGAR.util.doWhen(function(){
return $("#contentTable").length == 0;
}, SUGAR.themes.actionMenu);
{/literal}
</script>
<table cellpadding="0" cellspacing="0" border="0" width="100%" id="">
<tr>
<td class="buttons" align="left" NOWRAP width="80%">
<div class="actionsContainer">
<?php if (! isset ( $this->_tpl_vars['form']['buttons'] )): ?>
<?php echo smarty_function_sugar_button(array('module' => ($this->_tpl_vars['module']),'id' => 'EDIT','view' => ($this->_tpl_vars['view']),'form_id' => 'formDetailView','appendTo' => 'detail_header_buttons'), $this);?>
<?php echo smarty_function_sugar_button(array('module' => ($this->_tpl_vars['module']),'id' => 'DUPLICATE','view' => 'EditView','form_id' => 'formDetailView','appendTo' => 'detail_header_buttons'), $this);?>
<?php echo smarty_function_sugar_button(array('module' => ($this->_tpl_vars['module']),'id' => 'DELETE','view' => ($this->_tpl_vars['view']),'form_id' => 'formDetailView','appendTo' => 'detail_header_buttons'), $this);?>
<?php else: ?>
<?php echo smarty_function_counter(array('assign' => 'num_buttons','start' => 0,'print' => false), $this);?>
<?php $_from = $this->_tpl_vars['form']['buttons']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array'); }if (count($_from)):
foreach ($_from as $this->_tpl_vars['val'] => $this->_tpl_vars['button']):
?>
<?php if (! is_array ( $this->_tpl_vars['button'] ) && in_array ( $this->_tpl_vars['button'] , $this->_tpl_vars['built_in_buttons'] )): ?>
<?php echo smarty_function_counter(array('print' => false), $this);?>
<?php echo smarty_function_sugar_button(array('module' => ($this->_tpl_vars['module']),'id' => ($this->_tpl_vars['button']),'view' => 'EditView','form_id' => 'formDetailView','appendTo' => 'detail_header_buttons'), $this);?>
<?php endif; ?>
<?php endforeach; endif; unset($_from); ?>
<?php if (count ( $this->_tpl_vars['form']['buttons'] ) > $this->_tpl_vars['num_buttons']): ?>
<?php $_from = $this->_tpl_vars['form']['buttons']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array'); }if (count($_from)):
foreach ($_from as $this->_tpl_vars['val'] => $this->_tpl_vars['button']):
?>
<?php if (is_array ( $this->_tpl_vars['button'] ) && $this->_tpl_vars['button']['customCode']): ?>
<?php echo smarty_function_sugar_button(array('module' => ($this->_tpl_vars['module']),'id' => ($this->_tpl_vars['button']),'view' => 'EditView','form_id' => 'formDetailView','appendTo' => 'detail_header_buttons'), $this);?>
<?php endif; ?>
<?php endforeach; endif; unset($_from); ?>
<?php endif; ?>
<?php if (empty ( $this->_tpl_vars['form']['hideAudit'] ) || ! $this->_tpl_vars['form']['hideAudit']): ?>
<?php echo smarty_function_sugar_button(array('module' => ($this->_tpl_vars['module']),'id' => 'Audit','view' => 'EditView','form_id' => 'formDetailView','appendTo' => 'detail_header_buttons'), $this);?>
<?php endif; endif; ?>
<form action="index.php" method="post" name="DetailView" id="formDetailView">
<input type="hidden" name="module" value="{$module}">
<input type="hidden" name="record" value="{$fields.id.value}">
<input type="hidden" name="return_action">
<input type="hidden" name="return_module">
<input type="hidden" name="return_id">
<input type="hidden" name="module_tab">
<input type="hidden" name="isDuplicate" value="false">
<input type="hidden" name="offset" value="{$offset}">
<input type="hidden" name="action" value="EditView">
<input type="hidden" name="sugar_body_only">
<?php if (isset ( $this->_tpl_vars['form']['hidden'] )): $_from = $this->_tpl_vars['form']['hidden']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array'); }if (count($_from)):
foreach ($_from as $this->_tpl_vars['field']):
echo $this->_tpl_vars['field']; ?>
<?php endforeach; endif; unset($_from); endif; ?>
</form>
<?php echo smarty_function_sugar_action_menu(array('id' => 'detail_header_action_menu','buttons' => $this->_tpl_vars['detail_header_buttons'],'class' => 'fancymenu'), $this);?>
</div>
</td>
<td align="right" width="20%">{$ADMIN_EDIT}
<?php if ($this->_tpl_vars['panelCount'] == 0): ?>
<?php if ($this->_tpl_vars['SHOW_VCR_CONTROL']): ?>
{$PAGINATION}
<?php endif; ?>
<?php echo smarty_function_counter(array('name' => 'panelCount','print' => false), $this);?>
<?php endif; ?>
</td>
<?php if (! empty ( $this->_tpl_vars['form'] ) && isset ( $this->_tpl_vars['form']['links'] )): ?>
<td align="right" width="10%"> </td>
<td align="right" width="100%" NOWRAP class="buttons">
<div class="actionsContainer">
<?php $_from = $this->_tpl_vars['form']['links']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array'); }if (count($_from)):
foreach ($_from as $this->_tpl_vars['link']):
?>
<?php echo $this->_tpl_vars['link']; ?>
<?php endforeach; endif; unset($_from); ?>
</div>
</td>
<?php endif; ?>
</tr>
</table> | agpl-3.0 |
FiviumAustralia/OpenEyes | protected/modules/OphTrConsent/views/default/signature_table1.php | 2612 | <?php
/**
* OpenEyes.
*
* (C) Moorfields Eye Hospital NHS Foundation Trust, 2008-2011
* (C) OpenEyes Foundation, 2011-2013
* This file is part of OpenEyes.
* OpenEyes 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.
* OpenEyes 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 OpenEyes in a file titled COPYING. If not, see <http://www.gnu.org/licenses/>.
*
* @link http://www.openeyes.org.uk
*
* @author OpenEyes <info@openeyes.org.uk>
* @copyright Copyright (c) 2011-2013, OpenEyes Foundation
* @license http://www.gnu.org/licenses/agpl-3.0.html The GNU Affero General Public License V3.0
*/
?>
<?php if (@$vi) {?>
<table>
<tr>
<td>Signed:............................</td>
<td>Date:...............................</td>
</tr>
<tr>
<td>Name (PRINT): <?php if (!@$mask_consultant) { echo $consultant->fullNameAndTitle; } ?></td>
<td>Job title: <?php if (!@$mask_consultant) { echo $consultant->role; } ?></td>
</tr>
</table>
<?php if (@$lastmodified && $consultant->id != $lastmodified->id) {?>
<div class="spacer"></div>
<table>
<tr>
<td>Signed:............................</td>
<td>Date:...............................</td>
</tr>
<tr>
<td>Name (PRINT): <?php echo $lastmodified->fullNameAndTitle?></td>
<td>Job title: <?php echo $lastmodified->role?></td>
</tr>
</table>
<?php }?>
<?php } else {?>
<table>
<tr>
<td>Signed:.............................................</td>
<td>Date:...........................................</td>
</tr>
<tr>
<td>Name (PRINT): <?php if (!@$mask_consultant) { echo $consultant->fullNameAndTitle; } ?></td>
<td>Job title: <?php if (!@$mask_consultant) { echo $consultant->role; } ?></td>
</tr>
</table>
<?php if (@$lastmodified && $consultant->id != $lastmodified->id) {?>
<div class="spacer"></div>
<table>
<tr>
<td>Signed:.............................................</td>
<td>Date:...........................................</td>
</tr>
<tr>
<td>Name (PRINT): <?php echo $lastmodified->fullNameAndTitle?></td>
<td>Job title: <?php echo $lastmodified->role?></td>
</tr>
</table>
<?php }?>
<?php }?>
| agpl-3.0 |
OCA/sale-workflow | sale_automatic_workflow_payment_mode/models/__init__.py | 199 | # © 2016 Camptocamp SA, Sodexis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
from . import account_payment_mode
from . import sale_order
from . import automatic_workflow_job
| agpl-3.0 |
kmee/l10n-brazil | l10n_br_nfe/models/payment_line.py | 867 | # Copyright 2020 KMEE
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models, api
from odoo.addons.spec_driven_model.models import spec_models
class FiscalPaymentLine(spec_models.StackedModel):
_name = 'l10n_br_fiscal.payment.line'
_inherit = [_name, 'nfe.40.dup']
_stacked = 'nfe.40.dup'
_spec_module = 'odoo.addons.l10n_br_nfe_spec.models.v4_00.leiauteNFe'
_stack_skip = 'nfe40_dup_cobr_id'
nfe40_nDup = fields.Char(
related='communication',
)
nfe40_dVenc = fields.Date(
related='date_maturity',
)
nfe40_vDup = fields.Monetary(
related='amount',
)
company_id = fields.Many2one(
default=lambda self: self.env.user.company_id,
)
currency_id = fields.Many2one(
default=lambda self: self.env.user.company_id.currency_id,
)
| agpl-3.0 |
markramm/juju-core | cmd/jujud/agent_test.go | 7779 | // Copyright 2012, 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package main
import (
"bytes"
stderrors "errors"
"fmt"
"net/http"
"os"
"path/filepath"
"time"
. "launchpad.net/gocheck"
"launchpad.net/juju-core/agent"
"launchpad.net/juju-core/cmd"
"launchpad.net/juju-core/environs/tools"
"launchpad.net/juju-core/juju/testing"
"launchpad.net/juju-core/state"
"launchpad.net/juju-core/state/api/machineagent"
coretesting "launchpad.net/juju-core/testing"
"launchpad.net/juju-core/version"
"launchpad.net/juju-core/worker"
)
var _ = Suite(&toolSuite{})
type toolSuite struct {
coretesting.LoggingSuite
}
var errorImportanceTests = []error{
nil,
stderrors.New("foo"),
&UpgradeReadyError{},
worker.ErrTerminateAgent,
}
func (*toolSuite) TestErrorImportance(c *C) {
for i, err0 := range errorImportanceTests {
for j, err1 := range errorImportanceTests {
c.Assert(moreImportant(err0, err1), Equals, i > j)
}
}
}
func mkTools(s string) *state.Tools {
return &state.Tools{
Binary: version.MustParseBinary(s + "-foo-bar"),
}
}
type acCreator func() (cmd.Command, *AgentConf)
// CheckAgentCommand is a utility function for verifying that common agent
// options are handled by a Command; it returns an instance of that
// command pre-parsed, with any mandatory flags added.
func CheckAgentCommand(c *C, create acCreator, args []string) cmd.Command {
com, conf := create()
err := coretesting.InitCommand(com, args)
c.Assert(conf.dataDir, Equals, "/var/lib/juju")
badArgs := append(args, "--data-dir", "")
com, conf = create()
err = coretesting.InitCommand(com, badArgs)
c.Assert(err, ErrorMatches, "--data-dir option must be set")
args = append(args, "--data-dir", "jd")
com, conf = create()
c.Assert(coretesting.InitCommand(com, args), IsNil)
c.Assert(conf.dataDir, Equals, "jd")
return com
}
// ParseAgentCommand is a utility function that inserts the always-required args
// before parsing an agent command and returning the result.
func ParseAgentCommand(ac cmd.Command, args []string) error {
common := []string{
"--data-dir", "jd",
}
return coretesting.InitCommand(ac, append(common, args...))
}
type runner interface {
Run(*cmd.Context) error
Stop() error
}
// runWithTimeout runs an agent and waits
// for it to complete within a reasonable time.
func runWithTimeout(r runner) error {
done := make(chan error)
go func() {
done <- r.Run(nil)
}()
select {
case err := <-done:
return err
case <-time.After(5 * time.Second):
}
err := r.Stop()
return fmt.Errorf("timed out waiting for agent to finish; stop error: %v", err)
}
type entity interface {
state.Tagger
SetMongoPassword(string) error
SetPassword(string) error
PasswordValid(string) bool
Refresh() error
}
// agentSuite is a fixture to be used by agent test suites.
type agentSuite struct {
testing.JujuConnSuite
}
// primeAgent writes the configuration file and tools
// for an agent with the given entity name.
// It returns the agent's configuration and the current tools.
func (s *agentSuite) primeAgent(c *C, tag, password string) (*agent.Conf, *state.Tools) {
tools := s.primeTools(c, version.Current)
tools1, err := agent.ChangeAgentTools(s.DataDir(), tag, version.Current)
c.Assert(err, IsNil)
c.Assert(tools1, DeepEquals, tools)
conf := &agent.Conf{
DataDir: s.DataDir(),
StateInfo: s.StateInfo(c),
APIInfo: s.APIInfo(c),
}
conf.StateInfo.Tag = tag
conf.StateInfo.Password = password
conf.APIInfo.Tag = tag
conf.APIInfo.Password = password
err = conf.Write()
c.Assert(err, IsNil)
return conf, tools
}
// initAgent initialises the given agent command with additional
// arguments as provided.
func (s *agentSuite) initAgent(c *C, a cmd.Command, args ...string) {
args = append([]string{"--data-dir", s.DataDir()}, args...)
err := coretesting.InitCommand(a, args)
c.Assert(err, IsNil)
}
func (s *agentSuite) proposeVersion(c *C, vers version.Number) {
cfg, err := s.State.EnvironConfig()
c.Assert(err, IsNil)
cfg, err = cfg.Apply(map[string]interface{}{
"agent-version": vers.String(),
})
c.Assert(err, IsNil)
err = s.State.SetEnvironConfig(cfg)
c.Assert(err, IsNil)
}
func (s *agentSuite) uploadTools(c *C, vers version.Binary) *state.Tools {
tgz := coretesting.TarGz(
coretesting.NewTarFile("jujud", 0777, "jujud contents "+vers.String()),
)
storage := s.Conn.Environ.Storage()
err := storage.Put(tools.StorageName(vers), bytes.NewReader(tgz), int64(len(tgz)))
c.Assert(err, IsNil)
url, err := s.Conn.Environ.Storage().URL(tools.StorageName(vers))
c.Assert(err, IsNil)
return &state.Tools{URL: url, Binary: vers}
}
// primeTools sets up the current version of the tools to vers and
// makes sure that they're available JujuConnSuite's DataDir.
func (s *agentSuite) primeTools(c *C, vers version.Binary) *state.Tools {
err := os.RemoveAll(filepath.Join(s.DataDir(), "tools"))
c.Assert(err, IsNil)
version.Current = vers
tools := s.uploadTools(c, vers)
resp, err := http.Get(tools.URL)
c.Assert(err, IsNil)
defer resp.Body.Close()
err = agent.UnpackTools(s.DataDir(), tools, resp.Body)
c.Assert(err, IsNil)
return tools
}
func (s *agentSuite) testOpenAPIState(c *C, ent entity, agentCmd Agent) {
conf, err := agent.ReadConf(s.DataDir(), ent.Tag())
c.Assert(err, IsNil)
// Check that it starts initially and changes the password
err = ent.SetPassword("initial")
c.Assert(err, IsNil)
conf.OldPassword = "initial"
conf.APIInfo.Password = ""
conf.StateInfo.Password = ""
err = conf.Write()
c.Assert(err, IsNil)
assertOpen := func(conf *agent.Conf) {
st, gotEnt, err := openAPIState(conf, agentCmd)
c.Assert(err, IsNil)
c.Assert(st, NotNil)
st.Close()
c.Assert(gotEnt.(*machineagent.Machine).Tag(), Equals, ent.Tag())
}
assertOpen(conf)
// Check that the initial password is no longer valid.
err = ent.Refresh()
c.Assert(err, IsNil)
c.Assert(ent.PasswordValid("initial"), Equals, false)
// Check that the passwords in the configuration are correct.
c.Assert(ent.PasswordValid(conf.APIInfo.Password), Equals, true)
c.Assert(conf.StateInfo.Password, Equals, conf.APIInfo.Password)
c.Assert(conf.OldPassword, Equals, "initial")
// Read the configuration and check the same
c.Assert(refreshConfig(conf), IsNil)
c.Assert(ent.PasswordValid(conf.APIInfo.Password), Equals, true)
c.Assert(conf.StateInfo.Password, Equals, conf.APIInfo.Password)
c.Assert(conf.OldPassword, Equals, "initial")
// Read the configuration and check that we can connect with it.
c.Assert(refreshConfig(conf), IsNil)
// Check we can open the API with the new configuration.
assertOpen(conf)
newPassword := conf.StateInfo.Password
// Change the password in the configuration and check
// that it falls back to using the initial password
c.Assert(refreshConfig(conf), IsNil)
conf.APIInfo.Password = "spurious"
conf.OldPassword = newPassword
c.Assert(conf.Write(), IsNil)
assertOpen(conf)
// Check that it's changed the password again...
c.Assert(conf.APIInfo.Password, Not(Equals), "spurious")
c.Assert(conf.APIInfo.Password, Not(Equals), newPassword)
// ... and that we can still open the state with the new configuration.
assertOpen(conf)
}
func (s *agentSuite) testUpgrade(c *C, agent runner, currentTools *state.Tools) {
newVers := version.Current
newVers.Patch++
newTools := s.uploadTools(c, newVers)
s.proposeVersion(c, newVers.Number)
err := runWithTimeout(agent)
c.Assert(err, FitsTypeOf, &UpgradeReadyError{})
ug := err.(*UpgradeReadyError)
c.Assert(ug.NewTools, DeepEquals, newTools)
c.Assert(ug.OldTools, DeepEquals, currentTools)
}
func refreshConfig(c *agent.Conf) error {
nc, err := agent.ReadConf(c.DataDir, c.StateInfo.Tag)
if err != nil {
return err
}
*c = *nc
return nil
}
| agpl-3.0 |
automenta/narchy | lab/src/main/java/jurls/examples/approximation/RenderFunction2D.java | 377 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package jurls.examples.approximation;
import java.awt.*;
/**
*
* @author thorsten
*/
public interface RenderFunction2D {
double compute(double x, double y);
Color getColor();
}
| agpl-3.0 |
SKIRT/PTS | do/dustpedia/make_galaxy_table.py | 63024 | #!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
## \package pts.do.modeling.plot_galaxies Plot the positions of the galaxies in the DustPedia database.
# -----------------------------------------------------------------
# Ensure Python 3 compatibility
from __future__ import absolute_import, division, print_function
# Import standard modules
import numpy as np
from collections import OrderedDict
# Import the relevant PTS classes and modules
from pts.dustpedia.core.database import DustPediaDatabase
from pts.dustpedia.core.photometry import DustPediaPhotometry
from pts.dustpedia.core.sample import DustPediaSample
from pts.core.basics.configuration import ConfigurationDefinition, parse_arguments
from pts.magic.services.s4g import get_galaxy_names
from pts.core.basics.log import log
from pts.core.basics.table import SmartTable
from pts.magic.tools.catalogs import get_galaxy_info, get_galaxy_s4g_one_component_info
from pts.core.tools import strings
from pts.magic.tools.colours import calculate_colour
from pts.core.filter.filter import parse_filter
from pts.core.tools import sequences
from pts.core.tools import tables
# -----------------------------------------------------------------
# Basic info
name_name = "Name"
ra_name = "RA"
dec_name = "DEC"
stage_name = "Stage"
type_name = "Type"
velocity_name = "Velocity"
d25_name = "D25"
inclination_name = "Inclination"
old_name_name = "name"
old_ra_name = "ra"
old_dec_name = "dec"
old_stage_name = "stage"
old_type_name = "type"
old_velocity_name = "velocity"
old_d25_name = "d25"
old_inclination_name = "inclination"
# Properties
common_name_name = "Common name"
names_name = "Names"
distance_name = "Distance"
redshift_name = "Redshift"
old_common_name_name = "common_name"
old_names_name = "names"
old_distance_name = "distance"
old_redshift_name = "redshift"
# Morphology
has_s4g_name = "Has S4G"
position_angle_name = "Position angle"
ellipticity_name = "Ellipticity"
sersic_index_name = "Sersic index"
effective_radius_name = "Effective radius"
old_has_s4g_name = "has_s4g"
old_position_angle_name = "position_angle"
old_ellipticity_name = "ellipticity"
old_sersic_index_name = "sersic_index"
old_effective_radius_name = "effective_radius"
# Set luminosities
galex_fuv_name = "GALEX FUV"
galex_nuv_name = "GALEX NUV"
sdss_u_name = "SDSS u"
sdss_g_name = "SDSS g"
sdss_r_name = "SDSS r"
sdss_i_name = "SDSS i"
sdss_z_name = "SDSS z"
twomassj_name = "2MASS J"
twomassh_name = "2MASS H"
twomassk_name = "2MASS Ks"
wise_w1_name = "WISE W1"
wise_w2_name = "WISE W2"
wise_w3_name = "WISE W3"
wise_w4_name = "WISE W4"
iras12_name = "IRAS 12 micron"
iras25_name = "IRAS 25 micron"
iras60_name = "IRAS 60 micron"
iras100_name = "IRAS 100 micron"
i1_name = "IRAC I1"
i2_name = "IRAC I2"
i3_name = "IRAC I3"
i4_name = "IRAC I4"
mips24_name = "MIPS 24 micron"
mips70_name = "MIPS 70 micron"
mips160_name = "MIPS 160 micron"
pblue_name = "Pacs blue"
pgreen_name = "Pacs green"
pred_name = "Pacs red"
psw_name = "SPIRE PSW"
pmw_name = "SPIRE PMW"
plw_name = "SPIRE PLW"
hfi_350_name = "Planck 350 micron"
hfi_550_name = "Planck 550 micron"
hfi_850_name = "Planck 850 micron"
hfi_1380_name = "Planck 1380 micron"
hfi_2100_name = "Planck 2100 micron"
hfi_3000_name = "Planck 3000 micron"
old_galex_fuv_name = "galex_fuv"
old_galex_nuv_name = "galex_nuv"
old_sdss_u_name = "sdss_u"
old_sdss_g_name = "sdss_g"
old_sdss_r_name = "sdss_r"
old_sdss_i_name = "sdss_i"
old_sdss_z_name = "sdss_z"
old_twomassj_name = "2mass_j"
old_twomassh_name = "2mass_h"
old_twomassk_name = "2mass_k"
old_wise_w1_name = "wise_w1"
old_wise_w2_name = "wise_w2"
old_wise_w3_name = "wise_w3"
old_wise_w4_name = "wise_w4"
old_iras12_name = "iras12"
old_iras25_name = "iras25"
old_iras60_name = "iras60"
old_iras100_name = "iras100"
old_i1_name = "i1"
old_i2_name = "i2"
old_i3_name = "i3"
old_i4_name = "i4"
old_mips24_name = "mips24"
old_mips70_name = "mips70"
old_mips160_name = "mips160"
old_pblue_name = "pblue"
old_pgreen_name = "pgreen"
old_pred_name = "pred"
old_psw_name = "psw"
old_pmw_name = "pmw"
old_plw_name = "plw"
old_hfi_350_name = "hfi_350"
old_hfi_550_name = "hfi_550"
old_hfi_850_name = "hfi_850"
old_hfi_1380_name = "hfi_1380"
old_hfi_2100_name = "hfi_2100"
old_hfi_3000_name = "hfi_3000"
# Colours
fuv_nuv_name = "FUV-NUV"
fuv_h_name = "FUV-H"
fuv_j_name = "FUV-J"
fuv_k_name = "FUV-Ks"
fuv_u_name = "FUV-u"
fuv_g_name = "FUV-g"
fuv_r_name = "FUV_r"
fuv_i_name = "FUV_i"
fuv_z_name = "FUV_z"
fuv_mu3_name = "FUV - 3.5 micron"
fuv_mu4_name = "FUV - 4.5 micron"
nuv_h_name = "NUV-H"
nuv_j_name = "NUV-J"
nuv_k_name = "NUV-Ks"
nuv_u_name = "NUV-u"
nuv_g_name = "NUV-g"
nuv_r_name = "NUV-r"
nuv_i_name = "NUV-i"
nuv_z_name = "NUV-z"
nuv_mu3_name = "NUV - 3.5 micron"
nuv_mu4_name = "NUV - 4.5 micron"
mu25_mu70_name = "25 micron - 70 micron"
mu25_mu60_name = "25 micron - 60 micron"
mu60_mu100_name = "60 micron - 100 micron"
mu70_mu100_name = "70 micron - 100 micron"
mu100_mu160_name = "100 micron - 160 micron"
mu160_mu250_name = "160 micron - 250 micron"
mu250_mu350_name = "250 micron - 350 micron"
mu350_mu500_name = "350 micron - 500 micron"
mu350_mu550_name = "350 micron - 550 micron"
mu500_mu850_name = "500 micron - 850 micron"
mu550_mu850_name = "550 micron - 850 micron"
mu850_mu1380_name = "850 micron - 1380 micron"
mu1380_mu2100_name = "1380 micron - 2100 micron"
mu2100_mu3000_name = "2100 micron - 3000 micron"
old_fuv_nuv_name = "fuv_nuv"
old_fuv_h_name = "fuv_h"
old_fuv_j_name = "fuv_j"
old_fuv_k_name = "fuv_k"
old_fuv_u_name = "fuv_u"
old_fuv_g_name = "fuv_g"
old_fuv_r_name = "fuv_r"
old_fuv_i_name = "fuv_i"
old_fuv_z_name = "fuv_z"
old_fuv_mu3_name = "fuv_mu3"
old_fuv_mu4_name = "fuv_mu4"
old_nuv_h_name = "nuv_h"
old_nuv_j_name = "nuv_j"
old_nuv_k_name = "nuv_k"
old_nuv_u_name = "nuv_u"
old_nuv_g_name = "nuv_g"
old_nuv_r_name = "nuv_r"
old_nuv_i_name = "nuv_i"
old_nuv_z_name = "nuv_z"
old_nuv_mu3_name = "nuv_mu3"
old_nuv_mu4_name = "nuv_mu4"
old_mu25_mu70_name = "mu25_mu70"
old_mu25_mu60_name = "mu25_mu60"
old_mu60_mu100_name = "mu60_mu100"
old_mu70_mu100_name = "mu70_mu100"
old_mu100_mu160_name = "mu100_mu160"
old_mu160_mu250_name = "mu160_mu250"
old_mu250_mu350_name = "mu250_mu350"
old_mu350_mu500_name = "mu350_mu500"
old_mu350_mu550_name = "mu350_mu550"
old_mu500_mu850_name = "mu500_mu850"
old_mu550_mu850_name = "mu550_mu850"
old_mu850_mu1380_name = "mu850_mu1380"
old_mu1380_mu2100_name = "mu1380_mu2100"
old_mu2100_mu3000_name = "mu2100_mu3000"
# Models
sfr_name = "SFR"
sfr_error_name = "SFR error"
dust_mass_name = "Dust mass"
dust_mass_error_name = "Dust mass error"
dust_luminosity_name = "Dust luminosity"
dust_luminosity_error_name = "Dust luminosity error"
dust_temperature_name = "Dust temperature"
dust_temperature_error_name = "Dust temperature error"
stellar_mass_name = "Stellar mass"
stellar_mass_error_name = "Stellar mass error"
stellar_luminosity_name = "Stellar luminosity"
stellar_luminosity_error_name = "Stellar luminosity error"
old_sfr_name = "sfr"
old_sfr_error_name = "sfr_error"
old_dust_mass_name = "dust_mass"
old_dust_mass_error_name = "dust_mass_error"
old_dust_luminosity_name = "dust_luminosity"
old_dust_luminosity_error_name = "dust_luminosity_error"
old_dust_temperature_name = "dust_temperature"
old_dust_temperature_error_name = "dust_temperature_error"
old_stellar_mass_name = "stellar_mass"
old_stellar_mass_error_name = "stellar_mass_error"
old_stellar_luminosity_name = "stellar_luminosity"
old_stellar_luminosity_error_name = "stellar_luminosity_error"
# Presence
has_galex_name = "Has GALEX"
has_sdss_name = "Has SDSS"
has_2mass_name = "Has 2MASS"
has_irac_name = "Has IRAC"
has_mips_name = "Has MIPS"
has_wise_name = "Has WISE"
has_pacs_name = "Has Pacs"
has_spire_name = "Has SPIRE"
has_planck_name = "Has Planck"
old_has_galex_name = "has_galex"
old_has_sdss_name = "has_sdss"
old_has_2mass_name = "has_2mass"
old_has_irac_name = "has_irac"
old_has_mips_name = "has_mips"
old_has_wise_name = "has_wise"
old_has_pacs_name = "has_pacs"
old_has_spire_name = "has_spire"
old_has_planck_name = "has_planck"
# -----------------------------------------------------------------
info_names = [name_name, ra_name, dec_name, stage_name, type_name, velocity_name, d25_name,
inclination_name]
properties_names = [common_name_name, names_name, distance_name, redshift_name]
morphology_names = [has_s4g_name, position_angle_name, ellipticity_name, sersic_index_name, effective_radius_name]
luminosities_names = [galex_fuv_name, galex_nuv_name, sdss_u_name, sdss_g_name, sdss_r_name, sdss_i_name, sdss_z_name,
twomassj_name, twomassh_name, twomassk_name, wise_w1_name, wise_w2_name, wise_w3_name, wise_w4_name, iras12_name,
iras25_name, iras60_name, iras100_name, i1_name, i2_name, i3_name, i4_name, mips24_name, mips70_name, mips160_name,
pblue_name, pgreen_name, pred_name, psw_name, pmw_name, plw_name, hfi_350_name, hfi_550_name, hfi_850_name,
hfi_1380_name, hfi_2100_name, hfi_3000_name]
colours_names = [fuv_nuv_name, fuv_h_name, fuv_j_name, fuv_k_name, fuv_u_name,
fuv_g_name, fuv_r_name, fuv_i_name, fuv_z_name, fuv_mu3_name, fuv_mu4_name, nuv_h_name, nuv_j_name, nuv_k_name,
nuv_u_name, nuv_g_name, nuv_r_name, nuv_i_name, nuv_z_name, nuv_mu3_name, nuv_mu4_name, mu25_mu70_name,
mu25_mu60_name, mu60_mu100_name, mu70_mu100_name, mu100_mu160_name, mu160_mu250_name, mu250_mu350_name,
mu350_mu500_name, mu350_mu550_name, mu500_mu850_name, mu550_mu850_name, mu850_mu1380_name, mu1380_mu2100_name,
mu2100_mu3000_name]
models_names = [sfr_name, sfr_error_name, dust_mass_name, dust_mass_error_name, dust_luminosity_name,
dust_luminosity_error_name, dust_temperature_name, dust_temperature_error_name, stellar_mass_name,
stellar_mass_error_name, stellar_luminosity_name, stellar_luminosity_error_name]
presence_names = [has_galex_name, has_sdss_name, has_2mass_name, has_irac_name, has_mips_name, has_wise_name, has_pacs_name, has_spire_name, has_planck_name]
# -----------------------------------------------------------------
column_names = info_names + properties_names + morphology_names + luminosities_names + colours_names + models_names + presence_names
# -----------------------------------------------------------------
# Create the configuration
definition = ConfigurationDefinition()
# Maximum number of galaxies
definition.add_optional("ngalaxies", "positive_integer", "max number of galaxies")
definition.add_optional("filename", "string", "galaxy table filename", "galaxies")
definition.add_flag("random", "make random subset of ngalaxies galaxies")
# Galaxy names
definition.add_optional("names", "string_list", "galaxy names")
definition.add_optional("extend", "file_path", "extend existing table file")
# Adjust existing table
definition.add_optional("adjust", "file_path", "adjust existing table file")
definition.add_optional("columns", "string_list", "column names to adjust", choices=column_names)
# Get configuration
config = parse_arguments("make_galaxy_table", definition)
# -----------------------------------------------------------------
# Create the database instance
database = DustPediaDatabase()
#username, password = get_account()
#database.login(username, password)
# -----------------------------------------------------------------
current_table = None
if config.names is not None:
if config.extend is not None: raise ValueError("Cannot specify names and extend")
galaxy_names = config.names
else:
sample = DustPediaSample()
galaxy_names = sample.get_names()
# Check from current table
if config.extend is not None:
current_table = SmartTable.from_file(config.extend)
current_galaxy_names = list(current_table["name"])
galaxy_names = sequences.elements_not_in_other(galaxy_names, current_galaxy_names)
# Make subset
if config.ngalaxies is not None:
if config.random: galaxy_names = sequences.random_subset(galaxy_names, config.ngalaxies, avoid_duplication=True)
else: galaxy_names = sequences.get_first_values(galaxy_names, config.ngalaxies)
# -----------------------------------------------------------------
ngalaxies = len(galaxy_names)
# -----------------------------------------------------------------
# Photometry
photometry = DustPediaPhotometry()
# -----------------------------------------------------------------
s4g_names = get_galaxy_names()
# -----------------------------------------------------------------
galaxies = []
# -----------------------------------------------------------------
galaxy_catalog_names = ["IC", "UGC", "MCG", "CGCG", "VCC", "NPM1", "ESO", "NGC", "PGC", "UGCA", "IRAS", "KUG", "KIG", "MRC", "MRK", "DUKST", "GIN"]
# -----------------------------------------------------------------
# Initialize filter objects
fuv_filter = parse_filter("GALEX FUV")
nuv_filter = parse_filter("GALEX NUV")
u_filter = parse_filter("SDSS u")
g_filter = parse_filter("SDSS g")
r_filter = parse_filter("SDSS r")
i_filter = parse_filter("SDSS i")
z_filter = parse_filter("SDSS z")
j_filter = parse_filter("2MASS J")
h_filter = parse_filter("2MASS H")
k_filter = parse_filter("2MASS Ks")
w1_filter = parse_filter("WISE W1")
w2_filter = parse_filter("WISE W2")
w3_filter = parse_filter("WISE W3")
w4_filter = parse_filter("WISE W4")
iras12_filter = parse_filter("IRAS 12mu")
iras25_filter = parse_filter("IRAS 25mu")
iras60_filter = parse_filter("IRAS 60mu")
iras100_filter = parse_filter("IRAS 100mu")
i1_filter = parse_filter("IRAC I1")
i2_filter = parse_filter("IRAC I2")
i3_filter = parse_filter("IRAC I3")
i4_filter = parse_filter("IRAC I4")
mips24_filter = parse_filter("MIPS 24mu")
mips70_filter = parse_filter("MIPS 70mu")
mips160_filter = parse_filter("MIPS 160mu")
pblue_filter = parse_filter("Pacs blue")
pgreen_filter = parse_filter("Pacs green")
pred_filter = parse_filter("Pacs red")
psw_filter = parse_filter("SPIRE PSW")
pmw_filter = parse_filter("SPIRE PMW")
plw_filter = parse_filter("SPIRE PLW")
hfi_350_filter = parse_filter("HFI 857")
hfi_550_filter = parse_filter("HFI 545")
hfi_850_filter = parse_filter("HFI 353")
hfi_1380_filter = parse_filter("HFI 217")
hfi_2100_filter = parse_filter("HFI 143")
hfi_3000_filter = parse_filter("HFI 100")
# -----------------------------------------------------------------
# Check
if config.adjust is not None and config.columns is None: raise ValueError("Column names to adjust must be specified")
# Load table to extend
if config.extend is not None: table = current_table
elif config.adjust is not None: table = SmartTable.from_file(config.adjust)
else: table = None
# -----------------------------------------------------------------
def get_fluxes(galaxy_name):
# Get photometry
observed_sed = photometry.get_sed(galaxy_name, add_iras=True, add_planck=True, exact_name=True)
# Initialize fluxes
fuv_flux = None
nuv_flux = None
u_flux = None
g_flux = None
r_flux = None
i_flux = None
z_flux = None
j_flux = None
h_flux = None
k_flux = None
w1_flux = None
w2_flux = None
w3_flux = None
w4_flux = None
iras12_flux = None
iras25_flux = None
iras60_flux = None
iras100_flux = None
i1_flux = None
i2_flux = None
i3_flux = None
i4_flux = None
mips24_flux = None
mips70_flux = None
mips160_flux = None
pblue_flux = None
pgreen_flux = None
pred_flux = None
psw_flux = None
pmw_flux = None
plw_flux = None
hfi_350_flux = None
hfi_550_flux = None
hfi_850_flux = None
hfi_1380_flux = None
hfi_2100_flux = None
hfi_3000_flux = None
# Loop over the entries in the observed SED
for index in range(len(observed_sed)):
# Get the filter
fltr = observed_sed.get_filter(index)
#filter_name = str(fltr)
# Get the flux
flux = observed_sed.get_photometry(index, add_unit=True)
# Set correct flux
if fltr == fuv_filter: fuv_flux = flux
elif fltr == nuv_filter: nuv_flux = flux
elif fltr == u_filter: u_flux = flux
elif fltr == g_filter: g_flux = flux
elif fltr == r_filter: r_flux = flux
elif fltr == i_filter: i_flux = flux
elif fltr == z_filter: z_flux = flux
elif fltr == j_filter: j_flux = flux
elif fltr == h_filter: h_flux = flux
elif fltr == k_filter: k_flux = flux
elif fltr == w1_filter: w1_flux = flux
elif fltr == w2_filter: w2_flux = flux
elif fltr == w3_filter: w3_flux = flux
elif fltr == w4_filter: w4_flux = flux
elif fltr == iras12_filter: iras12_flux = flux
elif fltr == iras25_filter: iras25_flux = flux
elif fltr == iras60_filter: iras60_flux = flux
elif fltr == iras100_filter: iras100_flux = flux
elif fltr == i1_filter: i1_flux = flux
elif fltr == i2_filter: i2_flux = flux
elif fltr == i3_filter: i3_flux = flux
elif fltr == i4_filter: i4_flux = flux
elif fltr == mips24_filter: mips24_flux = flux
elif fltr == mips70_filter: mips70_flux = flux
elif fltr == mips160_filter: mips160_flux = flux
elif fltr == pblue_filter: pblue_flux = flux
elif fltr == pgreen_filter: pgreen_flux = flux
elif fltr == pred_filter: pred_flux = flux
elif fltr == psw_filter: psw_flux = flux
elif fltr == pmw_filter: pmw_flux = flux
elif fltr == plw_filter: plw_flux = flux
elif fltr == hfi_350_filter: hfi_350_flux = flux
elif fltr == hfi_550_filter: hfi_550_flux = flux
elif fltr == hfi_850_filter: hfi_850_flux = flux
elif fltr == hfi_1380_filter: hfi_1380_flux = flux
elif fltr == hfi_2100_filter: hfi_2100_flux = flux
elif fltr == hfi_3000_filter: hfi_3000_flux = flux
else: log.warning("Unknown filter: " + str(fltr))
# Return the fluxes
return fuv_flux, nuv_flux, u_flux, g_flux, r_flux, i_flux, z_flux, j_flux, h_flux, k_flux, w1_flux, w2_flux, \
w3_flux, w4_flux, iras12_flux, iras25_flux, iras60_flux, iras100_flux, i1_flux, i2_flux, i3_flux, i4_flux, \
mips24_flux, mips70_flux, mips160_flux, pblue_flux, pgreen_flux, pred_flux, psw_flux, pmw_flux, plw_flux, \
hfi_350_flux, hfi_550_flux, hfi_850_flux, hfi_1380_flux, hfi_2100_flux, hfi_3000_flux
# -----------------------------------------------------------------
def get_colours(fuv_flux, nuv_flux, u_flux, g_flux, r_flux, i_flux, z_flux, j_flux, h_flux, k_flux, w1_flux, w2_flux,
iras25_flux, iras60_flux, iras100_flux, i1_flux, i2_flux, mips24_flux, mips70_flux, mips160_flux,
pblue_flux, pgreen_flux, pred_flux, psw_flux, pmw_flux, plw_flux, hfi_350_flux, hfi_550_flux,
hfi_850_flux, hfi_1380_flux, hfi_2100_flux, hfi_3000_flux):
"""
This function ...
:return:
"""
# FUV-NUV
if fuv_flux is not None and nuv_flux is not None: fuv_nuv = calculate_colour(fuv_flux, nuv_flux)
else: fuv_nuv = None
# FUV-H
if fuv_flux is not None and h_flux is not None: fuv_h = calculate_colour(fuv_flux, h_flux)
else: fuv_h = None
# FUV-J
if fuv_flux is not None and j_flux is not None: fuv_j = calculate_colour(fuv_flux, j_flux)
else: fuv_j = None
# FUV-K
if fuv_flux is not None and k_flux is not None: fuv_k = calculate_colour(fuv_flux, k_flux)
else: fuv_k = None
# FUV-u
if fuv_flux is not None and u_flux is not None: fuv_u = calculate_colour(fuv_flux, u_flux)
else: fuv_u = None
# FUV-g
if fuv_flux is not None and g_flux is not None: fuv_g = calculate_colour(fuv_flux, g_flux)
else: fuv_g = None
# FUV-r
if fuv_flux is not None and r_flux is not None: fuv_r = calculate_colour(fuv_flux, r_flux)
else: fuv_r = None
# FUV-i
if fuv_flux is not None and i_flux is not None: fuv_i = calculate_colour(fuv_flux, i_flux)
else: fuv_i = None
# FUV-z
if fuv_flux is not None and z_flux is not None: fuv_z = calculate_colour(fuv_flux, z_flux)
else: fuv_z = None
# FUV-3.5
if fuv_flux is not None and i1_flux is not None: fuv_mu3 = calculate_colour(fuv_flux, i1_flux)
elif fuv_flux is not None and w1_flux is not None: fuv_mu3 = calculate_colour(fuv_flux, w1_flux)
else: fuv_mu3 = None
# FUV-4.5
if fuv_flux is not None and i2_flux is not None: fuv_mu4 = calculate_colour(fuv_flux, i2_flux)
elif fuv_flux is not None and w2_flux is not None: fuv_mu4 = calculate_colour(fuv_flux, w2_flux)
else: fuv_mu4 = None
# NUV-H
if nuv_flux is not None and h_flux is not None: nuv_h = calculate_colour(nuv_flux, h_flux)
else: nuv_h = None
# NUV-J
if nuv_flux is not None and j_flux is not None: nuv_j = calculate_colour(nuv_flux, j_flux)
else: nuv_j = None
# NUV-K
if nuv_flux is not None and k_flux is not None: nuv_k = calculate_colour(nuv_flux, k_flux)
else: nuv_k = None
# NUV-u
if nuv_flux is not None and u_flux is not None: nuv_u = calculate_colour(nuv_flux, u_flux)
else: nuv_u = None
# NUV-g
if nuv_flux is not None and g_flux is not None: nuv_g = calculate_colour(nuv_flux, g_flux)
else: nuv_g = None
# NUV-r
if nuv_flux is not None and r_flux is not None: nuv_r = calculate_colour(nuv_flux, r_flux)
else: nuv_r = None
# NUV-i
if nuv_flux is not None and i_flux is not None: nuv_i = calculate_colour(nuv_flux, i_flux)
else: nuv_i = None
# NUV-z
if nuv_flux is not None and z_flux is not None: nuv_z = calculate_colour(nuv_flux, z_flux)
else: nuv_z = None
# NUV-3.5
if nuv_flux is not None and i1_flux is not None: nuv_mu3 = calculate_colour(nuv_flux, i1_flux)
elif nuv_flux is not None and w1_flux is not None: nuv_mu3 = calculate_colour(nuv_flux, w1_flux)
else: nuv_mu3 = None
# NUV-4.5
if nuv_flux is not None and i2_flux is not None: nuv_mu4 = calculate_colour(nuv_flux, i2_flux)
elif nuv_flux is not None and w2_flux is not None: nuv_mu4 = calculate_colour(nuv_flux, w2_flux)
else: nuv_mu4 = None
# 25-70
if mips24_flux is not None and pblue_flux is not None: mu25_mu70 = calculate_colour(mips24_flux, pblue_flux)
elif mips24_flux is not None and mips70_flux is not None: mu25_mu70 = calculate_colour(mips24_flux, mips70_flux)
elif iras25_flux is not None and pblue_flux is not None: mu25_mu70 = calculate_colour(iras25_flux, pblue_flux)
elif iras25_flux is not None and mips70_flux is not None: mu25_mu70 = calculate_colour(iras25_flux, mips70_flux)
else: mu25_mu70 = None
# 25-60
if iras25_flux is not None and iras60_flux is not None: mu25_mu60 = calculate_colour(iras25_flux, iras60_flux)
elif mips24_flux is not None and iras60_flux is not None: mu25_mu60 = calculate_colour(mips24_flux, iras60_flux)
else: mu25_mu60 = None
# 60-100
if iras60_flux is not None and pgreen_flux is not None: mu60_mu100 = calculate_colour(iras60_flux, pgreen_flux)
elif iras60_flux is not None and iras100_flux is not None: mu60_mu100 = calculate_colour(iras60_flux, iras100_flux)
else: mu60_mu100 = None
# 70-100
if pblue_flux is not None and pgreen_flux is not None: mu70_mu100 = calculate_colour(pblue_flux, pgreen_flux)
elif pblue_flux is not None and iras100_flux is not None: mu70_mu100 = calculate_colour(pblue_flux, iras100_flux)
elif mips70_flux is not None and pgreen_flux is not None: mu70_mu100 = calculate_colour(mips70_flux, pgreen_flux)
elif mips70_flux is not None and iras100_flux is not None: mu70_mu100 = calculate_colour(mips70_flux, iras100_flux)
else: mu70_mu100 = None
# 100-160
if pgreen_flux is not None and pred_flux is not None: mu100_mu160 = calculate_colour(pgreen_flux, pred_flux)
elif pgreen_flux is not None and mips160_flux is not None: mu100_mu160 = calculate_colour(pgreen_flux, mips160_flux)
elif iras100_flux is not None and pred_flux is not None: mu100_mu160 = calculate_colour(iras100_flux, pred_flux)
elif iras100_flux is not None and mips160_flux is not None: mu100_mu160 = calculate_colour(iras100_flux, mips160_flux)
else: mu100_mu160 = None
# 160-250
if pred_flux is not None and psw_flux is not None: mu160_mu250 = calculate_colour(pred_flux, psw_flux)
elif mips160_flux is not None and psw_flux is not None: mu160_mu250 = calculate_colour(mips160_flux, psw_flux)
else: mu160_mu250 = None
# 250-350
if psw_flux is not None and pmw_flux is not None: mu250_mu350 = calculate_colour(psw_flux, pmw_flux)
elif psw_flux is not None and hfi_350_flux is not None: mu250_mu350 = calculate_colour(psw_flux, hfi_350_flux)
else: mu250_mu350 = None
# 350-500
if pmw_flux is not None and plw_flux is not None: mu350_mu500 = calculate_colour(pmw_flux, plw_flux)
elif hfi_350_flux is not None and plw_flux is not None: mu350_mu500 = calculate_colour(hfi_350_flux, plw_flux)
else: mu350_mu500 = None
# 350-550
if pmw_flux is not None and hfi_550_flux is not None: mu350_mu550 = calculate_colour(pmw_flux, hfi_550_flux)
elif hfi_350_flux is not None and hfi_550_flux is not None: mu350_mu550 = calculate_colour(hfi_350_flux, hfi_550_flux)
else: mu350_mu550 = None
# 500-850
if plw_flux is not None and hfi_850_flux is not None: mu500_mu850 = calculate_colour(plw_flux, hfi_850_flux)
else: mu500_mu850 = None
# 550-850
if hfi_550_flux is not None and hfi_850_flux is not None: mu550_mu850 = calculate_colour(hfi_550_flux, hfi_850_flux)
else: mu550_mu850 = None
# 850-1380
if hfi_850_flux is not None and hfi_1380_flux is not None: mu850_mu1380 = calculate_colour(hfi_850_flux, hfi_1380_flux)
else: mu850_mu1380 = None
# 1380-2100
if hfi_1380_flux is not None and hfi_2100_flux is not None: mu1380_mu2100 = calculate_colour(hfi_1380_flux, hfi_2100_flux)
else: mu1380_mu2100 = None
# 2100-3000
if hfi_2100_flux is not None and hfi_3000_flux is not None: mu2100_mu3000 = calculate_colour(hfi_2100_flux, hfi_3000_flux)
else: mu2100_mu3000 = None
# Check for NaN
if fuv_nuv is not None and np.isnan(fuv_nuv): fuv_nuv = None
if fuv_h is not None and np.isnan(fuv_h): fuv_h = None
if fuv_j is not None and np.isnan(fuv_j): fuv_j = None
if fuv_k is not None and np.isnan(fuv_k): fuv_k = None
if fuv_u is not None and np.isnan(fuv_u): fuv_u = None
if fuv_g is not None and np.isnan(fuv_g): fuv_g = None
if fuv_r is not None and np.isnan(fuv_r): fuv_r = None
if fuv_i is not None and np.isnan(fuv_i): fuv_i = None
if fuv_z is not None and np.isnan(fuv_z): fuv_z = None
if fuv_mu3 is not None and np.isnan(fuv_mu3): fuv_mu3 = None
if fuv_mu4 is not None and np.isnan(fuv_mu4): fuv_mu4 = None
if nuv_h is not None and np.isnan(nuv_h): nuv_h = None
if nuv_j is not None and np.isnan(nuv_j): nuv_j = None
if nuv_k is not None and np.isnan(nuv_k): nuv_k = None
if nuv_u is not None and np.isnan(nuv_u): nuv_u = None
if nuv_g is not None and np.isnan(nuv_g): nuv_g = None
if nuv_r is not None and np.isnan(nuv_r): nuv_r = None
if nuv_i is not None and np.isnan(nuv_i): nuv_i = None
if nuv_z is not None and np.isnan(nuv_z): nuv_z = None
if nuv_mu3 is not None and np.isnan(nuv_mu3): nuv_mu3 = None
if nuv_mu4 is not None and np.isnan(nuv_mu4): nuv_mu4 = None
if mu25_mu70 is not None and np.isnan(mu25_mu70): mu25_mu70 = None
if mu25_mu60 is not None and np.isnan(mu25_mu60): mu25_mu60 = None
if mu60_mu100 is not None and np.isnan(mu60_mu100): mu60_mu100 = None
if mu70_mu100 is not None and np.isnan(mu70_mu100): mu70_mu100 = None
if mu100_mu160 is not None and np.isnan(mu100_mu160): mu100_mu160 = None
if mu160_mu250 is not None and np.isnan(mu160_mu250): mu160_mu250 = None
if mu250_mu350 is not None and np.isnan(mu250_mu350): mu250_mu350 = None
if mu350_mu500 is not None and np.isnan(mu350_mu500): mu350_mu500 = None
if mu350_mu550 is not None and np.isnan(mu350_mu550): mu350_mu550 = None
if mu500_mu850 is not None and np.isnan(mu500_mu850): mu500_mu850 = None
if mu550_mu850 is not None and np.isnan(mu550_mu850): mu550_mu850 = None
if mu850_mu1380 is not None and np.isnan(mu850_mu1380): mu850_mu1380 = None
if mu1380_mu2100 is not None and np.isnan(mu1380_mu2100): mu1380_mu2100 = None
if mu2100_mu3000 is not None and np.isnan(mu2100_mu3000): mu2100_mu3000 = None
# Return the colours
return fuv_nuv, fuv_h, fuv_j, fuv_k, fuv_u, fuv_g, fuv_r, fuv_i, fuv_z, fuv_mu3, fuv_mu4, nuv_h, nuv_j, nuv_k, nuv_u, \
nuv_g, nuv_r, nuv_i, nuv_z, nuv_mu3, nuv_mu4, mu25_mu70, mu25_mu60, mu60_mu100, mu70_mu100, mu100_mu160, \
mu160_mu250, mu250_mu350, mu350_mu500, mu350_mu550, mu500_mu850, mu550_mu850, mu850_mu1380, mu1380_mu2100, mu2100_mu3000
# -----------------------------------------------------------------
def calculate_luminosities(fuv_flux, nuv_flux, u_flux, g_flux, r_flux, i_flux, z_flux, j_flux, h_flux, k_flux, w1_flux,
w2_flux, w3_flux, w4_flux, iras12_flux, iras25_flux, iras60_flux, iras100_flux, i1_flux,
i2_flux, i3_flux, i4_flux, mips24_flux, mips70_flux, mips160_flux, pblue_flux, pgreen_flux,
pred_flux, psw_flux, pmw_flux, plw_flux, hfi_350_flux, hfi_550_flux, hfi_850_flux,
hfi_1380_flux, hfi_2100_flux, hfi_3000_flux, gal_distance):
"""
This function ...
:return:
"""
# Convert fluxes to luminosities
if gal_distance is not None:
fuv_lum = fuv_flux.to("W/micron", distance=gal_distance, filter=fuv_filter) if fuv_flux is not None else None
nuv_lum = nuv_flux.to("W/micron", distance=gal_distance, filter=nuv_filter) if nuv_flux is not None else None
u_lum = u_flux.to("W/micron", distance=gal_distance, filter=u_filter) if u_flux is not None else None
g_lum = g_flux.to("W/micron", distance=gal_distance, filter=g_filter) if g_flux is not None else None
r_lum = r_flux.to("W/micron", distance=gal_distance, filter=r_filter) if r_flux is not None else None
i_lum = i_flux.to("W/micron", distance=gal_distance, filter=i_filter) if i_flux is not None else None
z_lum = z_flux.to("W/micron", distance=gal_distance, filter=z_filter) if z_flux is not None else None
j_lum = j_flux.to("W/micron", distance=gal_distance, filter=j_filter) if j_flux is not None else None
h_lum = h_flux.to("W/micron", distance=gal_distance, filter=h_filter) if h_flux is not None else None
k_lum = k_flux.to("W/micron", distance=gal_distance, filter=k_filter) if k_flux is not None else None
w1_lum = w1_flux.to("W/micron", distance=gal_distance, filter=w1_filter) if w1_flux is not None else None
w2_lum = w2_flux.to("W/micron", distance=gal_distance, filter=w2_filter) if w2_flux is not None else None
w3_lum = w3_flux.to("W/micron", distance=gal_distance, filter=w3_filter) if w3_flux is not None else None
w4_lum = w4_flux.to("W/micron", distance=gal_distance, filter=w4_filter) if w4_flux is not None else None
iras12_lum = iras12_flux.to("W/micron", distance=gal_distance, filter=iras12_filter) if iras12_flux is not None else None
iras25_lum = iras25_flux.to("W/micron", distance=gal_distance, filter=iras25_filter) if iras25_flux is not None else None
iras60_lum = iras60_flux.to("W/micron", distance=gal_distance, filter=iras60_filter) if iras60_flux is not None else None
iras100_lum = iras100_flux.to("W/micron", distance=gal_distance, filter=iras100_filter) if iras100_flux is not None else None
i1_lum = i1_flux.to("W/micron", distance=gal_distance, filter=i1_filter) if i1_flux is not None else None
i2_lum = i2_flux.to("W/micron", distance=gal_distance, filter=i2_filter) if i2_flux is not None else None
i3_lum = i3_flux.to("W/micron", distance=gal_distance, filter=i3_filter) if i3_flux is not None else None
i4_lum = i4_flux.to("W/micron", distance=gal_distance, filter=i4_filter) if i4_flux is not None else None
mips24_lum = mips24_flux.to("W/micron", distance=gal_distance, filter=mips24_filter) if mips24_flux is not None else None
mips70_lum = mips70_flux.to("W/micron", distance=gal_distance, filter=mips70_filter) if mips70_flux is not None else None
mips160_lum = mips160_flux.to("W/micron", distance=gal_distance, filter=mips160_filter) if mips160_flux is not None else None
pblue_lum = pblue_flux.to("W/micron", distance=gal_distance, filter=pblue_filter) if pblue_flux is not None else None
pgreen_lum = pgreen_flux.to("W/micron", distance=gal_distance, filter=pgreen_filter) if pgreen_flux is not None else None
pred_lum = pred_flux.to("W/micron", distance=gal_distance, filter=pred_filter) if pred_flux is not None else None
psw_lum = psw_flux.to("W/micron", distance=gal_distance, filter=psw_filter) if psw_flux is not None else None
pmw_lum = pmw_flux.to("W/micron", distance=gal_distance, filter=pmw_filter) if pmw_flux is not None else None
plw_lum = plw_flux.to("W/micron", distance=gal_distance, filter=plw_filter) if plw_flux is not None else None
hfi_350_lum = hfi_350_flux.to("W/micron", distance=gal_distance, filter=hfi_350_filter) if hfi_350_flux is not None else None
hfi_550_lum = hfi_550_flux.to("W/micron", distance=gal_distance, filter=hfi_550_filter) if hfi_550_flux is not None else None
hfi_850_lum = hfi_850_flux.to("W/micron", distance=gal_distance, filter=hfi_850_filter) if hfi_850_flux is not None else None
hfi_1380_lum = hfi_1380_flux.to("W/micron", distance=gal_distance, filter=hfi_1380_filter) if hfi_1380_flux is not None else None
hfi_2100_lum = hfi_2100_flux.to("W/micron", distance=gal_distance, filter=hfi_2100_filter) if hfi_2100_flux is not None else None
hfi_3000_lum = hfi_3000_flux.to("W/micron", distance=gal_distance, filter=hfi_3000_filter) if hfi_3000_flux is not None else None
# No distance: luminosities cannot be calculated
else: fuv_lum = nuv_lum = u_lum = g_lum = r_lum = i_lum = z_lum = j_lum = h_lum = k_lum = w1_lum = w2_lum =w3_lum = w4_lum = iras12_lum = iras25_lum = iras60_lum = iras100_lum = i1_lum = i2_lum = i3_lum = i4_lum = mips24_lum = mips70_lum = mips160_lum = pblue_lum = pgreen_lum = pred_lum = psw_lum = pmw_lum = plw_lum =hfi_350_lum = hfi_550_lum = hfi_850_lum = hfi_1380_lum = hfi_2100_lum = hfi_3000_lum = None
# Return
return fuv_lum, nuv_lum, u_lum, g_lum, r_lum, i_lum, z_lum, j_lum, h_lum, k_lum, w1_lum, w2_lum, w3_lum, w4_lum, \
iras12_lum, iras25_lum, iras60_lum, iras100_lum, i1_lum, i2_lum, i3_lum, i4_lum, mips24_lum, mips70_lum, \
mips160_lum, pblue_lum, pgreen_lum, pred_lum, psw_lum, pmw_lum, plw_lum, hfi_350_lum, hfi_550_lum, hfi_850_lum, \
hfi_1380_lum, hfi_2100_lum, hfi_3000_lum
# -----------------------------------------------------------------
def get_model_parameters(galaxy_name):
"""
This function ...
:param galaxy_name:
:return:
"""
# Initialize the parameters
sfr = None
sfr_error = None
dust_mass = None
dust_mass_error = None
dust_luminosity = None
dust_luminosity_error = None
dust_temperature = None
dust_temperature_error = None
stellar_mass = None
stellar_mass_error = None
stellar_luminosity = None
stellar_luminosity_error = None
# There are results from CIGALE fits
if database.has_cigale_parameters(galaxy_name):
# Get the parameters
parameters = database.get_cigale_parameters(galaxy_name)
# Dust parameters
dust_mass = parameters["dust_mass"]
dust_mass_error = parameters["dust_mass_error"]
dust_luminosity = parameters["dust_luminosity"]
dust_luminosity_error = parameters["dust_luminosity_error"]
#fuv_attenuation = parameters["fuv_attenuation"]
#fuv_attenuation_error = parameters["fuv_attenuation_error"]
# Stellar parameters
sfr = parameters["sfr"]
sfr_error = parameters["sfr_error"]
stellar_mass = parameters["stellar_mass"]
stellar_mass_error = parameters["stellar_mass_error"]
stellar_luminosity = parameters["stellar_luminosity"]
stellar_luminosity_error = parameters["stellar_luminosity_error"]
# There are results from black body fits
elif database.has_dust_black_body_table_parameters(galaxy_name):
# Get parameters
parameters = database.get_dust_black_body_table_parameters(galaxy_name)
# Dust parameters
dust_mass = parameters["dust_mass"]
dust_mass_error = parameters["dust_mass_error"]
dust_luminosity = parameters["dust_luminosity"]
dust_luminosity_error = parameters["dust_luminosity_error"]
dust_temperature = parameters["dust_temperature"]
dust_temperature_error = parameters["dust_temperature_error"]
else: log.warning("No model parameters available for galaxy '" + galaxy_name + "'")
# Return the parameters
return sfr, sfr_error, dust_mass, dust_mass_error, dust_luminosity, dust_luminosity_error, dust_temperature, \
dust_temperature_error, stellar_mass, stellar_mass_error, stellar_luminosity, stellar_luminosity_error
# -----------------------------------------------------------------
def get_presence(galaxy_name):
"""
This function ...
:param galaxy_name:
:return:
"""
#observatories = database.get_observatories(galaxy_name)
#print("OBS:", observatories)
#filters = database.get_image_filters_per_observatory(galaxy_name)
#print(filters)
# Check presence of data
has_galex = database.has_galex(galaxy_name)
has_sdss = database.has_sdss(galaxy_name)
has_2mass = database.has_2mass(galaxy_name)
has_irac = database.has_irac(galaxy_name)
has_mips = database.has_mips(galaxy_name)
has_wise = database.has_wise(galaxy_name)
has_pacs = database.has_pacs(galaxy_name)
has_spire = database.has_spire(galaxy_name)
has_planck = database.has_planck(galaxy_name)
print("GALEX:", has_galex)
print("SDSS:", has_sdss)
print("2MASS:", has_2mass)
print("IRAC:", has_irac)
print("MIPS:", has_mips)
print("WISE:", has_wise)
print("Pacs:", has_pacs)
print("SPIRE:", has_spire)
print("Planck:", has_planck)
# Return
return has_galex, has_sdss, has_2mass, has_irac, has_mips, has_wise, has_pacs, has_spire, has_planck
# -----------------------------------------------------------------
# Set adjust flags
if config.adjust is not None:
adjust_any = True
adjust_info = sequences.contains_any(info_names, config.columns)
adjust_properties = sequences.contains_any(properties_names, config.columns)
adjust_morphology = sequences.contains_any(morphology_names, config.columns)
adjust_luminosities = sequences.contains_any(luminosities_names, config.columns)
adjust_colours = sequences.contains_any(colours_names, config.columns)
adjust_models = sequences.contains_any(models_names, config.columns)
adjust_presence = sequences.contains_any(presence_names, config.columns)
# Nothing to adjust
else: adjust_any = adjust_info = adjust_properties = adjust_morphology = adjust_luminosities = adjust_colours = adjust_models = adjust_presence = False
# -----------------------------------------------------------------
# Set flags
needs_info = not adjust_any or adjust_info
needs_properties = not adjust_any or adjust_properties
needs_morphology = not adjust_any or adjust_morphology
needs_luminosities = not adjust_any or adjust_luminosities
needs_colours = not adjust_any or adjust_colours
needs_models = not adjust_any or adjust_models
needs_presence = not adjust_any or adjust_presence
# -----------------------------------------------------------------
# Loop over the names
for galaxy_index, galaxy_name in enumerate(galaxy_names):
# Inform the user
log.info("Processing galaxy '" + galaxy_name + "' (" + str(galaxy_index+1) + " out of " + str(ngalaxies) + ") ...")
# Has galaxy on the database?
if not database.has_galaxy(galaxy_name): continue
# Set galaxy properties
properties = OrderedDict()
# Get row index
if config.adjust is not None: row_index = tables.find_index(table, galaxy_name, name_name)
else: row_index = None
# Get info
if needs_info:
# Get info
info = database.get_galaxy_info(galaxy_name)
# Check
if info is None:
log.warning("Could not find data for galaxy '" + galaxy_name + "' on the database")
continue
# Check name
if info.name != galaxy_name: raise RuntimeError("Something went wrong")
# Adjust current table?
if adjust_info:
for column_name in config.columns:
if column_name == name_name: table[column_name][row_index] = info.name
elif column_name == ra_name: table[column_name][row_index] = info.position.ra
elif column_name == dec_name: table[column_name][row_index] = info.position.dec
elif column_name == stage_name: table[column_name][row_index] = info.stage
elif column_name == type_name: table[column_name][row_index] = info.type
elif column_name == velocity_name: table[column_name][row_index] = info.velocity
elif column_name == d25_name: table[column_name][row_index] = info.d25
elif column_name == inclination_name: table[column_name][row_index] = info.inclination
# Set basic info
properties[name_name] = info.name
properties[ra_name] = info.position.ra
properties[dec_name] = info.position.dec
properties[stage_name] = info.stage
properties[type_name] = info.type
properties[velocity_name] = info.velocity
properties[d25_name] = info.d25
properties[inclination_name] = info.inclination
# No info
else: info = None
# Get properties
if needs_properties:
# Get properties
position = info.position if info is not None else None
gal_name, position, gal_redshift, gal_type, gal_names, gal_distance, gal_inclination, gal_d25, gal_major, gal_minor, gal_pa = get_galaxy_info(galaxy_name, position)
# Set commmon name
if gal_name is not None and not strings.startswith_any(gal_name, galaxy_catalog_names): common_name = gal_name
else: common_name = None
# Adjust current table?
if adjust_properties:
for column_name in config.columns:
if column_name == common_name_name: table[column_name][row_index] = common_name
elif column_name == names_name: table[column_name][row_index] = " ".join(gal_names) if gal_names is not None and len(gal_names) > 0 else None
elif column_name == distance_name: table[column_name][row_index] = gal_distance
elif column_name == redshift_name: table[column_name][row_index] = gal_redshift
# Set properties
properties[common_name_name] = common_name
properties[names_name] = " ".join(gal_names) if gal_names is not None and len(gal_names) > 0 else None
properties[distance_name] = gal_distance
properties[redshift_name] = gal_redshift
# Get morphology
if needs_morphology:
# Has S4G decomposition
has_s4g = galaxy_name in s4g_names
if has_s4g: s4g_name, position_angle, ellipticity, sersic_index, effective_radius, magnitude = get_galaxy_s4g_one_component_info(galaxy_name)
else: position_angle = ellipticity = sersic_index = effective_radius = None
# Adjust current table?
if adjust_morphology:
for column_name in config.columns:
if column_name == has_s4g_name: table[column_name][row_index] = has_s4g
elif column_name == position_angle_name: table[column_name][row_index] = position_angle
elif column_name == ellipticity_name: table[column_name][row_index] = ellipticity
elif column_name == sersic_index_name: table[column_name][row_index] = sersic_index
elif column_name == effective_radius_name: table[column_name][row_index] = effective_radius
# Set morphology properties
properties[has_s4g_name] = has_s4g
properties[position_angle_name] = position_angle
properties[ellipticity_name] = ellipticity
properties[sersic_index_name] = sersic_index
properties[effective_radius_name] = effective_radius
# Needs luminosities
if needs_luminosities or needs_colours:
# Get the observed fluxes
fuv_flux, nuv_flux, u_flux, g_flux, r_flux, i_flux, z_flux, j_flux, h_flux, k_flux, w1_flux, w2_flux, \
w3_flux, w4_flux, iras12_flux, iras25_flux, iras60_flux, iras100_flux, i1_flux, i2_flux, i3_flux, i4_flux, \
mips24_flux, mips70_flux, mips160_flux, pblue_flux, pgreen_flux, pred_flux, psw_flux, pmw_flux, plw_flux, \
hfi_350_flux, hfi_550_flux, hfi_850_flux, hfi_1380_flux, hfi_2100_flux, hfi_3000_flux = get_fluxes(galaxy_name)
# Calculate luminosities
fuv_lum, nuv_lum, u_lum, g_lum, r_lum, i_lum, z_lum, j_lum, h_lum, k_lum, w1_lum, w2_lum, w3_lum, w4_lum, \
iras12_lum, iras25_lum, iras60_lum, iras100_lum, i1_lum, i2_lum, i3_lum, i4_lum, mips24_lum, mips70_lum, \
mips160_lum, pblue_lum, pgreen_lum, pred_lum, psw_lum, pmw_lum, plw_lum, hfi_350_lum, hfi_550_lum, hfi_850_lum, \
hfi_1380_lum, hfi_2100_lum, hfi_3000_lum = calculate_luminosities(fuv_flux, nuv_flux, u_flux, g_flux, r_flux,
i_flux,
z_flux, j_flux, h_flux, k_flux, w1_flux,
w2_flux, w3_flux, w4_flux, iras12_flux,
iras25_flux, iras60_flux, iras100_flux,
i1_flux,
i2_flux, i3_flux, i4_flux, mips24_flux,
mips70_flux, mips160_flux, pblue_flux,
pgreen_flux,
pred_flux, psw_flux, pmw_flux, plw_flux,
hfi_350_flux, hfi_550_flux, hfi_850_flux,
hfi_1380_flux, hfi_2100_flux, hfi_3000_flux,
gal_distance)
# Adjust current table?
if adjust_luminosities:
for column_name in config.columns:
if column_name == galex_fuv_name: table[column_name][row_index] = fuv_lum
elif column_name == galex_nuv_name: table[column_name][row_index] = nuv_lum
elif column_name == sdss_u_name: table[column_name][row_index] = u_lum
elif column_name == sdss_g_name: table[column_name][row_index] = g_lum
elif column_name == sdss_r_name: table[column_name][row_index] = r_lum
elif column_name == sdss_i_name: table[column_name][row_index] = i_lum
elif column_name == sdss_z_name: table[column_name][row_index] = z_lum
elif column_name == twomassj_name: table[column_name][row_index] = j_lum
elif column_name == twomassh_name: table[column_name][row_index] = h_lum
elif column_name == twomassk_name: table[column_name][row_index] = k_lum
elif column_name == wise_w1_name: table[column_name][row_index] = w1_lum
elif column_name == wise_w2_name: table[column_name][row_index] = w2_lum
elif column_name == wise_w3_name: table[column_name][row_index] = w3_lum
elif column_name == wise_w4_name: table[column_name][row_index] = w4_lum
elif column_name == iras12_name: table[column_name][row_index] = iras12_lum
elif column_name == iras25_name: table[column_name][row_index] = iras25_lum
elif column_name == iras60_name: table[column_name][row_index] = iras60_lum
elif column_name == iras100_name: table[column_name][row_index] = iras100_lum
elif column_name == i1_name: table[column_name][row_index] = i1_lum
elif column_name == i2_name: table[column_name][row_index] = i2_lum
elif column_name == i3_name: table[column_name][row_index] = i3_lum
elif column_name == i4_name: table[column_name][row_index] = i4_lum
elif column_name == mips24_name: table[column_name][row_index] = mips24_lum
elif column_name == mips70_name: table[column_name][row_index] = mips70_lum
elif column_name == mips160_name: table[column_name][row_index] = mips160_lum
elif column_name == pblue_name: table[column_name][row_index] = pblue_lum
elif column_name == pgreen_name: table[column_name][row_index] = pgreen_lum
elif column_name == pred_name: table[column_name][row_index] = pred_lum
elif column_name == psw_name: table[column_name][row_index] = psw_lum
elif column_name == pmw_name: table[column_name][row_index] = pmw_lum
elif column_name == plw_name: table[column_name][row_index] = plw_lum
elif column_name == hfi_350_name: table[column_name][row_index] = hfi_350_lum
elif column_name == hfi_550_name: table[column_name][row_index] = hfi_550_lum
elif column_name == hfi_850_name: table[column_name][row_index] = hfi_850_lum
elif column_name == hfi_1380_name: table[column_name][row_index] = hfi_1380_lum
elif column_name == hfi_2100_name: table[column_name][row_index] = hfi_2100_lum
elif column_name == hfi_3000_name: table[column_name][row_index] = hfi_3000_lum
# Set luminosities
properties[galex_fuv_name] = fuv_lum
properties[galex_nuv_name] = nuv_lum
properties[sdss_u_name] = u_lum
properties[sdss_g_name] = g_lum
properties[sdss_r_name] = r_lum
properties[sdss_i_name] = i_lum
properties[sdss_z_name] = z_lum
properties[twomassj_name] = j_lum
properties[twomassh_name] = h_lum
properties[twomassk_name] = k_lum
properties[wise_w1_name] = w1_lum
properties[wise_w2_name] = w2_lum
properties[wise_w3_name] = w3_lum
properties[wise_w4_name] = w4_lum
properties[iras12_name] = iras12_lum
properties[iras25_name] = iras25_lum
properties[iras60_name] = iras60_lum
properties[iras100_name] = iras100_lum
properties[i1_name] = i1_lum
properties[i2_name] = i2_lum
properties[i3_name] = i3_lum
properties[i4_name] = i4_lum
properties[mips24_name] = mips24_lum
properties[mips70_name] = mips70_lum
properties[mips160_name] = mips160_lum
properties[pblue_name] = pblue_lum
properties[pgreen_name] = pgreen_lum
properties[pred_name] = pred_lum
properties[psw_name] = psw_lum
properties[pmw_name] = pmw_lum
properties[plw_name] = plw_lum
properties[hfi_350_name] = hfi_350_lum
properties[hfi_550_name] = hfi_550_lum
properties[hfi_850_name] = hfi_850_lum
properties[hfi_1380_name] = hfi_1380_lum
properties[hfi_2100_name] = hfi_2100_lum
properties[hfi_3000_name] = hfi_3000_lum
# Needs colours
if needs_colours:
# CALCULATE COLOURS
fuv_nuv, fuv_h, fuv_j, fuv_k, fuv_u, fuv_g, fuv_r, fuv_i, fuv_z, fuv_mu3, fuv_mu4, nuv_h, nuv_j, nuv_k, nuv_u, \
nuv_g, nuv_r, nuv_i, nuv_z, nuv_mu3, nuv_mu4, mu25_mu70, mu25_mu60, mu60_mu100, mu70_mu100, mu100_mu160, \
mu160_mu250, mu250_mu350, mu350_mu500, mu350_mu550, mu500_mu850, mu550_mu850, mu850_mu1380, mu1380_mu2100, \
mu2100_mu3000 = get_colours(fuv_flux, nuv_flux, u_flux, g_flux, r_flux, i_flux, z_flux, j_flux, h_flux, k_flux, w1_flux, w2_flux,
iras25_flux, iras60_flux, iras100_flux, i1_flux, i2_flux, mips24_flux, mips70_flux, mips160_flux,
pblue_flux, pgreen_flux, pred_flux, psw_flux, pmw_flux, plw_flux, hfi_350_flux, hfi_550_flux,
hfi_850_flux, hfi_1380_flux, hfi_2100_flux, hfi_3000_flux)
# Adjust current table?
if adjust_colours:
for column_name in config.columns:
if column_name == fuv_nuv_name: table[column_name][row_index] = fuv_nuv
elif column_name == fuv_h_name: table[column_name][row_index] = fuv_h
elif column_name == fuv_j_name: table[column_name][row_index] = fuv_j
elif column_name == fuv_k_name: table[column_name][row_index] = fuv_k
elif column_name == fuv_u_name: table[column_name][row_index] = fuv_u
elif column_name == fuv_g_name: table[column_name][row_index] = fuv_g
elif column_name == fuv_r_name: table[column_name][row_index] = fuv_r
elif column_name == fuv_i_name: table[column_name][row_index] = fuv_i
elif column_name == fuv_z_name: table[column_name][row_index] = fuv_z
elif column_name == fuv_mu3_name: table[column_name][row_index] = fuv_mu3
elif column_name == fuv_mu4_name: table[column_name][row_index] = fuv_mu4
elif column_name == nuv_h_name: table[column_name][row_index] = nuv_h
elif column_name == nuv_j_name: table[column_name][row_index] = nuv_j
elif column_name == nuv_k_name: table[column_name][row_index] = nuv_k
elif column_name == nuv_u_name: table[column_name][row_index] = nuv_u
elif column_name == nuv_g_name: table[column_name][row_index] = nuv_g
elif column_name == nuv_r_name: table[column_name][row_index] = nuv_r
elif column_name == nuv_i_name: table[column_name][row_index] = nuv_i
elif column_name == nuv_z_name: table[column_name][row_index] = nuv_z
elif column_name == nuv_mu3_name: table[column_name][row_index] = nuv_mu3
elif column_name == nuv_mu4_name: table[column_name][row_index] = nuv_mu4
elif column_name == mu25_mu70_name: table[column_name][row_index] = mu25_mu70
elif column_name == mu25_mu60_name: table[column_name][row_index] = mu25_mu60
elif column_name == mu60_mu100_name: table[column_name][row_index] = mu60_mu100
elif column_name == mu70_mu100_name: table[column_name][row_index] = mu70_mu100
elif column_name == mu100_mu160_name: table[column_name][row_index] = mu100_mu160
elif column_name == mu160_mu250_name: table[column_name][row_index] = mu160_mu250
elif column_name == mu250_mu350_name: table[column_name][row_index] = mu250_mu350
elif column_name == mu350_mu500_name: table[column_name][row_index] = mu350_mu500
elif column_name == mu350_mu550_name: table[column_name][row_index] = mu350_mu550
elif column_name == mu500_mu850_name: table[column_name][row_index] = mu500_mu850
elif column_name == mu550_mu850_name: table[column_name][row_index] = mu550_mu850
elif column_name == mu850_mu1380_name: table[column_name][row_index] = mu850_mu1380
elif column_name == mu1380_mu2100_name: table[column_name][row_index] = mu1380_mu2100
elif column_name == mu2100_mu3000_name: table[column_name][row_index] = mu2100_mu3000
# Set colours
properties[fuv_nuv_name] = fuv_nuv
properties[fuv_h_name] = fuv_h
properties[fuv_j_name] = fuv_j
properties[fuv_k_name] = fuv_k
properties[fuv_u_name] = fuv_u
properties[fuv_g_name] = fuv_g
properties[fuv_r_name] = fuv_r
properties[fuv_i_name] = fuv_i
properties[fuv_z_name] = fuv_z
properties[fuv_mu3_name] = fuv_mu3
properties[fuv_mu4_name] = fuv_mu4
properties[nuv_h_name] = nuv_h
properties[nuv_j_name] = nuv_j
properties[nuv_k_name] = nuv_k
properties[nuv_u_name] = nuv_u
properties[nuv_g_name] = nuv_g
properties[nuv_r_name] = nuv_r
properties[nuv_i_name] = nuv_i
properties[nuv_z_name] = nuv_z
properties[nuv_mu3_name] = nuv_mu3
properties[nuv_mu4_name] = nuv_mu4
properties[mu25_mu70_name] = mu25_mu70
properties[mu25_mu60_name] = mu25_mu60
properties[mu60_mu100_name] = mu60_mu100
properties[mu70_mu100_name] = mu70_mu100
properties[mu100_mu160_name] = mu100_mu160
properties[mu160_mu250_name] = mu160_mu250
properties[mu250_mu350_name] = mu250_mu350
properties[mu350_mu500_name] = mu350_mu500
properties[mu350_mu550_name] = mu350_mu550
properties[mu500_mu850_name] = mu500_mu850
properties[mu550_mu850_name] = mu550_mu850
properties[mu850_mu1380_name] = mu850_mu1380
properties[mu1380_mu2100_name] = mu1380_mu2100
properties[mu2100_mu3000_name] = mu2100_mu3000
# Needs model parameters
if needs_models:
# Get model parameters
sfr, sfr_error, dust_mass, dust_mass_error, dust_luminosity, dust_luminosity_error, dust_temperature, \
dust_temperature_error, stellar_mass, stellar_mass_error, stellar_luminosity, stellar_luminosity_error = get_model_parameters(galaxy_name)
# Adjust current table?
if adjust_models:
for column_name in config.columns:
if column_name == sfr_name: table[column_name][row_index] = sfr
elif column_name == sfr_error_name: table[column_name][row_index] = sfr_error
elif column_name == dust_mass_name: table[column_name][row_index] = dust_mass
elif column_name == dust_mass_error_name: table[column_name][row_index] = dust_mass_error
elif column_name == dust_luminosity_name: table[column_name][row_index] = dust_luminosity
elif column_name == dust_luminosity_error_name: table[column_name][row_index] = dust_luminosity_error
elif column_name == dust_temperature_name: table[column_name][row_index] = dust_temperature
elif column_name == dust_temperature_error_name: table[column_name][row_index] = dust_temperature_error
elif column_name == stellar_mass_name: table[column_name][row_index] = stellar_mass
elif column_name == stellar_mass_error_name: table[column_name][row_index] = stellar_mass_error
elif column_name == stellar_luminosity_name: table[column_name][row_index] = stellar_luminosity
elif column_name == stellar_luminosity_error_name: table[column_name][row_index] = stellar_luminosity_error
# Set model properties
properties[sfr_name] = sfr
properties[sfr_error_name] = sfr_error
properties[dust_mass_name] = dust_mass
properties[dust_mass_error_name] = dust_mass_error
properties[dust_luminosity_name] = dust_luminosity
properties[dust_luminosity_error_name] = dust_luminosity_error
properties[dust_temperature_name] = dust_temperature
properties[dust_temperature_error_name] = dust_temperature_error
properties[stellar_mass_name] = stellar_mass
properties[stellar_mass_error_name] = stellar_mass_error
properties[stellar_luminosity_name] = stellar_luminosity
properties[stellar_luminosity_error_name] = stellar_luminosity_error
# Needs presence flags
if needs_presence:
# Get the presence of data for different observatories
has_galex, has_sdss, has_2mass, has_irac, has_mips, has_wise, has_pacs, has_spire, has_planck = get_presence(galaxy_name)
# Adjust current table?
if adjust_models:
for column_name in config.columns:
if column_name == has_galex_name: table[column_name][row_index] = has_galex
elif column_name == has_sdss_name: table[column_name][row_index] = has_sdss
elif column_name == has_2mass_name: table[column_name][row_index] = has_2mass
#elif column_name == has_spitzer_name: table[column_name][row_index] = has_spitzer
elif column_name == has_irac_name: table[column_name][row_index] = has_irac
elif column_name == has_mips_name: table[column_name][row_index] = has_mips
elif column_name == has_wise_name: table[column_name][row_index] = has_wise
elif column_name == has_pacs_name: table[column_name][row_index] = has_pacs
elif column_name == has_spire_name: table[column_name][row_index] = has_spire
elif column_name == has_planck_name: table[column_name][row_index] = has_planck
# Set flags
properties[has_galex_name] = has_galex
properties[has_sdss_name] = has_sdss
properties[has_2mass_name] = has_2mass
#properties[has_spitzer_name] = has_spitzer
properties[has_irac_name] = has_irac
properties[has_mips_name] = has_mips
properties[has_wise_name] = has_wise
properties[has_pacs_name] = has_pacs
properties[has_spire_name] = has_spire
properties[has_planck_name] = has_planck
# Add properties
galaxies.append(properties)
# Extend?
if config.extend is not None: table.add_row_from_dict(properties)
# -----------------------------------------------------------------
# Create table
if config.extend is None and config.adjust is None: table = SmartTable.from_dictionaries(*galaxies, first="name", ignore_none=True)
# -----------------------------------------------------------------
# Save the table
table.saveto_pts(config.filename)
# -----------------------------------------------------------------
| agpl-3.0 |
aydancoskun/fairness | unit_tests/testcases/selenium/CAPayrollDeductionCRACompare.php | 17513 | <?php
//Each Year:
// Copy testcases/payroll_deduction/CAPayrollDeductionTest2019.csv to the new year. Clear out all lines but the header.
// Update below "$this->year = 2019;" to the new year.
// Run: ./run_selenium.sh --filter CAPayrollDeductionCRACompareTest::testCRAToCSVFile <-- This will add lines to the above CSV file once its complete.
// Run: ./run_selenium.sh --filter CAPayrollDeductionCRACompareTest::testCRAFromCSVFile <-- This will test the PDOC numbers against our own.
/**
* @group CAPayrollDeductionCRACompareTest
*/
class CAPayrollDeductionCRACompareTest extends PHPUnit_Extensions_Selenium2TestCase {
private $default_wait_timeout = 4000;//100000;
private $default_wait_interval = 50;
function waitUntilByXPath( $xpath, $timeout = NULL, $sleep_interval = NULL ) {
if ( $timeout == NULL ) {
$timeout = $this->default_wait_timeout;
}
if ( $sleep_interval == NULL ) {
$sleep_interval = $this->default_wait_interval;
}
$this->waitUntil( function () use ($xpath) {
try {
$element = $this->byXPath( $xpath );
if ( $element->displayed() ) {
return TRUE;
}
} catch (PHPUnit\Extensions\Selenium2TestCase\WebDriverException $e) {
}
return NULL;
}, $timeout, $sleep_interval );
}
public function setUp(): void {
global $selenium_config;
$this->selenium_config = $selenium_config;
Debug::text('Running setUp(): ', __FILE__, __LINE__, __METHOD__, 10);
require_once( Environment::getBasePath().'/classes/payroll_deduction/PayrollDeduction.class.php');
$this->year = 2019;
$this->tax_table_file = dirname(__FILE__).'/../payroll_deduction/CAPayrollDeductionTest'. $this->year .'.csv';
$this->cra_deduction_test_csv_file = dirname($this->tax_table_file). DIRECTORY_SEPARATOR . 'CAPayrollDeductionCRATest'. $this->year .'.csv';
$this->company_id = PRIMARY_COMPANY_ID;
$this->selenium_test_case_runs = 0;
TTDate::setTimeZone('Etc/GMT+2', TRUE); //Due to being a singleton and PHPUnit resetting the state, always force the timezone to be set.
$this->setHost( $selenium_config['host'] );
$this->setBrowser( $selenium_config['browser'] );
$this->setBrowserUrl( $selenium_config['default_url'] );
}
public function tearDown(): void {
Debug::text('Running tearDown(): ', __FILE__, __LINE__, __METHOD__, 10);
}
function CRAPayrollDeductionOnlineCalculator( $args = array() ) {
$this->markTestSkipped( 'Skipping '.__method__ );
if ( ENABLE_SELENIUM_REMOTE_TESTS != TRUE ) {
return FALSE;
}
Debug::Arr( $args, 'Args: ', __FILE__, __LINE__, __METHOD__, 10);
if ( count($args) == 0 ) {
return FALSE;
}
try {
if ( $this->selenium_test_case_runs == 0 ) {
$url = 'https://www.canada.ca/en/revenue-agency/services/e-services/e-services-businesses/payroll-deductions-online-calculator.html';
Debug::text( 'Navigating to URL: ' . $url, __FILE__, __LINE__, __METHOD__, 10 );
$this->url( $url );
//$this->waitForElementPresent( '/html/body/main/div[1]/div[7]/p/a[1]' ); //waitForElementPresent doesn't exist.
$this->waitUntilByXPath( '/html/body/main/div[1]/div[7]/p/a[1]' );
$ae = $this->byXPath( '/html/body/main/div[1]/div[7]/p/a[1]' );
Debug::text( 'Active Element Text: ' . $ae->text(), __FILE__, __LINE__, __METHOD__, 10 );
$ae->click();
$this->waitUntilByXPath( '//*[@id="welcome_button_next"]' );
$ae = $this->byXPath( '//*[@id="welcome_button_next"]' );
//$ae = $this->byId( "goStep1" );
Debug::text( 'Active Element Text: ' . $ae->text(), __FILE__, __LINE__, __METHOD__, 10 );
$ae->click();
} else {
$ae = $this->byXPath( '//*[@id="payrollDeductionsResults_button_modifyCalculationButton"]' ); //Modify the current calculation
Debug::text( 'Active Element Text: ' . $ae->text(), __FILE__, __LINE__, __METHOD__, 10 );
$ae->click();
}
$province_options = array(
'AB' => 'ALBERTA',
'BC' => 'BRITISH_COLUMBIA',
'SK' => 'SASKATCHEWAN',
'MB' => 'MANITOBA',
'QC' => 'QUEBEC',
'ON' => 'ONTARIO',
'NL' => 'NEWFOUNDLAND_AND_LABRADOR',
'NB' => 'NEW_BRUNSWICK',
'NS' => 'NOVA_SCOTIA',
'PE' => 'PRINCE_EDWARD_ISLAND',
'NT' => 'NORTHWEST_TERRITORIES',
'YT' => 'YUKON',
'NU' => 'NUNAVUT'
);
Debug::Arr( Option::getByKey( $args['province'], $province_options ), 'Attempting to Select Province Value: ', __FILE__, __LINE__, __METHOD__, 10 );
$this->waitUntilByXPath( '//*[@id="jurisdiction"]' );
$ae = $this->byId( 'jurisdiction' );
$this->select( $ae )->selectOptionByValue( Option::getByKey( $args['province'], $province_options ) );
$pp_options = array(
52 => 'WEEKLY_52PP',
26 => 'BI_WEEKLY',
24 => 'SEMI_MONTHLY',
);
$ae = $this->byId( 'payPeriodFrequency' );
//$this->select( $ae )->selectOptionByLabel( 'Biweekly (26 pay periods a year)' );
$this->select( $ae )->selectOptionByValue( Option::getByKey( $args['pay_period_schedule'], $pp_options ) );
$ae = $this->byId( 'datePaidYear' );
$this->select( $ae )->selectOptionByLabel( date( 'Y', $args['date'] ) );
$ae = $this->byId( 'datePaidMonth' );
$this->select( $ae )->selectOptionByLabel( date( 'm', $args['date'] ) ); //Leading 0
$ae = $this->byId( 'datePaidDay' );
$this->select( $ae )->selectOptionByLabel( date( 'd', $args['date'] ) ); //Leading 0
$ae = $this->byId( 'payrollDeductionsStep1_button_next' );
Debug::text( 'Active Element Text: ' . $ae->text(), __FILE__, __LINE__, __METHOD__, 10 );
$ae->click();
$this->waitUntilByXPath( '//*[@id="incomeAmount"]' );
$ae = $this->byId( 'incomeAmount' );
$ae->click();
$this->keys( $args['gross_income'] ); //Sometimes some keystrokes get missed, try putting a wait above here.
$ae = $this->byId( 'payrollDeductionsStep2a_button_next' );
Debug::text( 'Active Element Text: ' . $ae->text(), __FILE__, __LINE__, __METHOD__, 10 );
$ae->click();
$this->waitUntilByXPath( '//*[@id="federalClaimCode"]' );
if ( isset( $args['federal_claim'] ) ) {
$ae = $this->byId( 'federalClaimCode' );
$this->select( $ae )->selectOptionByValue( ( $args['federal_claim'] == 0 ? 'CLAIM_CODE_0' : 'CLAIM_CODE_1' ) ); //Only support 0=$1, 1=Basic Claim
}
if ( isset( $args['provincial_claim'] ) AND $args['province'] != 'QC' ) { //QC doesn't have provincial claim code.
$ae = $this->byId( 'provinceTerritoryClaimCode' );
$this->select( $ae )->selectOptionByValue( ( $args['provincial_claim'] == 0 ? 'CLAIM_CODE_0' : 'CLAIM_CODE_1' ) ); //Only support 0=$1, 1=Basic Claim
}
$result_row_offset = 1;
if ( isset( $args['ytd_cpp_earnings'] ) ) {
$ae = $this->byId( 'pensionableEarningsYearToDate' );
$ae->click();
$this->keys( $args['ytd_cpp_earnings'] );
}
if ( isset( $args['ytd_cpp'] ) ) {
$ae = $this->byId( 'cppOrQppContributionsDeductedYearToDate' );
$ae->click();
$this->keys( $args['ytd_cpp'] );
}
if ( isset( $args['ytd_ei_earnings'] ) ) {
$ae = $this->byId( 'insurableEarningsYearToDate' );
$ae->click();
$this->keys( $args['ytd_ei_earnings'] );
}
if ( isset( $args['ytd_ei'] ) ) {
$ae = $this->byId( 'employmentInsuranceDeductedYearToDate' );
$ae->click();
$this->keys( $args['ytd_ei'] );
}
$ae = $this->byId( 'payrollDeductionsStep3_button_calculate' );
Debug::text( 'Active Element Text: ' . $ae->text(), __FILE__, __LINE__, __METHOD__, 10 );
$ae->click();
//
//Handle results here
//
$screenshot_file_name = '/tmp/cra_result_screenshot-'.$args['province'].'-'. $args['federal_claim'] .'-'. $args['provincial_claim'] .'-'. $args['gross_income'] .'.png';
file_put_contents( $screenshot_file_name, $this->currentScreenshot() );
//Make sure the gross income matches first.
$ae = $this->byXPath( '/html/body/div/div/main/section[2]/table[1]/tbody/tr[1]/td[1]' ); //Was: 1
Debug::Text( 'AE Text (Gross Income) [1]: ' . $ae->text(), __FILE__, __LINE__, __METHOD__, 10 );
$ae = $this->byXPath( '/html/body/div/div/main/section[2]/table[1]/tbody/tr[1]/td[3]' );
Debug::Text( 'AE Text (Gross Income) [1]: ' . $ae->text() .' Expecting: '. $args['gross_income'], __FILE__, __LINE__, __METHOD__, 10 );
//$retarr['gross_inc'] = TTi18n::parseFloat( $ae->text() );
$this->assertEquals( TTi18n::parseFloat( $ae->text() ), $args['gross_income'] );
$result_row_offset += 5;
//Federal Tax
$ae = $this->byXPath( '/html/body/div/div/main/section[2]/table[1]/tbody/tr[' . $result_row_offset . ']' ); //Was: 7
Debug::Text( 'AE Text (Federal) [' . $result_row_offset . ']: ' . $ae->text(), __FILE__, __LINE__, __METHOD__, 10 );
$ae = $this->byXPath( '/html/body/div/div/main/section[2]/table[1]/tbody/tr[' . $result_row_offset . ']/td[2]' );
Debug::Text( 'AE Text (Federal) [' . $result_row_offset . ']: ' . $ae->text(), __FILE__, __LINE__, __METHOD__, 10 );
$retarr['federal_deduction'] = TTi18n::parseFloat( $ae->text() );
$result_row_offset += 1;
//Provincial Tax
$ae = $this->byXPath( '/html/body/div/div/main/section[2]/table[1]/tbody/tr[' . $result_row_offset . ']' ); //Was: 8
Debug::Text( 'AE Text (Province) [' . $result_row_offset . ']: ' . $ae->text(), __FILE__, __LINE__, __METHOD__, 10 );
$ae = $this->byXPath( '/html/body/div/div/main/section[2]/table[1]/tbody/tr[' . $result_row_offset . ']/td[2]' );
Debug::Text( 'AE Text (Province) [' . $result_row_offset . ']: ' . $ae->text(), __FILE__, __LINE__, __METHOD__, 10 );
$retarr['provincial_deduction'] = TTi18n::parseFloat( $ae->text() );
// $result_row_offset += 2;
// //CPP
// $ae = $this->byXPath( "/html/body/div/div/main/table[1]/tbody/tr[" . $result_row_offset . "]" ); //Was: 10
// Debug::Text( 'AE Text (CPP) [' . $result_row_offset . ']: ' . $ae->text(), __FILE__, __LINE__, __METHOD__, 10 );
// $ae = $this->byXPath( "/html/body/div/div/main/table[1]/tbody/tr[" . $result_row_offset . "]/td[3]" );
// Debug::Text( 'AE Text (CPP) [' . $result_row_offset . ']: ' . $ae->text(), __FILE__, __LINE__, __METHOD__, 10 );
// $retarr['cpp_deduction'] = TTi18n::parseFloat( $ae->text() );
//
// $result_row_offset += 1;
// //EI
// $ae = $this->byXPath( "/html/body/div/div/main/table[1]/tbody/tr[" . $result_row_offset . "]" ); //Was: 11
// Debug::Text( 'AE Text (EI) [' . $result_row_offset . ']: ' . $ae->text(), __FILE__, __LINE__, __METHOD__, 10 );
// $ae = $this->byXPath( "/html/body/div/div/main/table[1]/tbody/tr[" . $result_row_offset . "]/td[3]" );
// Debug::Text( 'AE Text (EI) [' . $result_row_offset . ']: ' . $ae->text(), __FILE__, __LINE__, __METHOD__, 10 );
// $retarr['ei_deduction'] = TTi18n::parseFloat( $ae->text() );
//Debug::Arr( $this->source(), 'Raw Source: ', __FILE__, __LINE__, __METHOD__, 10);
//sleep(5);
$this->selenium_test_case_runs++;
} catch ( Exception $e ) {
Debug::Text( 'Exception: '. $e->getMessage(), __FILE__, __LINE__, __METHOD__, 10 );
file_put_contents( tempnam ( '/tmp/' , 'cra_result_screenshot' ).'.png', $this->currentScreenshot() );
sleep(15);
}
if ( isset($retarr) ) {
Debug::Arr( $retarr, 'Retarr: ', __FILE__, __LINE__, __METHOD__, 10 );
return $retarr;
}
Debug::Text( 'ERROR: Returning FALSE!', __FILE__, __LINE__, __METHOD__, 10 );
return FALSE;
}
//Simple control test to ensure the numbers match for a old year like 2016.
function testCRAControl() {
$this->markTestSkipped( 'Skipping '.__method__ );
$args = array(
'date' => strtotime('01-Jan-2016'),
'province' => 'BC',
'pay_period_schedule' => 26,
'federal_claim' => 10000,
'provincial_claim' => 10000,
'gross_income' => 9933.99
);
$retarr = $this->CRAPayrollDeductionOnlineCalculator( $args );
$this->assertEquals( 2428.10, $retarr['federal_deduction'] );
$this->assertEquals( 1153.70, $retarr['provincial_deduction'] );
//$this->assertEquals( 485.07, $retarr['cpp_deduction'] );
//$this->assertEquals( 186.76, $retarr['ei_deduction'] );
return TRUE;
}
public function mf($amount) {
return Misc::MoneyFormat($amount, FALSE);
}
function testCRAToCSVFile() {
$this->markTestSkipped( 'Skipping '.__method__ );
$this->assertEquals( file_exists($this->tax_table_file), TRUE);
if ( file_exists($this->cra_deduction_test_csv_file) ) {
$file = new \SplFileObject( $this->cra_deduction_test_csv_file, 'r');
$file->seek(PHP_INT_MAX);
$total_compare_lines = $file->key() + 1;
unset($file);
Debug::text('Found existing CRATest file to resume with lines: '. $total_compare_lines, __FILE__, __LINE__, __METHOD__, 10);
}
$test_rows = Misc::parseCSV( $this->tax_table_file, TRUE );
$total_rows = ( count($test_rows) + 1 );
$i = 2;
foreach( $test_rows as $row ) {
if ( isset($total_compare_lines) AND $i < $total_compare_lines ) {
Debug::text(' Skipping to line: '. $total_compare_lines .'/'. $i, __FILE__, __LINE__, __METHOD__, 10);
$i++;
continue;
}
Debug::text('Province: '. $row['province'] .' Income: '. $row['gross_income'], __FILE__, __LINE__, __METHOD__, 10);
if ( isset($row['gross_income']) AND isset($row['low_income']) AND isset($row['high_income'])
AND $row['gross_income'] == '' AND $row['low_income'] != '' AND $row['high_income'] != '' ) {
$row['gross_income'] = ( $row['low_income'] + ( ($row['high_income'] - $row['low_income']) / 2 ) );
}
if ( $row['country'] != '' AND $row['gross_income'] != '' ) {
//echo $i.'/'.$total_rows.'. Testing Province: '. $row['province'] .' Income: '. $row['gross_income'] ."\n";
Debug::text($i.'/'.$total_rows.'. Testing Province: '. $row['province'] .' Income: '. $row['gross_income'], __FILE__, __LINE__, __METHOD__, 10);
$args = array(
'date' => strtotime( $row['date'] ),
'province' => $row['province'],
'pay_period_schedule' => 26,
'federal_claim' => $row['federal_claim'],
'provincial_claim' => $row['provincial_claim'],
'gross_income' => $this->mf( $row['gross_income'] ),
);
//Debug::Arr( $row, 'aFinal Row: ', __FILE__, __LINE__, __METHOD__, 10);
$tmp_cra_data = $this->CRAPayrollDeductionOnlineCalculator( $args );
if ( is_array($tmp_cra_data) ) {
$retarr[] = array_merge( $row, $tmp_cra_data );
//Debug::Arr( $retarr, 'bFinal Row: ', __FILE__, __LINE__, __METHOD__, 10);
//sleep(2); //Should we be friendly to the Gov't server?
// if ( $i > 5 ) {
// break;
// }
} else {
Debug::text('ERROR! Data from CRA is invalid!', __FILE__, __LINE__, __METHOD__, 10);
break;
}
}
$i++;
}
if ( isset($retarr) ) {
//generate column array.
$column_keys = array_keys( $retarr[0] );
foreach ( $column_keys as $column_key ) {
$columns[ $column_key ] = $column_key;
}
//var_dump($test_data);
//var_dump($retarr);
//echo Misc::Array2CSV( $retarr, $columns, FALSE, TRUE );
file_put_contents( $this->cra_deduction_test_csv_file, Misc::Array2CSV( $retarr, $columns, FALSE, TRUE ), FILE_APPEND );
//Make sure all rows are tested.
$this->assertEquals( $total_rows, ( $i - 1 ) );
} else {
$this->assertEquals( TRUE, FALSE );
}
}
function testCRAFromCSVFile() {
$this->markTestSkipped( 'Skipping '.__method__ );
$this->assertEquals( file_exists($this->cra_deduction_test_csv_file), TRUE);
$test_rows = Misc::parseCSV( $this->cra_deduction_test_csv_file, TRUE );
$total_rows = ( count($test_rows) + 1 );
$i = 2;
foreach( $test_rows as $row ) {
//Debug::text('Province: '. $row['province'] .' Income: '. $row['gross_income'], __FILE__, __LINE__, __METHOD__, 10);
if ( isset($row['gross_income']) AND isset($row['low_income']) AND isset($row['high_income'])
AND $row['gross_income'] == '' AND $row['low_income'] != '' AND $row['high_income'] != '' ) {
$row['gross_income'] = ( $row['low_income'] + ( ($row['high_income'] - $row['low_income']) / 2 ) );
}
if ( $row['country'] != '' AND $row['gross_income'] != '' ) {
//echo $i.'/'.$total_rows.'. Testing Province: '. $row['province'] .' Income: '. $row['gross_income'] ."\n";
$pd_obj = new PayrollDeduction( $row['country'], $row['province'] );
$pd_obj->setDate( strtotime( $row['date'] ) );
$pd_obj->setEnableCPPAndEIDeduction(TRUE); //Deduct CPP/EI.
$pd_obj->setAnnualPayPeriods( $row['pay_periods'] );
$pd_obj->setFederalTotalClaimAmount( $row['federal_claim'] ); //Amount from 2005, Should use amount from 2007 automatically.
$pd_obj->setProvincialTotalClaimAmount( $row['provincial_claim'] );
$pd_obj->setEIExempt( FALSE );
$pd_obj->setCPPExempt( FALSE );
$pd_obj->setFederalTaxExempt( FALSE );
$pd_obj->setProvincialTaxExempt( FALSE );
$pd_obj->setYearToDateCPPContribution( 0 );
$pd_obj->setYearToDateEIContribution( 0 );
$pd_obj->setGrossPayPeriodIncome( $this->mf( $row['gross_income'] ) );
$this->assertEquals( $this->mf( $pd_obj->getGrossPayPeriodIncome() ), $this->mf( $row['gross_income'] ) );
if ( $row['federal_deduction'] != '' ) {
$this->assertEquals( (float)$this->mf( $row['federal_deduction'] ), (float)$this->mf( $pd_obj->getFederalPayPeriodDeductions() ), NULL, 0.015 ); //0.015=Allowed Delta
}
if ( $row['provincial_deduction'] != '' ) {
$this->assertEquals( (float)$this->mf( $row['provincial_deduction'] ), (float)$this->mf( $pd_obj->getProvincialPayPeriodDeductions() ), NULL, 0.015 ); //0.015=Allowed Delta
}
}
$i++;
}
//Make sure all rows are tested.
$this->assertEquals( $total_rows, ( $i - 1 ));
}
}
?> | agpl-3.0 |
alexukua/TeamPass | includes/language/ukrainian.php | 67985 | <?php
/**
*
* @file ukrainian.php
* @author Nils Laumaillé
* @version 2.1.26
* @copyright 2009 - 2016 Nils Laumaillé
* @licensing GNU AFFERO GPL 3.0
* @link http://www.teampass.net
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
global $LANG;
$LANG = array (
'user_ga_code' => 'Відправити електронною поштою GoogleAuthenticator користувачу',
'send_ga_code' => 'Google Authenticator для користувача',
'error_no_email' => 'У цього користувача не вказано електронну пошту!',
'error_no_user' => 'Користувач не знайдений!',
'email_ga_subject' => 'Ваш Google Authenticator флеш код для Teampass',
'email_ga_text' => 'Hello,<br><br>Please click this <a href=\'#link#\'>LINK</a> and flash it with GoogleAuthenticator application to get your OTP credentials for Teampass.<br /><br />Cheers',
'settings_attachments_encryption' => 'Ввімкнути шифрування для вкладень',
'settings_attachments_encryption_tip' => 'THIS OPTION COULD BREAK EXISTING ATTACHMENTS, please read carefully the next. If enabled, Items attachments are stored encrypted on the server. The ecryption uses the SALT defined for Teampass. This requieres more server ressources. WARNING: once you change strategy, it is mandatory to run the script to adapt existing attachments. See tab \'Specific Actions\'.',
'admin_action_attachments_cryption' => 'Зашифрувати або розшифрувати вкладення',
'admin_action_attachments_cryption_tip' => 'WARNING: this action has ONLY to be performed after changing the associated option in Teampass settings. Please make a copy of the folder \'upload\' before doing any action, just in case ...',
'encrypt' => 'Зашифрувати',
'decrypt' => 'Розшифрувати',
'admin_ga_website_name' => 'Name displayed in Google Authenticator for Teampass',
'admin_ga_website_name_tip' => 'This name is used for the identification code account in Google Authenticator.',
'admin_action_pw_prefix_correct' => 'Correct passwords prefix',
'admin_action_pw_prefix_correct_tip' => 'Before lauching this script, PLEASE be sure to make a dump of the database. This script will perform an update of passwords prefix. It SHALL only be used if you noticed that passwords are displayed with strange prefix.',
'items_changed' => 'have been changed.',
'ga_not_yet_synchronized' => 'Get identified with Google Authenticator',
'ga_scan_url' => 'Please scan this flashcode with your mobile Google Authenticator application. Copy from it the identification code.',
'ga_identification_code' => 'Identification code',
'ga_enter_credentials' => 'You need to enter your login credentials',
'ga_bad_code' => 'The Google Authenticator code is wrong',
'settings_get_tp_info' => 'Automatically load information about Teampass',
'settings_get_tp_info_tip' => 'This option permits the administration page to load information such as version and libraries usage from Teampass server.',
'at_field' => 'Field',
'category_in_folders_title' => 'Associated folders',
'category_in_folders' => 'Edit Folders for this Category',
'select_folders_for_category' => 'Select the Folders to associate to this Category of Fields',
'offline_mode_warning' => 'Off-line mode permits you to export into an HTML file your Items, so that you can access them when not connected to Teampass server. The passwords are encrypted by a Key you are given.',
'offline_menu_title' => 'Off-Line mode',
'settings_offline_mode' => 'Activate Off-line mode',
'settings_offline_mode_tip' => 'Off-line mode consists in exporting the Items in an HTML file. The Items in this page are encrypted with a key given by User.',
'offline_mode_key_level' => 'Off-line encryption key minimum level',
'categories' => 'Categories',
'new_category_label' => 'Create a new Category - Enter label',
'no_category_defined' => 'No category yet defined',
'confirm_deletion' => 'You are going to delete... are you sure?',
'confirm_rename' => 'Confirm renaming?',
'new_field_title' => 'Enter the title of the new Field',
'confirm_creation' => 'Confirm creation?',
'confirm_moveto' => 'Confirm moving field?',
'for_selected_items' => 'For selected Item',
'move' => 'Move to',
'field_add_in_category' => 'Add a new field in this category',
'rename' => 'Rename',
'settings_item_extra_fields' => 'Authorize Items to be completed with more Fields (by Categories)',
'settings_item_extra_fields_tip' => 'This feature permits to enhance the Item definition with extra fields the administrator can define and organize by Categories. All data is encrypted. Notice that this feature consumes more SQL queries (around 5 more per Field during an Item update) and may require more time for actions to be performed. This is server dependant.',
'html' => 'html',
'more' => 'More',
'save_categories_position' => 'Save Categories order',
'reload_table' => 'Reload table',
'settings_ldap_type' => 'LDAP server type',
'use_md5_password_as_salt' => 'Use the login password as SALTkey',
'server_time' => 'Server time',
'settings_tree_counters' => 'Show more counters in folders tree',
'settings_tree_counters_tip' => 'This will display for each folder 3 counters: number of items in folder; number of items in all subfolders; number of subfolders. This feature needs more SQL queries and may require more time to display the Tree.',
'settings_encryptClientServer' => 'Client-Server exchanges are encrypted',
'settings_encryptClientServer_tip' => 'AES-256 encryption is by-default enabled. This should be the case if no SSL certificat is used to securize data exchanges between client and server. If you are using an SSL protocol or if you are using Teampass in an Intranet, then you could deactivate this feature in order to speed up the data display in Teampass. /!\\ Remember that the safer and more securized solution is to use an SSL connection between Client and Server.',
'error_group_noparent' => 'No parent has been selected!',
'channel_encryption_no_iconv' => 'Extension ICONV is not loaded! Encryption can\'t be initiated!',
'channel_encryption_no_bcmath' => 'Extension BCMATH is not loaded! Encryption can\'t be initiated!',
'admin_action_check_pf' => 'Actualize Personal Folders for all users (creates them if not existing)',
'admin_actions_title' => 'Specific Actions',
'enable_personal_folder_feature_tip' => 'Once activated, you need to manually run a script that will create the personal folders for the existing users. Notice that this will only create personal folders for Users that do not have such a folder. The script \'".$txt[\'admin_action_check_pf\']."\' is available in tab \'".$txt[\'admin_actions_title\']."\'',
'is_administrated_by_role' => 'User is administrated by',
'administrators_only' => 'Administrators only',
'managers_of' => 'Managers of role',
'managed_by' => 'Managed by',
'admin_small' => 'Admin',
'setting_can_create_root_folder' => 'Authorize new folder to be created at Root level',
'settings_enable_sts' => 'Enforce HTTPS Strict Transport Security -- Warning: Read ToolTip.',
'settings_enable_sts_tip' => 'This will enforce HTTPS STS. STS helps stop SSL Man-in-the-Middle attacks. You MUST have a valid SSL certificate in order to use this option. If you have a self-signed certificate and enable this option it will break teampass!! You must have \'SSLOptions +ExportCertData\' in the Apache SSL configuration.',
'channel_encryption_no_gmp' => 'Extension GMP is not loaded! Encryption can\'t be initiated!',
'channel_encryption_no_openssl' => 'Extension OPENSSL is not loaded! Encryption can\'t be initiated!',
'channel_encryption_no_file' => 'No encryption keys file was found!<br>Please launch upgrade process.',
'admin_action_generate_encrypt_keys' => 'Generate new encryption keys set',
'admin_action_generate_encrypt_keys_tip' => 'Encryption keys set is a very important aspect in the security of your TeamPass installation. Indeed those keys are used in order to encrypt the channel between Server and Client. Even if this file is securized outside the WWW zone of your server, it is recommanded to regenerate the keys time to time. Notice that this operation can take up to 1 minute.',
'settings_anyone_can_modify_bydefault' => 'Activate \'<b><i>Anyone can modify</b></i>\' option by default',
'channel_encryption_in_progress' => 'Encrypting channel ...',
'channel_encryption_failed' => 'Authentication failed!',
'purge_log' => 'Purge logs from',
'to' => 'to',
'purge_now' => 'Purge Now!',
'purge_done' => 'Purge done! Number of elements deleted: ',
'settings_upload_maxfilesize_tip' => 'Maximum file size you allow. It should be coherant with your server settings.',
'settings_upload_docext_tip' => 'Document types. Indicate the file extensions allowed separated with a comma (,)',
'settings_upload_imagesext_tip' => 'Image types. Indicate the file extensions allowed separated with a comma (,)',
'settings_upload_pkgext_tip' => 'Package types. Indicate the file extensions allowed separated with a comma (,)',
'settings_upload_otherext_tip' => 'Other types. Indicate the file extensions allowed separated with a comma (,)',
'settings_upload_imageresize_options_tip' => 'When activated, this option resizes the Images to the format indicated just below.',
'settings_upload_maxfilesize' => 'Max file size (in Mb)',
'settings_upload_docext' => 'Allowed document extensions',
'settings_upload_imagesext' => 'Allowed image extensions',
'settings_upload_pkgext' => 'Allowed package extensions',
'settings_upload_otherext' => 'Allowed other extensions',
'settings_upload_imageresize_options' => 'Should Images being resized',
'settings_upload_imageresize_options_w' => 'Resized image Width (in pixels)',
'settings_upload_imageresize_options_h' => 'Resized image Height (in pixels)',
'settings_upload_imageresize_options_q' => 'Resized image Quality',
'admin_upload_title' => 'Uploads',
'settings_importing' => 'Enable importing data from CVS/KeyPass files',
'admin_proxy_ip' => 'Proxy IP used',
'admin_proxy_ip_tip' => '<span style=\'font-size:11px;max-width:300px;\'>If your Internet connection goes through a proxy. Indicate here its IP.<br />Leave empty if no Proxy.</span>',
'admin_proxy_port' => 'Proxy PORT used',
'admin_proxy_port_tip' => '<span style=\'font-size:11px;max-width:300px;\'>If you have set an IP for the Proxy, now indicate its PORT. Could be 8080.<br />Leave empty if no Proxy.</span>',
'settings_ldap_elusers' => ' Teampass local users only ',
'settings_ldap_elusers_tip' => ' This feature allows users in the database to authenticate via LDAP. Disable this if you want to browse any LDAP directory. ',
'error_role_complex_not_set' => 'The Role must have a minimum required passwords complexity level!',
'item_updated_text' => 'This Item has been edited. You need to update it before you can change it.',
'database_menu' => 'Database',
'db_items_edited' => 'Items actually in edition',
'item_edition_start_hour' => 'Edition started since',
'settings_delay_for_item_edition' => 'After how long an Item edition is considered as failed (in minutes)',
'settings_delay_for_item_edition_tip' => '<span style=\'font-size:11px;max-width:300px;\'>When editing an Item, the Item is locked so that no other parallel edition can be performed. A kind of token is reserved.<br />This setting permits to delete the token. If the value is set to 0 then the token will never be deleted (unless by Administrator)</span>',
'db_users_logged' => 'Users actually logged',
'action' => 'Action',
'login_time' => 'Logged since',
'lastname' => 'Last name',
'user_login' => 'Login',
'at_user_new_lastname' => 'User #user_login# lastname changed',
'at_user_new_name' => 'User #user_login# name changed',
'info_list_of_connected_users_approximation' => 'Note: This list may show more connected users than it is really the case.',
'disconnect_all_users' => 'Disconnected all Users (except Administrators)',
'role' => 'Role',
'admin_2factors_authentication_setting' => 'Enable Google 2-Factors authentication',
'admin_2factors_authentication_setting_tip' => '<span style=\'font-size:11px;max-width:300px;\'>Google 2-Factors autentication permits to add one more security level for user autentication. When user wants to login TeamPass, a QR code is generated. This QR code needs to be scanned by the user to get a one-time password.<br />WARNING: this extra needs an Internet connection and a scanner such as a smartphone.</span>',
'2factors_tile' => '2-Factors Autentication',
'2factors_image_text' => 'Please, scan the QR code',
'2factors_confirm_text' => 'Enter the one-time password',
'bad_onetime_password' => 'Wrong One-Time password!',
'error_string_not_utf8' => 'An error appears because string format is not UTF8!',
'error_role_exist' => 'This Role already exists!',
'error_no_edition_possible_locked' => 'Edition not possible. This Item is presently edited!',
'error_mcrypt_not_loaded' => 'Extension \'mcrypt\' is actually not loaded in PHP module. This module is required for TeamPass to work. Please inform your administrator if you see this message.',
'at_user_added' => 'User #user_login# added',
'at_user_deleted' => 'User #user_login# deleted',
'at_user_locked' => 'User #user_login# locked',
'at_user_unlocked' => 'User #user_login# unlocked',
'at_user_email_changed' => 'User #user_login# email changed',
'at_user_pwd_changed' => 'User #user_login# password changed',
'at_user_initial_pwd_changed' => 'User #user_login# initial password change',
'user_mngt' => 'User Management',
'select' => 'select',
'user_activity' => 'User Activity',
'items' => 'Items',
'enable_personal_saltkey_cookie' => 'Enable personal SALTKey to be stored in a cookie',
'personal_saltkey_cookie_duration' => 'Personal SALTKey cookie DAYS life time before expiration',
'admin_emails' => 'Emails',
'admin_emails_configuration' => 'Emails Configuration',
'admin_emails_configuration_testing' => 'Configuration testing',
'admin_email_smtp_server' => 'SMTP server',
'admin_email_auth' => 'SMTP server needs authentification',
'admin_email_auth_username' => 'Authentification Username',
'admin_email_auth_pwd' => 'Authentification Password',
'admin_email_port' => 'Server Port',
'admin_email_from' => 'Sender Email (from Email)',
'admin_email_from_name' => 'Sender Name (from Name)',
'admin_email_test_configuration' => 'Test the Email configuration',
'admin_email_test_configuration_tip' => 'This test should send an email to the address indicated. If you don\'t receive it, please check your credentials.',
'admin_email_test_subject' => '[TeamPass] Test email',
'admin_email_test_body' => 'Hi,<br><br>Email sent successfully.<br><br>Cheers.',
'admin_email_result_ok' => 'Email sent to #email# ... check your inbox.',
'admin_email_result_nok' => 'Email not sent ... check your configuration. See associated error: ',
'email_subject_item_updated' => 'Password has been updated',
'email_body_item_updated' => 'Hello,<br><br>Password for \'#item_label#\' has been updated.<br /><br />You can check it <a href=\'".@$_SESSION[\'settings\'][\'cpassman_url\']."/index.php?page=items&group=#item_category#&id=#item_id#\'>HERE</a><br /><br />Cheers',
'email_bodyalt_item_updated' => 'Password for #item_label# has been updated.',
'admin_email_send_backlog' => 'Send emails backlog (actually #nb_emails# emails)',
'admin_email_send_backlog_tip' => 'This script permits to force the emails in the database to be sent.<br />This could take some time depending of the number of emails to send.',
'please_wait' => 'Please wait!',
'admin_url_to_files_folder' => 'URL to Files folder',
'admin_path_to_files_folder' => 'Path to Files folder',
'admin_path_to_files_folder_tip' => '<span style=\'font-size:11px;max-width:300px;\'>Files folder is used to store all generated files by TeamPass and also some uploaded files.<br />IMPORTANT: for security reason, this folder should not be in the WWW folder of your website. It should be set in a protected area with a specific redirection rule in your Server configuration.<br />IMPORTANT 2:It could be good to set a CRON task in order to clean up periodically this folder.</span>',
'admin_path_to_upload_folder_tip' => '<span style=\'font-size:11px;max-width:300px;\'>Upload folder is used to store all uploaded files associated to Items.<br />IMPORTANT: for security reason, this folder should not be in the WWW folder of your website. It should be set in a protected area with a specific redirection rule in your Server configuration.<br />IMPORTANT 2:This folder should never be clean up! Those files are associated to the Items.</span>',
'pdf_export' => 'PDF exports',
'pdf_password' => 'PDF encryption key',
'pdf_password_warning' => 'You must provide an encryption key!',
'admin_pwd_maximum_length' => 'Maximum length for passwords',
'admin_pwd_maximum_length_tip' => 'The default value for passwords length is set to 40. It is important to know that setting a high value length will have impact on performances. Indeed more long is this value, more time the server needs to encrypt and decrypt, and to display passwords.',
'settings_insert_manual_entry_item_history' => 'Enable permitting manual insertions in Items History log',
'settings_insert_manual_entry_item_history_tip' => 'For any reason you may need to add manually an entry in the history of the Item. By activating this feature, it is possible.',
'add_history_entry' => 'Add entry in History log',
'at_manual' => 'Manual action',
'at_manual_add' => 'Added manually',
'admin_path_to_upload_folder' => 'Path to Upload folder',
'admin_url_to_upload_folder' => 'URL to Upload folder',
'automatic_del_after_date_text' => 'or after date',
'at_automatically_deleted' => 'Automatically deleted',
'admin_setting_enable_delete_after_consultation' => 'Item consulted can be automatically deleted',
'admin_setting_enable_delete_after_consultation_tip' => '<span style=\'font-size:11px;max-width:300px;\'>When enabled, the Item creator can decide that Item will be automatically deleted after being seen X times.</span>',
'enable_delete_after_consultation' => 'Item will be automatically deleted after being seen',
'times' => 'times.',
'automatic_deletion_activated' => 'Automatic deletion engaged',
'at_automatic_del' => 'automatic deletion',
'error_times_before_deletion' => 'Number of consultation before deletion needs to be more than 0!',
'enable_notify' => 'Enable notify',
'disable_notify' => 'Disable notify',
'notify_activated' => 'Notification enabled',
'at_email' => 'email',
'enable_email_notification_on_item_shown' => 'Send notification by email when Item is shown',
'bad_email_format' => 'Email address doesn\'t have the expected format!',
'item_share_text' => 'In order to share this item by mail, enter the email address and press SEND button.',
'share' => 'Share this Item',
'share_sent_ok' => 'Email has been sent',
'email_share_item_subject' => '[TeamPass] An Item was shared with you',
'email_share_item_mail' => 'Hello,<br><br><u>#tp_user#</u> has shared with you the item <b>#tp_item#</b><br>Click the <a href=\'#tp_link#\'>LINK</a> to access.<br><br>Best regards.',
'see_item_title' => 'Item Details',
'email_on_open_notification_subject' => '[TeamPass] Notification on Item open',
'email_on_open_notification_mail' => 'Hello,<br><br>#tp_user# has opened and watched the Item \'#tp_item#\'.<br>Click the <a href=\'#tp_link#\'>LINK</a> to access.<br><br>Best regards.',
'pdf' => 'PDF',
'csv' => 'CSV',
'user_admin_migrate_pw' => 'Migrate personal Items to a user account',
'migrate_pf_select_to' => 'Migrate personal Items to user',
'migrate_pf_user_salt' => 'Enter the SALT key for selected User',
'migrate_pf_no_sk' => 'You have not entered your SALT Key',
'migrate_pf_no_sk_user' => 'You must enter the User SALT Key',
'migrate_pf_no_user_id' => 'You must select the User";',
'email_subject_new_user' => '[TeamPass] Your account creation',
'email_new_user_mail' => 'Hello,<br><br>An administrator has created your account for Teampass.<br>You can use the next credentials for being logged:<br>- Login: #tp_login#<br>- Password: #tp_pw#<br><br>Click the <a href=\'#tp_link#\'>LINK</a> to access.<br><br>Best regards.',
'error_empty_data' => 'No data to proceed!',
'error_not_allowed_to' => 'You are not allowed to do that!',
'personal_saltkey_lost' => 'Reset my Personal Saltkey',
'new_saltkey_warning_lost' => 'You have lost your saltkey? What a pitty, this one can\'t be recovered, so please be sure before continuing.<br>By reseting your saltkey, all your previous personal items will be deleted!',
'previous_pw' => 'Previous passwords used:',
'no_previous_pw' => 'No previous password',
'request_access_ot_item' => 'Request an access to author',
'email_request_access_subject' => '[TeamPass] Request an access to item',
'email_request_access_mail' => 'Hello #tp_item_author#,<br><br>User #tp_user# has required an access to \'#tp_item#\'.<br><br>Be sure of the rights of this user before changing the restriction to the Item.<br><br>Regards.',
'admin_action_change_salt_key' => 'Change the main SALT Key',
'admin_action_change_salt_key_tip' => 'Before changing the SALT key, please be sure to do a full backup of the database, and to put the tool in maintenance in order to avoid any users being logged.',
'block_admin_info' => 'Administrator\'s Info',
'admin_new1' => '<i><u>14FEB2012:</i></u><br>Administrator profile is no more allowed to see items. This profile is now only an Administrative account.<br />See <a href=\'http://www.teampass.net/how-to-handle-changes-on-administrator-profile\' target=\'_blank\'>TeamPass.net page</a> concerning the way to handle this change.',
'nb_items_by_query' => 'Number of items to get at each query iterration',
'nb_items_by_query_tip' => '<span style=\'font-size:11px;max-width:300px;\'>More items means more time to display the list.<br />Set to \'auto\' to let the tool to adapt this number depending on the size screen of the user.<br />Set to \'max\' to force to display the complet list in one time.<br />Set a number corresding to the number of items to get at each query iterration.</span>',
'error_no_selected_folder' => 'You need to select a Folder',
'open_url_link' => 'Open in new page',
'error_pw_too_long' => 'Password is too long! Maximum characters is 40.',
'at_restriction' => 'Restriction',
'pw_encryption_error' => 'Error encryption of the password!',
'enable_send_email_on_user_login' => 'Send an email to Admins on User log in',
'email_subject_on_user_login' => '[TeamPass] A user has connected',
'email_body_on_user_login' => 'Hello,<br><br>User #tp_user# has connected to TeamPass the #tp_date# at #tp_time#.<br><br>Regards.',
'account_is_locked' => 'This account is locked',
'activity' => 'Activity',
'add_button' => 'Add',
'add_new_group' => 'Add a new folder',
'add_role_tip' => 'Add a new role.',
'admin' => 'Administration',
'admin_action' => 'Please validate your action',
'admin_action_db_backup' => 'Create a backup of the database',
'admin_action_db_backup_key_tip' => 'Please enter the encryption key. Save it somewhere, it will be asked when restoring. (leave empty to not encrypt)',
'admin_action_db_backup_start_tip' => 'Start',
'admin_action_db_backup_tip' => 'It is a good practice to create a backup that could be used to restore your database.',
'admin_action_db_clean_items' => 'Remove orphan items from database',
'admin_action_db_clean_items_result' => 'items have been deleted.',
'admin_action_db_clean_items_tip' => 'This will only delete those items and associated logs that have not been deleted after the associated folder has been deleted. It is suggested to create a backup before.',
'admin_action_db_optimize' => 'Optimize the database',
'admin_action_db_restore' => 'Restore the database',
'admin_action_db_restore_key' => 'Please enter the encryption key.',
'admin_action_db_restore_tip' => 'It has to be done using an SQL backup file created by the backup functionality.',
'admin_action_purge_old_files' => 'Purge old files',
'admin_action_purge_old_files_result' => 'files have been deleted.',
'admin_action_purge_old_files_tip' => 'This will delete all temporary files older than 7 days.',
'admin_action_reload_cache_table' => 'Reload Cache table',
'admin_action_reload_cache_table_tip' => 'This permits to reload the full content of table Cache. Can be usefull to be done sometimes.',
'admin_backups' => 'Backups',
'admin_error_no_complexity' => '(<a href=\'index.php?page=manage_groups\'>Define?</a>)',
'admin_error_no_visibility' => 'No one can see this item. (<a href=\'index.php?page=manage_roles\'>Customize roles</a>)',
'admin_functions' => 'Roles management',
'admin_groups' => 'Folders management',
'admin_help' => 'Help',
'admin_info' => 'Some information concerning the tool',
'admin_info_loading' => 'Loading data ... please wait',
'admin_ldap_configuration' => 'LDAP configuration',
'admin_ldap_menu' => 'LDAP options',
'admin_main' => 'Information',
'admin_misc_cpassman_dir' => 'Full path to TeamPass',
'admin_misc_cpassman_url' => 'Full URL to TeamPass',
'admin_misc_custom_login_text' => 'Custom Login text',
'admin_misc_custom_logo' => 'Full url to Custom Login Logo',
'admin_misc_favicon' => 'Full URL to favicon file',
'admin_misc_title' => 'Customize',
'admin_one_shot_backup' => 'One shot backup and restore',
'admin_script_backups' => 'Settings for Backups script',
'admin_script_backups_tip' => 'For more security, it is recommended to parameter a scheduled backup of the database.<br />Use your server to schedule a daily cron task by calling the file \'script.backup.php\' in \'backups\' folder.<br />You first need to set the 2 first paramteres and SAVE them.',
'admin_script_backup_decrypt' => 'Name of the file you want to decrypt',
'admin_script_backup_decrypt_tip' => 'In order to decrypt a backup file, just indicate the name of the backup file (no extension and no path).<br />The file will be decrypted in the same folder as the backup files are.',
'admin_script_backup_encryption' => 'Encryption key (optional)',
'admin_script_backup_encryption_tip' => 'If set, this key will be used to encrypted your file',
'admin_script_backup_filename' => 'Backup file name',
'admin_script_backup_filename_tip' => 'File name you want for your backups file',
'admin_script_backup_path' => 'Path where backups have to be stored',
'admin_script_backup_path_tip' => 'The folder in which the backup files will be stored',
'admin_settings' => 'Settings',
'admin_settings_title' => 'TeamPass Settings',
'admin_setting_activate_expiration' => 'Enable passwords expiration',
'admin_setting_activate_expiration_tip' => 'When enabled, items expired will not be displayed to users.',
'admin_users' => 'Users management',
'admin_views' => 'Views',
'alert_message_done' => 'Done!',
'alert_message_personal_sk_missing' => 'You must enter your personal saltkey!',
'all' => 'all',
'anyone_can_modify' => 'Allow this item to be modified by anyone that can access it',
'associated_role' => 'What role to associate this folder to :',
'associate_kb_to_items' => 'Select the items to associate to this KB',
'assoc_authorized_groups' => 'Allowed Associated Folders',
'assoc_forbidden_groups' => 'Forbidden Associated Folders',
'at' => 'at',
'at_add_file' => 'File added',
'at_category' => 'Folder',
'at_copy' => 'Copy done',
'at_creation' => 'Creation',
'at_delete' => 'Deletion',
'at_del_file' => 'File deleted',
'at_description' => 'Description.',
'at_file' => 'File',
'at_import' => 'Importation',
'at_label' => 'Label',
'at_login' => 'Login',
'at_modification' => 'Modification',
'at_moved' => 'Moved',
'at_personnel' => 'Personal',
'at_pw' => 'Password changed.',
'at_restored' => 'Restored',
'at_shown' => 'Accessed',
'at_url' => 'URL',
'auteur' => 'Author',
'author' => 'Author',
'authorized_groups' => 'Allowed Folders',
'auth_creation_without_complexity' => 'Allow creating an item without respecting the required password complexity',
'auth_modification_without_complexity' => 'Allow modifying an item without respecting the required password complexity',
'auto_create_folder_role' => 'Create folder and role for ',
'block_last_created' => 'Last created',
'bugs_page' => 'If you discover a bug, you can directly post it in <a href=\'https://sourceforge.net/tracker/?group_id=280505&atid=1190333\' target=\'_blank\'><u>Bugs Forum</u></a>.',
'by' => 'by',
'cancel' => 'Cancel',
'cancel_button' => 'Cancel',
'can_create_root_folder' => 'Can create a folder at root level',
'changelog' => 'Latest news',
'change_authorized_groups' => 'Change authorized folders',
'change_forbidden_groups' => 'Change forbidden folders',
'change_function' => 'Change roles',
'change_group_autgroups_info' => 'Select the authorized folders this Role can see and use',
'change_group_autgroups_title' => 'Customize the authorized folders',
'change_group_forgroups_info' => 'Select the forbidden folders this Role can\'t see and use',
'change_group_forgroups_title' => 'Customize the forbidden folders',
'change_user_autgroups_info' => 'Select the authorized folders this account can see and use',
'change_user_autgroups_title' => 'Customize the authorized folders',
'change_user_forgroups_info' => 'Select the forbidden folders this account can\'t see nor use',
'change_user_forgroups_title' => 'Customize the forbidden folders',
'change_user_functions_info' => 'Select the functions associated to this account',
'change_user_functions_title' => 'Customize associated functions',
'check_all_text' => 'Check all',
'close' => 'Close',
'complexity' => 'Complexity',
'complex_asked' => 'Required complexity',
'complex_level0' => 'Very weak',
'complex_level1' => 'Weak',
'complex_level2' => 'Medium',
'complex_level3' => 'Strong',
'complex_level4' => 'Very strong',
'complex_level5' => 'Heavy',
'complex_level6' => 'Very heavy',
'confirm' => 'Confirm',
'confirm_delete_group' => 'You have decided to delete this Folder and all included Items ... are you sure?',
'confirm_del_account' => 'You have decided to delete this Account. Are you sure?',
'confirm_del_from_fav' => 'Please confirm deletion from Favourites',
'confirm_del_role' => 'Please confirm the deletion of the next role:',
'confirm_edit_role' => 'Please enter the name of the next role:',
'confirm_lock_account' => 'You have decided to LOCK this Account. Are you sure?',
'connection' => 'Connection',
'connections' => 'connections',
'copy' => 'Copy',
'copy_to_clipboard_small_icons' => 'Enable copy to clipboard small icons in items page',
'copy_to_clipboard_small_icons_tip' => '<span style=\'font-size:11px;max-width:300px;\'>This could help preventing memory usage if users have no recent computer.<br /> Indeed, the clipboard is not loaded with items informations. But no quick copy of password and login is possible.</spa',
'creation_date' => 'Creation date',
'csv_import_button_text' => 'Browse CSV file',
'date' => 'Date',
'date_format' => 'Date format',
'days' => 'days',
'definition' => 'Definition',
'delete' => 'Delete',
'deletion' => 'Deletions',
'deletion_title' => 'List of Items deleted',
'del_button' => 'Delete',
'del_function' => 'Delete Roles',
'del_group' => 'Delete Folder',
'description' => 'Description',
'disconnect' => 'Logout',
'disconnection' => 'Logout',
'div_dialog_message_title' => 'Information',
'done' => 'Done',
'drag_drop_helper' => 'Drag and drop item',
'duplicate_folder' => 'Authorize to have several folders with the same name.',
'duplicate_item' => 'Authorize to have several items with the same name.',
'email' => 'Email',
'email_altbody_1' => 'Item',
'email_altbody_2' => 'has been created.',
'email_announce' => 'Announce this Item by email',
'email_body1' => 'Hi,<br><br>Item \'',
'email_body2' => 'has been created.<br /><br />You may view it by clicking <a href=\'',
'email_body3' => '>HERE</a><br /><br />Regards.',
'email_change' => 'Change the account\'s email',
'email_changed' => 'Email changed!',
'email_select' => 'Select persons to inform',
'email_subject' => 'Creating a new Item in Passwords Manager',
'email_text_new_user' => 'Hi,<br /><br />Your account has been created in TeamPass.<br />You can now access $TeamPass_url using the next credentials:<br />',
'enable_favourites' => 'Enable the Users to store Favourites',
'enable_personal_folder' => 'Enable Personal folder',
'enable_personal_folder_feature' => 'Enable Personal folder feature',
'enable_user_can_create_folders' => 'Users are allowed to manage folders in allowed parent folders',
'encrypt_key' => 'Encryption key',
'errors' => 'errors',
'error_complex_not_enought' => 'Password complexity is not fulfilled!',
'error_confirm' => 'Password confirmation is not correct!',
'error_cpassman_dir' => 'No path for TeamPass is set. Please select \'TeamPass settings\' tab in Admin Settings page.',
'error_cpassman_url' => 'No URL for TeamPass is set. Please select \'TeamPass settings\' tab in Admin Settings page.',
'error_fields_2' => 'The 2 fields are mandatory!',
'error_group' => 'A folder is mandatory!',
'error_group_complex' => 'The Folder must have a minimum required passwords complexity level!',
'error_group_exist' => 'This folder already exists!',
'error_group_label' => 'The Folder must be named!',
'error_html_codes' => 'Some text contains HTML codes! This is not allowed.',
'error_item_exists' => 'This Item already exists!',
'error_label' => 'A label is mandatory!',
'error_must_enter_all_fields' => 'You must fill in each fields!',
'error_mysql' => 'MySQL Error!',
'error_not_authorized' => 'You are not allowed to see this page.',
'error_not_exists' => 'This page does not exist.',
'error_no_folders' => 'You should start by creating some folders.',
'error_no_password' => 'You need to enter your password!',
'error_no_roles' => 'You should also create some roles and associate them to folders.',
'error_password_confirmation' => 'Passwords should be the same',
'error_pw' => 'A password is mandatory!',
'error_renawal_period_not_integer' => 'Renewal period should be expressed in months!',
'error_salt' => '<b>The SALT KEY is too long! Please don\'t use the tool until an Admin has modified the salt key.</b> In settings.php file, SALT should not be longer than 32 characters.',
'error_tags' => 'No punctuation characters allowed in TAGS! Only space.',
'error_user_exists' => 'User already exists',
'expiration_date' => 'Expiration date',
'expir_one_month' => '1 month',
'expir_one_year' => '1 year',
'expir_six_months' => '6 months',
'expir_today' => 'today',
'files_&_images' => 'Files & Images',
'find' => 'Find',
'find_text' => 'Your search',
'folders' => 'Folders',
'forbidden_groups' => 'Forbidden Folders',
'forgot_my_pw' => 'Forgot your password?',
'forgot_my_pw_email_sent' => 'Email has been sent',
'forgot_my_pw_error_email_not_exist' => 'This email doesn\'t exist!',
'forgot_my_pw_text' => 'Your password will be sent to the email associated to your account.',
'forgot_pw_email_altbody_1' => 'Hi, Your identification credentials for TeamPass are:',
'forgot_pw_email_body' => 'Hi,<br /><br />Your new password for TeamPass is :',
'forgot_pw_email_body_1' => 'Hi, <br /><br />Your identification credentials for TeamPass are:<br /><br />',
'forgot_pw_email_subject' => 'TeamPass - Your password',
'forgot_pw_email_subject_confirm' => '[TeamPass] Your password step 2',
'functions' => 'Roles',
'function_alarm_no_group' => 'This role is not associated to any Folder!',
'generate_pdf' => 'Generate a PDF file',
'generation_options' => 'Generation options',
'gestionnaire' => 'Manager',
'give_function_tip' => 'Add a new role',
'give_function_title' => 'Add a new Role',
'give_new_email' => 'Please enter new email for',
'give_new_login' => 'Please select the account',
'give_new_pw' => 'Please indicate the new password for',
'god' => 'Administrator',
'group' => 'Folder',
'group_parent' => 'Parent Folder',
'group_pw_duration' => 'Renewal period',
'group_pw_duration_tip' => 'In months. Use 0 to disable.',
'group_select' => 'Select folder',
'group_title' => 'Folder label',
'history' => 'History',
'home' => 'Home',
'home_personal_menu' => 'Personal Actions',
'home_personal_saltkey' => 'Your personal SALTKey',
'home_personal_saltkey_button' => 'Set the Saltkey',
'home_personal_saltkey_info' => 'You should enter your personal saltkey if you need to use your personal items.',
'home_personal_saltkey_label' => 'Enter your personal salt key',
'importing_details' => 'List of details',
'importing_folders' => 'Importing folders',
'importing_items' => 'Importing items',
'import_button' => 'Import',
'import_csv_anyone_can_modify_in_role_txt' => 'Set "anyone in the same role can modify" right on all imported items.',
'import_csv_anyone_can_modify_txt' => 'Set "anyone can modify" right on all imported items.',
'import_csv_dialog_info' => 'Information: import must be done using a CSV file. Typically a file exported from KeePass has the expected structure.<br />If you use a file generated by another tool, please check that CSV structure is as follows: `Account`,`Login Name`,`Password`,`Web Site`,`Comments`.',
'import_csv_menu_title' => 'Import Items',
'import_error_no_file' => 'You must select a file!',
'import_error_no_read_possible' => 'Can\'t read the file!',
'import_error_no_read_possible_kp' => 'Can\'t read the file! It must be a KeePass file.',
'import_keepass_dialog_info' => 'Please use this to select an XML file generated by KeePass export functionality. Will only work with KeePass file! Notice that the import script will not import folders or elements that already exist at the same level of the tree structure.',
'import_keepass_to_folder' => 'Select the destination folder',
'import_kp_finished' => 'Import from KeePass is now finished !<br />By default, the complexity level for new folders have been set to `Medium`. Perhaps will you need to change it.',
'import_to_folder' => 'Tick the items you want to import to folder:',
'index_add_one_hour' => 'Extend session by 1 hour',
'index_alarm' => 'ALARM!!!',
'index_bas_pw' => 'Bad password for this account!',
'index_change_pw' => 'Change my password',
'index_change_pw_button' => 'Change',
'index_change_pw_confirmation' => 'Confirm',
'index_expiration_in' => 'session expiration in',
'index_get_identified' => 'Please identify yourself',
'index_identify_button' => 'Enter',
'index_identify_you' => 'Please identify yourself',
'index_last_pw_change' => 'Password changed the',
'index_last_seen' => 'Last connection, the',
'index_login' => 'Account',
'index_maintenance_mode' => 'Maintenance mode has been activated. Only Administrators can log in.',
'index_maintenance_mode_admin' => 'Maintenance mode is activated. Users currently can not access TeamPass.',
'index_new_pw' => 'New password',
'index_password' => 'Password',
'index_pw_error_identical' => 'The passwords have to be identical!',
'index_pw_expiration' => 'Actual password expiration in',
'index_pw_level_txt' => 'Complexity',
'index_refresh_page' => 'Refresh page',
'index_session_duration' => 'Session duration',
'index_session_ending' => 'Your session will end in less than 1 minute.',
'index_session_expired' => 'Your session has expired or you are not correctly identified!',
'index_welcome' => 'Welcome',
'info' => 'Information',
'info_click_to_edit' => 'Click on a cell to edit its value',
'is_admin' => 'Is Admin',
'is_manager' => 'Is Manager',
'is_read_only' => 'Is Read Only',
'items_browser_title' => 'Folders',
'item_copy_to_folder' => 'Please select a folder in which the item has to be copied.',
'item_menu_add_elem' => 'Add item',
'item_menu_add_rep' => 'Add a Folder',
'item_menu_add_to_fav' => 'Add to Favourites',
'item_menu_collab_disable' => 'Edition is not allowed',
'item_menu_collab_enable' => 'Edition is allowed',
'item_menu_copy_elem' => 'Copy item',
'item_menu_copy_login' => 'Copy login',
'item_menu_copy_pw' => 'Copy password',
'item_menu_del_elem' => 'Delete item',
'item_menu_del_from_fav' => 'Delete from Favourites',
'item_menu_del_rep' => 'Delete a Folder',
'item_menu_edi_elem' => 'Edit item',
'item_menu_edi_rep' => 'Edit a Folder',
'item_menu_find' => 'Search',
'item_menu_mask_pw' => 'Mask password',
'item_menu_refresh' => 'Refresh page',
'kbs' => 'KBs',
'kb_menu' => 'Knowledge Base',
'keepass_import_button_text' => 'Browse XML file and import entries',
'label' => 'Label',
'last_items_icon_title' => 'Show/Hide Last items seen',
'last_items_title' => 'Last items seen',
'ldap_extension_not_loaded' => 'The LDAP extension is not activated on the server.',
'level' => 'Level',
'link_copy' => 'Get a link to this item',
'link_is_copied' => 'The link to this Item has been copied to clipboard.',
'login' => 'Login (if needed)',
'login_attempts_on' => ' login attempts on ',
'login_copied_clipboard' => 'Login copied in clipboard',
'login_copy' => 'Copy account to clipboard',
'logs' => 'Logs',
'logs_1' => 'Generate the log file for the passwords renewal done the',
'logs_passwords' => 'Generate Passwords Log',
'maj' => 'Uppercase letters',
'mask_pw' => 'Mask/Display the password',
'max_last_items' => 'Maximum number of last items seen by user (default is 10)',
'menu_title_new_personal_saltkey' => 'Change my Personal Saltkey',
'minutes' => 'minutes',
'modify_button' => 'Modify',
'my_favourites' => 'My favourites',
'name' => 'Name',
'nb_false_login_attempts' => 'Number of false login attempts before account is disabled (0 to disable)',
'nb_folders' => 'Number of Folders',
'nb_items' => 'Number of Items',
'nb_items_by_page' => 'Number of items by page',
'new_label' => 'New label',
'new_role_title' => 'New role title',
'new_saltkey' => 'New Saltkey',
'new_saltkey_warning' => 'Please be sure to use the original SaltKey, otherwize the new encryption will be corrupted. Before doing any change, please test your actual SaltKey!',
'new_user_title' => 'Add a new user',
'no' => 'No',
'nom' => 'Name',
'none' => 'None',
'none_selected_text' => 'None selected',
'not_allowed_to_see_pw' => 'You are not allowed to see that Item!',
'not_allowed_to_see_pw_is_expired' => 'This item has expired!',
'not_defined' => 'Not defined',
'no_last_items' => 'No items seen',
'no_restriction' => 'No restriction',
'numbers' => 'Numbers',
'number_of_used_pw' => 'Number of new passwords a user has to enter before reusing an old one.',
'ok' => 'OK',
'pages' => 'Pages',
'pdf_del_date' => 'PDF generated the',
'pdf_del_title' => 'Passwords renewal follow-up',
'pdf_download' => 'Download file',
'personal_folder' => 'Personal folder',
'personal_saltkey_change_button' => 'Change it!',
'personal_salt_key' => 'Your personal salt key',
'personal_salt_key_empty' => 'Personal salt key has not been entered!',
'personal_salt_key_info' => 'This salt key will be used to encrypt and decrypt your passwords.<br />It is not stored in database, you are the only person who knows it.<br />So don\'t loose it!',
'please_update' => 'Please update the tool!',
'print' => 'Print',
'print_out_menu_title' => 'Export items',
'print_out_pdf_title' => 'TeamPass - List of exported Items',
'print_out_warning' => 'By writing the file containing unencrypted items/passwords, you are accepting the full responsibility for further protection of this list! Your PDF export will be logged.',
'pw' => 'Password',
'pw_change' => 'Change the account\'s password',
'pw_changed' => 'Password changed!',
'pw_copied_clipboard' => 'Password copied to clipboard',
'pw_copy_clipboard' => 'Copy password to clipboard',
'pw_generate' => 'Generate',
'pw_is_expired_-_update_it' => 'This item has expired! You need to change its password.',
'pw_life_duration' => 'Users\' password life duration before expiration (in days, 0 to disable)',
'pw_recovery_asked' => 'You have asked for a password recovery',
'pw_recovery_button' => 'Send me my new password',
'pw_recovery_info' => 'By clicking on the next button, you will receive an email that contains the new password for your account.',
'pw_used' => 'This password has already been used!',
'readme_open' => 'Open full readme file',
'read_only_account' => 'Read Only',
'refresh_matrix' => 'Refresh Matrix',
'renewal_menu' => 'Renewal follow-up',
'renewal_needed_pdf_title' => 'List of Items that need to be renewed',
'renewal_selection_text' => 'List all items that will expire:',
'restore' => 'Restore',
'restricted_to' => 'Restricted to',
'restricted_to_roles' => 'Allow to restrict items to Users and Roles',
'rights_matrix' => 'Users rights matrix',
'roles' => 'Roles',
'role_cannot_modify_all_seen_items' => 'Set this role not allowed to modify all accessible items (normal setting)',
'role_can_modify_all_seen_items' => 'Set this role allowed to modify all accessible items (not secure setting)',
'root' => 'Root',
'save_button' => 'Save',
'secure' => 'Secure',
'see_logs' => 'See Logs',
'select_folders' => 'Select folders',
'select_language' => 'Select your language',
'send' => 'Send',
'settings_anyone_can_modify' => 'Activate an option for each item that allows anyone to modify it',
'settings_anyone_can_modify_tip' => '<span style=\'font-size:11px;max-width:300px;\'>When activated, this will add a checkbox in the item form that permits the creator to allow the modification of this item by anyone.</span>',
'settings_default_language' => 'Define the Default Language',
'settings_kb' => 'Enable Knowledge Base (beta)',
'settings_kb_tip' => '<span style=\'font-size:11px;max-width:300px;\'>When activated, this will add a page where you can build your knowledge base.</span>',
'settings_ldap_domain' => 'LDAP account suffix for your domain',
'settings_ldap_domain_controler' => 'LDAP array of domain controllers',
'settings_ldap_domain_controler_tip' => '<span style=\'font-size:11px;max-width:300px;\'>Specifiy multiple controllers if you would like the class to balance the LDAP queries amongst multiple servers.<br />You must delimit the domains by a comma (,)!<br />By example: domain_1,domain_2,domain_3</span>',
'settings_ldap_domain_dn' => 'LDAP base dn for your domain',
'settings_ldap_mode' => 'Enable users authentification through LDAP server',
'settings_ldap_mode_tip' => 'Enable only if you have an LDAP server and if you want to use it to authentify TeamPass users through it.',
'settings_ldap_ssl' => 'Use LDAP through SSL (LDAPS)',
'settings_ldap_tls' => 'Use LDAP through TLS',
'settings_log_accessed' => 'Enable logging who accessed the items',
'settings_log_connections' => 'Enable logging all users connections into database.',
'settings_maintenance_mode' => 'Set TeamPass in Maintenance mode',
'settings_maintenance_mode_tip' => 'This mode will refuse any user connection except for Administrators.',
'settings_manager_edit' => 'Managers can edit and delete Items they are allowed to see',
'settings_printing' => 'Enable printing items to PDF file',
'settings_printing_tip' => 'When enabled, a button will be added to user\'s home page that will permit him/her to write a listing of items to a PDF file he/she can view. Notice that the listed passwords will be uncrypted.',
'settings_restricted_to' => 'Enable Restricted To functionality on Items',
'settings_richtext' => 'Enable richtext for item description',
'settings_richtext_tip' => '<span style=\'font-size:11px;max-width:300px;\'>This will activate a richtext with BBCodes in description field.</span>',
'settings_send_stats' => 'Send monthly statistics to author for better understand your usage of TeamPass',
'settings_send_stats_tip' => 'These statistics are entirely anonymous!<br /><span style=\'font-size:10px;max-width:300px;\'>Your IP is not sent, just the following data are transmitted: amount of Items, Folders, Users, TeamPass version, personal folders enabled, ldap enabled.<br />Many thanks if you enable those statistics. By this you help me further develop TeamPass.</span>',
'settings_show_description' => 'Show Description in list of Items',
'show' => 'Show',
'show_help' => 'Show Help',
'show_last_items' => 'Show last items block on main page',
'size' => 'Size',
'start_upload' => 'Start uploading files',
'sub_group_of' => 'Dependent on',
'support_page' => 'For any support, please use the <a href=\'https://sourceforge.net/projects/communitypasswo/forums\' target=\'_blank\'><u>Forum</u></a>.',
'symbols' => 'Symbols',
'tags' => 'Tags',
'thku' => 'Thank you for using TeamPass!',
'timezone_selection' => 'Timezone selection',
'time_format' => 'Time format',
'uncheck_all_text' => 'Uncheck all',
'unlock_user' => 'User is locked. Do you want to unlock this account?',
'update_needed_mode_admin' => 'It is recommended to update your TeamPass installation. Click <a href=\'install/upgrade.php\'>HERE</a>',
'uploaded_files' => 'Existing Files',
'upload_button_text' => 'Browse',
'upload_files' => 'Upload New Files',
'url' => 'URL',
'url_copied' => 'URL has been copied!',
'used_pw' => 'Used password',
'user' => 'User',
'users' => 'Users',
'users_online' => 'users online',
'user_action' => 'Action on a user',
'user_alarm_no_function' => 'This user has no Roles!',
'user_del' => 'Delete account',
'user_lock' => 'Lock user',
'version' => 'Current version',
'views_confirm_items_deletion' => 'Do you really want to delete the selected items from database?',
'views_confirm_restoration' => 'Please confirm the restoration of this Item',
'visibility' => 'Visibility',
'warning_screen_height' => 'WARNING: screen height is not enough for displaying items list!',
'yes' => 'Yes',
'your_version' => 'Your version',
'disconnect_all_users_sure' => 'Are you sure you\'d like to disconnect all users?',
'Test the Email configuration' => 'Test the email configuration',
'url_copied_clipboard' => 'URL copied in clipboard',
'url_copy' => 'Copy URL in clipboard',
'one_time_item_view' => 'One time view link',
'one_time_view_item_url_box' => 'Share the One-Time URL with a person of Trust <br><br>#URL#<br><br>Remember that this link will only be visible one time until the #DAY#',
'admin_api' => 'API',
'settings_api' => 'Enable access to Teampass Items through API',
'settings_api_tip' => 'API access permits to do access the Items from a third party application in JSON format.',
'settings_api_keys_list' => 'List of Keys',
'settings_api_keys_list_tip' => 'This is the keys that are allowed to access to Teampass. Without a valid Key, the access is not possible. You should share those Keys carrefuly!',
'settings_api_generate_key' => 'Generate a key',
'settings_api_delete_key' => 'Delete key',
'settings_api_add_key' => 'Add new key',
'settings_api_key' => 'Key',
'settings_api_key_label' => 'Label',
'settings_api_ip_whitelist' => 'White-list of authorized IPs',
'settings_api_ip_whitelist_tip' => 'If no IP is listed then any IP is authorized.',
'settings_api_add_ip' => 'Add new IP',
'settings_api_db_intro' => 'Give a label for this new Key (not mandatory but recommended)',
'error_too_long' => 'Error - Too long string!',
'settings_api_ip' => 'IP',
'settings_api_db_intro_ip' => 'Give a label for this new IP',
'settings_api_world_open' => 'No IP defined. The feature is totally open from any location (maybe unsecure).',
'subfolder_rights_as_parent' => 'New sub-folder inherits rights from parent folder',
'subfolder_rights_as_parent_tip' => 'When this feature is disabled, each new sub-folder inherits the rights associated to the Creator roles. If enabled, then each new sub-folder inherits the rights of the parent folder.',
'show_only_accessible_folders_tip' => 'By default, the user see the complete path of the tree even if he doesn\'t have access to all of the folders. You may simplify this removing from the tree the folders he has no access to.',
'show_only_accessible_folders' => 'Simplify the Items Tree by removing the Folders the user has no access to',
'suggestion' => 'Items suggestion',
'suggestion_add' => 'Add an item suggestion',
'comment' => 'Comment',
'suggestion_error_duplicate' => 'A similar suggestion already exists!',
'suggestion_delete_confirm' => 'Please confirm Suggestion deletion',
'suggestion_validate_confirm' => 'Please confirm Suggestion validation',
'suggestion_validate' => 'You have decided to add this Suggestion to the Items list ... please confirm.',
'suggestion_error_cannot_add' => 'ERROR - The suggestion could not be added as an Item!',
'suggestion_is_duplicate' => 'CAUTION: this suggestion has a similar Item (with equal Label and Folder). If you click on ADD button, this Item will be updated with data from this Suggestion.',
'suggestion_menu' => 'Suggestions',
'settings_suggestion' => 'Enable item suggestion for Read-Only users',
'settings_suggestion_tip' => 'Item suggestion permits the Read-Only users to propose new items or items modification. Those suggestions will be validated by Administrator or Manager users.',
'imported_via_api' => 'API',
'settings_ldap_bind_dn' => 'LDAP Bind DN',
'settings_ldap_bind_passwd' => 'LDAP Bind Password',
'settings_ldap_search_base' => 'LDAP Search Base',
'settings_ldap_bind_dn_tip' => 'A Bind DN which can bind and search users in the tree',
'settings_ldap_bind_passwd_tip' => 'Password for the bind DN which can bind and search users in the tree',
'settings_ldap_search_base_tip' => 'Search root DN for searches on the tree',
'old_saltkey' => 'Old SALT key',
'define_old_saltkey' => 'I want to specify the old SALT Key to use (optional)',
'admin_email_server_url_tip' => 'Customize the URL to be used in links present in emails if you don\'t want the by-default one used.',
'admin_email_server_url' => 'Server URL for links in emails',
'generated_pw' => 'Generated password',
'enable_email_notification_on_user_pw_change' => 'Send an email to User when his password has been changed',
'settings_otv_expiration_period' => 'Delay before expiration of one time view (OTV) shared items (in days)',
'change_right_access' => 'Define the access rights',
'write' => 'Write',
'read' => 'Read',
'no_access' => 'No Access',
'right_types_label' => 'Select the type of access on this folder for the selected group of users',
'groups' => 'Folders',
'duplicate' => 'Duplicate',
'duplicate_title_in_same_folder' => 'A similar Item name exists in current Folder! Duplicates are not allowed!',
'duplicate_item_in_folder' => 'Allow items with similar label in a common folder',
'find_message' => '<i class="fa fa-info-circle"></i> %X% objects found',
'settings_roles_allowed_to_print' => 'Define the roles that are allowed to print items',
'settings_roles_allowed_to_print_tip' => 'The selected roles will be allowed to print out Items in a file.',
'user_profile_dialogbox_menu' => 'Your Teampass informations',
'admin_email_security' => 'SMTP security',
'alert_page_will_reload' => 'The page will now be reloaded',
'csv_import_items_selection' => 'Select the items to import',
'csv_import_options' => 'Select import options',
'file_protection_password' => 'Define file password',
'button_export_file' => 'Export items',
'error_export_format_not_selected' => 'A format for export file is required',
'select_file_format' => 'Select file format',
'button_offline_generate' => 'Generate Offline mode file',
'upload_new_avatar' => 'Select avatar PNG file',
'expand' => 'Expand',
'collapse' => 'Collapse',
'error_file_is_missing' => 'Error: The file is missing!',
'click_to_change' => 'Click to change',
'settings_ldap_user_attribute' => 'User attribute to search',
'settings_ldap_user_attribute_tip' => 'LDAP attribute to search the username in',
'user_ga_code_sent_by_email' => 'Your new GoogleAuthenticator code was sent to your email address.',
'log_user_initial_pwd_changed' => 'Initial password defined',
'log_user_email_changed' => 'User email changed to ',
'log_user_created' => 'User account created',
'log_user_locked' => 'User has been locked',
'log_user_unlocked' => 'User has been unlocked',
'log_user_pwd_changed' => 'User password has been changed',
'edit_user' => 'Edit user',
'pf_change_encryption' => 'The encryption algorithm has changed and your personal passwords have to be re-encoded. You need to run this process to use your passwords. This process may take several minutes depending on the number of items you have.',
'operation_encryption_done' => 'Re-encryption has been performed. You can close this dialogbox.',
'show_password' => 'Click and maintain to show password',
'change_password' => 'Change password',
'pf_sk_set' => 'Your personal Salt Key is correctly set, You can click on button Start',
'pf_sk_not_set' => 'Your personal Salt Key is NOT set! Please enter it.',
'upgrade_needed' => 'Upgrade needed',
'item_menu_mov_rep' => 'Move a Folder',
'settings_default_session_expiration_time' => 'By default delay for session expiration',
'duo_message' => 'DUO Security checks are now done. Sending your credentials to Teampass.<br />Please wait ... the page will be reloaded once authentication process will be done.',
'duo_loading_iframe' => 'DUOSecurity authentication frame is currently being loaded. Please wait.',
'settings_duo' => 'Enable DUO Security as User 2-Factor authentication',
'settings_duo_tip' => 'User 2-Factor authentication can be ensured using DUOSecurity.com. This library guarantees a high level of security related to user authentication.',
'admin_duo_akey' => 'AKEY',
'admin_duo_ikey' => 'IKEY',
'admin_duo_skey' => 'SKEY',
'admin_duo_host' => 'HOST',
'generate_random_key' => 'Generate consistent random key',
'duo_save_sk_file' => 'Save data in sk.php file',
'settings_duo_explanation' => 'Those credentials are issued from the web application you specially created for Teampass from the DUOSecurity administration page.<br />By clicking the save button they will stored in the sk.php file.',
'admin_duo_intro' => 'Fill in the next fields with expected data',
'admin_duo_stored' => 'Credentials stored successfully!',
'user_not_exists' => 'This user does not exist!',
'dialog_admin_user_edit_title' => 'User account edition',
'user_info_delete' => 'Please reclick to confirm the DELETION of this account.',
'user_info_delete_warning' => 'By clicking the Save button, you will delete this account from Teampass.<br />No return is possible.',
'edit' => 'Edit',
'user_info_locked' => 'User is currently LOCKED.',
'user_info_unlock_question' => 'Unlock account?',
'user_info_lock_question' => 'Lock account?',
'user_info_delete_question' => 'Delete account?',
'user_info_active' => 'User is currently ENABLED.',
'settings_ldap_domain_posix' => 'LDAP account suffix for your domain',
'refresh' => 'Refresh',
'loading' => 'Loading',
'at_password_shown' => 'Password shown',
'at_password_copied' => 'Password copied',
'search_results' => 'Search results',
'searching' => 'Searching ...',
'search_tag_results' => 'Search results for tag',
'searching_tag' => 'Searching for tag',
'list_items_with_tag' => 'List items with this tag',
'no_item_to_display' => 'No items to display',
'opening_folder' => 'Reading folder ...',
'please_confirm' => 'Please confirm',
'suggestion_notify_subject' => '[Teampass] A new suggestion has been done.',
'suggestion_notify_body' => 'Hello,<br><br>A new suggestion has been done. You need to validate it before it can be used by other users.<br>Some information about it:<br>- Label: #tp_label#<br>- Folder: #tp_folder#<br>- User: #tp_user#<br><br>Notice that this email has been sent to all Managers.<br><br>Best regards.',
'error_unknown' => 'An unexpected error occurred!',
'no_edit_no_delete' => 'Write but no edition and no deletion',
'no_edit' => 'Write but no edition',
'role_cannot_edit_item' => 'Cannot edit Items',
'no_delete' => 'Write but no delete',
'role_cannot_delete_item' => 'Cannot delete Items',
'text_without_symbols' => 'Only numbers, letters and symbols # & % * $ @ ( ) are allowed. Other characters are not possible.',
'my_profile' => 'My profile',
'at_suggestion' => 'Suggestion accepted',
'character_not_allowed' => 'Character is not allowed!',
'error_saltkey_length' => 'SaltKey must be a 16 characters string!',
'starting' => 'Starting ...',
'total_number_of_items' => 'Total number of items',
'finalizing' => 'Finalizing',
'treating_items' => 'Treating items',
'number_of_items_treated' => 'Number of treated items',
'error_sent_back' => 'Next error occured',
'full' => 'Full',
'sequential' => 'Sequential',
'tree_load_strategy' => 'Tree load strategy',
'syslog_enable' => 'Enable log with Syslog',
'syslog_host' => 'Syslog server',
'syslog_port' => 'Syslog port',
'error_bad_credentials' => 'Login credentials do not correspond!',
'reload_page_after_user_account_creation' => 'Your account has been created. This page will be automatically reloaded in 3 seconds ...',
'settings_ldap_usergroup' => 'LDAP group to search',
'settings_ldap_usergroup_tip' => 'LDAP group a user has to be member of in order to log in. Example: cn=sysadmins,ou=groups,dc=example,dc=com',
'server_password_change_enable' => 'Enable changing password on distant server (using ssh connection)',
'error_login_missing' => 'Login is missing!',
'error_pwd_missing' => 'Password is missing!',
'error_url_missing' => 'URL is missing!',
'error_ssh_credentials_missing' => 'SSH credentials are missing!',
'error_url_must_be_ssh' => 'URL must start with SSH protocol!',
'auto_update_server_password_info' => 'Clicking START button will automatically perform next steps:<ul><li>Connect through SSH to Linux server using login credentials and field `URL`,</li><li>Change user password on Linux server</il><li>Save the new password in Teampass</il><li>Close SSH connection</li></ul><br /><b>Please ensure that user has root privileges on the server (if not, indicate the root login and password) before starting.</b>',
'update_server_password' => 'Update server\'s password',
'error_personal_sk_expected' => 'You shall first enter your personal saltkey!',
'click_to_generate' => 'Click to generate',
'error_new_pwd_missing' => 'New password is missing!',
'ssh_pwd' => 'SSH password',
'ssh_user' => 'SSH user',
'ssh_action_performed_with_error' => 'Action was performed with error.<br>Check answer from server and made correction.',
'ssh_action_performed' => 'Password updated for this Item.<br /><br />You can now close this popup.',
'ssh_answer_from_server' => 'Answer from server',
'ssh_password_frequency_change_info' => 'You may want the change to be done automatically at a special frequency. For this, you need to select the frequency at which the server user passwords shall be changed (selecting 0 will disable task).<br />Notice that this will only work if your administrator has enabled the task in the server cron schedule.',
'ssh_password_frequency_change' => 'Password change frequency (in month)',
'ssh_scheduled_change' => 'Scheduled change',
'ssh_one_shot_change' => 'One shot change',
'month' => 'month',
'server_auto_update_password_enabled_tip' => 'Automatic user password change enabled',
'server_password_change_enable_tip' => 'This option permits to allow users to automatically change the user\'s password of a server located in the url field using SSH connection.<br>Notice that the automatic change at specific frequency can be done if the file <i>/files/script.ssh.php</i> is added to the crontab of this server. The advice would be to run it once a day.',
'can_manage_all_users' => 'Human Resources<br><i>Can manage all Users independately of his/hers group.<br>Will be also promoted to Manager role.<br>Will not be able to change an existing administrator (only an Administrator can remove administrator rights on a user).</i>',
'error_bad_credentials_more_than_3_times' => 'Login credentials do not correspond!<br>Please wait 10 seconds before new try',
'settings_ldap_object_class' => 'Class to search',
'settings_ldap_object_class_tip' => 'LDAP class to search, e.g. Person or posixAccount',
'rebuild_config_file' => 'Rebuild the configuration file',
'rebuild_config_file_tip' => 'Configuration file is located in folder ./includes/config/tp.config.php. It contains the configuration variables as defined in Settings and Customize tabs. Rebuilding the configuration file can be done at any moment.',
'error_folder_complexity_lower_than_top_folder' => 'It is required to have a Password Complexity at least equal to the Top Folder',
'rebuild_config_file' => 'Rebuild configuration file',
'csv_import_information' => 'The CSV file needs to fullfil next rules:<ul><li>The 1st line must be a header,</li><li>It must contain 5 columns,</li><li>The separator character is a comma `,`,</li><li>The encalupsation character is a double quotes `"`,</li><li>Expected columns are: `Label` , `Login` , `Password` , `URL` , `Comments`.</li></ul>',
'' => ''
); | agpl-3.0 |
precog/labcoat-legacy | js/app/eggmanager.js | 2685 | /*
* _ _ _
* | | | | | |
* | | __ _| |__ ___ ___ __ _| |_ 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/>.
*
*/
define([
"app/config/eggs"
, "app/util/notification"
],
function(eggs, notification) {
function normalize(content) {
return content.toLowerCase().replace(/\W+/, ' ').replace(/\s+/gm, ' ').trim();
}
function cleanQuery(q) {
if(q.split("\n").length > 1) return null;
q = q.trim();
if(q.substr(0, 2) === '--')
return q.substr(2);
if(q.substr(0, 2) === "(*" && q.substr(q.length-2) === "*)")
return q.substr(2, q.length-4);
return null;
}
for(var i = 0; i < eggs.length; i++) {
eggs[i].normalized = normalize(eggs[i].question);
}
return {
findEgg : function(content) {
var normalized = normalize(content);
for(var i = 0; i < eggs.length; i++) {
if(normalized === eggs[i].normalized) {
return i;
}
}
return -1;
},
isEgg : function(content) {
return this.findEgg(content) >= 0;
},
displayEgg : function(index, question) {
if(index < 0) return;
notification.main(question, {
text : '<div class="pg-easter">' + eggs[index].answer + '</div>',
min_height : '100px'
});
},
easterEgg : function(question) {
var q = cleanQuery(question);
if(null === q) return false;
var index = this.findEgg(q);
if(index < 0) return false;
this.displayEgg(index, q);
return true;
}
}
}) | agpl-3.0 |
CircuitCoder/ConsoleiT-Frontend | ts/avatar.ts | 595 | import {Input, Component} from "@angular/core";
import {generateGravatar} from "./util";
@Component({
selector: "ci-avatar",
template: require("html/tmpl/avatar.html")
})
export class CIAvatar {
@Input() name: string;
@Input() email: string;
showImg: boolean = false;
loaded: boolean = false;
ngAfterViewInit() {
this.loaded = true;
}
loadSuccess() {
this.showImg = true;
}
getInitials() {
return this.name.split(" ").reduce((prev, e) => {
return prev + e.charAt(0);
}, "");
}
getGravatar() {
return generateGravatar(this.email);
}
}
| agpl-3.0 |
mohamedhagag/community-addons | crm_lead_lost_reason/wizard/lost_reason.py | 1840 | # -*- coding: utf-8 -*-
#
#
# Author: Romain Deheele
# Copyright 2015 Camptocamp SA
#
# 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, fields, api
class CrmLeadLost(models.TransientModel):
""" Ask a reason for the opportunity lost."""
_name = 'crm.lead.lost'
_description = __doc__
def _default_reason(self):
active_id = self._context.get('active_id')
active_model = self._context.get('active_model')
if active_id and active_model == 'crm.lead':
lead = self.env['crm.lead'].browse(active_id)
return lead.lost_reason_id.id
reason_id = fields.Many2one(
'crm.lead.lost.reason',
string='Reason',
required=True,
default=_default_reason)
@api.one
def confirm_lost(self):
act_close = {'type': 'ir.actions.act_window_close'}
lead_ids = self._context.get('active_ids')
if lead_ids is None:
return act_close
assert len(lead_ids) == 1, "Only 1 lead ID expected"
lead = self.env['crm.lead'].browse(lead_ids)
lead.lost_reason_id = self.reason_id.id
lead.case_mark_lost()
return act_close
| agpl-3.0 |
afshinnj/php-mvc | assets/framework/ckeditor/plugins/iframe/lang/nb.js | 374 | /*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'iframe', 'nb', {
border: 'Vis ramme rundt iframe',
noUrl: 'Vennligst skriv inn URL for iframe',
scrolling: 'Aktiver scrollefelt',
title: 'Egenskaper for IFrame',
toolbar: 'IFrame'
} );
| agpl-3.0 |
lmaslag/test | engine/core/class/sSystem.php | 6360 | <?php
/**
* Shopware 4
* Copyright © shopware AG
*
* 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 with an additional
* permission and of our proprietary license can be found at and
* 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.
*
* "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, title and interest in
* our trademarks remain entirely with us.
*/
use Shopware\Components\LegacyRequestWrapper\PostWrapper;
use Shopware\Components\LegacyRequestWrapper\GetWrapper;
use Shopware\Components\LegacyRequestWrapper\CookieWrapper;
/**
* Deprecated Shopware Class
*/
class sSystem
{
/**
* Shopware configuration
*
* @var Shopware_Components_Config
* @deprecated Use Shopware()->Config()
*/
public $sCONFIG;
/**
* Current session id
*
* @var string
* @deprecated Use Shopware()->SessionID()
*/
public $sSESSION_ID;
/**
* Pointer to Smarty
*
* @var Enlight_Template_Manager
* @deprecated Use Shopware()->Template()
*/
public $sSMARTY;
/**
* Current database connection
*
* @var Enlight_Components_Adodb
* @deprecated Use Shopware()->Db()
*/
public $sDB_CONNECTION;
/**
* Pointer to the different modules and its inherits
*
* @var Shopware_Components_Modules
* @deprecated Use Shopware()->Modules()
*/
public $sMODULES;
/**
* Current customer group
*
* @var string
*/
public $sUSERGROUP;
/**
* Information about customer group
*
* @var array
*/
public $sUSERGROUPDATA;
/**
* Session data
*
* @var Enlight_Components_Session_Namespace Session
* @deprecated Use Shopware()->Session()
*/
public $_SESSION;
/**
* @var \Shopware\Components\LegacyRequestWrapper\PostWrapper Wrapper for _POST
*/
private $postWrapper;
/**
* @var \Shopware\Components\LegacyRequestWrapper\GetWrapper Wrapper for _GET
*/
private $getWrapper;
/**
* @var \Shopware\Components\LegacyRequestWrapper\CookieWrapper Wrapper for _COOKIE
*/
private $cookieWrapper;
/**
* Path to article images
*
* @var string
*/
public $sPathArticleImg;
/**
* Path to banners
*
* @var string
*/
public $sPathBanner;
/**
* Path to Article downloads
*
* @var string
*/
public $sPathArticleFiles;
/**
* Path to Start
*
* @var string
*/
public $sPathStart;
/**
* Strip parts of rewritten urls and append them
*
* @var array
*/
public $sExtractor;
/**
* All active languages
*
* @var array
*/
public $sLanguageData;
/**
* Current language
*
* @var int
* @deprecated Shopware()->Shop()->getId()
*/
public $sLanguage;
/**
* Current active currency
*
* @var array
* @deprecated Use Shopware()->Shop()->getCurrency() or Shopware()->Shop()->getCurrency()->toArray()
*/
public $sCurrency;
/**
* Current active subshop
*
* @var array
*/
public $sSubShop;
/**
* Information about licensed subshops
*
* @var array
*/
public $sSubShops;
/**
* Pointer to PHP-Mailer Object
*
* @var
* @deprecated Use Shopware()->Mail()
*/
public $sMailer;
/**
* True if user is identified as bot
*
* @var bool
* @deprecated Use Shopware()->Session()->Bot
*/
public $sBotSession;
/**
* Reference to $this, for compability reasons.
*
* @var sSystem
* @deprecated
*/
public $sSYSTEM;
/**
* @param Enlight_Controller_Request_RequestHttp $request The request object
*/
public function __construct(Enlight_Controller_Request_RequestHttp $request = null)
{
$request = $request ? : new Enlight_Controller_Request_RequestHttp();
$this->postWrapper = new PostWrapper($request);
$this->getWrapper = new GetWrapper($request);
$this->cookieWrapper = new CookieWrapper($request);
$this->sSYSTEM = $this;
}
public function __set($property, $value)
{
switch ($property) {
case '_POST':
$this->postWrapper->setAll($value);
break;
case '_GET':
$this->getWrapper->setAll($value);
break;
}
}
public function __get($property)
{
switch ($property) {
case '_POST':
return $this->postWrapper;
break;
case '_GET':
return $this->getWrapper;
break;
case '_COOKIE':
return $this->cookieWrapper;
break;
}
return null;
}
/**
* @deprecated Throw your specific exceptions
*
* @param $WARNING_ID
* @param $WARNING_MESSAGE
* @throws Enlight_Exception
*/
public function E_CORE_WARNING($WARNING_ID,$WARNING_MESSAGE)
{
throw new Enlight_Exception($WARNING_ID.': '.$WARNING_MESSAGE);
}
/**
* @deprecated Use Shopware()->Modules()->Core()->(method name)
*
* @param $name
* @param null $params
* @return mixed
*/
public function __call($name, $params = null)
{
return call_user_func_array(array(Shopware()->Modules()->Core(), $name), $params);
}
}
| agpl-3.0 |
WaywardRealms/Wayward | WaywardLocks/src/main/java/net/wayward_realms/waywardlocks/GetKeyCommand.java | 1111 | package net.wayward_realms.waywardlocks;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class GetKeyCommand implements CommandExecutor {
private WaywardLocks plugin;
public GetKeyCommand(WaywardLocks plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender.hasPermission("wayward.locks.command.getkey")) {
if (sender instanceof Player) {
plugin.setGettingKey((Player) sender, true);
sender.sendMessage(plugin.getPrefix() + ChatColor.GREEN + "Click the block you want to get the key for.");
} else {
sender.sendMessage(plugin.getPrefix() + ChatColor.RED + "You must be a player to get keys.");
}
} else {
sender.sendMessage(plugin.getPrefix() + ChatColor.RED + "You do not have permission.");
}
return true;
}
}
| agpl-3.0 |
petterreinholdtsen/alaveteli | db/migrate/114_add_attention_requested_flag_to_info_requests.rb | 323 | # -*- encoding : utf-8 -*-
require 'digest/sha1'
class AddAttentionRequestedFlagToInfoRequests < ActiveRecord::Migration
def self.up
add_column :info_requests, :attention_requested, :boolean, :default => false
end
def self.down
remove_column :info_requests, :attention_requested
end
end
| agpl-3.0 |
Anon215/movim | app/controllers/FeedController.php | 197 | <?php
use Movim\Controller\Base;
class FeedController extends Base
{
function load() {
$this->session_only = false;
$this->raw = true;
}
function dispatch() {
}
}
| agpl-3.0 |
ambition-vietnam/mastodon | app/javascript/mastodon/features/ui/index.js | 13961 | import classNames from 'classnames';
import React from 'react';
import NotificationsContainer from './containers/notifications_container';
import PropTypes from 'prop-types';
import LoadingBarContainer from './containers/loading_bar_container';
import TabsBar from './components/tabs_bar';
import ModalContainer from './containers/modal_container';
import { connect } from 'react-redux';
import { Redirect, withRouter } from 'react-router-dom';
import { isMobile } from '../../is_mobile';
import { debounce } from 'lodash';
import { uploadCompose, resetCompose } from '../../actions/compose';
import { refreshHomeTimeline } from '../../actions/timelines';
import { refreshNotifications } from '../../actions/notifications';
import { clearHeight } from '../../actions/height_cache';
import { WrappedSwitch, WrappedRoute } from './util/react_router_helpers';
import UploadArea from './components/upload_area';
import ColumnsAreaContainer from './containers/columns_area_container';
import {
Compose,
Status,
GettingStarted,
KeyboardShortcuts,
PublicTimeline,
CommunityTimeline,
AccountTimeline,
AccountGallery,
HomeTimeline,
Followers,
Following,
Reblogs,
Favourites,
HashtagTimeline,
Notifications,
FollowRequests,
GenericNotFound,
FavouritedStatuses,
ListTimeline,
Blocks,
Mutes,
PinnedStatuses,
Lists,
SuggestedAccountsColumn,
} from './util/async-components';
import { HotKeys } from 'react-hotkeys';
import { me } from '../../initial_state';
import { defineMessages, injectIntl } from 'react-intl';
// Dummy import, to make sure that <Status /> ends up in the application bundle.
// Without this it ends up in ~8 very commonly used bundles.
import '../../components/status';
const messages = defineMessages({
beforeUnload: { id: 'ui.beforeunload', defaultMessage: 'Your draft will be lost if you leave Mastodon.' },
});
const mapStateToProps = state => ({
isComposing: state.getIn(['compose', 'is_composing']),
hasComposingText: state.getIn(['compose', 'text']) !== '',
dropdownMenuIsOpen: state.getIn(['dropdown_menu', 'openId']) !== null,
});
const keyMap = {
help: '?',
new: 'n',
search: 's',
forceNew: 'option+n',
focusColumn: ['1', '2', '3', '4', '5', '6', '7', '8', '9'],
reply: 'r',
favourite: 'f',
boost: 'b',
mention: 'm',
open: ['enter', 'o'],
openProfile: 'p',
moveDown: ['down', 'j'],
moveUp: ['up', 'k'],
back: 'backspace',
goToHome: 'g h',
goToNotifications: 'g n',
goToLocal: 'g l',
goToFederated: 'g t',
goToStart: 'g s',
goToFavourites: 'g f',
goToPinned: 'g p',
goToProfile: 'g u',
goToBlocked: 'g b',
goToMuted: 'g m',
};
class SwitchingColumnsArea extends React.PureComponent {
static propTypes = {
children: PropTypes.node,
location: PropTypes.object,
onLayoutChange: PropTypes.func.isRequired,
};
state = {
mobile: isMobile(window.innerWidth),
};
componentWillMount () {
window.addEventListener('resize', this.handleResize, { passive: true });
}
componentDidUpdate (prevProps) {
if (![this.props.location.pathname, '/'].includes(prevProps.location.pathname)) {
this.node.handleChildrenContentChange();
}
}
componentWillUnmount () {
window.removeEventListener('resize', this.handleResize);
}
handleResize = debounce(() => {
// The cached heights are no longer accurate, invalidate
this.props.onLayoutChange();
this.setState({ mobile: isMobile(window.innerWidth) });
}, 500, {
trailing: true,
});
setRef = c => {
this.node = c.getWrappedInstance().getWrappedInstance();
}
render () {
const { children } = this.props;
const { mobile } = this.state;
return (
<ColumnsAreaContainer ref={this.setRef} singleColumn={mobile}>
<WrappedSwitch>
<Redirect from='/' to='/getting-started' exact />
<WrappedRoute path='/getting-started' component={GettingStarted} content={children} />
<WrappedRoute path='/keyboard-shortcuts' component={KeyboardShortcuts} content={children} />
<WrappedRoute path='/timelines/home' component={HomeTimeline} content={children} />
<WrappedRoute path='/timelines/public' exact component={PublicTimeline} content={children} />
<WrappedRoute path='/timelines/public/local' component={CommunityTimeline} content={children} />
<WrappedRoute path='/timelines/tag/:id' component={HashtagTimeline} content={children} />
<WrappedRoute path='/timelines/list/:id' component={ListTimeline} content={children} />
<WrappedRoute path='/notifications' component={Notifications} content={children} />
<WrappedRoute path='/favourites' component={FavouritedStatuses} content={children} />
<WrappedRoute path='/pinned' component={PinnedStatuses} content={children} />
<WrappedRoute path='/statuses/new' component={Compose} content={children} />
<WrappedRoute path='/statuses/:statusId' exact component={Status} content={children} />
<WrappedRoute path='/statuses/:statusId/reblogs' component={Reblogs} content={children} />
<WrappedRoute path='/statuses/:statusId/favourites' component={Favourites} content={children} />
<WrappedRoute path='/accounts/:accountId' exact component={AccountTimeline} content={children} />
<WrappedRoute path='/accounts/:accountId/with_replies' component={AccountTimeline} content={children} componentParams={{ withReplies: true }} />
<WrappedRoute path='/accounts/:accountId/followers' component={Followers} content={children} />
<WrappedRoute path='/accounts/:accountId/following' component={Following} content={children} />
<WrappedRoute path='/accounts/:accountId/media' component={AccountGallery} content={children} />
<WrappedRoute path='/follow_requests' component={FollowRequests} content={children} />
<WrappedRoute path='/blocks' component={Blocks} content={children} />
<WrappedRoute path='/mutes' component={Mutes} content={children} />
<WrappedRoute path='/lists' component={Lists} content={children} />
<WrappedRoute path='/suggested_accounts' component={SuggestedAccountsColumn} content={children} />
<WrappedRoute component={GenericNotFound} content={children} />
</WrappedSwitch>
</ColumnsAreaContainer>
);
}
}
@connect(mapStateToProps)
@injectIntl
@withRouter
export default class UI extends React.PureComponent {
static contextTypes = {
router: PropTypes.object.isRequired,
};
static propTypes = {
dispatch: PropTypes.func.isRequired,
children: PropTypes.node,
isComposing: PropTypes.bool,
hasComposingText: PropTypes.bool,
location: PropTypes.object,
intl: PropTypes.object.isRequired,
dropdownMenuIsOpen: PropTypes.bool,
};
state = {
draggingOver: false,
};
handleBeforeUnload = (e) => {
const { intl, isComposing, hasComposingText } = this.props;
if (isComposing && hasComposingText) {
// Setting returnValue to any string causes confirmation dialog.
// Many browsers no longer display this text to users,
// but we set user-friendly message for other browsers, e.g. Edge.
e.returnValue = intl.formatMessage(messages.beforeUnload);
}
}
handleLayoutChange = () => {
// The cached heights are no longer accurate, invalidate
this.props.dispatch(clearHeight());
}
handleDragEnter = (e) => {
e.preventDefault();
if (!this.dragTargets) {
this.dragTargets = [];
}
if (this.dragTargets.indexOf(e.target) === -1) {
this.dragTargets.push(e.target);
}
if (e.dataTransfer && e.dataTransfer.types.includes('Files')) {
this.setState({ draggingOver: true });
}
}
handleDragOver = (e) => {
e.preventDefault();
e.stopPropagation();
try {
e.dataTransfer.dropEffect = 'copy';
} catch (err) {
}
return false;
}
handleDrop = (e) => {
e.preventDefault();
this.setState({ draggingOver: false });
if (e.dataTransfer && e.dataTransfer.files.length === 1) {
this.props.dispatch(uploadCompose(e.dataTransfer.files));
}
}
handleDragLeave = (e) => {
e.preventDefault();
e.stopPropagation();
this.dragTargets = this.dragTargets.filter(el => el !== e.target && this.node.contains(el));
if (this.dragTargets.length > 0) {
return;
}
this.setState({ draggingOver: false });
}
closeUploadModal = () => {
this.setState({ draggingOver: false });
}
handleServiceWorkerPostMessage = ({ data }) => {
if (data.type === 'navigate') {
this.context.router.history.push(data.path);
} else {
console.warn('Unknown message type:', data.type);
}
}
componentWillMount () {
window.addEventListener('beforeunload', this.handleBeforeUnload, false);
document.addEventListener('dragenter', this.handleDragEnter, false);
document.addEventListener('dragover', this.handleDragOver, false);
document.addEventListener('drop', this.handleDrop, false);
document.addEventListener('dragleave', this.handleDragLeave, false);
document.addEventListener('dragend', this.handleDragEnd, false);
if ('serviceWorker' in navigator) {
navigator.serviceWorker.addEventListener('message', this.handleServiceWorkerPostMessage);
}
this.props.dispatch(refreshHomeTimeline());
this.props.dispatch(refreshNotifications());
}
componentDidMount () {
this.hotkeys.__mousetrap__.stopCallback = (e, element) => {
return ['TEXTAREA', 'SELECT', 'INPUT'].includes(element.tagName);
};
}
componentWillUnmount () {
window.removeEventListener('beforeunload', this.handleBeforeUnload);
document.removeEventListener('dragenter', this.handleDragEnter);
document.removeEventListener('dragover', this.handleDragOver);
document.removeEventListener('drop', this.handleDrop);
document.removeEventListener('dragleave', this.handleDragLeave);
document.removeEventListener('dragend', this.handleDragEnd);
}
setRef = c => {
this.node = c;
}
handleHotkeyNew = e => {
e.preventDefault();
const element = this.node.querySelector('.compose-form__autosuggest-wrapper textarea');
if (element) {
element.focus();
}
}
handleHotkeySearch = e => {
e.preventDefault();
const element = this.node.querySelector('.search__input');
if (element) {
element.focus();
}
}
handleHotkeyForceNew = e => {
this.handleHotkeyNew(e);
this.props.dispatch(resetCompose());
}
handleHotkeyFocusColumn = e => {
const index = (e.key * 1) + 1; // First child is drawer, skip that
const column = this.node.querySelector(`.column:nth-child(${index})`);
if (column) {
const status = column.querySelector('.focusable');
if (status) {
status.focus();
}
}
}
handleHotkeyBack = () => {
if (window.history && window.history.length === 1) {
this.context.router.history.push('/');
} else {
this.context.router.history.goBack();
}
}
setHotkeysRef = c => {
this.hotkeys = c;
}
handleHotkeyToggleHelp = () => {
if (this.props.location.pathname === '/keyboard-shortcuts') {
this.context.router.history.goBack();
} else {
this.context.router.history.push('/keyboard-shortcuts');
}
}
handleHotkeyGoToHome = () => {
this.context.router.history.push('/timelines/home');
}
handleHotkeyGoToNotifications = () => {
this.context.router.history.push('/notifications');
}
handleHotkeyGoToLocal = () => {
this.context.router.history.push('/timelines/public/local');
}
handleHotkeyGoToFederated = () => {
this.context.router.history.push('/timelines/public');
}
handleHotkeyGoToStart = () => {
this.context.router.history.push('/getting-started');
}
handleHotkeyGoToFavourites = () => {
this.context.router.history.push('/favourites');
}
handleHotkeyGoToPinned = () => {
this.context.router.history.push('/pinned');
}
handleHotkeyGoToProfile = () => {
this.context.router.history.push(`/accounts/${me}`);
}
handleHotkeyGoToBlocked = () => {
this.context.router.history.push('/blocks');
}
handleHotkeyGoToMuted = () => {
this.context.router.history.push('/mutes');
}
render () {
const { draggingOver } = this.state;
const { children, isComposing, location, dropdownMenuIsOpen } = this.props;
const handlers = {
help: this.handleHotkeyToggleHelp,
new: this.handleHotkeyNew,
search: this.handleHotkeySearch,
forceNew: this.handleHotkeyForceNew,
focusColumn: this.handleHotkeyFocusColumn,
back: this.handleHotkeyBack,
goToHome: this.handleHotkeyGoToHome,
goToNotifications: this.handleHotkeyGoToNotifications,
goToLocal: this.handleHotkeyGoToLocal,
goToFederated: this.handleHotkeyGoToFederated,
goToStart: this.handleHotkeyGoToStart,
goToFavourites: this.handleHotkeyGoToFavourites,
goToPinned: this.handleHotkeyGoToPinned,
goToProfile: this.handleHotkeyGoToProfile,
goToBlocked: this.handleHotkeyGoToBlocked,
goToMuted: this.handleHotkeyGoToMuted,
};
return (
<HotKeys keyMap={keyMap} handlers={handlers} ref={this.setHotkeysRef}>
<div className={classNames('ui', { 'is-composing': isComposing })} ref={this.setRef} style={{ pointerEvents: dropdownMenuIsOpen ? 'none' : null }}>
<TabsBar />
<SwitchingColumnsArea location={location} onLayoutChange={this.handleLayoutChange}>
{children}
</SwitchingColumnsArea>
<NotificationsContainer />
<LoadingBarContainer className='loading-bar' />
<ModalContainer />
<UploadArea active={draggingOver} onClose={this.closeUploadModal} />
</div>
</HotKeys>
);
}
}
| agpl-3.0 |
getintouchapp/tigase-muc | src/main/java/tigase/muc/history/PostgreSqlHistoryProvider.java | 4396 | /*
* Tigase Jabber/XMPP Multi-User Chat Component
* Copyright (C) 2008 "Bartosz M. Małkowski" <bartosz.malkowski@tigase.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.
*
* 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. Look for COPYING file in the top folder.
* If not, see http://www.gnu.org/licenses/.
*
* $Rev$
* Last modified by $Author$
* $Date$
*/
package tigase.muc.history;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import tigase.db.DataRepository;
import tigase.db.Repository;
import tigase.muc.Room;
import tigase.xml.Element;
import tigase.xmpp.JID;
/**
* @author bmalkow
*
*/
@Repository.Meta( supportedUris = { "jdbc:postgresql:.*" } )
public class PostgreSqlHistoryProvider extends AbstractJDBCHistoryProvider {
public static final String ADD_MESSAGE_QUERY_VAL = "insert into muc_history (room_name, event_type, timestamp, sender_jid, sender_nickname, body, public_event, msg) values (?, 1, ?, ?, ?, ?, ?, ?)";
private static final String CREATE_MUC_HISTORY_TABLE_VAL = "create table muc_history (" + "room_name char(128) NOT NULL,\n"
+ "event_type int, \n" + "timestamp bigint,\n" + "sender_jid varchar(2049),\n" + "sender_nickname char(128),\n"
+ "body text,\n" + "public_event boolean,\n " + "msg text " + ")";
public static final String DELETE_MESSAGES_QUERY_VAL = "delete from muc_history where room_name=?";
public static final String GET_MESSAGES_MAXSTANZAS_QUERY_VAL = "select room_name, event_type, timestamp, sender_jid, sender_nickname, body, msg from (select * from muc_history where room_name=? order by timestamp desc limit ? ) AS t order by t.timestamp";
public static final String GET_MESSAGES_SINCE_QUERY_VAL = "select room_name, event_type, timestamp, sender_jid, sender_nickname, body, msg from (select * from muc_history where room_name=? and timestamp >= ? order by timestamp desc limit ? ) AS t order by t.timestamp";
private Logger log = Logger.getLogger(this.getClass().getName());
/**
* @param dataRepository
*/
public PostgreSqlHistoryProvider() {
}
/** {@inheritDoc} */
@Override
public void addJoinEvent(Room room, Date date, JID senderJID, String nickName) {
// TODO Auto-generated method stub
}
/** {@inheritDoc} */
@Override
public void addLeaveEvent(Room room, Date date, JID senderJID, String nickName) {
// TODO Auto-generated method stub
}
/** {@inheritDoc} */
@Override
public void addSubjectChange(Room room, Element message, String subject, JID senderJid, String senderNickname, Date time) {
// TODO Auto-generated method stub
}
/** {@inheritDoc} */
@Override
public void init(Map<String, Object> props) {
try {
this.dataRepository.checkTable("muc_history", CREATE_MUC_HISTORY_TABLE_VAL);
internalInit();
} catch (SQLException e) {
e.printStackTrace();
if (log.isLoggable(Level.WARNING))
log.log(Level.WARNING, "Initializing problem", e);
try {
if (log.isLoggable(Level.INFO))
log.info("Trying to create tables: " + CREATE_MUC_HISTORY_TABLE_VAL);
Statement st = this.dataRepository.createStatement(null);
st.execute(CREATE_MUC_HISTORY_TABLE_VAL);
internalInit();
} catch (SQLException e1) {
if (log.isLoggable(Level.WARNING))
log.log(Level.WARNING, "Can't initialize muc history", e1);
throw new RuntimeException(e1);
}
}
}
private void internalInit() throws SQLException {
this.dataRepository.initPreparedStatement(ADD_MESSAGE_QUERY_KEY, ADD_MESSAGE_QUERY_VAL);
this.dataRepository.initPreparedStatement(DELETE_MESSAGES_QUERY_KEY, DELETE_MESSAGES_QUERY_VAL);
this.dataRepository.initPreparedStatement(GET_MESSAGES_SINCE_QUERY_KEY, GET_MESSAGES_SINCE_QUERY_VAL);
this.dataRepository.initPreparedStatement(GET_MESSAGES_MAXSTANZAS_QUERY_KEY, GET_MESSAGES_MAXSTANZAS_QUERY_VAL);
}
}
| agpl-3.0 |
lihaoalbert/crm-fat | spec/lib/dropbox_spec.rb | 14353 | require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
require File.dirname(__FILE__) + '/dropbox/email_samples'
require "fat_free_crm/dropbox"
describe "IMAP Dropbox" do
before(:each) do
@crawler = FatFreeCRM::Dropbox.new
@crawler.stub!("expunge!").and_return(true)
end
def mock_imap
@imap = mock
@settings = @crawler.instance_variable_get("@settings")
@settings[:address] = "dropbox@example.com"
Net::IMAP.stub!(:new).with(@settings[:server], @settings[:port], @settings[:ssl]).and_return(@imap)
end
def mock_connect
mock_imap
@imap.stub!(:login).and_return(true)
@imap.stub!(:select).and_return(true)
end
def mock_disconnect
@imap.stub!(:disconnected?).and_return(false)
@imap.stub!(:logout).and_return(true)
@imap.stub!(:disconnect).and_return(true)
end
def mock_message(body = EMAIL[:plain])
@fetch_data = mock
@fetch_data.stub!(:attr).and_return("RFC822" => body)
@imap.stub!(:uid_search).and_return([ :uid ])
@imap.stub!(:uid_fetch).and_return([ @fetch_data ])
@imap.stub!(:uid_copy).and_return(true)
@imap.stub!(:uid_store).and_return(true)
body
end
#------------------------------------------------------------------------------
describe "Connecting to the IMAP server" do
it "should connect to the IMAP server and login as user, and select folder" do
mock_imap
@imap.should_receive(:login).once.with(@settings[:user], @settings[:password])
@imap.should_receive(:select).once.with(@settings[:scan_folder])
@crawler.send(:connect!)
end
it "should connect to the IMAP server, login as user, but not select folder when requested so" do
mock_imap
@imap.should_receive(:login).once.with(@settings[:user], @settings[:password])
@imap.should_not_receive(:select).with(@settings[:scan_folder])
@crawler.send(:connect!, :setup => true)
end
it "should raise the error if connection fails" do
Net::IMAP.should_receive(:new).and_raise(SocketError) # No mocks this time! :-)
@crawler.send(:connect!).should == nil
end
end
#------------------------------------------------------------------------------
describe "Disconnecting from the IMAP server" do
it "should logout and diconnect" do
mock_connect
mock_disconnect
@imap.should_receive(:logout).once
@imap.should_receive(:disconnect).once
@crawler.send(:connect!)
@crawler.send(:disconnect!)
end
end
#------------------------------------------------------------------------------
describe "Discarding a message" do
before(:each) do
mock_connect
@uid = mock
@crawler.send(:connect!)
end
it "should copy message to invalid folder if it's set and flag the message as deleted" do
@settings[:move_invalid_to_folder] = "invalid"
@imap.should_receive(:uid_copy).once.with(@uid, @settings[:move_invalid_to_folder])
@imap.should_receive(:uid_store).once.with(@uid, "+FLAGS", [:Deleted])
@crawler.send(:discard, @uid)
end
it "should not copy message to invalid folder if it's not set and flag the message as deleted" do
@settings[:move_invalid_to_folder] = nil
@imap.should_not_receive(:uid_copy)
@imap.should_receive(:uid_store).once.with(@uid, "+FLAGS", [:Deleted])
@crawler.send(:discard, @uid)
end
end
#------------------------------------------------------------------------------
describe "Archiving a message" do
before(:each) do
mock_connect
@uid = mock
@crawler.send(:connect!)
end
it "should copy message to archive folder if it's set and flag the message as seen" do
@settings[:move_to_folder] = "processed"
@imap.should_receive(:uid_copy).once.with(@uid, @settings[:move_to_folder])
@imap.should_receive(:uid_store).once.with(@uid, "+FLAGS", [:Seen])
@crawler.send(:archive, @uid)
end
it "should not copy message to archive folder if it's not set and flag the message as seen" do
@settings[:move_to_folder] = nil
@imap.should_not_receive(:uid_copy)
@imap.should_receive(:uid_store).once.with(@uid, "+FLAGS", [:Seen])
@crawler.send(:archive, @uid)
end
end
#------------------------------------------------------------------------------
describe "Validating email" do
before(:each) do
@email = mock
end
it "should be valid email if its contents type is text/plain" do
@email.stub!(:content_type).and_return("text/plain")
@crawler.send(:is_valid?, @email).should == true
end
it "should be invalid email if its contents type is not text/plain" do
@email.stub!(:content_type).and_return("text/html")
@crawler.send(:is_valid?, @email).should == false
end
end
#------------------------------------------------------------------------------
describe "Finding email sender among users" do
before(:each) do
@from = [ "Aaron@Example.Com", "Ben@Example.com" ]
@email = mock
@email.stub!(:from).and_return(@from)
end
it "should find non-suspended user that matches From: field" do
@user = FactoryGirl.create(:user, :email => @from.first, :suspended_at => nil)
@crawler.send(:sent_from_known_user?, @email).should == true
@crawler.instance_variable_get("@sender").should == @user
end
it "should not find user if his email doesn't match From: field" do
FactoryGirl.create(:user, :email => "nobody@example.com")
@crawler.send(:sent_from_known_user?, @email).should == false
@crawler.instance_variable_get("@sender").should == nil
end
it "should not find user if his email matches From: field but is suspended" do
FactoryGirl.create(:user, :email => @from.first, :suspended_at => Time.now)
@crawler.send(:sent_from_known_user?, @email).should == false
@crawler.instance_variable_get("@sender").should == nil
end
end
#------------------------------------------------------------------------------
describe "Running the crawler" do
before(:each) do
mock_connect
mock_disconnect
mock_message
end
it "should discard a message if it's invalid" do
@crawler.should_receive(:is_valid?).once.and_return(false)
FactoryGirl.create(:user, :email => "aaron@example.com")
@crawler.should_not_receive(:archive)
@crawler.should_receive(:discard).once
@crawler.run
end
it "should discard a message if it can't find the user" do
@crawler.should_receive(:is_valid?).once.and_return(true)
@crawler.should_not_receive(:archive)
@crawler.should_receive(:discard).once
@crawler.run
end
it "should process a message if it finds the user" do
FactoryGirl.create(:user, :email => "aaron@example.com")
@crawler.should_receive(:archive).once
@crawler.should_not_receive(:discard)
@crawler.run
end
end
#------------------------------------------------------------------------------
describe "Pipeline: processing keywords on the first line" do
before(:each) do
mock_connect
mock_disconnect
FactoryGirl.create(:user, :email => "aaron@example.com")
end
it "should find the named asset and attach the email message" do
mock_message(EMAIL[:first_line])
@campaign = FactoryGirl.create(:campaign, :name => "Got milk!?")
@crawler.should_receive(:archive).once
@crawler.should_not_receive(:with_recipients)
@crawler.run
@campaign.emails.size.should == 1
@campaign.emails.first.mediator.should == @campaign
end
it "should create the named asset and attach the email message" do
mock_message(EMAIL[:first_line])
@crawler.should_receive(:archive).once
@crawler.should_not_receive(:with_recipients)
@crawler.run
@campaign = Campaign.first(:conditions => "name = 'Got milk'")
@campaign.should be_instance_of(Campaign)
@campaign.emails.size.should == 1
@campaign.emails.first.mediator.should == @campaign
end
it "should find the lead and attach the email message" do
mock_message(EMAIL[:first_line_lead])
@lead = FactoryGirl.create(:lead, :first_name => "Cindy", :last_name => "Cluster")
@crawler.should_receive(:archive).once
@crawler.should_not_receive(:with_recipients)
@crawler.run
@lead.emails.size.should == 1
@lead.emails.first.mediator.should == @lead
end
it "should create the lead and attach the email message" do
mock_message(EMAIL[:first_line_lead])
@crawler.should_receive(:archive).once
@crawler.should_not_receive(:with_recipients)
@crawler.run
@lead = Lead.first(:conditions => "first_name = 'Cindy' AND last_name = 'Cluster'")
@lead.should be_instance_of(Lead)
@lead.status.should == "contacted"
@lead.emails.size.should == 1
@lead.emails.first.mediator.should == @lead
end
it "should find the contact and attach the email message" do
mock_message(EMAIL[:first_line_contact])
@contact = FactoryGirl.create(:contact, :first_name => "Cindy", :last_name => "Cluster")
@crawler.should_receive(:archive).once
@crawler.should_not_receive(:with_recipients)
@crawler.run
@contact.emails.size.should == 1
@contact.emails.first.mediator.should == @contact
end
it "should create the contact and attach the email message" do
mock_message(EMAIL[:first_line_contact])
@crawler.should_receive(:archive).once
@crawler.should_not_receive(:with_recipients)
@crawler.run
@contact = Contact.first(:conditions => "first_name = 'Cindy' AND last_name = 'Cluster'")
@contact.should be_instance_of(Contact)
@contact.emails.size.should == 1
@contact.emails.first.mediator.should == @contact
end
it "should move on if first line has no keyword" do
mock_message(EMAIL[:plain])
@crawler.should_receive(:with_recipients).twice
@crawler.should_receive(:with_forwarded_recipient).twice
@crawler.run
end
end
#------------------------------------------------------------------------------
describe "Pipieline: processing recipients (To: recipient, Bcc: dropbox)" do
before(:each) do
mock_connect
mock_disconnect
mock_message(EMAIL[:plain])
FactoryGirl.create(:user, :email => "aaron@example.com")
end
it "should find the asset and attach the email message" do
@lead = FactoryGirl.create(:lead, :email => "ben@example.com", :access => "Public")
@crawler.should_receive(:archive).once
@crawler.should_not_receive(:with_forwarded_recipient)
@crawler.run
@lead.emails.size.should == 1
@lead.emails.first.mediator.should == @lead
end
it "should move on if asset recipients did not match" do
@crawler.should_receive(:with_recipients).twice
@crawler.should_receive(:with_forwarded_recipient).twice
@crawler.run
end
end
#------------------------------------------------------------------------------
describe "Pipieline: processing forwarded recipient (To: dropbox)" do
before(:each) do
mock_connect
mock_disconnect
FactoryGirl.create(:user, :email => "aaron@example.com")
mock_message(EMAIL[:forwarded])
end
it "should find the asset and attach the email message" do
@lead = FactoryGirl.create(:lead, :email => "ben@example.com", :access => "Public")
@crawler.should_receive(:archive).once
@crawler.run
@lead.emails.size.should == 1
@lead.emails.first.mediator.should == @lead
end
it "should touch the asset" do
now = Time.zone.now
timezone = ActiveRecord::Base.default_timezone
begin
ActiveRecord::Base.default_timezone = :utc
@lead = FactoryGirl.create(:lead, :email => "ben@example.com", :access => "Public", :updated_at => 5.day.ago)
@crawler.run
@lead.reload.updated_at.to_i.should >= now.to_i
ensure
ActiveRecord::Base.default_timezone = timezone
end
end
it "should change lead's status (:new => :contacted)" do
@lead = FactoryGirl.create(:lead, :email => "ben@example.com", :access => "Public", :status => "new")
@crawler.run
@lead.reload.status.should == "contacted"
end
it "should move on if forwarded recipient did not match" do
@crawler.should_receive(:with_forwarded_recipient).twice
@crawler.run
end
end
#------------------------------------------------------------------------------
describe "Pipieline: creating recipient if s/he was not found" do
before(:each) do
mock_connect
mock_disconnect
FactoryGirl.create(:user, :email => "aaron@example.com")
end
it "should create a contact from the email recipient (To: recipient, Bcc: dropbox)" do
mock_message(EMAIL[:plain])
@crawler.should_receive(:archive).once
@crawler.run
@contact = Contact.first
@contact.email.should == "ben@example.com"
@contact.emails.size.should == 1
@contact.emails.first.mediator.should == @contact
end
it "should create a contact from the forwarded email (To: dropbox)" do
mock_message(EMAIL[:forwarded])
@crawler.should_receive(:archive).once
@crawler.run
@contact = Contact.first
@contact.email.should == "ben@example.com"
@contact.emails.size.should == 1
@contact.emails.first.mediator.should == @contact
end
end
#------------------------------------------------------------------------------
describe "Default values" do
describe "'access'" do
it "should be 'Private' if default setting is 'Private'" do
Setting.stub!(:default_access).and_return('Private')
@crawler.send(:default_access).should == "Private"
end
it "should be 'Public' if default setting is 'Public'" do
Setting.stub!(:default_access).and_return('Public')
@crawler.send(:default_access).should == "Public"
end
it "should be 'Private' if default setting is 'Shared'" do
Setting.stub!(:default_access).and_return('Shared')
@crawler.send(:default_access).should == "Private"
end
end
end
end
| agpl-3.0 |
splicemachine/spliceengine | db-engine/src/main/java/com/splicemachine/db/impl/sql/GenericActivationHolder.java | 25495 | /*
* 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/>.
*
* Some parts of this source code are based on Apache Derby, and the following notices apply to
* Apache Derby:
*
* Apache Derby is a subproject of the Apache DB project, and is licensed under
* the Apache License, Version 2.0 (the "License"); you may not use these files
* except in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Splice Machine, Inc. has modified the Apache Derby code in this file.
*
* All such Splice Machine modifications are Copyright 2012 - 2020 Splice Machine, Inc.,
* and are licensed to you under the GNU Affero General Public License.
*/
package com.splicemachine.db.impl.sql;
import com.splicemachine.db.catalog.Dependable;
import com.splicemachine.db.catalog.DependableFinder;
import com.splicemachine.db.catalog.UUID;
import com.splicemachine.db.iapi.sql.compile.DataSetProcessorType;
import com.splicemachine.db.iapi.sql.compile.SparkExecutionType;
import com.splicemachine.db.iapi.sql.conn.LanguageConnectionContext;
import com.splicemachine.db.iapi.sql.conn.SQLSessionContext;
import com.splicemachine.db.iapi.store.access.conglomerate.Conglomerate;
import com.splicemachine.db.iapi.types.DataValueFactory;
import com.splicemachine.db.iapi.sql.execute.ExecPreparedStatement;
import com.splicemachine.db.iapi.sql.execute.ExecRow;
import com.splicemachine.db.iapi.sql.execute.ExecutionFactory;
import com.splicemachine.db.iapi.sql.execute.ConstantAction;
import com.splicemachine.db.impl.sql.catalog.ManagedCache;
import com.splicemachine.db.impl.sql.execute.BaseActivation;
import com.splicemachine.db.iapi.sql.depend.Provider;
import com.splicemachine.db.iapi.types.DataTypeDescriptor;
import com.splicemachine.db.iapi.sql.ParameterValueSet;
import com.splicemachine.db.iapi.sql.ResultSet;
import com.splicemachine.db.iapi.sql.ResultDescription;
import com.splicemachine.db.iapi.sql.Row;
import com.splicemachine.db.iapi.sql.Activation;
import com.splicemachine.db.iapi.sql.execute.CursorResultSet;
import com.splicemachine.db.iapi.sql.execute.TemporaryRowHolder;
import com.splicemachine.db.iapi.sql.dictionary.TableDescriptor;
import com.splicemachine.db.iapi.reference.SQLState;
import com.splicemachine.db.iapi.error.StandardException;
import com.splicemachine.db.iapi.services.loader.GeneratedClass;
import com.splicemachine.db.iapi.store.access.ConglomerateController;
import com.splicemachine.db.iapi.store.access.ScanController;
import com.splicemachine.db.iapi.types.RowLocation;
import com.splicemachine.db.iapi.services.sanity.SanityManager;
import com.splicemachine.db.iapi.store.access.TransactionController;
import com.splicemachine.utils.Pair;
import java.sql.PreparedStatement;
import java.sql.SQLWarning;
import java.util.Iterator;
import java.util.Vector;
import java.util.Hashtable;
/**
* This class holds an Activation, and passes through most of the calls
* to the activation. The purpose of this class is to allow a PreparedStatement
* to be recompiled without the caller having to detect this and get a new
* activation.
*
* In addition to the Activation, this class holds a reference to the
* PreparedStatement that created it, along with a reference to the
* GeneratedClass that was associated with the PreparedStatement at the time
* this holder was created. These references are used to validate the
* Activation, to ensure that an activation is used only with the
* PreparedStatement that created it, and to detect when recompilation has
* happened.
*
* We detect recompilation by checking whether the GeneratedClass has changed.
* If it has, we try to let the caller continue to use this ActivationHolder.
* We create a new instance of the new GeneratedClass (that is, we create a
* new Activation), and we compare the number and type of parameters. If these
* are compatible, we copy the parameters from the old to the new Activation.
* If they are not compatible, we throw an exception telling the user that
* the Activation is out of date, and they need to get a new one.
*
*/
final public class GenericActivationHolder implements Activation
{
public BaseActivation ac;
ExecPreparedStatement ps;
public GeneratedClass gc;
DataTypeDescriptor[] paramTypes;
private final LanguageConnectionContext lcc;
private boolean isSubStatement = false;
private boolean isRowTrigger = false;
/**
* Constructor for an ActivationHolder
*
* @param gc The GeneratedClass of the Activation
* @param ps The PreparedStatement this ActivationHolder is associated
* with
*
* @exception StandardException Thrown on error
*/
GenericActivationHolder(LanguageConnectionContext lcc, GeneratedClass gc, ExecPreparedStatement ps, boolean scrollable)
throws StandardException
{
this.lcc = lcc;
if (SanityManager.DEBUG)
{
SanityManager.ASSERT(gc != null, "generated class is null , ps is a " + ps.getClass());
}
this.gc = gc;
this.ps = ps;
ac = (BaseActivation) gc.newInstance(lcc);
ac.setupActivation(ps, scrollable);
paramTypes = ps.getParameterTypes();
}
/* Activation interface */
/**
* @see Activation#reset
*
* @exception StandardException thrown on failure
*/
public void reset() throws StandardException
{
ac.reset();
}
public long getRowsSeen() {
return ac.getRowsSeen();
}
public void addRowsSeen(long rowsSeen) {
ac.addRowsSeen(rowsSeen);
}
/**
* Temporary tables can be declared with ON COMMIT DELETE ROWS. But if the table has a held curosr open at
* commit time, data should not be deleted from the table. This method, (gets called at commit time) checks if this
* activation held cursor and if so, does that cursor reference the passed temp table name.
*
* @return true if this activation has held cursor and if it references the passed temp table name
*/
public boolean checkIfThisActivationHasHoldCursor(String tableName)
{
return ac.checkIfThisActivationHasHoldCursor(tableName);
}
/**
* @see Activation#setCursorName
*
*/
public void setCursorName(String cursorName)
{
ac.setCursorName(cursorName);
}
/**
* @see Activation#getCursorName
*/
public String getCursorName()
{
return ac.getCursorName();
}
/**
* @see Activation#setResultSetHoldability
*
*/
public void setResultSetHoldability(boolean resultSetHoldability)
{
ac.setResultSetHoldability(resultSetHoldability);
}
/**
* @see Activation#getResultSetHoldability
*/
public boolean getResultSetHoldability()
{
return ac.getResultSetHoldability();
}
/** @see Activation#setAutoGeneratedKeysResultsetInfo */
public void setAutoGeneratedKeysResultsetInfo(int[] columnIndexes, String[] columnNames)
{
ac.setAutoGeneratedKeysResultsetInfo(columnIndexes, columnNames);
}
/** @see Activation#getAutoGeneratedKeysResultsetMode */
public boolean getAutoGeneratedKeysResultsetMode()
{
return ac.getAutoGeneratedKeysResultsetMode();
}
/** @see Activation#getAutoGeneratedKeysColumnIndexes */
public int[] getAutoGeneratedKeysColumnIndexes()
{
return ac.getAutoGeneratedKeysColumnIndexes();
}
/** @see Activation#getAutoGeneratedKeysColumnNames */
public String[] getAutoGeneratedKeysColumnNames()
{
return ac.getAutoGeneratedKeysColumnNames();
}
/** @see com.splicemachine.db.iapi.sql.Activation#getLanguageConnectionContext */
public LanguageConnectionContext getLanguageConnectionContext()
{
return lcc;
}
public TransactionController getTransactionController()
{
return ac.getTransactionController();
}
/** @see Activation#getExecutionFactory */
public ExecutionFactory getExecutionFactory()
{
return ac.getExecutionFactory();
}
/**
* @see Activation#getParameterValueSet
*/
public ParameterValueSet getParameterValueSet()
{
return ac.getParameterValueSet();
}
/**
* @see Activation#setParameters
*/
public void setParameters(ParameterValueSet parameterValues, DataTypeDescriptor[] parameterTypes) throws StandardException
{
ac.setParameters(parameterValues, parameterTypes);
}
/**
* @see Activation#execute
*
* @exception StandardException Thrown on failure
*/
public ResultSet execute() throws StandardException
{
/*
** Synchronize to avoid problems if another thread is preparing
** the statement at the same time we're trying to execute it.
*/
// synchronized (ps)
{
/* Has the activation class changed or has the activation been
* invalidated? */
final boolean needNewClass =
gc == null || gc != ps.getActivationClass();
if (needNewClass || !ac.isValid())
{
GeneratedClass newGC;
if (needNewClass) {
// The statement has been re-prepared since the last time
// we executed it. Get the new activation class.
newGC = ps.getActivationClass();
if (newGC == null) {
// There is no class associated with the statement.
// Tell the caller that the statement needs to be
// recompiled.
throw StandardException.newException(
SQLState.LANG_STATEMENT_NEEDS_RECOMPILE);
}
} else {
// Reuse the generated class, we just want a new activation
// since the old is no longer valid.
newGC = gc;
}
/*
** If we get here, it means the Activation has been invalidated
** or the PreparedStatement has been recompiled. Get a new
** Activation and check whether the parameters are compatible.
** If so, transfer the parameters from the old Activation to
** the new one, and make that the current Activation. If not,
** throw an exception.
*/
BaseActivation newAC = (BaseActivation) newGC.newInstance(lcc);
DataTypeDescriptor[] newParamTypes = ps.getParameterTypes();
/*
** Link the new activation to the prepared statement.
*/
newAC.setupActivation(ps, ac.getScrollable());
newAC.setParameters(ac.getParameterValueSet(), paramTypes);
Pair<PreparedStatement, Iterator<ParameterValueSet>> batch = ac.getBatch();
newAC.setBatch(batch.getSecond(), batch.getFirst());
/*
** IMPORTANT
**
** Copy any essential state from the old activation
** to the new activation. This must match the state
** setup in EmbedStatement.
** singleExecution, cursorName, holdability, maxRows.
*/
if (ac.isSingleExecution())
newAC.setSingleExecution();
newAC.setCursorName(ac.getCursorName());
newAC.setResultSetHoldability(ac.getResultSetHoldability());
if (ac.getAutoGeneratedKeysResultsetMode()) //Need to do copy only if auto generated mode is on
newAC.setAutoGeneratedKeysResultsetInfo(ac.getAutoGeneratedKeysColumnIndexes(),
ac.getAutoGeneratedKeysColumnNames());
newAC.setMaxRows(ac.getMaxRows());
// break the link with the prepared statement
ac.setupActivation(null, false);
ac.close();
/* Remember the new class information */
ac = newAC;
gc = newGC;
paramTypes = newParamTypes;
}
}
String cursorName = ac.getCursorName();
if (cursorName != null)
{
// have to see if another activation is open
// with the same cursor name. If so we can't use this name
Activation activeCursor = lcc.lookupCursorActivation(cursorName);
if ((activeCursor != null) && (activeCursor != ac)) {
throw StandardException.newException(SQLState.LANG_CURSOR_ALREADY_EXISTS, cursorName);
}
}
return ac.execute();
}
/**
* @see Activation#getResultSet
*
* @return the current ResultSet of this activation.
*/
public ResultSet getResultSet()
{
return ac.getResultSet();
}
/**
* @see Activation#setCurrentRow
*
*/
public void setCurrentRow(ExecRow currentRow, int resultSetNumber)
{
ac.setCurrentRow(currentRow, resultSetNumber);
}
/**
* @see Activation#getCurrentRow
*
*/
public Row getCurrentRow(int resultSetNumber)
{
return ac.getCurrentRow( resultSetNumber );
}
/**
* @see Activation#clearCurrentRow
*/
public void clearCurrentRow(int resultSetNumber)
{
ac.clearCurrentRow(resultSetNumber);
}
/**
* @see Activation#getPreparedStatement
*/
public ExecPreparedStatement getPreparedStatement()
{
return ps;
}
public void checkStatementValidity() throws StandardException {
ac.checkStatementValidity();
}
/**
* @see Activation#getResultDescription
*/
public ResultDescription getResultDescription()
{
return ac.getResultDescription();
}
/**
* @see Activation#getDataValueFactory
*/
public DataValueFactory getDataValueFactory()
{
return ac.getDataValueFactory();
}
/**
* @see Activation#getRowLocationTemplate
*/
public RowLocation getRowLocationTemplate(int itemNumber)
{
return ac.getRowLocationTemplate(itemNumber);
}
/**
* @see Activation#getHeapConglomerateController
*/
public ConglomerateController getHeapConglomerateController()
{
return ac.getHeapConglomerateController();
}
/**
* @see Activation#setHeapConglomerateController
*/
public void setHeapConglomerateController(ConglomerateController updateHeapCC)
{
ac.setHeapConglomerateController(updateHeapCC);
}
/**
* @see Activation#clearHeapConglomerateController
*/
public void clearHeapConglomerateController()
{
ac.clearHeapConglomerateController();
}
/**
* @see Activation#getIndexScanController
*/
public ScanController getIndexScanController()
{
return ac.getIndexScanController();
}
/**
* @see Activation#setIndexScanController
*/
public void setIndexScanController(ScanController indexSC)
{
ac.setIndexScanController(indexSC);
}
/**
* @see Activation#getIndexConglomerateNumber
*/
public long getIndexConglomerateNumber()
{
return ac.getIndexConglomerateNumber();
}
/**
* @see Activation#setIndexConglomerateNumber
*/
public void setIndexConglomerateNumber(long indexConglomerateNumber)
{
ac.setIndexConglomerateNumber(indexConglomerateNumber);
}
/**
* @see Activation#clearIndexScanInfo
*/
public void clearIndexScanInfo()
{
ac.clearIndexScanInfo();
}
/**
* @see Activation#close
*
* @exception StandardException Thrown on error
*/
public void close() throws StandardException
{
ac.close();
}
/**
* @see Activation#isClosed
*/
public boolean isClosed()
{
return ac.isClosed();
}
/**
Set the activation for a single execution.
@see Activation#setSingleExecution
*/
public void setSingleExecution() {
ac.setSingleExecution();
}
/**
Is the activation set up for a single execution.
@see Activation#isSingleExecution
*/
public boolean isSingleExecution() {
return ac.isSingleExecution();
}
/**
Get the number of subqueries in the entire query.
@return int The number of subqueries in the entire query.
*/
public int getNumSubqueries() {
return ac.getNumSubqueries();
}
/**
* @see Activation#setForCreateTable()
*/
public void setForCreateTable()
{
ac.setForCreateTable();
}
/**
* @see Activation#getForCreateTable()
*/
public boolean getForCreateTable()
{
return ac.getForCreateTable();
}
/**
* @see Activation#setDDLTableDescriptor
*/
public void setDDLTableDescriptor(TableDescriptor td)
{
ac.setDDLTableDescriptor(td);
}
/**
* @see Activation#getDDLTableDescriptor
*/
public TableDescriptor getDDLTableDescriptor()
{
return ac.getDDLTableDescriptor();
}
/**
* @see Activation#setMaxRows
*/
public void setMaxRows(int maxRows)
{
ac.setMaxRows(maxRows);
}
/**
* @see Activation#getMaxRows
*/
public int getMaxRows()
{
return ac.getMaxRows();
}
public void setTargetVTI(java.sql.ResultSet targetVTI)
{
ac.setTargetVTI(targetVTI);
}
public java.sql.ResultSet getTargetVTI()
{
return ac.getTargetVTI();
}
public SQLSessionContext getSQLSessionContextForChildren() {
return ac.getSQLSessionContextForChildren();
}
public SQLSessionContext setupSQLSessionContextForChildren(boolean push) {
return ac.setupSQLSessionContextForChildren(push);
}
public void setParentActivation(Activation a) {
ac.setParentActivation(a);
}
public Activation getParentActivation() {
return ac.getParentActivation();
}
/* Dependable interface implementation */
/**
* @see Dependable#getDependableFinder
*/
public DependableFinder getDependableFinder()
{
// Vacuous implementation to make class concrete, only needed for
// BaseActivation
if (SanityManager.DEBUG) {
SanityManager.NOTREACHED();
}
return null;
}
/**
* @see Dependable#getObjectName
*/
public String getObjectName()
{
// Vacuous implementation to make class concrete, only needed for
// BaseActivation
if (SanityManager.DEBUG) {
SanityManager.NOTREACHED();
}
return null;
}
/**
* @see Dependable#getObjectID
*/
public UUID getObjectID()
{
// Vacuous implementation to make class concrete, only needed for
// BaseActivation
if (SanityManager.DEBUG) {
SanityManager.NOTREACHED();
}
return null;
}
/**
* @see Dependable#getClassType
*/
public String getClassType()
{
// Vacuous implementation to make class concrete, only needed for
// BaseActivation
if (SanityManager.DEBUG) {
SanityManager.NOTREACHED();
}
return null;
}
/**
* @see Dependable#isPersistent
*/
public boolean isPersistent()
{
// Vacuous implementation to make class concrete, only needed for
// BaseActivation
if (SanityManager.DEBUG) {
SanityManager.NOTREACHED();
}
return false;
}
/* Dependent interface implementation */
/**
* @see com.splicemachine.db.iapi.sql.depend.Dependent#isValid
*/
public boolean isValid() {
// Vacuous implementation to make class concrete, only needed for
// BaseActivation
if (SanityManager.DEBUG) {
SanityManager.NOTREACHED();
}
return false;
}
/**
* @see com.splicemachine.db.iapi.sql.depend.Dependent#makeInvalid
*/
public void makeInvalid(int action,
LanguageConnectionContext lcc)
throws StandardException {
// Vacuous implementation to make class concrete, only needed for
// BaseActivation
if (SanityManager.DEBUG) {
SanityManager.NOTREACHED();
}
}
/**
* @see com.splicemachine.db.iapi.sql.depend.Dependent#prepareToInvalidate
*/
public void prepareToInvalidate(Provider p, int action,
LanguageConnectionContext lcc)
throws StandardException {
// Vacuous implementation to make class concrete, only needed for
// BaseActivation
if (SanityManager.DEBUG) {
SanityManager.NOTREACHED();
}
}
/* Class implementation */
/**
* Mark the activation as unused.
*/
public void markUnused()
{
ac.markUnused();
}
/**
* Is the activation in use?
*
* @return true/false
*/
public boolean isInUse()
{
return ac.isInUse();
}
/**
@see com.splicemachine.db.iapi.sql.Activation#addWarning
*/
public void addWarning(SQLWarning w)
{
ac.addWarning(w);
}
/**
@see com.splicemachine.db.iapi.sql.Activation#getWarnings
*/
public SQLWarning getWarnings()
{
return ac.getWarnings();
}
/**
@see com.splicemachine.db.iapi.sql.Activation#clearWarnings
*/
public void clearWarnings()
{
ac.clearWarnings();
}
/**
* @see Activation#isCursorActivation
*/
public boolean isCursorActivation()
{
return ac.isCursorActivation();
}
public ConstantAction getConstantAction() {
return ac.getConstantAction();
}
public void setParentResultSet(TemporaryRowHolder rs, String resultSetId)
{
ac.setParentResultSet(rs, resultSetId);
}
public Vector getParentResultSet(String resultSetId)
{
return ac.getParentResultSet(resultSetId);
}
public void clearParentResultSets()
{
ac.clearParentResultSets();
}
public Hashtable getParentResultSets()
{
return ac.getParentResultSets();
}
public void setForUpdateIndexScan(CursorResultSet forUpdateResultSet)
{
ac.setForUpdateIndexScan(forUpdateResultSet);
}
public CursorResultSet getForUpdateIndexScan()
{
return ac.getForUpdateIndexScan();
}
public java.sql.ResultSet[][] getDynamicResults() {
return ac.getDynamicResults();
}
public int getMaxDynamicResults() {
return ac.getMaxDynamicResults();
}
public void materialize() throws StandardException {
ac.materialize();
}
public boolean isMaterialized() {
return ac.isMaterialized();
}
@Override
public boolean isBatched() {
return ac.isBatched();
}
@Override
public boolean nextBatchElement() throws StandardException {
return ac.nextBatchElement();
}
@Override
public void setBatch(Iterator<ParameterValueSet> params, PreparedStatement ps) {
ac.setBatch(params, ps);
}
@Override
public Pair<PreparedStatement, Iterator<ParameterValueSet>> getBatch() {
return ac.getBatch();
}
@Override
public DataSetProcessorType datasetProcessorType() {
return ac.datasetProcessorType();
}
@Override
public SparkExecutionType sparkExecutionType() {
return ac.sparkExecutionType();
}
@Override
public boolean isSubStatement() { return isSubStatement; }
@Override
public void setSubStatement(boolean newValue) {
isSubStatement = newValue;
ac.setSubStatement(newValue);
}
@Override
public boolean isRowTrigger() { return isRowTrigger; }
@Override
public void setIsRowTrigger(boolean newValue) {
isRowTrigger = newValue;
ac.setIsRowTrigger(newValue);
}
}
| agpl-3.0 |
vimvim/AkkaTest | src/main/scala/jcodec/MP4Writer.scala | 4005 | package jcodec
import org.jcodec.codecs.h264.mp4.AvcCBox
import org.jcodec.containers.mp4.muxer.MP4Muxer
import org.jcodec.common.NIOUtils._
import org.jcodec.containers.mp4.{MP4Packet, TrackType, Brand}
import java.nio.ByteBuffer
import org.jcodec.codecs.h264.io.model.{NALUnitType, NALUnit}
import org.jcodec.codecs.h264.H264Utils
/**
* Created by vim on 5/11/14.
*/
class MP4Writer(filename:String, avcBox: AvcCBox) {
val spsList = avcBox.getSpsList
val ppsList = avcBox.getPpsList
val muxer = new MP4Muxer(writableFileChannel(filename), Brand.MP4)
val videoTrack = muxer.addTrack(TrackType.VIDEO, 25000)
var frameIdx = 0
def writeFrame(frame:MP4Frame) = {
// val filteredNalUnits = new java.util.ArrayList[ByteBuffer]()
val movPacket = ByteBuffer.allocate(1024*100)
println(" Write NAL units")
for( nalUnitData <- frame.nalUnits ) {
nalUnitData.mark()
val nalUnit = NALUnit.read(nalUnitData)
nalUnitData.reset()
val size = nalUnitData.limit()-nalUnitData.position()
println(" NAL:"+nalUnit.`type`+" size:"+size)
nalUnit.`type` match {
case NALUnitType.PPS =>
println(" remove PPS")
ppsList.add(nalUnitData)
case NALUnitType.SPS =>
println(" remove SPS")
spsList.add(nalUnitData)
case _ =>
// filteredNalUnits.add(nalUnitData)
movPacket.putInt(size)
movPacket.put(nalUnitData)
}
}
// TODO: Take into account - that length on the NAL is variable and configured n the AVC.
// TODO: So we may needs to use joinNALUnits+encodeMOVPacket or create our own function for this
movPacket.flip()
val size = movPacket.limit()-movPacket.position()
println(s" Write packet data size:$size")
// H264Utils.joinNALUnits(filteredNalUnits, movPacket)
// H264Utils.encodeMOVPacket(movPacket)
// for( nalUnitData <- filteredNalUnits ) {
// movPacket.putInt(nalUnitData.)
// }
// new MP4Packet(
// result, Bytebuffer that contains encoded frame
// i, Presentation timestamp ( think seconds ) expressed in timescale units ( just multiply second by
// timescale value below. This is to avoid floats.
// Example: timescale = 25, pts = 0, 1, 2, 3, 4, 5 .... ( PAL 25 fps )
// Example: timescale = 30000, pts = 1001, 2002, 3003, 4004, 5005, 6006, 7007 ( NTSC 29.97 fps )
// timescale, // See above
// 1, Duration of a frame in timescale units ( think seconds multiplied by number above)
// Examlle: timescale = 25, duration = 1 ( PAL 25 fps )
// Example: timescale = 30000, duration = 1001 ( NTSC 29.97 fps )
// frameNo, Just a number of frame, doesn't have anything to do with timing
// true, Is it an I-frame, i.e. is this a seek point? Players use this information to instantly know where to seek
// null, just ignore, should be null. This is used by the older brother of MP4 - Apple Quicktime which supports
// tape timecode
// i, just put the same as pts above
// 0 sample entry, should be 0
// )
// val mp4Packet = new MP4Packet(new Packet(frame, data), frame.getPts(), 0)
val mp4Packet = new MP4Packet(movPacket, frame.pts, frame.ts, frame.duration, frameIdx, frame.keyFrame, null, frame.pts, 0)
println(s" Write packet MediaPTS:${mp4Packet.getMediaPts} PTS:${mp4Packet.getPts} TS:${mp4Packet.getTimescale} Duration:${mp4Packet.getDuration} FrameNO:${mp4Packet.getFrameNo} KeyFrame:${mp4Packet.isKeyFrame} offset:${mp4Packet.getFileOff} size:${mp4Packet.getSize}")
videoTrack.addFrame(mp4Packet)
frameIdx = frameIdx + 1
}
def complete() = {
val sampleEntry = H264Utils.createMOVSampleEntry(spsList, ppsList)
videoTrack.addSampleEntry(sampleEntry)
muxer.writeHeader()
}
}
| agpl-3.0 |
RestComm/jss7 | tcap/tcap-api/src/main/java/org/restcomm/protocols/ss7/tcap/api/tc/dialog/events/TCUserAbortRequest.java | 2751 | /*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. 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.tcap.api.tc.dialog.events;
import org.restcomm.protocols.ss7.sccp.parameter.SccpAddress;
import org.restcomm.protocols.ss7.tcap.asn.ApplicationContextName;
import org.restcomm.protocols.ss7.tcap.asn.DialogServiceUserType;
import org.restcomm.protocols.ss7.tcap.asn.UserInformation;
/**
* <pre>
* -- NOTE � When the Abort Message is generated by the Transaction sublayer, a p-Abort Cause must be
* -- present.The u-abortCause may be generated by the component sublayer in which case it is an ABRT
* -- APDU, or by the TC-User in which case it could be either an ABRT APDU or data in some user-defined
* -- abstract syntax.
* </pre>
*
* .......
*
* @author amit bhayani
* @author baranowb
*/
public interface TCUserAbortRequest extends DialogRequest {
void setReturnMessageOnError(boolean val);
boolean getReturnMessageOnError();
/**
* Sets origin address. This parameter is used only in first TCUserAbort, sent as response to TCBegin. This parameter, if
* set, changes local peer address(remote end will send request to value set by this method).
*
* @return
*/
SccpAddress getOriginatingAddress();
void setOriginatingAddress(SccpAddress dest);
ApplicationContextName getApplicationContextName();
void setApplicationContextName(ApplicationContextName acn);
UserInformation getUserInformation();
void setUserInformation(UserInformation acn);
/**
* Setting of {@link DialogServiceUserType} will create the AARE else ABRT is formed
*
* @param dialogServiceUserType
*/
void setDialogServiceUserType(DialogServiceUserType dialogServiceUserType);
DialogServiceUserType getDialogServiceUserType();
}
| agpl-3.0 |
gbour/mediadb | lib/mediadb/mediadb.py | 1064 | #!/usr/bin/env python
# -*- coding: utf8 -*-
import os
import os.path
import glob
import sys
import inspect
import imp
class Plugin(object):
def __init__(self):
pass
def help(self):
pass
def do(self, args):
pass
def get_plugins():
modfile = dict(inspect.getmembers(sys.modules[__name__]))['__file__']
path = os.path.join(os.path.split(modfile)[0], 'plugins')
plugins = {}
for fname in os.listdir(path):
if fname.startswith('.') or not fname.endswith('.py') or fname == '__init__.py':
continue
fname = os.path.splitext(fname)[0]
(fp, fpath, desc) = imp.find_module(fname, [path])
try:
mod = imp.load_module(fname, fp, fpath, desc)
plugins.update(
[(plug.__name__.lower(), plug) for plug in dict(inspect.getmembers(mod)).values()
if inspect.isclass(plug) and plug != Plugin and plug.__base__ == Plugin]
)
finally:
if fp:
fp.close()
return plugins
| agpl-3.0 |
CaptainCourierIntegration/captain-courier-cidr | src/Cidr/Exception/IllegalStateException.php | 376 | <?php
/*
* (c) Captain Courier Integration <captain@captaincourier.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Created by PhpStorm.
* User: joseph
* Date: 29/08/2013
* Time: 12:25
*/
namespace Cidr\Exception;
class IllegalStateException extends \LogicException
{
} | agpl-3.0 |
Tatwi/legend-of-hondo | MMOCoreORB/bin/scripts/mobile/lok/flit_youth.lua | 765 | flit_youth = Creature:new {
objectName = "@mob/creature_names:flit_youth",
socialGroup = "flit",
faction = "",
level = 6,
chanceHit = 0.25,
damageMin = 50,
damageMax = 55,
baseXp = 147,
baseHAM = 180,
baseHAMmax = 220,
armor = 0,
resists = {0,0,0,0,0,0,0,-1,-1},
meatType = "meat_avian",
meatAmount = 5,
hideType = "",
hideAmount = 0,
boneType = "bone_avian",
boneAmount = 5,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY,
creatureBitmask = PACK,
optionsBitmask = AIENABLED,
diet = CARNIVORE,
templates = {"object/mobile/flit_youth.iff"},
scale = 0.8,
lootGroups = {},
weapons = {},
conversationTemplate = "",
attacks = {
}
}
CreatureTemplates:addCreatureTemplate(flit_youth, "flit_youth")
| agpl-3.0 |
ssivadier/puppetmanager | config/environments/production.rb | 3382 | PuppetManager::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both thread web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# SQL Query caching
config.action_controller.perform_caching = true
config.cache_store = :mem_cache_store, "cache-1"
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = false
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
#config.log_formatter = ::Logger::Formatter.new
end
| agpl-3.0 |
ComPlat/chemotion_ELN | app/packs/src/components/fetchers/AdminFetcher.js | 12919 | import 'whatwg-fetch';
import BaseFetcher from './BaseFetcher';
export default class AdminFetcher {
static fetchUnitsSystem() {
return fetch('/units_system/units_system.json', {
credentials: 'same-origin', cache: 'no-store', headers: { 'cache-control': 'no-cache' }
}).then(response => response.json()).then(json => json).catch((errorMessage) => {
console.log(errorMessage);
});
}
static fetchLocalCollector() {
return fetch('/api/v1/admin/listLocalCollector/all.json', {
credentials: 'same-origin'
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.log(errorMessage); });
}
static checkDiskSpace() {
return fetch('/api/v1/admin/disk.json', {
credentials: 'same-origin'
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.log(errorMessage); });
}
static fetchDevices() {
return fetch('/api/v1/admin/listDevices/all.json', {
credentials: 'same-origin'
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.log(errorMessage); });
}
static fetchDeviceById(deviceId) {
return fetch(`/api/v1/admin/device/${deviceId}`, {
credentials: 'same-origin'
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.log(errorMessage); });
}
static fetchDeviceMetadataByDeviceId(deviceId) {
return fetch(`/api/v1/admin/deviceMetadata/${deviceId}`, {
credentials: 'same-origin'
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.log(errorMessage); });
}
static postDeviceMetadata(params) {
return fetch('/api/v1/admin/deviceMetadata', {
credentials: 'same-origin',
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.log(errorMessage); });
}
static syncDeviceMetadataToDataCite(params) {
return fetch(`/api/v1/admin/deviceMetadata/${params.device_id}/sync_to_data_cite`, {
credentials: 'same-origin',
method: 'PUT',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.log(errorMessage); });
}
static testSFTP(params) {
return fetch('/api/v1/admin/sftpDevice/', {
credentials: 'same-origin',
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.log(errorMessage); });
}
static removeDeviceMethod(params) {
return fetch('/api/v1/admin/removeDeviceMethod/', {
credentials: 'same-origin',
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.log(errorMessage); });
}
static updateDeviceMethod(params) {
return fetch('/api/v1/admin/updateDeviceMethod/', {
credentials: 'same-origin',
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.log(errorMessage); });
}
static editNovncSettings(params) {
return fetch('/api/v1/admin/editNovncSettings/', {
credentials: 'same-origin',
method: 'PUT',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
}).then((response) => {
if (response.status === 204) { return ''; }
return 'error';
});
}
static resetUserPassword(params) {
return fetch('/api/v1/admin/resetPassword/', {
credentials: 'same-origin',
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.log(errorMessage); });
}
static createUserAccount(params) {
return fetch('/api/v1/admin/newUser/', {
credentials: 'same-origin',
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.log(errorMessage); });
}
static updateUser(params) {
return fetch('/api/v1/admin/updateUser/', {
credentials: 'same-origin',
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.log(errorMessage); });
}
static fetchUsers() {
return fetch('/api/v1/admin/listUsers/all.json', {
credentials: 'same-origin'
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.log(errorMessage); });
}
static updateAccount(params) {
return fetch('/api/v1/admin/updateAccount/', {
credentials: 'same-origin',
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.log(errorMessage); });
}
static olsTermDisableEnable(params) {
return fetch('/api/v1/admin/olsEnableDisable/', {
credentials: 'same-origin',
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
}).then((response) => {
if (response.status === 204) {
return true;
}
});
}
static importOlsTerms(file) {
const data = new FormData();
data.append('file', file);
return fetch('/api/v1/admin/importOlsTerms/', {
credentials: 'same-origin',
method: 'POST',
body: data
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.log(errorMessage); });
}
static fetchGroupsDevices(type) {
return fetch(`/api/v1/admin/group_device/list?type=${type}`, {
credentials: 'same-origin'
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.log(errorMessage); });
}
static updateGroup(params = {}) {
return fetch(`/api/v1/admin/group_device/update/${params.id}`, {
credentials: 'same-origin',
method: 'PUT',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.log(errorMessage); });
}
static fetchUsersByNameType(name, type) {
return fetch(`/api/v1/admin/group_device/name.json?type=${type}&name=${name}`, {
credentials: 'same-origin'
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.log(errorMessage); });
}
static createGroupDevice(params = {}) {
return fetch('/api/v1/admin/group_device/create', {
credentials: 'same-origin',
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.log(errorMessage); });
}
static fetchUserGroupByName(name) {
return fetch(`/api/v1/admin/matrix/find_user.json?name=${name}`, {
credentials: 'same-origin'
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.log(errorMessage); });
}
static fetchMatrices() {
return fetch('/api/v1/admin/matrix/list.json', {
credentials: 'same-origin'
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.log(errorMessage); });
}
static updateMatrice(params) {
return fetch('/api/v1/admin/matrix/update/', {
credentials: 'same-origin',
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.log(errorMessage); });
}
static updateMatriceJson(params) {
return fetch('/api/v1/admin/matrix/update_json/', {
credentials: 'same-origin',
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.log(errorMessage); });
}
static exec(path, method) {
return BaseFetcher.withoutBodyData({
apiEndpoint: path, requestMethod: method, jsonTranformation: json => json
});
}
static genericKlass(params, path) {
return BaseFetcher.withBodyData({
apiEndpoint: `/api/v1/admin/${path}/`, requestMethod: 'POST', bodyData: params, jsonTranformation: json => json
});
}
static fetchElementKlasses() {
return this.exec('/api/v1/generic_elements/klasses_all.json', 'GET');
}
static updateGElTemplates(params) {
return this.genericKlass(params, 'update_element_template');
}
static createElementKlass(params) {
return this.genericKlass(params, 'create_element_klass');
}
static updateElementKlass(params) {
return this.genericKlass(params, 'update_element_klass');
}
static activeInActiveElementKlass(params) {
return this.genericKlass(params, 'de_active_element_klass');
}
static deleteElementKlass(params) {
return this.genericKlass(params, 'delete_element_klass');
}
static createSegmentKlass(params) {
return this.genericKlass(params, 'create_segment_klass');
}
static updateSegmentKlass(params) {
return this.genericKlass(params, 'update_segment_klass');
}
static deActiveSegmentKlass(params) {
return this.genericKlass(params, 'de_active_segment_klass');
}
static updateSegmentTemplate(params) {
return this.genericKlass(params, 'update_segment_template');
}
static deleteKlassRevision(params) {
return this.genericKlass(params, 'delete_klass_revision');
}
static deleteGenericRevision(id) {
return this.exec(`/api/v1/admin/delete_generic_revision/${id}`, 'DELETE');
}
static listSegmentKlass(params = {}) {
const api = params.is_active === undefined ? '/api/v1/admin/list_segment_klass.json' : `/api/v1/admin/list_segment_klass.json?is_active=${params.is_active}`;
return this.exec(api, 'GET');
}
static listDatasetKlass(params = {}) {
const api = params.is_active === undefined ? '/api/v1/admin/list_dataset_klass.json' : `/api/v1/admin/list_dataset_klass.json?is_active=${params.is_active}`;
return this.exec(api, 'GET');
}
static deActiveDatasetKlass(params) {
return this.genericKlass(params, 'de_active_dataset_klass');
}
static updateDatasetTemplate(params) {
return this.genericKlass(params, 'update_dataset_template');
}
static fetchJobs() {
return fetch('/api/v1/admin/jobs', {
credentials: 'same-origin',
method: 'GET',
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.error(errorMessage); });
}
static restartJob(id) {
return fetch('/api/v1/admin/jobs/restart/', {
credentials: 'same-origin',
method: 'PUT',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(id)
}).then(response => response.json())
.then(json => json)
.catch((errorMessage) => { console.error(errorMessage); });
}
static fetchKlassRevisions(id, klass) {
return this.exec(`/api/v1/admin/klass_revisions.json?id=${id}&klass=${klass}`, 'GET');
}
}
| agpl-3.0 |
Sparfel/iTop-s-Portal | library/Zend/InfoCard/Cipher/Pki/Rsa/Interface.php | 1851 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_InfoCard
* @subpackage Zend_InfoCard_Cipher
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* Zend_InfoCard_Cipher_PKI_Adapter_Abstract
*/
//$1 'Zend/InfoCard/Cipher/Pki/Adapter/Abstract.php';
/**
* The interface which defines the RSA Public-key encryption object
*
* @category Zend
* @package Zend_InfoCard
* @subpackage Zend_InfoCard_Cipher
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
interface Zend_InfoCard_Cipher_Pki_Rsa_Interface
{
/**
* Decrypts RSA encrypted data using the given private key
*
* @throws Zend_InfoCard_Cipher_Exception
* @param string $encryptedData The encrypted data in binary format
* @param string $privateKey The private key in binary format
* @param string $password The private key passphrase
* @param integer $padding The padding to use during decryption (of not provided object value will be used)
* @return string The decrypted data
*/
public function decrypt($encryptedData, $privateKey, $password = null, $padding = Zend_InfoCard_Cipher_Pki_Adapter_Abstract::NO_PADDING);
}
| agpl-3.0 |
AyuntamientoMadrid/consul | spec/models/complan/beneficiary_spec.rb | 359 | require "rails_helper"
RSpec.describe Complan::Beneficiary, type: :model do
let(:beneficiary) { build(:complan_beneficiary) }
context "validations" do
it "is valid" do
expect(beneficiary).to be_valid
end
it "is invalid count" do
beneficiary.count_participants = 200
expect(beneficiary).not_to be_valid
end
end
end
| agpl-3.0 |
southskies/osdial | www/phpsysinfo/includes/os/class.Haiku.inc.php | 13319 | <?php
/**
* Haiku System Class
*
* PHP version 5
*
* @category PHP
* @package PSI Haiku OS class
* @author Mieczyslaw Nalewaj <namiltd@users.sourceforge.net>
* @copyright 2012 phpSysInfo
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @version SVN: $Id: class.Haiku.inc.php 687 2012-09-06 20:54:49Z namiltd $
* @link http://phpsysinfo.sourceforge.net
*/
/**
* Haiku sysinfo class
* get all the required information from Haiku system
*
* @category PHP
* @package PSI Haiku OS class
* @author Mieczyslaw Nalewaj <namiltd@users.sourceforge.net>
* @copyright 2012 phpSysInfo
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @version Release: 3.0
* @link http://phpsysinfo.sourceforge.net
*/
class Haiku extends OS
{
/**
* content of the syslog
*
* @var array
*/
private $_dmesg = array();
/**
* call parent constructor
*/
public function __construct()
{
parent::__construct();
}
/**
* get the cpu information
*
* @return array
*/
protected function _cpuinfo()
{
if (CommonFunctions::executeProgram('sysinfo', '-cpu', $bufr, PSI_DEBUG)) {
$cpus = preg_split("/\nCPU #\d+/", $bufr, -1, PREG_SPLIT_NO_EMPTY);
$cpuspeed = "";
foreach ($cpus as $cpu) {
if (preg_match("/^.*running at (\d+)MHz/", $cpu, $ar_buf)) {
$cpuspeed = $ar_buf[1];
} elseif (preg_match("/^: \"(.*)\"/", $cpu, $ar_buf)) {
$dev = new CpuDevice();
$dev->setModel($ar_buf[1]);
$arrLines = preg_split("/\n/", $cpu, -1, PREG_SPLIT_NO_EMPTY);
foreach ($arrLines as $Line) {
if (preg_match("/^\s+Data TLB:\s+(.*)K-byte/", $Line, $Line_buf)) {
$dev->setCache(max($Line_buf[1]*1024,$dev->getCache()));
} elseif (preg_match("/^\s+Data TLB:\s+(.*)M-byte/", $Line, $Line_buf)) {
$dev->setCache(max($Line_buf[1]*1024*1024,$dev->getCache()));
} elseif (preg_match("/^\s+Data TLB:\s+(.*)G-byte/", $Line, $Line_buf)) {
$dev->setCache(max($Line_buf[1]*1024*1024*1024,$dev->getCache()));
} elseif (preg_match("/\s+VMX/", $Line, $Line_buf)) {
$dev->setVirt("vmx");
} elseif (preg_match("/\s+SVM/", $Line, $Line_buf)) {
$dev->setVirt("svm");
}
}
if ($cpuspeed != "" )$dev->setCpuSpeed($cpuspeed);
$this->sys->setCpus($dev);
//echo ">>>>>".$cpu;
}
}
}
}
/**
* PCI devices
* get the pci device information
*
* @return void
*/
protected function _pci()
{
if (CommonFunctions::executeProgram('listdev', '', $bufr, PSI_DEBUG)) {
// $devices = preg_split("/^device |\ndevice /", $bufr, -1, PREG_SPLIT_NO_EMPTY);
$devices = preg_split("/^device /m", $bufr, -1, PREG_SPLIT_NO_EMPTY);
foreach ($devices as $device) {
$ar_buf = preg_split("/\n/", $device);
if (count($ar_buf) >= 3) {
if (preg_match("/^([^\(\[\n]*)/", $device, $ar_buf2)) {
if (preg_match("/^[^\(]*\((.*)\)/", $device, $ar_buf3)) {
$ar_buf2[1] = $ar_buf3[1];
}
$name = trim($ar_buf2[1]).": ";
if (preg_match("/^\s+vendor\s+[0-9a-fA-F]{4}:\s+(.*)/", $ar_buf[1], $ar_buf3)) {
$name .=$ar_buf3[1]." ";
}
if (preg_match("/^\s+device\s+[0-9a-fA-F]{4}:\s+(.*)/", $ar_buf[2], $ar_buf3)) {
$name .=$ar_buf3[1]." ";
}
$dev = new HWDevice();
$dev->setName(trim($name));
$this->sys->setPciDevices($dev);
}
}
}
}
}
/**
* USB devices
* get the usb device information
*
* @return void
*/
protected function _usb()
{
if (CommonFunctions::executeProgram('listusb', '', $bufr, PSI_DEBUG)) {
$devices = preg_split("/\n/", $bufr);
foreach ($devices as $device) {
if (preg_match("/^\S+\s+\S+\s+\"(.*)\"\s+\"(.*)\"/", $device, $ar_buf)) {
$dev = new HWDevice();
$dev->setName(trim($ar_buf[1]." ".$ar_buf[2]));
$this->sys->setUSBDevices($dev);
}
}
}
}
/**
* Haiku Version
*
* @return void
*/
private function _kernel()
{
if (CommonFunctions::executeProgram('uname', '-rvm', $ret)) {
$this->sys->setKernel($ret);
}
}
/**
* Distribution
*
* @return void
*/
protected function _distro()
{
if (CommonFunctions::executeProgram('uname', '-sr', $ret))
$this->sys->setDistribution($ret);
else
$this->sys->setDistribution('Haiku');
$this->sys->setDistributionIcon('Haiku.png');
}
/**
* UpTime
* time the system is running
*
* @return void
*/
private function _uptime()
{
if (CommonFunctions::executeProgram('uptime', '-u', $buf)) {
if (preg_match("/^up (\d+) minute[s]?/", $buf, $ar_buf)) {
$min = $ar_buf[1];
$this->sys->setUptime($min * 60);
} elseif (preg_match("/^up (\d+) hour[s]?, (\d+) minute[s]?/", $buf, $ar_buf)) {
$min = $ar_buf[2];
$hours = $ar_buf[1];
$this->sys->setUptime($hours * 3600 + $min * 60);
} elseif (preg_match("/^up (\d+) day[s]?, (\d+) hour[s]?, (\d+) minute[s]?/", $buf, $ar_buf)) {
$min = $ar_buf[3];
$hours = $ar_buf[2];
$days = $ar_buf[1];
$this->sys->setUptime($days * 86400 + $hours * 3600 + $min * 60);
}
}
}
/**
* Processor Load
* optionally create a loadbar
*
* @return void
*/
private function _loadavg()
{
if (CommonFunctions::executeProgram('top', '-n 1 -i 1', $buf)) {
if (preg_match("/\s+(\S+)%\s+TOTAL\s+\(\S+%\s+idle time/", $buf, $ar_buf)) {
$this->sys->setLoad($ar_buf[1]);
if (PSI_LOAD_BAR) {
$this->sys->setLoadPercent(round($ar_buf[1]));
}
}
}
}
/**
* Number of Users
*
* @return void
*/
private function _users()
{
$this->sys->setUsers(1);
}
/**
* Virtual Host Name
*
* @return void
*/
private function _hostname()
{
if (PSI_USE_VHOST === true) {
$this->sys->setHostname(getenv('SERVER_NAME'));
} else {
if (CommonFunctions::executeProgram('uname', '-n', $result, PSI_DEBUG)) {
$ip = gethostbyname($result);
if ($ip != $result) {
$this->sys->setHostname(gethostbyaddr($ip));
}
}
}
}
/**
* IP of the Virtual Host Name
*
* @return void
*/
private function _ip()
{
if (PSI_USE_VHOST === true) {
$this->sys->setIp(gethostbyname($this->sys->getHostname()));
} else {
if (!($result = getenv('SERVER_ADDR'))) {
$this->sys->setIp(gethostbyname($this->sys->getHostname()));
} else {
$this->sys->setIp($result);
}
}
}
/**
* Physical memory information and Swap Space information
*
* @return void
*/
private function _memory()
{
if (CommonFunctions::executeProgram('sysinfo', '-mem', $bufr, PSI_DEBUG)) {
if (preg_match("/(.*)bytes free\s+\(used\/max\s+(.*)\s+\/\s+(.*)\)\s*\n\s+\(cached\s+(.*)\)/", $bufr, $ar_buf)) {
$this->sys->setMemTotal($ar_buf[3]);
$this->sys->setMemFree($ar_buf[1]);
$this->sys->setMemCache($ar_buf[4]);
$this->sys->setMemUsed($ar_buf[2]);
}
}
if (CommonFunctions::executeProgram('vmstat', '', $bufr, PSI_DEBUG)) {
if (preg_match("/max swap space:\s+(.*)\nfree swap space:\s+(.*)\n/", $bufr, $ar_buf)) {
if ($ar_buf[1]>0) {
$dev = new DiskDevice();
$dev->setMountPoint("/boot/common/var/swap");
$dev->setName("SWAP");
$dev->setTotal($ar_buf[1]);
$dev->setFree($ar_buf[2]);
$dev->setUSed($ar_buf[1]-$ar_buf[2]);
$this->sys->setSwapDevices($dev);
}
}
}
}
/**
* filesystem information
*
* @return void
*/
private function _filesystems()
{
$arrResult = array();
if (CommonFunctions::executeProgram('df', '-b', $df, PSI_DEBUG)) {
$df = preg_split("/\n/", $df, -1, PREG_SPLIT_NO_EMPTY);
foreach ($df as $df_line) {
$ar_buf = preg_split("/\s+/", $df_line);
if ((substr($df_line,0 ,1 ) == "/") && (count($ar_buf) == 6 )) {
$dev = new DiskDevice();
$dev->setMountPoint($ar_buf[0]);
$dev->setName($ar_buf[5]);
$dev->setFsType($ar_buf[1]);
$dev->setOptions($ar_buf[4]);
$dev->setTotal($ar_buf[2] * 1024);
$dev->setFree($ar_buf[3] * 1024);
$dev->setUsed($dev->getTotal() - $dev->getFree());
$this->sys->setDiskDevices($dev);
}
}
}
}
/**
* network information
*
* @return void
*/
private function _network()
{
if (CommonFunctions::executeProgram('ifconfig', '', $bufr, PSI_DEBUG)) {
$lines = preg_split("/\n/", $bufr, -1, PREG_SPLIT_NO_EMPTY);
$notwas = true;
foreach ($lines as $line) {
if (preg_match("/^(\S+)/", $line, $ar_buf)) {
if (!$notwas) {
$dev->setErrors($errors);
$dev->setDrops($drops);
$this->sys->setNetDevices($dev);
}
$errors = 0;
$drops = 0;
$dev = new NetDevice();
$dev->setName($ar_buf[1]);
$notwas = false;
} else {
if (!$notwas) {
if (preg_match('/\sReceive:\s\d+\spackets,\s(\d+)\serrors,\s(\d+)\sbytes,\s\d+\smcasts,\s(\d+)\sdropped/i', $line, $ar_buf2)) {
$errors +=$ar_buf2[1];
$drops +=$ar_buf2[3];
$dev->setRxBytes($ar_buf2[2]);
} elseif (preg_match('/\sTransmit:\s\d+\spackets,\s(\d+)\serrors,\s(\d+)\sbytes,\s\d+\smcasts,\s(\d+)\sdropped/i', $line, $ar_buf2)) {
$errors +=$ar_buf2[1];
$drops +=$ar_buf2[3];
$dev->setTxBytes($ar_buf2[2]);
}
if (defined('PSI_SHOW_NETWORK_INFOS') && (PSI_SHOW_NETWORK_INFOS)) {
if (preg_match('/\sEthernet,\s+Address:\s(\S*)/i', $line, $ar_buf2))
$dev->setInfo(preg_replace('/:/', '-', $ar_buf2[1]));
elseif (preg_match('/^\s+inet\saddr:\s(\S*),/i', $line, $ar_buf2))
$dev->setInfo(($dev->getInfo()?$dev->getInfo().';':'').$ar_buf2[1]);
elseif (preg_match('/^\s+inet6\saddr:\s(\S*),/i', $line, $ar_buf2))
if (!preg_match('/^fe80::/i',$ar_buf2[1]))
$dev->setInfo(($dev->getInfo()?$dev->getInfo().';':'').$ar_buf2[1]);
}
}
}
}
if (!$notwas) {
$dev->setErrors($errors);
$dev->setDrops($drops);
$this->sys->setNetDevices($dev);
}
}
}
/**
* get the information
*
* @return Void
*/
public function build()
{
$this->error->addError("WARN", "The Haiku version of phpSysInfo is a work in progress, some things currently don't work");
$this->_hostname();
$this->_ip();
$this->_distro();
$this->_kernel();
$this->_uptime();
$this->_users();
$this->_loadavg();
$this->_pci();
$this->_usb();
$this->_cpuinfo();
$this->_memory();
$this->_filesystems();
$this->_network();
}
}
| agpl-3.0 |
OlafRadicke/peruschim_cpp | src/RouteReverse/manager/Manager.cpp | 4011 | /*
* Copyright (C) 2013 Olaf Radicke <briefkasten@olaf-radicke.de>
*
*
* 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 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/>.
*/
#include <RouteReverse/manager/Manager.h>
#include <Core/models/PeruschimException.h>
#include <cxxtools/log.h>
#include <string>
#include <map>
#include <iostream>
#include <ostream>
#include <exception>
namespace RouteReverse
{
log_define("RouteReverse.Manager")
// std::map< std::string, std::string > Manager::reverseMAP = std::map< std::string, std::string >();
std::map< std::string, std::string > Manager::reverseMAP;
// A --------------------------------------------------------------------------
void Manager::addRoute( const URLData &urlData, tnt::Tntnet &app ) {
if ( urlData.urlRegEx != "" && urlData.componentName != "" ) {
if ( urlData.componentPathInfo != "" ) {
app.mapUrl( urlData.urlRegEx, urlData.componentName )
.setPathInfo( urlData.componentPathInfo );
} else {
app.mapUrl( urlData.urlRegEx, urlData.componentName );
}
}
if ( urlData.reverseRoute != "") {
if ( Manager::reverseMAP.count( urlData.componentName ) > 0 ) {
std::ostringstream errorText;
errorText << "[" << __FILE__ << " "
<< __LINE__ << "] "
<< " the url " << urlData.componentName
<< " is all ready set as reverse route!";
log_debug( errorText );
throw Core::PeruschimException( errorText.str() );
}
Manager::reverseMAP[ urlData.componentName ] = urlData.reverseRoute;
log_debug( "List of know reverse routes: \n" <<
RouteReverse::Manager::getAllReversesRoutes() );
}
}
// G --------------------------------------------------------------------------
std::string Manager::getAllReversesRoutes(){
std::string returnString;
std::map< std::string, std::string >::const_iterator it;
for (
it = Manager::reverseMAP.begin();
it != Manager::reverseMAP.end();
++it
){
returnString += it->first + " => " + it->second + "\n";
}
return returnString;
}
std::string Manager::getLinkTo(
const std::string componentName,
const tnt::HttpRequest& request ){
std::string targetURL;
std::string returnURL;
std::string currentURL = request.getUrl ();
std::map<std::string, std::string>::const_iterator it =
Manager::reverseMAP.find( componentName );
if (it != Manager::reverseMAP.end())
targetURL = it->second;
returnURL = targetURL;
size_t pathDepth = std::count( currentURL.begin(), currentURL.end(), '/' );
for ( unsigned int i = 1; i < pathDepth; i++){
returnURL = "../" + returnURL;
}
return returnURL;
}
std::string Manager::getAbsolutURL(
const std::string componentName,
const tnt::HttpRequest& request ){
std::string targetURL;
std::string returnURL;
std::map<std::string, std::string>::const_iterator it =
Manager::reverseMAP.find( componentName );
if (it != Manager::reverseMAP.end())
targetURL = it->second;
if ( request.isSsl() ) {
returnURL = "https://" +request.getVirtualHost()
+ "/" + targetURL;
} else{
returnURL = "http://" +request.getVirtualHost()
+ "/" + targetURL;
}
return returnURL;
}
} // END namespace SessionForm
| agpl-3.0 |
Tatwi/legend-of-hondo | MMOCoreORB/bin/scripts/mobile/corellia/ragtag_kook.lua | 2012 | ragtag_kook = Creature:new {
objectName = "@mob/creature_names:ragtag_kook",
randomNameType = NAME_GENERIC,
randomNameTag = true,
socialGroup = "ragtag",
faction = "thug",
level = 5,
chanceHit = 0.250000,
damageMin = 45,
damageMax = 50,
baseXp = 85,
baseHAM = 135,
baseHAMmax = 165,
armor = 0,
resists = {0,0,0,0,0,0,0,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0.000000,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = HERD,
diet = HERBIVORE,
templates = {
"object/mobile/dressed_criminal_thug_aqualish_female_01.iff",
"object/mobile/dressed_criminal_thug_aqualish_female_02.iff",
"object/mobile/dressed_criminal_thug_aqualish_male_01.iff",
"object/mobile/dressed_criminal_thug_aqualish_male_02.iff",
"object/mobile/dressed_criminal_thug_rodian_female_01.iff",
"object/mobile/dressed_criminal_thug_rodian_male_01.iff",
"object/mobile/dressed_criminal_thug_trandoshan_female_01.iff",
"object/mobile/dressed_criminal_thug_trandoshan_male_01.iff",
"object/mobile/dressed_criminal_thug_zabrak_female_01.iff",
"object/mobile/dressed_criminal_thug_zabrak_male_01.iff",
"object/mobile/dressed_commoner_tatooine_aqualish_male_06.iff",
"object/mobile/dressed_commoner_tatooine_rodian_male_04.iff",
"object/mobile/dressed_commoner_tatooine_devaronian_male_03.iff",
"object/mobile/dressed_commoner_old_twilek_male_01.iff",
"object/mobile/dressed_commoner_tatooine_aqualish_female_08.iff"
},
lootGroups = {
{
groups = {
{group = "junk", chance = 4000000},
{group = "wearables_common", chance = 3000000},
{group = "loot_kit_parts", chance = 1500000},
{group = "crystals_poor", chance = 500000},
{group = "tailor_components", chance = 1000000}
}
}
},
weapons = {"pirate_weapons_light"},
reactionStf = "@npc_reaction/slang",
attacks = merge(brawlernovice,marksmannovice)
}
CreatureTemplates:addCreatureTemplate(ragtag_kook, "ragtag_kook")
| agpl-3.0 |
zhenzhai/edx-platform | common/lib/sandbox-packages/hint/hint_class/Week7/Prob6_Part10.py | 899 | # Make sure you name your file with className.py
from hint_class_helpers.find_matches import find_matches
class Prob6_Part10:
"""
Author: Shen Ting Ang
Date: 11/7/2016
"""
def check_attempt(self, params):
self.attempt = params['attempt'] #student's attempt
self.answer = params['answer'] #solution
self.att_tree = params['att_tree'] #attempt tree
self.ans_tree = params['ans_tree'] #solution tree
matches = find_matches(params)
matching_node = [m[0] for m in matches]
try:
hint = 'The Variance of X is E[X^2] - (E[X})^2. '
return hint + 'If X is a flip of an unbiased coin, and heads = 1, what is Var[X]??', '0.25'
except Exception:
return '',''
def get_problems(self):
self.problem_list = ["ExpectationVariance/cov_dep_uncor.imd"]
return self.problem_list | agpl-3.0 |
42wim/platform | api/channel_test.go | 33742 | // Copyright (c) 2015 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package api
import (
"github.com/mattermost/platform/model"
"github.com/mattermost/platform/store"
"github.com/mattermost/platform/utils"
"net/http"
"strings"
"testing"
"time"
)
func TestCreateChannel(t *testing.T) {
th := Setup().InitBasic()
Client := th.BasicClient
team := th.BasicTeam
Client.Must(Client.Logout())
team2 := th.CreateTeam(th.BasicClient)
th.LoginBasic()
th.BasicClient.SetTeamId(team.Id)
channel := model.Channel{DisplayName: "Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
rchannel, err := Client.CreateChannel(&channel)
if err != nil {
t.Fatal(err)
}
if rchannel.Data.(*model.Channel).Name != channel.Name {
t.Fatal("full name didn't match")
}
rget := Client.Must(Client.GetChannels("")).Data.(*model.ChannelList)
nameMatch := false
for _, c := range rget.Channels {
if c.Name == channel.Name {
nameMatch = true
}
}
if !nameMatch {
t.Fatal("Did not create channel with correct name")
}
if _, err := Client.CreateChannel(rchannel.Data.(*model.Channel)); err == nil {
t.Fatal("Cannot create an existing")
}
savedId := rchannel.Data.(*model.Channel).Id
rchannel.Data.(*model.Channel).Id = ""
if _, err := Client.CreateChannel(rchannel.Data.(*model.Channel)); err != nil {
if err.Message != "A channel with that URL already exists" {
t.Fatal(err)
}
}
if _, err := Client.DoApiPost(Client.GetTeamRoute()+"/channels/create", "garbage"); err == nil {
t.Fatal("should have been an error")
}
Client.DeleteChannel(savedId)
if _, err := Client.CreateChannel(rchannel.Data.(*model.Channel)); err != nil {
if err.Message != "A channel with that URL was previously created" {
t.Fatal(err)
}
}
channel = model.Channel{DisplayName: "Channel on Different Team", Name: "aaaa" + model.NewId() + "abbb", Type: model.CHANNEL_OPEN, TeamId: team2.Id}
if _, err := Client.CreateChannel(&channel); err.StatusCode != http.StatusForbidden {
t.Fatal(err)
}
channel = model.Channel{DisplayName: "Test API Name", Name: model.NewId() + "__" + model.NewId(), Type: model.CHANNEL_OPEN, TeamId: team.Id}
if _, err := Client.CreateChannel(&channel); err == nil {
t.Fatal("Should have errored out on invalid '__' character")
}
channel = model.Channel{DisplayName: "Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_DIRECT, TeamId: team.Id}
if _, err := Client.CreateChannel(&channel); err == nil {
t.Fatal("Should have errored out on direct channel type")
}
}
func TestCreateDirectChannel(t *testing.T) {
th := Setup().InitBasic()
Client := th.BasicClient
user := th.BasicUser
user2 := th.BasicUser2
rchannel, err := Client.CreateDirectChannel(th.BasicUser2.Id)
if err != nil {
t.Fatal(err)
}
channelName := ""
if user2.Id > user.Id {
channelName = user.Id + "__" + user2.Id
} else {
channelName = user2.Id + "__" + user.Id
}
if rchannel.Data.(*model.Channel).Name != channelName {
t.Fatal("channel name didn't match")
}
if rchannel.Data.(*model.Channel).Type != model.CHANNEL_DIRECT {
t.Fatal("channel type was not direct")
}
// don't fail on direct channels already existing
if _, err := Client.CreateDirectChannel(th.BasicUser2.Id); err != nil {
t.Fatal(err)
}
if _, err := Client.CreateDirectChannel("junk"); err == nil {
t.Fatal("should have failed with bad user id")
}
if _, err := Client.CreateDirectChannel("12345678901234567890123456"); err == nil {
t.Fatal("should have failed with non-existent user")
}
}
func TestUpdateChannel(t *testing.T) {
th := Setup().InitSystemAdmin()
Client := th.SystemAdminClient
team := th.SystemAdminTeam
sysAdminUser := th.SystemAdminUser
user := th.CreateUser(Client)
LinkUserToTeam(user, team)
user2 := th.CreateUser(Client)
LinkUserToTeam(user2, team)
Client.Login(user.Email, user.Password)
channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel)
Client.AddChannelMember(channel1.Id, user.Id)
header := "a" + model.NewId() + "a"
purpose := "a" + model.NewId() + "a"
upChannel1 := &model.Channel{Id: channel1.Id, Header: header, Purpose: purpose}
upChannel1 = Client.Must(Client.UpdateChannel(upChannel1)).Data.(*model.Channel)
if upChannel1.Header != header {
t.Fatal("Channel admin failed to update header")
}
if upChannel1.Purpose != purpose {
t.Fatal("Channel admin failed to update purpose")
}
if upChannel1.DisplayName != channel1.DisplayName {
t.Fatal("Channel admin failed to skip displayName")
}
rget := Client.Must(Client.GetChannels(""))
data := rget.Data.(*model.ChannelList)
for _, c := range data.Channels {
if c.Name == model.DEFAULT_CHANNEL {
c.Header = "new header"
c.Name = "pseudo-square"
if _, err := Client.UpdateChannel(c); err == nil {
t.Fatal("should have errored on updating default channel name")
}
break
}
}
Client.Login(user2.Email, user2.Password)
if _, err := Client.UpdateChannel(upChannel1); err == nil {
t.Fatal("Standard User should have failed to update")
}
Client.Must(Client.JoinChannel(channel1.Id))
UpdateUserToTeamAdmin(user2, team)
Client.Logout()
Client.Login(user2.Email, user2.Password)
Client.SetTeamId(team.Id)
if _, err := Client.UpdateChannel(upChannel1); err != nil {
t.Fatal(err)
}
Client.Login(sysAdminUser.Email, sysAdminUser.Password)
Client.Must(Client.JoinChannel(channel1.Id))
if _, err := Client.UpdateChannel(upChannel1); err != nil {
t.Fatal(err)
}
Client.Must(Client.DeleteChannel(channel1.Id))
if _, err := Client.UpdateChannel(upChannel1); err == nil {
t.Fatal("should have failed - channel deleted")
}
}
func TestUpdateChannelHeader(t *testing.T) {
th := Setup().InitBasic()
Client := th.BasicClient
team := th.BasicTeam
channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel)
data := make(map[string]string)
data["channel_id"] = channel1.Id
data["channel_header"] = "new header"
var upChannel1 *model.Channel
if result, err := Client.UpdateChannelHeader(data); err != nil {
t.Fatal(err)
} else {
upChannel1 = result.Data.(*model.Channel)
}
if upChannel1.Header != data["channel_header"] {
t.Fatal("Failed to update header")
}
data["channel_id"] = "junk"
if _, err := Client.UpdateChannelHeader(data); err == nil {
t.Fatal("should have errored on junk channel id")
}
data["channel_id"] = "12345678901234567890123456"
if _, err := Client.UpdateChannelHeader(data); err == nil {
t.Fatal("should have errored on non-existent channel id")
}
data["channel_id"] = channel1.Id
data["channel_header"] = strings.Repeat("a", 1050)
if _, err := Client.UpdateChannelHeader(data); err == nil {
t.Fatal("should have errored on bad channel header")
}
rchannel := Client.Must(Client.CreateDirectChannel(th.BasicUser2.Id)).Data.(*model.Channel)
data["channel_id"] = rchannel.Id
data["channel_header"] = "new header"
var upChanneld *model.Channel
if result, err := Client.UpdateChannelHeader(data); err != nil {
t.Fatal(err)
} else {
upChanneld = result.Data.(*model.Channel)
}
if upChanneld.Header != data["channel_header"] {
t.Fatal("Failed to update header")
}
th.LoginBasic2()
data["channel_id"] = channel1.Id
data["channel_header"] = "new header"
if _, err := Client.UpdateChannelHeader(data); err == nil {
t.Fatal("should have errored non-channel member trying to update header")
}
}
func TestUpdateChannelPurpose(t *testing.T) {
th := Setup().InitBasic()
Client := th.BasicClient
team := th.BasicTeam
channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel)
data := make(map[string]string)
data["channel_id"] = channel1.Id
data["channel_purpose"] = "new purpose"
var upChannel1 *model.Channel
if result, err := Client.UpdateChannelPurpose(data); err != nil {
t.Fatal(err)
} else {
upChannel1 = result.Data.(*model.Channel)
}
if upChannel1.Purpose != data["channel_purpose"] {
t.Fatal("Failed to update purpose")
}
data["channel_id"] = "junk"
if _, err := Client.UpdateChannelPurpose(data); err == nil {
t.Fatal("should have errored on junk channel id")
}
data["channel_id"] = "12345678901234567890123456"
if _, err := Client.UpdateChannelPurpose(data); err == nil {
t.Fatal("should have errored on non-existent channel id")
}
data["channel_id"] = channel1.Id
data["channel_purpose"] = strings.Repeat("a", 150)
if _, err := Client.UpdateChannelPurpose(data); err == nil {
t.Fatal("should have errored on bad channel purpose")
}
th.LoginBasic2()
data["channel_id"] = channel1.Id
data["channel_purpose"] = "new purpose"
if _, err := Client.UpdateChannelPurpose(data); err == nil {
t.Fatal("should have errored non-channel member trying to update purpose")
}
}
func TestGetChannel(t *testing.T) {
th := Setup().InitBasic()
Client := th.BasicClient
team := th.BasicTeam
team2 := th.CreateTeam(Client)
channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel)
channel2 := &model.Channel{DisplayName: "B Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channel2 = Client.Must(Client.CreateChannel(channel2)).Data.(*model.Channel)
rget := Client.Must(Client.GetChannels(""))
data := rget.Data.(*model.ChannelList)
if data.Channels[0].DisplayName != channel1.DisplayName {
t.Fatal("full name didn't match")
}
if data.Channels[1].DisplayName != channel2.DisplayName {
t.Fatal("full name didn't match")
}
// test etag caching
if cache_result, err := Client.GetChannels(rget.Etag); err != nil {
t.Fatal(err)
} else if cache_result.Data.(*model.ChannelList) != nil {
t.Log(cache_result.Data)
t.Fatal("cache should be empty")
}
if _, err := Client.UpdateLastViewedAt(channel2.Id); err != nil {
t.Fatal(err)
}
if resp, err := Client.GetChannel(channel1.Id, ""); err != nil {
t.Fatal(err)
} else {
data := resp.Data.(*model.ChannelData)
if data.Channel.DisplayName != channel1.DisplayName {
t.Fatal("name didn't match")
}
// test etag caching
if cache_result, err := Client.GetChannel(channel1.Id, resp.Etag); err != nil {
t.Fatal(err)
} else if cache_result.Data.(*model.ChannelData) != nil {
t.Log(cache_result.Data)
t.Fatal("cache should be empty")
}
}
if _, err := Client.GetChannel("junk", ""); err == nil {
t.Fatal("should have failed - bad channel id")
}
Client.SetTeamId(team2.Id)
if _, err := Client.GetChannel(channel2.Id, ""); err == nil {
t.Fatal("should have failed - wrong team")
}
}
func TestGetMoreChannel(t *testing.T) {
th := Setup().InitBasic()
Client := th.BasicClient
team := th.BasicTeam
channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel)
channel2 := &model.Channel{DisplayName: "B Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channel2 = Client.Must(Client.CreateChannel(channel2)).Data.(*model.Channel)
th.LoginBasic2()
rget := Client.Must(Client.GetMoreChannels(""))
data := rget.Data.(*model.ChannelList)
if data.Channels[0].DisplayName != channel1.DisplayName {
t.Fatal("full name didn't match")
}
if data.Channels[1].DisplayName != channel2.DisplayName {
t.Fatal("full name didn't match")
}
// test etag caching
if cache_result, err := Client.GetMoreChannels(rget.Etag); err != nil {
t.Fatal(err)
} else if cache_result.Data.(*model.ChannelList) != nil {
t.Log(cache_result.Data)
t.Fatal("cache should be empty")
}
}
func TestGetChannelCounts(t *testing.T) {
th := Setup().InitBasic()
Client := th.BasicClient
team := th.BasicTeam
channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel)
channel2 := &model.Channel{DisplayName: "B Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channel2 = Client.Must(Client.CreateChannel(channel2)).Data.(*model.Channel)
if result, err := Client.GetChannelCounts(""); err != nil {
t.Fatal(err)
} else {
counts := result.Data.(*model.ChannelCounts)
if len(counts.Counts) != 5 {
t.Fatal("wrong number of channel counts")
}
if len(counts.UpdateTimes) != 5 {
t.Fatal("wrong number of channel update times")
}
if cache_result, err := Client.GetChannelCounts(result.Etag); err != nil {
t.Fatal(err)
} else if cache_result.Data.(*model.ChannelCounts) != nil {
t.Log(cache_result.Data)
t.Fatal("result data should be empty")
}
}
}
func TestJoinChannelById(t *testing.T) {
th := Setup().InitBasic()
Client := th.BasicClient
team := th.BasicTeam
channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel)
channel3 := &model.Channel{DisplayName: "B Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_PRIVATE, TeamId: team.Id}
channel3 = Client.Must(Client.CreateChannel(channel3)).Data.(*model.Channel)
th.LoginBasic2()
Client.Must(Client.JoinChannel(channel1.Id))
if _, err := Client.JoinChannel(channel3.Id); err == nil {
t.Fatal("shouldn't be able to join secret group")
}
rchannel := Client.Must(Client.CreateDirectChannel(th.BasicUser.Id)).Data.(*model.Channel)
user3 := th.CreateUser(th.BasicClient)
LinkUserToTeam(user3, team)
Client.Must(Client.Login(user3.Email, "Password1"))
if _, err := Client.JoinChannel(rchannel.Id); err == nil {
t.Fatal("shoudn't be able to join direct channel")
}
th.LoginBasic()
if _, err := Client.JoinChannel(channel1.Id); err != nil {
t.Fatal("should be able to join public channel that we're a member of")
}
if _, err := Client.JoinChannel(channel3.Id); err != nil {
t.Fatal("should be able to join private channel that we're a member of")
}
if _, err := Client.JoinChannel(rchannel.Id); err != nil {
t.Fatal("should be able to join direct channel that we're a member of")
}
}
func TestJoinChannelByName(t *testing.T) {
th := Setup().InitBasic()
Client := th.BasicClient
team := th.BasicTeam
channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel)
channel3 := &model.Channel{DisplayName: "B Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_PRIVATE, TeamId: team.Id}
channel3 = Client.Must(Client.CreateChannel(channel3)).Data.(*model.Channel)
th.LoginBasic2()
Client.Must(Client.JoinChannelByName(channel1.Name))
if _, err := Client.JoinChannelByName(channel3.Name); err == nil {
t.Fatal("shouldn't be able to join secret group")
}
rchannel := Client.Must(Client.CreateDirectChannel(th.BasicUser.Id)).Data.(*model.Channel)
user3 := th.CreateUser(th.BasicClient)
LinkUserToTeam(user3, team)
Client.Must(Client.Login(user3.Email, "Password1"))
if _, err := Client.JoinChannelByName(rchannel.Name); err == nil {
t.Fatal("shoudn't be able to join direct channel")
}
th.LoginBasic()
if _, err := Client.JoinChannelByName(channel1.Name); err != nil {
t.Fatal("should be able to join public channel that we're a member of")
}
if _, err := Client.JoinChannelByName(channel3.Name); err != nil {
t.Fatal("should be able to join private channel that we're a member of")
}
if _, err := Client.JoinChannelByName(rchannel.Name); err != nil {
t.Fatal("should be able to join direct channel that we're a member of")
}
}
func TestLeaveChannel(t *testing.T) {
th := Setup().InitBasic()
Client := th.BasicClient
team := th.BasicTeam
channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel)
channel3 := &model.Channel{DisplayName: "B Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_PRIVATE, TeamId: team.Id}
channel3 = Client.Must(Client.CreateChannel(channel3)).Data.(*model.Channel)
th.LoginBasic2()
Client.Must(Client.JoinChannel(channel1.Id))
// Cannot leave a the private group if you are the only member
if _, err := Client.LeaveChannel(channel3.Id); err == nil {
t.Fatal("should have errored, cannot leave private group if only one member")
}
rchannel := Client.Must(Client.CreateDirectChannel(th.BasicUser.Id)).Data.(*model.Channel)
if _, err := Client.LeaveChannel(rchannel.Id); err == nil {
t.Fatal("should have errored, cannot leave direct channel")
}
rget := Client.Must(Client.GetChannels(""))
cdata := rget.Data.(*model.ChannelList)
for _, c := range cdata.Channels {
if c.Name == model.DEFAULT_CHANNEL {
if _, err := Client.LeaveChannel(c.Id); err == nil {
t.Fatal("should have errored on leaving default channel")
}
break
}
}
}
func TestDeleteChannel(t *testing.T) {
th := Setup().InitSystemAdmin()
Client := th.SystemAdminClient
team := th.SystemAdminTeam
userSystemAdmin := th.SystemAdminUser
userTeamAdmin := th.CreateUser(Client)
LinkUserToTeam(userTeamAdmin, team)
user2 := th.CreateUser(Client)
LinkUserToTeam(user2, team)
Client.Login(user2.Email, user2.Password)
channelMadeByCA := &model.Channel{DisplayName: "C Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channelMadeByCA = Client.Must(Client.CreateChannel(channelMadeByCA)).Data.(*model.Channel)
Client.AddChannelMember(channelMadeByCA.Id, userTeamAdmin.Id)
Client.Login(userTeamAdmin.Email, "pwd")
channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel)
channel2 := &model.Channel{DisplayName: "B Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channel2 = Client.Must(Client.CreateChannel(channel2)).Data.(*model.Channel)
if _, err := Client.DeleteChannel(channel1.Id); err != nil {
t.Fatal(err)
}
if _, err := Client.DeleteChannel(channelMadeByCA.Id); err != nil {
t.Fatal("Team admin failed to delete Channel Admin's channel")
}
post1 := &model.Post{ChannelId: channel1.Id, Message: "a" + model.NewId() + "a"}
if _, err := Client.CreatePost(post1); err == nil {
t.Fatal("should have failed to post to deleted channel")
}
userStd := th.CreateUser(Client)
LinkUserToTeam(userStd, team)
Client.Login(userStd.Email, userStd.Password)
if _, err := Client.JoinChannel(channel1.Id); err == nil {
t.Fatal("should have failed to join deleted channel")
}
Client.Must(Client.JoinChannel(channel2.Id))
if _, err := Client.DeleteChannel(channel2.Id); err == nil {
t.Fatal("should have failed to delete channel you're not an admin of")
}
rget := Client.Must(Client.GetChannels(""))
cdata := rget.Data.(*model.ChannelList)
for _, c := range cdata.Channels {
if c.Name == model.DEFAULT_CHANNEL {
if _, err := Client.DeleteChannel(c.Id); err == nil {
t.Fatal("should have errored on deleting default channel")
}
break
}
}
UpdateUserToTeamAdmin(userStd, team)
Client.Logout()
Client.Login(userStd.Email, userStd.Password)
Client.SetTeamId(team.Id)
if _, err := Client.DeleteChannel(channel2.Id); err != nil {
t.Fatal(err)
}
channel3 := &model.Channel{DisplayName: "B Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channel3 = Client.Must(Client.CreateChannel(channel3)).Data.(*model.Channel)
Client.Login(userSystemAdmin.Email, userSystemAdmin.Password)
Client.Must(Client.JoinChannel(channel3.Id))
if _, err := Client.DeleteChannel(channel3.Id); err != nil {
t.Fatal(err)
}
if _, err := Client.DeleteChannel(channel3.Id); err == nil {
t.Fatal("should have failed - channel already deleted")
}
}
func TestGetChannelExtraInfo(t *testing.T) {
th := Setup().InitBasic()
Client := th.BasicClient
team := th.BasicTeam
channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel)
rget := Client.Must(Client.GetChannelExtraInfo(channel1.Id, -1, ""))
data := rget.Data.(*model.ChannelExtra)
if data.Id != channel1.Id {
t.Fatal("couldnt't get extra info")
} else if len(data.Members) != 1 {
t.Fatal("got incorrect members")
} else if data.MemberCount != 1 {
t.Fatal("got incorrect member count")
}
//
// Testing etag caching
//
currentEtag := rget.Etag
if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, -1, currentEtag); err != nil {
t.Fatal(err)
} else if cache_result.Data.(*model.ChannelExtra) != nil {
t.Log(cache_result.Data)
t.Fatal("response should be empty")
} else {
currentEtag = cache_result.Etag
}
Client2 := model.NewClient("http://localhost" + utils.Cfg.ServiceSettings.ListenAddress)
user2 := &model.User{Email: "success+" + model.NewId() + "@simulator.amazonses.com", Nickname: "Tester 2", Password: "pwd"}
user2 = Client2.Must(Client2.CreateUser(user2, "")).Data.(*model.User)
LinkUserToTeam(user2, team)
Client2.SetTeamId(team.Id)
store.Must(Srv.Store.User().VerifyEmail(user2.Id))
Client2.Login(user2.Email, "pwd")
Client2.Must(Client2.JoinChannel(channel1.Id))
if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, -1, currentEtag); err != nil {
t.Fatal(err)
} else if cache_result.Data.(*model.ChannelExtra) == nil {
t.Log(cache_result.Data)
t.Fatal("response should not be empty")
} else {
currentEtag = cache_result.Etag
}
if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, -1, currentEtag); err != nil {
t.Fatal(err)
} else if cache_result.Data.(*model.ChannelExtra) != nil {
t.Log(cache_result.Data)
t.Fatal("response should be empty")
} else {
currentEtag = cache_result.Etag
}
Client2.Must(Client2.LeaveChannel(channel1.Id))
if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, -1, currentEtag); err != nil {
t.Fatal(err)
} else if cache_result.Data.(*model.ChannelExtra) == nil {
t.Log(cache_result.Data)
t.Fatal("response should not be empty")
} else {
currentEtag = cache_result.Etag
}
if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, -1, currentEtag); err != nil {
t.Fatal(err)
} else if cache_result.Data.(*model.ChannelExtra) != nil {
t.Log(cache_result.Data)
t.Fatal("response should be empty")
} else {
currentEtag = cache_result.Etag
}
Client2.Must(Client2.JoinChannel(channel1.Id))
if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, 2, currentEtag); err != nil {
t.Fatal(err)
} else if extra := cache_result.Data.(*model.ChannelExtra); extra == nil {
t.Fatal("response should not be empty")
} else if len(extra.Members) != 2 {
t.Fatal("should've returned 2 members")
} else if extra.MemberCount != 2 {
t.Fatal("should've returned member count of 2")
} else {
currentEtag = cache_result.Etag
}
if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, 1, currentEtag); err != nil {
t.Fatal(err)
} else if extra := cache_result.Data.(*model.ChannelExtra); extra == nil {
t.Fatal("response should not be empty")
} else if len(extra.Members) != 1 {
t.Fatal("should've returned only 1 member")
} else if extra.MemberCount != 2 {
t.Fatal("should've returned member count of 2")
} else {
currentEtag = cache_result.Etag
}
if cache_result, err := Client.GetChannelExtraInfo(channel1.Id, 1, currentEtag); err != nil {
t.Fatal(err)
} else if cache_result.Data.(*model.ChannelExtra) != nil {
t.Log(cache_result.Data)
t.Fatal("response should be empty")
} else {
currentEtag = cache_result.Etag
}
}
func TestAddChannelMember(t *testing.T) {
th := Setup().InitBasic()
Client := th.BasicClient
team := th.BasicTeam
user2 := th.BasicUser2
user3 := th.CreateUser(Client)
channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel)
if _, err := Client.AddChannelMember(channel1.Id, user2.Id); err != nil {
t.Fatal(err)
}
if _, err := Client.AddChannelMember(channel1.Id, "dsgsdg"); err == nil {
t.Fatal("Should have errored, bad user id")
}
if _, err := Client.AddChannelMember(channel1.Id, "12345678901234567890123456"); err == nil {
t.Fatal("Should have errored, bad user id")
}
if _, err := Client.AddChannelMember(channel1.Id, user2.Id); err != nil {
t.Fatal(err)
}
if _, err := Client.AddChannelMember("sgdsgsdg", user2.Id); err == nil {
t.Fatal("Should have errored, bad channel id")
}
channel2 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channel2 = Client.Must(Client.CreateChannel(channel2)).Data.(*model.Channel)
th.LoginBasic2()
if _, err := Client.AddChannelMember(channel2.Id, user2.Id); err == nil {
t.Fatal("Should have errored, user not in channel")
}
th.LoginBasic()
Client.Must(Client.DeleteChannel(channel2.Id))
if _, err := Client.AddChannelMember(channel2.Id, user2.Id); err == nil {
t.Fatal("Should have errored, channel deleted")
}
if _, err := Client.AddChannelMember(channel1.Id, user3.Id); err == nil {
t.Fatal("Should have errored, user not on team")
}
}
func TestRemoveChannelMember(t *testing.T) {
th := Setup().InitBasic()
Client := th.BasicClient
team := th.BasicTeam
user2 := th.BasicUser2
UpdateUserToTeamAdmin(user2, team)
channelMadeByCA := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channelMadeByCA = Client.Must(Client.CreateChannel(channelMadeByCA)).Data.(*model.Channel)
Client.Must(Client.AddChannelMember(channelMadeByCA.Id, user2.Id))
th.LoginBasic2()
channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel)
userStd := th.CreateUser(th.BasicClient)
LinkUserToTeam(userStd, team)
Client.Must(Client.AddChannelMember(channel1.Id, userStd.Id))
Client.Must(Client.AddChannelMember(channelMadeByCA.Id, userStd.Id))
if _, err := Client.RemoveChannelMember(channel1.Id, "dsgsdg"); err == nil {
t.Fatal("Should have errored, bad user id")
}
if _, err := Client.RemoveChannelMember("sgdsgsdg", userStd.Id); err == nil {
t.Fatal("Should have errored, bad channel id")
}
if _, err := Client.RemoveChannelMember(channel1.Id, userStd.Id); err != nil {
t.Fatal(err)
}
if _, err := Client.RemoveChannelMember(channelMadeByCA.Id, userStd.Id); err != nil {
t.Fatal("Team Admin failed to remove member from Channel Admin's channel")
}
channel2 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channel2 = Client.Must(Client.CreateChannel(channel2)).Data.(*model.Channel)
Client.Login(userStd.Email, userStd.Password)
if _, err := Client.RemoveChannelMember(channel2.Id, userStd.Id); err == nil {
t.Fatal("Should have errored, user not channel admin")
}
th.LoginBasic2()
Client.Must(Client.AddChannelMember(channel2.Id, userStd.Id))
Client.Must(Client.DeleteChannel(channel2.Id))
if _, err := Client.RemoveChannelMember(channel2.Id, userStd.Id); err == nil {
t.Fatal("Should have errored, channel deleted")
}
}
func TestUpdateNotifyProps(t *testing.T) {
th := Setup().InitBasic()
Client := th.BasicClient
team := th.BasicTeam
user := th.BasicUser
user2 := th.BasicUser2
channel1 := &model.Channel{DisplayName: "A Test API Name", Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
channel1 = Client.Must(Client.CreateChannel(channel1)).Data.(*model.Channel)
data := make(map[string]string)
data["channel_id"] = channel1.Id
data["user_id"] = user.Id
data["desktop"] = model.CHANNEL_NOTIFY_MENTION
timeBeforeUpdate := model.GetMillis()
time.Sleep(100 * time.Millisecond)
// test updating desktop
if result, err := Client.UpdateNotifyProps(data); err != nil {
t.Fatal(err)
} else if notifyProps := result.Data.(map[string]string); notifyProps["desktop"] != model.CHANNEL_NOTIFY_MENTION {
t.Fatal("NotifyProps[\"desktop\"] did not update properly")
} else if notifyProps["mark_unread"] != model.CHANNEL_MARK_UNREAD_ALL {
t.Fatalf("NotifyProps[\"mark_unread\"] changed to %v", notifyProps["mark_unread"])
}
rget := Client.Must(Client.GetChannels(""))
rdata := rget.Data.(*model.ChannelList)
if len(rdata.Members) == 0 || rdata.Members[channel1.Id].NotifyProps["desktop"] != data["desktop"] {
t.Fatal("NotifyProps[\"desktop\"] did not update properly")
} else if rdata.Members[channel1.Id].LastUpdateAt <= timeBeforeUpdate {
t.Fatal("LastUpdateAt did not update")
}
// test an empty update
delete(data, "desktop")
if result, err := Client.UpdateNotifyProps(data); err != nil {
t.Fatal(err)
} else if notifyProps := result.Data.(map[string]string); notifyProps["mark_unread"] != model.CHANNEL_MARK_UNREAD_ALL {
t.Fatalf("NotifyProps[\"mark_unread\"] changed to %v", notifyProps["mark_unread"])
} else if notifyProps["desktop"] != model.CHANNEL_NOTIFY_MENTION {
t.Fatalf("NotifyProps[\"desktop\"] changed to %v", notifyProps["desktop"])
}
// test updating mark unread
data["mark_unread"] = model.CHANNEL_MARK_UNREAD_MENTION
if result, err := Client.UpdateNotifyProps(data); err != nil {
t.Fatal(err)
} else if notifyProps := result.Data.(map[string]string); notifyProps["mark_unread"] != model.CHANNEL_MARK_UNREAD_MENTION {
t.Fatal("NotifyProps[\"mark_unread\"] did not update properly")
} else if notifyProps["desktop"] != model.CHANNEL_NOTIFY_MENTION {
t.Fatalf("NotifyProps[\"desktop\"] changed to %v", notifyProps["desktop"])
}
// test updating both
data["desktop"] = model.CHANNEL_NOTIFY_NONE
data["mark_unread"] = model.CHANNEL_MARK_UNREAD_MENTION
if result, err := Client.UpdateNotifyProps(data); err != nil {
t.Fatal(err)
} else if notifyProps := result.Data.(map[string]string); notifyProps["desktop"] != model.CHANNEL_NOTIFY_NONE {
t.Fatal("NotifyProps[\"desktop\"] did not update properly")
} else if notifyProps["mark_unread"] != model.CHANNEL_MARK_UNREAD_MENTION {
t.Fatal("NotifyProps[\"mark_unread\"] did not update properly")
}
// test error cases
data["user_id"] = "junk"
if _, err := Client.UpdateNotifyProps(data); err == nil {
t.Fatal("Should have errored - bad user id")
}
data["user_id"] = "12345678901234567890123456"
if _, err := Client.UpdateNotifyProps(data); err == nil {
t.Fatal("Should have errored - bad user id")
}
data["user_id"] = user.Id
data["channel_id"] = "junk"
if _, err := Client.UpdateNotifyProps(data); err == nil {
t.Fatal("Should have errored - bad channel id")
}
data["channel_id"] = "12345678901234567890123456"
if _, err := Client.UpdateNotifyProps(data); err == nil {
t.Fatal("Should have errored - bad channel id")
}
data["desktop"] = "junk"
data["mark_unread"] = model.CHANNEL_MARK_UNREAD_ALL
if _, err := Client.UpdateNotifyProps(data); err == nil {
t.Fatal("Should have errored - bad desktop notify level")
}
data["desktop"] = model.CHANNEL_NOTIFY_ALL
data["mark_unread"] = "junk"
if _, err := Client.UpdateNotifyProps(data); err == nil {
t.Fatal("Should have errored - bad mark unread level")
}
th.LoginBasic2()
data["channel_id"] = channel1.Id
data["user_id"] = user2.Id
data["desktop"] = model.CHANNEL_NOTIFY_MENTION
data["mark_unread"] = model.CHANNEL_MARK_UNREAD_MENTION
if _, err := Client.UpdateNotifyProps(data); err == nil {
t.Fatal("Should have errored - user not in channel")
}
}
func TestFuzzyChannel(t *testing.T) {
th := Setup().InitBasic()
Client := th.BasicClient
team := th.BasicTeam
// Strings that should pass as acceptable channel names
var fuzzyStringsPass = []string{
"*", "?", ".", "}{][)(><", "{}[]()<>",
"qahwah ( قهوة)",
"שָׁלוֹם עֲלֵיכֶם",
"Ramen チャーシュー chāshū",
"言而无信",
"Ṫ͌ó̍ ̍͂̓̍̍̀i̊ͯ͒",
"& < &qu",
"' or '1'='1' -- ",
"' or '1'='1' ({ ",
"' or '1'='1' /* ",
"1;DROP TABLE users",
"<b><i><u><strong><em>",
"sue@thatmightbe",
"sue@thatmightbe.",
"sue@thatmightbe.c",
"sue@thatmightbe.co",
"su+san@thatmightbe.com",
"a@b.中国",
"1@2.am",
"a@b.co.uk",
"a@b.cancerresearch",
"local@[127.0.0.1]",
}
for i := 0; i < len(fuzzyStringsPass); i++ {
channel := model.Channel{DisplayName: fuzzyStringsPass[i], Name: "a" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id}
_, err := Client.CreateChannel(&channel)
if err != nil {
t.Fatal(err)
}
}
}
| agpl-3.0 |
VolumetricPixels/Politics | src/main/java/com/volumetricpixels/politics/command/universe/UniverseCreateCommand.java | 4368 | /*
* This file is part of Politics.
*
* Copyright (c) 2012-2012, VolumetricPixels <http://volumetricpixels.com/>
* Politics is licensed under the Affero General Public License Version 3.
*
* 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.volumetricpixels.politics.command.universe;
import java.util.ArrayList;
import java.util.List;
import org.spout.api.Server;
import org.spout.api.command.Command;
import org.spout.api.command.CommandArguments;
import org.spout.api.command.CommandSource;
import org.spout.api.exception.CommandException;
import org.spout.api.geo.World;
import com.volumetricpixels.politics.Politics;
import com.volumetricpixels.politics.event.PoliticsEventFactory;
import com.volumetricpixels.politics.universe.Universe;
import com.volumetricpixels.politics.universe.UniverseRules;
import com.volumetricpixels.politics.world.PoliticsWorld;
/**
* Used to create universes.
*/
public class UniverseCreateCommand extends UniverseCommand {
/**
* C'tor
*/
public UniverseCreateCommand() {
super("create");
}
@Override
public void execute(final CommandSource source, final Command command, final CommandArguments args) throws CommandException {
final String name = args.get().get(0).toLowerCase();
if (name.contains(" ")) {
source.sendMessage("Spaces are not allowed in universe names.");
return;
}
if (name.contains("/") || name.contains("\\")) {
source.sendMessage("Slashes are not allowed in universe names.");
return;
}
final Universe existing = Politics.getUniverse(name);
if (existing != null) {
source.sendMessage("A universe named '" + name
+ "' already exists. Please destroy that universe via the 'universe destroy' command if you wish to overwrite that universe.");
return;
}
final String rules = args.get().get(1).toLowerCase();
final UniverseRules theRules = Politics.getUniverseManager().getRules(rules);
if (theRules == null) {
source.sendMessage("Invalid rules. To see the available rules, use.");
return;
}
final String worldsStr = args.get().get(2);
final List<PoliticsWorld> worlds = new ArrayList<PoliticsWorld>();
if (worldsStr == null) {
for (final World world : Politics.getPlugin().getEngine().getWorlds()) {
worlds.add(Politics.getWorld(world));
}
} else {
final String[] worldNames = worldsStr.split(",");
for (final String worldName : worldNames) {
final String trimmed = worldName.trim();
final World world = ((Server) Politics.getPlugin().getEngine()).getWorld(trimmed);
if (world == null) {
continue;
}
final PoliticsWorld pw = Politics.getWorld(world);
worlds.add(pw);
}
}
if (worlds.size() <= 0) {
source.sendMessage("There were no valid worlds specified.");
return;
}
final Universe universe = Politics.getUniverseManager().createUniverse(name, theRules);
PoliticsEventFactory.callUniverseCreateEvent(universe);
source.sendMessage("You have created the universe '" + name + "' with the rules '" + rules + "'.");
}
@Override
protected String[] getAliases() {
return new String[] { "new", "c", "n" };
}
@Override
public void setupCommand(final Command cmd) {
cmd.setHelp("Creates a new Universe with the given rules.");
cmd.setUsage("<name> <rules> [worlds...]");
}
}
| agpl-3.0 |
Asqatasun/Asqatasun | rules/rules-rgaa4.0/src/main/java/org/asqatasun/rules/rgaa40/Rgaa40Rule130401.java | 2541 | /**
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2020 Asqatasun.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 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/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.rules.rgaa40;
import org.asqatasun.entity.audit.TestSolution;
import org.asqatasun.ruleimplementation.link.AbstractDownloadableLinkRuleImplementation;
import org.asqatasun.rules.elementchecker.text.TextEndsWithChecker;
import static org.asqatasun.rules.keystore.AttributeStore.HREF_ATTR;
import static org.asqatasun.rules.keystore.RemarkMessageStore.OFFICE_DOCUMENT_DETECTED_MSG2;
import org.asqatasun.rules.textbuilder.TextAttributeOfElementBuilder;
/**
* Implementation of rule 13.4.1 (referential RGAA 4.0)
*
* For more details about implementation, refer to <a href="https://gitlab.com/asqatasun/Asqatasun/-/blob/master/documentation/en/90_Rules/rgaa4.0/13.Consultation/Rule-13-4-1.md">rule 13.4.1 design page</a>.
* @see <a href="https://www.numerique.gouv.fr/publications/rgaa-accessibilite/methode/criteres/#test-13-4-1">13.4.1 rule specification</a>
*/
public class Rgaa40Rule130401 extends AbstractDownloadableLinkRuleImplementation {
/* the office document extensions nomenclature */
private static final String OFFICE_DOC_EXT_NOM = "OfficeDocumentExtensions";
/**
* Default constructor
*/
public Rgaa40Rule130401() {
super(
new TextEndsWithChecker(
// the href attribute is tested
new TextAttributeOfElementBuilder(HREF_ATTR),
// the nomenclature listing the extensions to test
OFFICE_DOC_EXT_NOM,
// the result when detected
TestSolution.NEED_MORE_INFO,
// the message when detected
OFFICE_DOCUMENT_DETECTED_MSG2,
// the evidence elements
HREF_ATTR)
);
}
}
| agpl-3.0 |
ich-net-du/subwire | spec/controllers/articles_controller.rb | 740 | require 'spec_helper'
describe ArticlesController do
describe "GET 'index'" do
# Following doesn't work here
context "and user is not assigned to the chosen instance" do
context "but is superadmin" do
it "should render articles index of that instance" do
# TODO
end
end
context "and no superadmin" do
it "should redirect back to the instance chooser" do
@rel1 = FactoryGirl.create(:user1_with_instance)
# Then choose a instance to which the current user is not assigned to
set_current_instance @rel1.instance
# Then request the startpage
get :index
response.should redirect_to(instances_url)
current_instance.should be_nil
end
end
end
end
end
| agpl-3.0 |
CecileBONIN/Silverpeas-Core | web-core/src/main/java/com/stratelia/webactiv/util/viewGenerator/html/arrayPanes/ArrayPaneSilverpeasV5.java | 7776 | /**
* Copyright (C) 2000 - 2013 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.stratelia.webactiv.util.viewGenerator.html.arrayPanes;
import java.util.Collections;
import com.stratelia.silverpeas.silvertrace.SilverTrace;
import com.stratelia.webactiv.util.viewGenerator.html.GraphicElementFactory;
import com.stratelia.webactiv.util.viewGenerator.html.pagination.Pagination;
/**
* The default implementation of ArrayPane interface.
* @author squere
* @version 1.0
*/
public class ArrayPaneSilverpeasV5 extends AbstractArrayPane {
/**
* Default constructor as this class may be instanciated by method newInstance(), constructor
* contains no parameter. init methods must be used to initialize properly the instance.
* @see init
*/
public ArrayPaneSilverpeasV5() {
// initialisation is made in init methods
}
/**
* Method declaration
* @return
* @see
*/
private String printPseudoColumn() {
return ("<td><img src=\"" + GraphicElementFactory.getIconsPath() + "/1px.gif\" width=\"2\" height=\"2\" alt=\"\"/></td>");
}
/**
* Method declaration
* @return
* @see
*/
@Override
public String print() {
GraphicElementFactory gef =
(GraphicElementFactory) getSession().getAttribute(GraphicElementFactory.GE_FACTORY_SESSION_ATT);
Pagination pagination =
gef.getPagination(getLines().size(), getState().getMaximumVisibleLine(), getState().getFirstVisibleLine());
String sep = "&";
if (isXHTML()) {
sep = "&";
}
String baseUrl = getUrl();
StringBuilder url = new StringBuilder(baseUrl);
if (baseUrl.indexOf('?') < 0) {
url.append("?");
} else {
url.append(sep);
}
url.append(ACTION_PARAMETER_NAME).append("=ChangePage").append(sep).
append(TARGET_PARAMETER_NAME).append("=").append(getName()).append(sep).append(
INDEX_PARAMETER_NAME).append("=");
pagination.setBaseURL(url.toString());
int columnsCount = getColumns().size();
if ((getLines().size() > 0) && (getColumnToSort() != 0) && (getColumnToSort() <= columnsCount)) {
SilverTrace.info("viewgenerator", "ArrayPaneSilverpeasV5.print()",
"root.MSG_GEN_PARAM_VALUE", "Tri des lignes");
Collections.sort(getLines());
}
// when there is no cell spacing, add pseudo columns as fillers
if (getCellSpacing() == 0) {
columnsCount = columnsCount * 2 + 1;
}
StringBuilder result = new StringBuilder();
result.append("<table width=\"98%\" cellspacing=\"0\" cellpadding=\"2\" border=\"0\" ");
result.append("class=\"arrayPane\"><tr><td>\n").append("<table width=\"100%\" cellspacing=\"");
result.append(getCellSpacing()).append("\" cellpadding=\"").append(getCellPadding());
result.append("\" border=\"").append(getCellBorderWidth()).append("\"");
result.append(" id=\"").append(getName()).append("\" class=\"tableArrayPane\"");
result.append(" summary=\"").append(getSummary()).append("\">");
if (getTitle() != null) {
result.append("<caption>").append(getTitle()).append("</caption>");
}
if (getCellSpacing() == 0) {
result.append("<tr>");
result.append("<td colspan=\"").append(columnsCount).append("\">");
result.append("<img src=\"").append(getIconsPath()).append(
"/1px.gif\" width=\"1\" height=\"1\" alt=\"\"/>");
result.append("</td>");
result.append("</tr>\n");
}
result.append("<thead>\n");
result.append("<tr>\n");
if (getCellSpacing() == 0) {
result.append(printPseudoColumn());
}
for (ArrayColumn column : getColumns()) {
result.append(column.print(isXHTML()));
if (getCellSpacing() == 0) {
result.append(printPseudoColumn());
}
}
result.append("</tr>\n").append("</thead>\n").append("<tbody>\n");
if (getLines().isEmpty()) {
result.append("<tr><td> </td></tr>\n");
} else {
// No need pagination
if (getState().getMaximumVisibleLine() == -1) {
for (ArrayLine curLine : getLines()) {
printArrayPaneLine(result, curLine);
}
} else {
// Paginate ArrayPane result
getState().setFirstVisibleLine(pagination.getIndexForCurrentPage());
int first = pagination.getIndexForCurrentPage();
int lastIndex;
if (pagination.isLastPage()) {
lastIndex = pagination.getLastItemIndex();
} else {
lastIndex = pagination.getIndexForNextPage();
}
for (int i = first; i < lastIndex; i++) {
printArrayPaneLine(result, getLines().get(i));
}
}
}
result.append("</tbody>\n");
result.append("</table>\n");
boolean paginationVisible =
-1 != getState().getMaximumVisibleLine() && getLines().size() > getState().getMaximumVisibleLine();
if (paginationVisible || getExportData()) {
result.append(
"<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n");
result.append("<tr class=\"intfdcolor\">\n");
if (paginationVisible) {
result.append("<td align=\"center\">");
result.append(pagination.printIndex(getPaginationJavaScriptCallback()));
result.append("</td>");
}
if (getExportData()) {
// Add export data GUI
result.append("<td class=\"exportlinks\">");
result.append("<div>");
result.append(gef.getMultilang().getString("GEF.export.label")).append(" :");
result.append("<a href=\"").append(getExportUrl()).append(
"\"><span class=\"export csv\">");
result.append(gef.getMultilang().getString("GEF.export.option.csv")).append("</span></a>");
result.append("</div>");
// Be careful we only put a unique name in the session, so we cannot export two ArrayPanes
// which are displayed in the same page (use this.name instead of "arraypane")
getSession().setAttribute("Silverpeas_arraypane_columns", getColumns());
getSession().setAttribute("Silverpeas_arraypane_lines", getLines());
result.append("</td>");
}
result.append("</tr>\n");
result.append("</table>");
}
result.append("</td></tr></table>\n");
if (isSortableLines()) {
result.append(printSortJavascriptFunction());
}
return result.toString();
}
/**
* Print an ArrayPane line
* @param result the string builder
* @param curLine the array pane line to print
*/
private void printArrayPaneLine(StringBuilder result, ArrayLine curLine) {
if (getCellSpacing() == 0) {
result.append(curLine.printWithPseudoColumns());
} else {
result.append(curLine.print());
}
}
} | agpl-3.0 |
aborg0/rapidminer-studio | src/main/java/com/rapidminer/gui/tools/ProgressThreadDialog.java | 8799 | /**
* Copyright (C) 2001-2019 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.gui.tools;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import com.rapidminer.RapidMiner;
import com.rapidminer.gui.ApplicationFrame;
import com.rapidminer.gui.tools.dialogs.ButtonDialog;
/**
* Displays information about all pending {@link ProgressThread}s.
*
* @author Simon Fischer, Marco Boeck
*/
public class ProgressThreadDialog extends ButtonDialog {
private static final long serialVersionUID = 1L;
/** the singleton instance */
private static ProgressThreadDialog INSTANCE;
/** Create dialog in EDT */
static {
if (!RapidMiner.getExecutionMode().isHeadless()) {
SwingTools.invokeLater(new Runnable() {
@Override
public void run() {
INSTANCE = new ProgressThreadDialog();
}
});
}
}
/** mapping between ProgressThread and the UI panel for it */
private static final Map<ProgressThread, ProgressThreadDisplay> MAPPING_PG_TO_UI = new ConcurrentHashMap<>();
/** the panel displaying the running and waiting threads */
private JPanel threadPanel;
/** if true, the user opened the dialog; false otherwise */
private boolean openedByUser;
/**
* Private default constructor.
*/
private ProgressThreadDialog() {
super(ApplicationFrame.getApplicationFrame(), "progress_dialog", ModalityType.APPLICATION_MODAL, new Object[] {});
// listener to be notified when the ProgressThread tasks change
ProgressThread.addProgressThreadStateListener(new ProgressThreadStateListener() {
@Override
public void progressThreadStarted(ProgressThread pg) {
updatePanelInEDT();
updateUI();
}
@Override
public void progressThreadQueued(ProgressThread pg) {
updatePanelInEDT();
updateUI();
}
@Override
public void progressThreadFinished(ProgressThread pg) {
updatePanelInEDT();
updateUI();
MAPPING_PG_TO_UI.remove(pg);
}
@Override
public void progressThreadCancelled(ProgressThread pg) {
updatePanelInEDT();
updateUI();
MAPPING_PG_TO_UI.remove(pg);
}
/**
* Updates the ProgressThread panel in the EDT.
*/
private void updatePanelInEDT() {
SwingUtilities.invokeLater(() -> updateThreadPanel(false));
}
});
SwingUtilities.invokeLater(ProgressThreadDialog.this::initGUI);
}
/**
* Inits the GUI.
*/
private void initGUI() {
JPanel outerPanel = new JPanel(new BorderLayout());
outerPanel.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1));
threadPanel = new JPanel(new GridBagLayout());
threadPanel.setOpaque(true);
threadPanel.setBackground(Color.WHITE);
// add thread panel to outer panel
JScrollPane scrollPane = new ExtendedJScrollPane(threadPanel);
scrollPane.setBorder(null);
outerPanel.add(scrollPane, BorderLayout.CENTER);
setDefaultSize(ButtonDialog.NORMAL);
layoutDefault(outerPanel, makeCancelButton("hide"));
setModalExclusionType(ModalExclusionType.APPLICATION_EXCLUDE);
setModalityType(ModalityType.APPLICATION_MODAL);
}
/**
* Updates the thread display panel which shows running/queued threads.
*
* @param forceUpdate
* will update even when the dialog is not visible
*/
private synchronized void updateThreadPanel(boolean forceUpdate) {
if (!forceUpdate && !isVisible()) {
return;
}
threadPanel.removeAll();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 0.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 10;
// add currently running tasks
for (ProgressThread currentThread : ProgressThread.getCurrentThreads()) {
ProgressThreadDisplay pgPanel = new ProgressThreadDisplay(currentThread, false);
threadPanel.add(pgPanel, gbc);
MAPPING_PG_TO_UI.put(currentThread, pgPanel);
updateProgressMessage(currentThread);
updateProgress(currentThread);
gbc.gridy += 1;
}
// add pending tasks
for (ProgressThread queuedThread : ProgressThread.getQueuedThreads()) {
ProgressThreadDisplay pgPanel = new ProgressThreadDisplay(queuedThread, true);
threadPanel.add(pgPanel, gbc);
MAPPING_PG_TO_UI.put(queuedThread, pgPanel);
gbc.gridy += 1;
}
// add filler component
gbc.gridy += 1;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
threadPanel.add(new JLabel(), gbc);
threadPanel.revalidate();
threadPanel.repaint();
}
/**
* Updates the status bar in the ApplicationFrame and refreshes the dialog if need be.
*/
private void updateUI() {
if (ProgressThread.isEmpty()) {
// close dialog if not opened by user
if (!openedByUser) {
SwingUtilities.invokeLater(ProgressThreadDialog.this::dispose);
}
// hide status bar
if (ApplicationFrame.getApplicationFrame() != null) {
ApplicationFrame.getApplicationFrame().getStatusBar().setProgress("", 100, 100);
}
} else {
if (!ProgressThread.isForegroundRunning()) {
// close dialog if not opened by user
if (!openedByUser) {
SwingUtilities.invokeLater(ProgressThreadDialog.this::dispose);
}
}
Iterator<ProgressThread> iterator = ProgressThread.getCurrentThreads().iterator();
if (iterator.hasNext()) {
ProgressThread pg = iterator.next();
// while there is at least one running, take first one and display in status
// bar
if (ApplicationFrame.getApplicationFrame() != null) {
StatusBar statusBar = ApplicationFrame.getApplicationFrame().getStatusBar();
if (pg.isIndeterminate()) {
statusBar.setIndeterminateProgress(pg.getName(), 0, 100);
} else {
statusBar.setProgress(pg.getName(), pg.getDisplay().getCompleted(), pg.getDisplay().getTotal());
}
}
} else {
// no task running, hide status bar
if (ApplicationFrame.getApplicationFrame() != null) {
ApplicationFrame.getApplicationFrame().getStatusBar().setProgress("", 100, 100);
}
}
}
}
/**
* Updates the progress of the specified ProgressThread.
*
* @param pg
*/
public void updateProgress(final ProgressThread pg) {
final ProgressThreadDisplay ui = MAPPING_PG_TO_UI.get(pg);
if (ui != null) {
SwingTools.invokeLater(() -> ui.setProgress(pg.getDisplay().getCompleted()));
}
updateUI();
}
/**
* Updates the progress message of the specified ProgressThread.
*
* @param pg
*/
public void updateProgressMessage(final ProgressThread pg) {
final ProgressThreadDisplay ui = MAPPING_PG_TO_UI.get(pg);
if (ui != null) {
SwingTools.invokeLater(() -> ui.setMessage(pg.getDisplay().getMessage()));
}
updateUI();
}
/**
* Sets the dialog to visible. If this was invoked by a user action, set openedByUser to
* <code>true</code>; <code>false</code> otherwise. This needed so that the dialog will not
* close itself if opened by the user.
*
* @param openedByUser
* @param visible
*/
public void setVisible(boolean openedByUser, boolean visible) {
this.openedByUser = openedByUser;
if (visible) {
updateThreadPanel(true);
setIconImage(ApplicationFrame.getApplicationFrame().getIconImage());
setLocationRelativeTo(ApplicationFrame.getApplicationFrame());
}
super.setVisible(visible);
}
@Override
public void setVisible(boolean b) {
setVisible(false, b);
}
/**
* Singleton access to the {@link ProgressThreadDialog} or {@code null} if running in headless mode
*/
public static ProgressThreadDialog getInstance() {
return INSTANCE;
}
}
| agpl-3.0 |
StrictlySkyler/simplval | jquery.thickval.js | 8233 | /******
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/>.
*****
PROJECT- Thick Validator jQuery Plugin (thickval)
COPYRIGHT- 2011 © Skyler Brungardt
AUTHOR- Skyler Brungardt
CREATED- 03/29/11
NOTES- This plugin is an extension of the simplval plugin, including error display
for invalid fields.
REQUIREMENTS- 1. Most any version of jQuery, recommended 1.2.6+.
2. The form element on which this validator is called should have a unique ID
attribute.
VERSION- 1.0.0: Initial release.
******/
// JQUERY $ NAMESPACE
(function($){
// BEGIN PLUGIN
// DECLARE PLUGIN NAME AND ARGS. TWO ARGUMENTS WHICH SHOULD BE PASSED ARE THE TYPE OF
// VALIDATION EXPECTED (POSSIBLE VALUES ARE STRINGS EQUAL TO THE REGEX VARS BELOW), AND A
// BOOLEAN DETERMINING WHETHER THE FORM IS REQUIRED OR NOT.
$.fn.thickval = function(type,required) {
//REGEX VARIABLES FOR FORM FIELD VALIDATION - THIS LIST CAN BE EXTENDED. EACH VARIABLE
// NAME HERE CAN BE PASSED AS AN ARGUMENT TO THE PLUGIN, AGAINST WHICH A FORM CAN BE
// VALIDATED.
var checkCompoundName = /^[a-z\,\-\. ]*$/i,
checkEmail = /^[a-z\d\.\-\_\ ]+@[a-z\d\.\-_]{2,}\.[a-z]{2,10}$/i,
checkPhone = /^[\d \-\(\)\+]*$/,
checkZIP = /^\d{5}$/,
// ERRORS TO ASSOCIATE WITH SPECIFIC KINDS OF VALIDATION. THESE SHOULD MATCH THE
// REGEX USED ABOVE, WITH THE ADDITION OF ONE FOR BLANK FIELDS.
blankError = "<p>This field cannot be blank.</p>",
compoundNameError = "<p>Only letters, hyphens, spaces, and periods are allowed.</p>",
emailError = "<p>Please enter a valid email address.</p>",
phoneError = "<p>Please enter a valid phone number.</p>",
ZIPError = "<p>Please enter a valid ZIP code.</p>",
// CONTENTS OF THE FIELD BEING VALIDATED
value = $(this).val(),
// RETURNED AS TRUEY OR FALSEY BASED ON WHETHER THE CONTENTS MATCH THE REGEX OR NOT
validField,
// FUNCTION TO VALIDATE FIELDS MARKED AS "REQUIRED" BY THE FORM. ACCEPTS THREE
// ARGUMENTS: OBJECT BEING VALIDATED (USUALLY "this"), REGEX AGAINST WHICH TO TEST, AND
// TYPE OF FIELD BEING VALIDATED.
requiredField = function(obj,re,type) {
// TEST TO SEE IF THE FIELD PASSES THE REGEX
var valid = re.test(value),
// ASSIGN THE ERROR MESSAGE LOCATION RELATIVE TO THE FIELD BEING TESTED
top = ($(obj).position().top) + 2,
left = ($(obj).position().left) + ($(obj).width()) + 10,
// CREATE A UNIQUE ID FOR THE ERROR, BASED UPON THE UNIQUE ID OF THE FORM ELEMENT
// BEING VALIDATED. THIS WILL BEHAVE ERRATICALLY IF THE OBJECT DOESN'T HAVE A
// UNIQUE ID.
errorId = $(obj).attr("id") + "Error";
// CHECK TO SEE IF THE FIELD IS BLANK, AND CREATE APPROPRIATE ERROR IF SO
if (value === "") {
// CHECK TO SEE IF ERROR ALREADY EXISTS
if ($("#"+errorId).text() === "") {
// CREATE BLANK ERROR
$(obj).after(blankError);
$(obj).next().attr("id",errorId);
} else {
// REPLACE EXISTING ERROR WITH BLANK ERROR
$("#"+errorId).replaceWith(blankError);
$(obj).next().attr("id",errorId);
}
$("#"+errorId).css("display","block");
$("#"+errorId).css("color","#f00");
$("#"+errorId).css("position","absolute");
$("#"+errorId).css("top", top);
$("#"+errorId).css("left", left);
$(obj).addClass("errorBorder");
// REPORT THAT FIELD IS NOT VALID, SINCE REQUIRED FIELDS CANNOT BE BLANK
valid = false;
// CHECK TO SEE IF FIELD HAS IMPROPER DATA
} else if (!valid) {
// SAME AS ABOVE - CREATE THE ERROR IF IT DOESN'T EXIST ALREADY, OR REPLACE IT
// WITH THE APPROPRIATE ERROR IF IT DOES
if ($("#"+errorId).text() === "") {
$(obj).after(type);
$(obj).next().attr("id",errorId);
} else {
$("#"+errorId).replaceWith(type);
$(obj).next().attr("id",errorId);
}
$("#"+errorId).css("display","block");
$("#"+errorId).css("color","#f00");
$("#"+errorId).css("position","absolute");
$("#"+errorId).css("top", top);
$("#"+errorId).css("left", left);
$(obj).addClass("errorBorder");
// IF THE FIELD IS VALID AND NOT BLANK, PROCEED
} else if ((valid) && (value !== "")) {
// HIDE THE ERROR MESSAGE IF IT EXISTS
if ($("#"+errorId).css("display") === "block") {
$("#"+errorId).css("display","none");
$(obj).removeClass("errorBorder");
}
}
// REPORT WHETHER FIELD IS VALID OR NOT
return valid;
},
// THIS FUNCTION IS IDENTICAL TO requiredField ABOVE, WITH THE EXCEPTION THAT BLANK
// FORM ELEMENTS ARE ALLOWED, SINCE THIS IS USED TO TEST AGAINST OPTIONAL FIELDS OR NOT.
optionalField = function(obj,re,type) {
var valid = re.test(value),
top = $(obj).position().top + 2,
left = $(obj).position().left + $(obj).width() + 10,
errorId = $(obj).attr("id") + "Error";
if (!valid) {
if ($("#"+errorId).text() === "") {
$(obj).after(type);
$(obj).next().attr("id",errorId);
} else {
$("#"+errorId).replaceWith(type);
$(obj).next().attr("id",errorId);
}
$("#"+errorId).css("display","block");
$("#"+errorId).css("color","#f00");
$("#"+errorId).css("position","absolute");
$("#"+errorId).css("top", top);
$("#"+errorId).css("left", left);
$(obj).addClass("errorBorder");
} else if (valid) {
if ($("#"+errorId).css("display") === "block") {
$("#"+errorId).css("display","none");
$(obj).removeClass("errorBorder");
}
}
return valid;
};
// LOGIC TO DETERMINE HOW TO VALIDATE THE FORM, WITH TWO POSSIBILITIES: THE FORM
// ELEMENT IS REQUIRED OR IT IS OPTIONAL. THESE ARE PASSED TO THE PLUGIN AS BOOLEANS;
// TRUE IS REQUIRED, FALSE IS OPTIONAL, AND DEFAULT BEHAVIOR (WITH ANYTHING OTHER THAN
// TRUEY OR FALSEY VALUES) REPORTS THAT IT NEEDS TO KNOW WHETHER THE FIELD IS
// REQUIRED OR NOT, AND THE ARGUMENT IS MISSING.
switch (required) {
// IF THE FIELD IS REQUIRED, DETERMINE WHICH KIND OF VALIDATION TO USE
case true:
// THERE SHOULD BE A CASE FOR EACH OF THE KINDS OF REGEX VARIABLES ABOVE,
// REPORTING AN ERROR IF SOMETHING IS CHOSEN THAT ISN'T LISTED HERE
switch (type) {
case "compoundName":
validField = requiredField(this,checkCompoundName,compoundNameError);
break;
case "email":
validField = requiredField(this,checkEmail,emailError);
break;
case "phone":
validField = requiredField(this,checkPhone,phoneError);
break;
case "zip":
validField = requiredField(this,checkZIP,ZIPError);
break;
default:
console.log("There's no validation logic for what you chose; you need to build it into the switch statement!");
break;
}
break;
case false:
// SAME AS THE SWITCH STATEMENT FOR REQUIRED FORMS, ABOVE
switch (type) {
case "compoundName":
validField = optionalField(this,checkCompoundName,compoundNameError);
break;
case "email":
validField = optionalField(this,checkEmail,emailError);
break;
case "phone":
validField = optionalField(this,checkPhone,phoneError);
break;
case "zip":
validField = optionalField(this,checkZIP,ZIPError);
break;
default:
console.log("There's no validation logic for what you chose; you need to build it into the switch statement!");
break;
}
break;
default:
console.log("You didn't enter the arguments properly!");
break;
}
// RETURN WHETHER THE FIELD PASSED VALIDATION OR NOT WITH A TRUEY OR FALSEY VALUE
return validField;
};
// END PLUGIN
})( jQuery );
//END | agpl-3.0 |
rschnapka/account-closing | account_multicurrency_revaluation/report/currency_unrealized_report.py | 10807 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright 2012 Camptocamp SA
#
# 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 report import report_sxw
from openerp.tools.translate import _
import pooler
class ShellAccount(object):
# Small class that avoid to override account account object
# only for pure perfomance reason.
# Browsing an account account object is not efficient
# beacause of function fields
# This object aim to be easly transpose to account account if needed
def __init__(self, cr, uid, pool, acc_id, context=None):
self._context = context or {}
self.cursor = cr
self.uid = uid
self.acc_id = acc_id
self.pool = pool
tmp = self.pool['account.account'].read(
cr, uid, [acc_id], ['id', 'name', 'code', 'currency_revaluation'],
self._context)
self.name = tmp[0].get('name')
self.code = tmp[0].get('code')
self.account_id = tmp[0]['id']
self.ordered_lines = []
self.currency_revaluation = tmp[0].get('currency_revaluation', False)
self.keys_to_sum = ['gl_foreign_balance', 'gl_currency_rate',
'gl_revaluated_balance', 'gl_balance',
'gl_ytd_balance']
def get_lines(self, period_id):
"""Get all line account move line that are need on report for current
account.
"""
sql = """Select res_partner.name,
account_move_line.date,
account_move_line.gl_foreign_balance,
account_move_line.gl_currency_rate,
account_move_line.gl_revaluated_balance,
account_move_line.gl_balance,
account_move_line.gl_revaluated_balance -
account_move_line.gl_balance as gl_ytd_balance,
res_currency.name as curr_name
FROM account_move_line
LEFT join res_partner on
(account_move_line.partner_id = res_partner.id)
LEFT join account_move on
(account_move_line.move_id = account_move.id)
LEFT join res_currency on
(account_move_line.currency_id = res_currency.id)
WHERE account_move_line.account_id = %s
AND account_move.to_be_reversed = true
AND account_move_line.gl_balance is not null
AND account_move_line.period_id = %s
ORDER BY res_partner.name,
account_move_line.gl_foreign_balance,
account_move_line.date"""
self.cursor.execute(sql, (self.account_id, period_id))
self.ordered_lines = self.cursor.dictfetchall()
return self.ordered_lines
def compute_totals(self):
"""Compute the sum of values in self.ordered_lines"""
totals = dict.fromkeys(self.keys_to_sum, 0.0)
for line in self.ordered_lines:
for tot in self.keys_to_sum:
totals[tot] += line.get(tot, 0.0)
for key, val in totals.iteritems():
setattr(self, key + '_total', val)
class CurrencyUnrealizedReport(report_sxw.rml_parse):
def _get_period_name(self, data):
return data.get('form', {}).get('period_name', '')
def __init__(self, cursor, uid, name, context):
super(CurrencyUnrealizedReport, self).__init__(
cursor, uid, name, context=context)
self.pool = pooler.get_pool(self.cr.dbname)
self.cursor = self.cr
self.company = self.pool.get('res.users').browse(
self.cr, uid, uid, context=context).company_id
self.localcontext.update({
'cr': cursor,
'uid': uid,
'period_name': self._get_period_name,
'report_name': _('Exchange Rate Gain and Loss Report')}
)
def sort_accounts_with_structure(self, root_account_ids, account_ids,
context=None):
"""Sort accounts by code respecting their structure. code Take from
financial webkit report in order not to depends from it"""
def recursive_sort_by_code(accounts, parent):
sorted_accounts = []
# add all accounts with same parent
level_accounts = [account for account in accounts
if account['parent_id'] and
account['parent_id'][0] == parent['id']]
# add consolidation children of parent, as they are logically on
# the same level
if parent.get('child_consol_ids'):
level_accounts.extend([account for account in accounts
if account['id'] in
parent['child_consol_ids']])
# stop recursion if no children found
if not level_accounts:
return []
level_accounts = sorted(level_accounts, key=lambda a: a['code'])
for level_account in level_accounts:
sorted_accounts.append(level_account['id'])
sorted_accounts.extend(
recursive_sort_by_code(accounts, parent=level_account))
return sorted_accounts
if not account_ids:
return []
accounts_data = self.pool['account.account'].read(
self.cr, self.uid, account_ids,
['id', 'parent_id', 'level', 'code', 'child_consol_ids'],
context=context)
sorted_accounts = []
root_accounts_data = [account_data for account_data in accounts_data
if account_data['id'] in root_account_ids]
for root_account_data in root_accounts_data:
sorted_accounts.append(root_account_data['id'])
sorted_accounts.extend(
recursive_sort_by_code(accounts_data, root_account_data))
# fallback to unsorted accounts when sort failed
# sort fails when the levels are miscalculated by account.account
# check lp:783670
if len(sorted_accounts) != len(account_ids):
sorted_accounts = account_ids
return sorted_accounts
def get_all_accounts(self, account_ids, exclude_type=None, only_type=None,
filter_report_type=None, context=None):
"""Get all account passed in params with their childrens.
TAKEN FROM webkit general ledger
@param exclude_type: list of types to exclude (view, receivable,
payable, consolidation, other)
@param only_type: list of types to filter on (view, receivable,
payable, consolidation, other)
@param filter_report_type: list of report type to filter on
"""
context = context or {}
accounts = []
if not isinstance(account_ids, list):
account_ids = [account_ids]
acc_obj = self.pool.get('account.account')
for account_id in account_ids:
accounts.append(account_id)
accounts += acc_obj._get_children_and_consol(
self.cursor, self.uid, account_id, context=context)
res_ids = list(set(accounts))
res_ids = self.sort_accounts_with_structure(
account_ids, res_ids, context=context)
if exclude_type or only_type or filter_report_type:
sql_filters = {'ids': tuple(res_ids)}
sql_select = "SELECT a.id FROM account_account a"
sql_join = ""
sql_where = "WHERE a.id IN %(ids)s"
if exclude_type:
sql_where += " AND a.type not in %(exclude_type)s"
sql_filters.update({'exclude_type': tuple(exclude_type)})
if only_type:
sql_where += " AND a.type IN %(only_type)s"
sql_filters.update({'only_type': tuple(only_type)})
if filter_report_type:
sql_join += "INNER JOIN account_account_type t" \
" ON t.id = a.user_type"
sql_join += " AND t.report_type IN %(report_type)s"
sql_filters.update({'report_type': tuple(filter_report_type)})
sql_join += " order by account_account.code"
sql = ' '.join((sql_select, sql_join, sql_where))
self.cursor.execute(sql, sql_filters)
fetch_only_ids = self.cursor.fetchall()
if not fetch_only_ids:
return []
only_ids = [only_id[0] for only_id in fetch_only_ids]
# keep sorting but filter ids
res_ids = [res_id for res_id in res_ids if res_id in only_ids]
return res_ids
def set_context(self, objects, data, ids, report_type=None):
"""Populate a ledger_lines attribute on each browse record that will
be used by mako template.
"""
for mand in ['account_ids', 'period_id']:
if not data['form'][mand]:
raise Exception(
_('%s argument is not set in wizard') % (mand,))
# we replace object
objects = []
new_ids = data['form']['account_ids']
period_id = data['form']['period_id']
# get_all_account is in charge of ordering the accounts
for acc_id in self.get_all_accounts(new_ids):
acc = ShellAccount(
self.cursor, self.uid, self.pool, acc_id,
context=self.localcontext)
if not acc.currency_revaluation:
continue
acc.get_lines(period_id)
if acc.ordered_lines:
objects.append(acc)
acc.compute_totals()
return super(CurrencyUnrealizedReport, self).set_context(
objects, data, ids, report_type=None)
report_sxw.report_sxw(
'report.currency_unrealized', 'account.account',
'addons/account_unrealized_currency_gain_loss/report/templates/'
'unrealized_currency_gain_loss.mako', parser=CurrencyUnrealizedReport)
| agpl-3.0 |
VietOpenCPS/opencps-v2 | modules/backend-api-rest/src/main/java/org/opencps/api/eform/model/EFormSearchModel.java | 3353 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.09.11 at 06:53:24 PM ICT
//
package org.opencps.api.eform.model;
import com.liferay.petra.string.StringPool;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.QueryParam;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="keyword" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="administration" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="domain" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="level" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="start" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="end" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="sort" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="order" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"keyword",
"service",
"state",
"start",
"end",
"sort",
"order"
})
@XmlRootElement(name = "EformSearchModel")
public class EFormSearchModel {
@QueryParam(value = "keyword")
protected String keyword;
@DefaultValue(StringPool.BLANK)
@QueryParam(value = "service")
protected String service;
@QueryParam(value = "state")
protected String state;
@QueryParam(value = "start")
protected int start;
@QueryParam(value = "end")
protected int end;
@DefaultValue("checkinDate")
@QueryParam("sort")
protected String sort;
@QueryParam(value = "order")
protected String order;
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}
}
| agpl-3.0 |
kaltura/server | infra/general/KCryptoWrapper.class.php | 3771 | <?php
class KCryptoWrapper
{
public static function getEncryptorClassName()
{
if (extension_loaded('mcrypt')){
return 'McryptWrapper';
}else{
return 'OpenSSLWrapper';
}
}
public static function __callStatic($func, $args)
{
$encryptorClass = self::getEncryptorClassName();
return call_user_func_array(array($encryptorClass, $func), $args);
}
public static function getEncryptor()
{
$encryptorClass = self::getEncryptorClassName();
return new $encryptorClass();
}
}
class OpenSSLWrapper
{
const AES_BLOCK_SIZE = 16;
const DES3_BLOCK_SIZE = 8;
const DES3_METHOD = 'DES-EDE3';
protected static function get_aes_method($key)
{
switch (strlen($key))
{
case 32:
return 'AES-256-CBC';
case 24:
return 'AES-192-CBC';
default:
return 'AES-128-CBC';
}
}
public static function random_pseudo_bytes($length)
{
return openssl_random_pseudo_bytes($length);
}
public static function encrypt_3des($str, $key)
{
if (strlen($str) % self::DES3_BLOCK_SIZE) {
$padLength = self::DES3_BLOCK_SIZE - strlen($str) % self::DES3_BLOCK_SIZE;
$str .= str_repeat("\0", $padLength);
}
return openssl_encrypt(
$str,
self::DES3_METHOD,
$key,
OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING
);
}
public static function decrypt_3des($str, $key)
{
return openssl_decrypt(
$str,
self::DES3_METHOD,
$key,
OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING
);
}
public static function encrypt_aes($str, $key, $iv)
{
// Pad with null byte to be compatible with mcrypt PKCS#5 padding
// See http://thefsb.tumblr.com/post/110749271235/using-opensslendecrypt-in-php-instead-of as
if (strlen($str) % self::AES_BLOCK_SIZE) {
$padLength = self::AES_BLOCK_SIZE - strlen($str) % self::AES_BLOCK_SIZE;
$str .= str_repeat("\0", $padLength);
}
return openssl_encrypt(
$str,
self::get_aes_method($key),
$key,
OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING,
$iv
);
}
public static function decrypt_aes($str, $key, $iv)
{
return openssl_decrypt(
$str,
self::get_aes_method($key),
$key,
OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING,
$iv
);
}
}
class McryptWrapper
{
public static function random_pseudo_bytes($length)
{
return mcrypt_create_iv($length,MCRYPT_DEV_URANDOM);
}
public static function encrypt_3des($str, $key)
{
$td = mcrypt_module_open('tripledes', '', 'ecb', '');
$key = substr($key, 0, mcrypt_enc_get_key_size($td));
mcrypt_generic_init($td, $key, str_repeat("\0", 8));
$encrypted_data = mcrypt_generic($td, $str);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $encrypted_data;
}
public static function decrypt_3des($str, $key)
{
$td = mcrypt_module_open('tripledes', '', 'ecb', '');
$key = substr($key, 0, mcrypt_enc_get_key_size($td));
mcrypt_generic_init($td, $key, str_repeat("\0", 8));
$decrypted_data = mdecrypt_generic($td, $str);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $decrypted_data;
}
public static function encrypt_aes($str, $key, $iv)
{
return mcrypt_encrypt(
MCRYPT_RIJNDAEL_128,
$key,
$str,
MCRYPT_MODE_CBC,
$iv
);
}
public static function decrypt_aes($str, $key, $iv)
{
return mcrypt_decrypt(
MCRYPT_RIJNDAEL_128,
$key,
$str,
MCRYPT_MODE_CBC,
$iv
);
}
}
| agpl-3.0 |
INRIA/osc | db/migrate/026_create_soumission_europe_partenaires.rb | 464 | class CreateSoumissionEuropePartenaires < ActiveRecord::Migration
def self.up
create_table :soumission_europe_partenaires do |t|
t.column :soumission_id, :integer
t.column :nom, :string
t.column :etablissement_gestionnaire, :string
t.column :ville, :string
t.column :pays, :string
t.column :localisation, :string, :default => 'europe'
end
end
def self.down
drop_table :soumission_europe_partenaires
end
end
| agpl-3.0 |